@utk09/ui-observability 0.1.1 → 0.1.2

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.
@@ -6,7 +6,7 @@ var e = "[ui-observability]", t = 1e3, n = "ui-observability.session", r = "ui-o
6
6
  WARN: 13,
7
7
  ERROR: 17,
8
8
  FATAL: 21
9
- }, _ = g, v = "log.type", y = "log.seq", b = "app.namespace", x = "page.url", S = "url.full", C = "journey.id", w = "journey.name", T = "journey.parent_id", E = "uiobs.sanitize_failed", D = "uiobs.attributes_dropped", O = "uiobs.attributes_bytes", k = "service.name", A = "service.version", j = "deployment.environment", M = "telemetry.sdk.name", N = "telemetry.sdk.version", P = "telemetry.sdk.language", F = "host.platform", I = "session.id", L = "tab.id", R = "context.id", z = "browser.user_agent", B = "openfin.uuid", V = "openfin.name", H = "@utk09/ui-observability", U = "0.1.0", W = "webjs", G = "otlp", K = "application/json", q = "application/x-ndjson", J = 1000000n, Y = /^\d+$/, ee = "Content-Type", X = "Content-Encoding", Z = "Retry-After", Q = "X-UiObs-Batch-Id", $ = "X-UiObs-Attempt", te = "gzip", ne = 1e3, re = 6e4, ie = "text/plain;charset=UTF-8", ae = "uiobs_batch_id", oe = "uiobs_exit", se = "ui-observability.batch.", ce = "ui-observability.emergency.", le = "ui-observability.probe", ue = "QuotaExceededError", de = "indexeddb", fe = "localstorage", pe = "memory", me = "none", he = "ui-observability.drain", ge = "ui-observability.emergency", _e = "ui-observability.journey", ve = 2e3, ye = "uiObsJourney", be = /\+/g, xe = /\//g, Se = /=+$/, Ce = /-/g, we = /_/g, Te = 3e5, Ee = 2166136261, De = 16777619, Oe = 4294967295, ke = "metric", Ae = "ui-observability/1", je = "ui-observability.runtime", Me = 1e4, Ne = "color:#888", Pe = 1e3, Fe = 6e4, Ie = "uiobs.capture", Le = "uiobs.storage", Re = "count", ze = "unknown-service", Be = [
9
+ }, _ = g, v = "log.type", y = "log.seq", b = "app.namespace", x = "page.url", S = "url.full", C = "journey.id", w = "journey.name", T = "journey.parent_id", E = "uiobs.sanitize_failed", D = "uiobs.attributes_dropped", O = "uiobs.attributes_bytes", k = "service.name", A = "service.version", j = "deployment.environment", M = "telemetry.sdk.name", N = "telemetry.sdk.version", P = "telemetry.sdk.language", F = "host.platform", I = "session.id", L = "tab.id", R = "context.id", z = "browser.user_agent", B = "openfin.uuid", V = "openfin.name", H = "@utk09/ui-observability", U = "0.1.2", W = "webjs", G = "otlp", K = "application/json", q = "application/x-ndjson", J = 1000000n, Y = /^\d+$/, ee = "Content-Type", X = "Content-Encoding", Z = "Retry-After", Q = "X-UiObs-Batch-Id", $ = "X-UiObs-Attempt", te = "gzip", ne = 1e3, re = 6e4, ie = "text/plain;charset=UTF-8", ae = "uiobs_batch_id", oe = "uiobs_exit", se = "ui-observability.batch.", ce = "ui-observability.emergency.", le = "ui-observability.probe", ue = "QuotaExceededError", de = "indexeddb", fe = "localstorage", pe = "memory", me = "none", he = "ui-observability.drain", ge = "ui-observability.emergency", _e = "ui-observability.journey", ve = 2e3, ye = "uiObsJourney", be = /\+/g, xe = /\//g, Se = /=+$/, Ce = /-/g, we = /_/g, Te = 3e5, Ee = 2166136261, De = 16777619, Oe = 4294967295, ke = "metric", Ae = "ui-observability/1", je = "ui-observability.runtime", Me = 1e4, Ne = "color:#888", Pe = 1e3, Fe = 6e4, Ie = "uiobs.capture", Le = "uiobs.storage", Re = "count", ze = "unknown-service", Be = [
10
10
  "redact",
11
11
  "onDiagnostic",
12
12
  "headers",
@@ -107,4 +107,4 @@ var e = "[ui-observability]", t = 1e3, n = "ui-observability.session", r = "ui-o
107
107
  //#endregion
108
108
  export { u as $, he as A, fe as At, Q as B, Be as Bt, Ne as C, G as Ct, He as D, g as Dt, ie as E, a as Et, Me as F, W as Ft, p as G, ee as H, h as Ht, Ee as I, H as It, _ as J, c as K, De as L, U as Lt, ge as M, me as Mt, ce as N, le as Nt, Re as O, Le as Ot, te as P, r as Pt, ne as Q, Fe as R, Te as Rt, Ve as S, f as St, q as T, n as Tt, Z as U, d as Ut, X as V, ze as Vt, m as W, ke as X, e as Y, l as Z, xe as _, L as _t, C as a, ae as at, Ae as b, N as bt, y as c, z as ct, E as d, F as dt, Y as et, S as f, V as ft, be as g, I as gt, Se as h, A as ht, D as i, o as it, Pe as j, pe as jt, t as k, de as kt, v as l, R as lt, we as m, k as mt, b as n, ye as nt, w as o, oe as ot, Ce as p, B as pt, _e as q, O as r, ve as rt, T as s, ue as st, s as t, J as tt, x as u, j as ut, se as v, P as vt, K as w, i as wt, Ie as x, je as xt, re as y, M as yt, $ as z, Oe as zt };
109
109
 
110
- //# sourceMappingURL=constants-4eu3x1qw.js.map
110
+ //# sourceMappingURL=constants-CYedFKrL.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants-4eu3x1qw.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// All limits, thresholds, timing windows, storage keys, patterns, and\n// defaults used by the library.\n\nimport type { ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/** Throttle window per diagnostic code, in milliseconds. Limits how often an error loop can spam the handler. */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Log level to OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names records carry on the wire, following\n// OpenTelemetry conventions. `uiobs.` marks this library's own fields.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number within its context, from zero. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key, set by network capture. Don't reuse `ATTR_PAGE_URL`; it would overwrite the request's target.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record whose attributes were dropped for exceeding the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.1.0\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. Retryable. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large; batch must be split. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. CORS-safelisted, avoids a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a parked batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch parked by exit flush. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store evicted on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/** IndexedDB schema version. Bumping it requires a matching Dexie migration. */\nexport const INDEXEDDB_SCHEMA_VERSION = 1;\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. A tripwire, not validation.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * How long to wait for `fin.me.getOptions()` before giving up on a seeded journey,\n * in milliseconds.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants, used to turn a sampling key into a stable 0-1\n// fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n/** Batches held per stream buffer before the oldest is dropped. */\nexport const PENDING_BUFFER_BATCHES = 10;\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. Mismatched versions are dropped. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** CSS styling applied to console prefix labels. */\nexport const CONSOLE_PREFIX_STYLE = \"color:#888\";\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\"redact\", \"onDiagnostic\", \"headers\", \"serializer\"] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\n \"streams\",\n \"storage\",\n \"retry\",\n \"sampling\",\n \"journey\",\n \"bus\",\n \"capture\",\n \"limits\",\n \"console\",\n] as const;\n\n/**\n * Default runtime config, before a consumer's `configure()` call.\n * Excludes `serializer`; `resolveConfig` supplies its default to avoid a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n streams: {\n logs: { flushIntervalMs: 2000, batchSize: 100 },\n // Metrics batch harder than logs: higher volume, nothing waits on them.\n metrics: { flushIntervalMs: 10_000, batchSize: 500 },\n },\n maxConcurrentRequests: 2,\n requestTimeoutMs: 15000,\n compression: \"gzip\",\n compressionThresholdBytes: 1024,\n credentials: \"include\",\n storage: {\n strategy: \"auto\",\n dbName: \"UiObservability\",\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n },\n retry: { baseDelayMs: 2000, maxDelayMs: 60000, idleDelayMs: 30000 },\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n journey: {\n maxAgeMs: 30 * 60 * 1000,\n endOnOwnerClose: false,\n urlParam: \"__uiobs_journey\",\n },\n bus: {\n mode: \"auto\",\n channelName: \"ui_observability_control\",\n trustedOrigins: [],\n handshakeTimeoutMs: 1500,\n openFinHost: \"provider\",\n openFinRole: \"auto\",\n maxBootBufferRecords: 500,\n orphanPolicy: \"auto\",\n maxHandshakeAttempts: 3,\n },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n maxBreadcrumbs: 50,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n errorDedupeMs: 5000,\n },\n limits: {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxRecordBytes: 32768,\n },\n console: { enabled: false, level: \"DEBUG\" },\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"constants-CYedFKrL.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// All limits, thresholds, timing windows, storage keys, patterns, and\n// defaults used by the library.\n\nimport type { ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/** Throttle window per diagnostic code, in milliseconds. Limits how often an error loop can spam the handler. */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Log level to OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names records carry on the wire, following\n// OpenTelemetry conventions. `uiobs.` marks this library's own fields.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number within its context, from zero. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key, set by network capture. Don't reuse `ATTR_PAGE_URL`; it would overwrite the request's target.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record whose attributes were dropped for exceeding the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.1.2\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. Retryable. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large; batch must be split. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. CORS-safelisted, avoids a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a parked batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch parked by exit flush. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store evicted on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/** IndexedDB schema version. Bumping it requires a matching Dexie migration. */\nexport const INDEXEDDB_SCHEMA_VERSION = 1;\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. A tripwire, not validation.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * How long to wait for `fin.me.getOptions()` before giving up on a seeded journey,\n * in milliseconds.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants, used to turn a sampling key into a stable 0-1\n// fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n/** Batches held per stream buffer before the oldest is dropped. */\nexport const PENDING_BUFFER_BATCHES = 10;\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. Mismatched versions are dropped. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** CSS styling applied to console prefix labels. */\nexport const CONSOLE_PREFIX_STYLE = \"color:#888\";\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\"redact\", \"onDiagnostic\", \"headers\", \"serializer\"] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\n \"streams\",\n \"storage\",\n \"retry\",\n \"sampling\",\n \"journey\",\n \"bus\",\n \"capture\",\n \"limits\",\n \"console\",\n] as const;\n\n/**\n * Default runtime config, before a consumer's `configure()` call.\n * Excludes `serializer`; `resolveConfig` supplies its default to avoid a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n streams: {\n logs: { flushIntervalMs: 2000, batchSize: 100 },\n // Metrics batch harder than logs: higher volume, nothing waits on them.\n metrics: { flushIntervalMs: 10_000, batchSize: 500 },\n },\n maxConcurrentRequests: 2,\n requestTimeoutMs: 15000,\n compression: \"gzip\",\n compressionThresholdBytes: 1024,\n credentials: \"include\",\n storage: {\n strategy: \"auto\",\n dbName: \"UiObservability\",\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n },\n retry: { baseDelayMs: 2000, maxDelayMs: 60000, idleDelayMs: 30000 },\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n journey: {\n maxAgeMs: 30 * 60 * 1000,\n endOnOwnerClose: false,\n urlParam: \"__uiobs_journey\",\n },\n bus: {\n mode: \"auto\",\n channelName: \"ui_observability_control\",\n trustedOrigins: [],\n handshakeTimeoutMs: 1500,\n openFinHost: \"provider\",\n openFinRole: \"auto\",\n maxBootBufferRecords: 500,\n orphanPolicy: \"auto\",\n maxHandshakeAttempts: 3,\n },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n maxBreadcrumbs: 50,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n errorDedupeMs: 5000,\n },\n limits: {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxRecordBytes: 32768,\n },\n console: { enabled: false, level: \"DEBUG\" },\n};\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- var e=/OpenFin/i,t=/\bwv\b/,n=/\b(iPhone|iPad|iPod)\b/,r=/\bMacintosh\b/,i=/\bMobile\b/,a={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17,FATAL:21},o=a,s=`log.type`,c=`log.seq`,l=`app.namespace`,u=`page.url`,d=`url.full`,f=`journey.id`,p=`journey.name`,m=`journey.parent_id`,h=`uiobs.sanitize_failed`,g=`uiobs.attributes_dropped`,_=`uiobs.attributes_bytes`,v=`service.name`,y=`service.version`,b=`deployment.environment`,x=`telemetry.sdk.name`,S=`telemetry.sdk.version`,C=`telemetry.sdk.language`,w=`host.platform`,T=`session.id`,E=`tab.id`,D=`context.id`,O=`browser.user_agent`,k=`openfin.uuid`,A=`openfin.name`,j=`@utk09/ui-observability`,M=`0.1.0`,N=`webjs`,P=`otlp`,F=`application/json`,I=`application/x-ndjson`,L=1000000n,R=/^\d+$/,z=`Content-Type`,B=`Content-Encoding`,V=`Retry-After`,H=`X-UiObs-Batch-Id`,U=`X-UiObs-Attempt`,W=`gzip`,G=1e3,ee=6e4,K=`text/plain;charset=UTF-8`,q=`uiobs_batch_id`,J=`uiobs_exit`,Y=`ui-observability.batch.`,X=`ui-observability.emergency.`,Z=`ui-observability.probe`,Q=`QuotaExceededError`,$=`indexeddb`,te=`localstorage`,ne=`memory`,re=`none`,ie=`ui-observability.drain`,ae=`ui-observability.emergency`,oe=`ui-observability.journey`,se=2e3,ce=`uiObsJourney`,le=/\+/g,ue=/\//g,de=/=+$/,fe=/-/g,pe=/_/g,me=3e5,he=2166136261,ge=16777619,_e=4294967295,ve=`metric`,ye=`ui-observability/1`,be=`ui-observability.runtime`,xe=1e4,Se=`color:#888`,Ce=1e3,we=6e4,Te=`uiobs.capture`,Ee=`uiobs.storage`,De=`count`,Oe=`unknown-service`,ke=[`redact`,`onDiagnostic`,`headers`,`serializer`],Ae=[`streams`,`storage`,`retry`,`sampling`,`journey`,`bus`,`capture`,`limits`,`console`],je={endpoint:``,serviceName:``,serviceVersion:``,environment:``,enabled:!0,minLevel:`INFO`,streams:{logs:{flushIntervalMs:2e3,batchSize:100},metrics:{flushIntervalMs:1e4,batchSize:500}},maxConcurrentRequests:2,requestTimeoutMs:15e3,compression:`gzip`,compressionThresholdBytes:1024,credentials:`include`,storage:{strategy:`auto`,dbName:`UiObservability`,maxBatches:500,maxAgeMs:864e5,maxAttempts:5},retry:{baseDelayMs:2e3,maxDelayMs:6e4,idleDelayMs:3e4},sampling:{defaultRate:1,rates:{},alwaysSampleTypes:[`action`]},journey:{maxAgeMs:18e5,endOnOwnerClose:!1,urlParam:`__uiobs_journey`},bus:{mode:`auto`,channelName:`ui_observability_control`,trustedOrigins:[],handshakeTimeoutMs:1500,openFinHost:`provider`,openFinRole:`auto`,maxBootBufferRecords:500,orphanPolicy:`auto`,maxHandshakeAttempts:3},capture:{errors:!0,rejections:!0,resourceErrors:!1,fetch:!1,xhr:!1,interactions:!1,navigation:!1,webVitals:!1,maxBreadcrumbs:50,ignoreUrls:[],propagateTraceHeaderTo:[],errorDedupeMs:5e3},limits:{maxBodyChars:4096,maxAttributeChars:8192,maxAttributeCount:128,maxStackChars:8192,maxDepth:6,maxArrayLength:100,maxRecordBytes:32768},console:{enabled:!1,level:`DEBUG`}};Object.defineProperty(exports,"$",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,"At",{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"Bt",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,"Ct",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return je}}),Object.defineProperty(exports,"Dt",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"Et",{enumerable:!0,get:function(){return 6e4}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,"Ft",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return 55296}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"Ht",{enumerable:!0,get:function(){return 2048}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,"It",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"J",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,"Lt",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"Mt",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"Nt",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,"Ot",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"Pt",{enumerable:!0,get:function(){return`ui-observability.tab`}}),Object.defineProperty(exports,"Q",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return we}}),Object.defineProperty(exports,"Rt",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,"St",{enumerable:!0,get:function(){return`Safari/`}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"Tt",{enumerable:!0,get:function(){return`ui-observability.session`}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"Ut",{enumerable:!0,get:function(){return`AppleWebKit`}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"Vt",{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return 56319}}),Object.defineProperty(exports,"X",{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,"Y",{enumerable:!0,get:function(){return`[ui-observability]`}}),Object.defineProperty(exports,"Z",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,"_t",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"at",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,"bt",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"ct",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"dt",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"et",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"ft",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,"gt",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,"ht",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"it",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,"jt",{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return 1e3}}),Object.defineProperty(exports,"kt",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"lt",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,"mt",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"nt",{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"ot",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,"pt",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"rt",{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"st",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"tt",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"ut",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"vt",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"wt",{enumerable:!0,get:function(){return 18e5}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,"xt",{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"yt",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"zt",{enumerable:!0,get:function(){return _e}});
2
- //# sourceMappingURL=constants-Daya7Mc-.cjs.map
1
+ var e=/OpenFin/i,t=/\bwv\b/,n=/\b(iPhone|iPad|iPod)\b/,r=/\bMacintosh\b/,i=/\bMobile\b/,a={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17,FATAL:21},o=a,s=`log.type`,c=`log.seq`,l=`app.namespace`,u=`page.url`,d=`url.full`,f=`journey.id`,p=`journey.name`,m=`journey.parent_id`,h=`uiobs.sanitize_failed`,g=`uiobs.attributes_dropped`,_=`uiobs.attributes_bytes`,v=`service.name`,y=`service.version`,b=`deployment.environment`,x=`telemetry.sdk.name`,S=`telemetry.sdk.version`,C=`telemetry.sdk.language`,w=`host.platform`,T=`session.id`,E=`tab.id`,D=`context.id`,O=`browser.user_agent`,k=`openfin.uuid`,A=`openfin.name`,j=`@utk09/ui-observability`,M=`0.1.2`,N=`webjs`,P=`otlp`,F=`application/json`,I=`application/x-ndjson`,L=1000000n,R=/^\d+$/,z=`Content-Type`,B=`Content-Encoding`,V=`Retry-After`,H=`X-UiObs-Batch-Id`,U=`X-UiObs-Attempt`,W=`gzip`,G=1e3,ee=6e4,K=`text/plain;charset=UTF-8`,q=`uiobs_batch_id`,J=`uiobs_exit`,Y=`ui-observability.batch.`,X=`ui-observability.emergency.`,Z=`ui-observability.probe`,Q=`QuotaExceededError`,$=`indexeddb`,te=`localstorage`,ne=`memory`,re=`none`,ie=`ui-observability.drain`,ae=`ui-observability.emergency`,oe=`ui-observability.journey`,se=2e3,ce=`uiObsJourney`,le=/\+/g,ue=/\//g,de=/=+$/,fe=/-/g,pe=/_/g,me=3e5,he=2166136261,ge=16777619,_e=4294967295,ve=`metric`,ye=`ui-observability/1`,be=`ui-observability.runtime`,xe=1e4,Se=`color:#888`,Ce=1e3,we=6e4,Te=`uiobs.capture`,Ee=`uiobs.storage`,De=`count`,Oe=`unknown-service`,ke=[`redact`,`onDiagnostic`,`headers`,`serializer`],Ae=[`streams`,`storage`,`retry`,`sampling`,`journey`,`bus`,`capture`,`limits`,`console`],je={endpoint:``,serviceName:``,serviceVersion:``,environment:``,enabled:!0,minLevel:`INFO`,streams:{logs:{flushIntervalMs:2e3,batchSize:100},metrics:{flushIntervalMs:1e4,batchSize:500}},maxConcurrentRequests:2,requestTimeoutMs:15e3,compression:`gzip`,compressionThresholdBytes:1024,credentials:`include`,storage:{strategy:`auto`,dbName:`UiObservability`,maxBatches:500,maxAgeMs:864e5,maxAttempts:5},retry:{baseDelayMs:2e3,maxDelayMs:6e4,idleDelayMs:3e4},sampling:{defaultRate:1,rates:{},alwaysSampleTypes:[`action`]},journey:{maxAgeMs:18e5,endOnOwnerClose:!1,urlParam:`__uiobs_journey`},bus:{mode:`auto`,channelName:`ui_observability_control`,trustedOrigins:[],handshakeTimeoutMs:1500,openFinHost:`provider`,openFinRole:`auto`,maxBootBufferRecords:500,orphanPolicy:`auto`,maxHandshakeAttempts:3},capture:{errors:!0,rejections:!0,resourceErrors:!1,fetch:!1,xhr:!1,interactions:!1,navigation:!1,webVitals:!1,maxBreadcrumbs:50,ignoreUrls:[],propagateTraceHeaderTo:[],errorDedupeMs:5e3},limits:{maxBodyChars:4096,maxAttributeChars:8192,maxAttributeCount:128,maxStackChars:8192,maxDepth:6,maxArrayLength:100,maxRecordBytes:32768},console:{enabled:!1,level:`DEBUG`}};Object.defineProperty(exports,"$",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,"At",{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"Bt",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,"Ct",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return je}}),Object.defineProperty(exports,"Dt",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"Et",{enumerable:!0,get:function(){return 6e4}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,"Ft",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return 55296}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"Ht",{enumerable:!0,get:function(){return 2048}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,"It",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"J",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,"Lt",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"Mt",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"Nt",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,"Ot",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"Pt",{enumerable:!0,get:function(){return`ui-observability.tab`}}),Object.defineProperty(exports,"Q",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return we}}),Object.defineProperty(exports,"Rt",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,"St",{enumerable:!0,get:function(){return`Safari/`}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"Tt",{enumerable:!0,get:function(){return`ui-observability.session`}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"Ut",{enumerable:!0,get:function(){return`AppleWebKit`}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"Vt",{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return 56319}}),Object.defineProperty(exports,"X",{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,"Y",{enumerable:!0,get:function(){return`[ui-observability]`}}),Object.defineProperty(exports,"Z",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,"_t",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"at",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,"bt",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"ct",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"dt",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"et",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"ft",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,"gt",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,"ht",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"it",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,"jt",{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return 1e3}}),Object.defineProperty(exports,"kt",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"lt",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,"mt",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"nt",{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"ot",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,"pt",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"rt",{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"st",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"tt",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"ut",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"vt",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"wt",{enumerable:!0,get:function(){return 18e5}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,"xt",{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"yt",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"zt",{enumerable:!0,get:function(){return _e}});
2
+ //# sourceMappingURL=constants-CeqjB0Aa.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants-Daya7Mc-.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// All limits, thresholds, timing windows, storage keys, patterns, and\n// defaults used by the library.\n\nimport type { ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/** Throttle window per diagnostic code, in milliseconds. Limits how often an error loop can spam the handler. */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Log level to OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names records carry on the wire, following\n// OpenTelemetry conventions. `uiobs.` marks this library's own fields.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number within its context, from zero. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key, set by network capture. Don't reuse `ATTR_PAGE_URL`; it would overwrite the request's target.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record whose attributes were dropped for exceeding the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.1.0\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. Retryable. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large; batch must be split. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. CORS-safelisted, avoids a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a parked batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch parked by exit flush. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store evicted on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/** IndexedDB schema version. Bumping it requires a matching Dexie migration. */\nexport const INDEXEDDB_SCHEMA_VERSION = 1;\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. A tripwire, not validation.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * How long to wait for `fin.me.getOptions()` before giving up on a seeded journey,\n * in milliseconds.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants, used to turn a sampling key into a stable 0-1\n// fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n/** Batches held per stream buffer before the oldest is dropped. */\nexport const PENDING_BUFFER_BATCHES = 10;\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. Mismatched versions are dropped. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** CSS styling applied to console prefix labels. */\nexport const CONSOLE_PREFIX_STYLE = \"color:#888\";\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\"redact\", \"onDiagnostic\", \"headers\", \"serializer\"] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\n \"streams\",\n \"storage\",\n \"retry\",\n \"sampling\",\n \"journey\",\n \"bus\",\n \"capture\",\n \"limits\",\n \"console\",\n] as const;\n\n/**\n * Default runtime config, before a consumer's `configure()` call.\n * Excludes `serializer`; `resolveConfig` supplies its default to avoid a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n streams: {\n logs: { flushIntervalMs: 2000, batchSize: 100 },\n // Metrics batch harder than logs: higher volume, nothing waits on them.\n metrics: { flushIntervalMs: 10_000, batchSize: 500 },\n },\n maxConcurrentRequests: 2,\n requestTimeoutMs: 15000,\n compression: \"gzip\",\n compressionThresholdBytes: 1024,\n credentials: \"include\",\n storage: {\n strategy: \"auto\",\n dbName: \"UiObservability\",\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n },\n retry: { baseDelayMs: 2000, maxDelayMs: 60000, idleDelayMs: 30000 },\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n journey: {\n maxAgeMs: 30 * 60 * 1000,\n endOnOwnerClose: false,\n urlParam: \"__uiobs_journey\",\n },\n bus: {\n mode: \"auto\",\n channelName: \"ui_observability_control\",\n trustedOrigins: [],\n handshakeTimeoutMs: 1500,\n openFinHost: \"provider\",\n openFinRole: \"auto\",\n maxBootBufferRecords: 500,\n orphanPolicy: \"auto\",\n maxHandshakeAttempts: 3,\n },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n maxBreadcrumbs: 50,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n errorDedupeMs: 5000,\n },\n limits: {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxRecordBytes: 32768,\n },\n console: { enabled: false, level: \"DEBUG\" },\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"constants-CeqjB0Aa.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// All limits, thresholds, timing windows, storage keys, patterns, and\n// defaults used by the library.\n\nimport type { ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/** Throttle window per diagnostic code, in milliseconds. Limits how often an error loop can spam the handler. */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Log level to OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names records carry on the wire, following\n// OpenTelemetry conventions. `uiobs.` marks this library's own fields.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number within its context, from zero. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key, set by network capture. Don't reuse `ATTR_PAGE_URL`; it would overwrite the request's target.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record whose attributes were dropped for exceeding the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.1.2\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. Retryable. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large; batch must be split. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. CORS-safelisted, avoids a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a parked batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch parked by exit flush. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store evicted on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/** IndexedDB schema version. Bumping it requires a matching Dexie migration. */\nexport const INDEXEDDB_SCHEMA_VERSION = 1;\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. A tripwire, not validation.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * How long to wait for `fin.me.getOptions()` before giving up on a seeded journey,\n * in milliseconds.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants, used to turn a sampling key into a stable 0-1\n// fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n/** Batches held per stream buffer before the oldest is dropped. */\nexport const PENDING_BUFFER_BATCHES = 10;\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. Mismatched versions are dropped. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** CSS styling applied to console prefix labels. */\nexport const CONSOLE_PREFIX_STYLE = \"color:#888\";\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\"redact\", \"onDiagnostic\", \"headers\", \"serializer\"] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\n \"streams\",\n \"storage\",\n \"retry\",\n \"sampling\",\n \"journey\",\n \"bus\",\n \"capture\",\n \"limits\",\n \"console\",\n] as const;\n\n/**\n * Default runtime config, before a consumer's `configure()` call.\n * Excludes `serializer`; `resolveConfig` supplies its default to avoid a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n streams: {\n logs: { flushIntervalMs: 2000, batchSize: 100 },\n // Metrics batch harder than logs: higher volume, nothing waits on them.\n metrics: { flushIntervalMs: 10_000, batchSize: 500 },\n },\n maxConcurrentRequests: 2,\n requestTimeoutMs: 15000,\n compression: \"gzip\",\n compressionThresholdBytes: 1024,\n credentials: \"include\",\n storage: {\n strategy: \"auto\",\n dbName: \"UiObservability\",\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n },\n retry: { baseDelayMs: 2000, maxDelayMs: 60000, idleDelayMs: 30000 },\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n journey: {\n maxAgeMs: 30 * 60 * 1000,\n endOnOwnerClose: false,\n urlParam: \"__uiobs_journey\",\n },\n bus: {\n mode: \"auto\",\n channelName: \"ui_observability_control\",\n trustedOrigins: [],\n handshakeTimeoutMs: 1500,\n openFinHost: \"provider\",\n openFinRole: \"auto\",\n maxBootBufferRecords: 500,\n orphanPolicy: \"auto\",\n maxHandshakeAttempts: 3,\n },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n maxBreadcrumbs: 50,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n errorDedupeMs: 5000,\n },\n limits: {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxRecordBytes: 32768,\n },\n console: { enabled: false, level: \"DEBUG\" },\n};\n"],"mappings":"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"}
@@ -137,7 +137,7 @@ export declare const TELEMETRY_SDK_NAME = "@utk09/ui-observability";
137
137
  * Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.
138
138
  * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}
139
139
  */
140
- export declare const TELEMETRY_SDK_VERSION = "0.1.0";
140
+ export declare const TELEMETRY_SDK_VERSION = "0.1.2";
141
141
  /**
142
142
  * Value of `telemetry.sdk.language`.
143
143
  * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-Daya7Mc-.cjs");let t=require("@opentelemetry/api"),n=require("rxjs");function r(t){return Math.round((performance.now()-t)*e.j)/e.j}function i(e,t,n,i,a){e.logMetric(`${t}.duration`,r(n),`ms`,`histogram`,{status:i,...a})}function a(e,t,n,i,a){e.error(`${t} failed`,i,{"action.duration_ms":r(n),status:`FAILURE`,...a})}function o(e,t,n,r){let o=performance.now();try{let a=n();return i(e,t,o,`SUCCESS`,r),a}catch(n){throw a(e,t,o,n,r),n}}async function s(e,t,n,r){let o=performance.now();try{let a=await n();return i(e,t,o,`SUCCESS`,r),a}catch(n){throw a(e,t,o,n,r),n}}function c(e){return e instanceof Error?e:Error(String(e))}var l=class t{runtime;namespace;options;constructor(e,t,n={}){this.runtime=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.runtime,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.O,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>o(this,e,t,n);timeAsync=(e,t,n)=>s(this,e,t,n);write(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let i=this.runtime.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});i&&t!==`metric`&&this.runtime.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.runtime.console.write(e,n,i?.attributes),this.runtime.emit(i)}writeError(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let i=n===void 0?void 0:c(n),a=this.runtime.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...r,...i?{"error.type":i.name,"error.message":i.message,"error.stack_trace":i.stack}:{},breadcrumbs:this.runtime.breadcrumbs.snapshot()}});this.runtime.console.write(e,t,i??a?.attributes),this.runtime.emit(a)}};function u(e){typeof e!=`number`&&e.unref?.()}function d(t){return{p:e.b,m:t}}function f(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.p!==`ui-observability/1`||typeof t.m!=`object`||t.m===null)return null;let n=t.m;return typeof n.t==`string`?n:null}var p=Symbol.for(e.xt);function m(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[p]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`direct call into the parent runtime`,()=>{r.busAccept(n,e)})},close(){i=!1}}}function h(e,t){if(typeof window>`u`||window.parent===window)return null;let n=t=>{let n=f(t.data);n&&t.source===window.parent&&e(n,{link:`parent`,origin:t.origin})};return addEventListener(`message`,n),{kind:`parent`,post(e){t.guard(`bus.send_failed`,`postMessage to parent`,()=>{window.parent.postMessage(d(e),`*`)})},close(){removeEventListener(`message`,n)}}}function g(e,t,n){if(typeof window>`u`)return null;let r=new Set([window.location.origin,...t]),i=new Set,a=t=>{let a=f(t.data);if(a){if(!r.has(t.origin)){n.report(`bus.untrusted_origin`,`ignored a bus message from ${t.origin}. Add it to bus.trustedOrigins if it is yours.`,{origin:t.origin,type:a.t});return}t.source&&i.add(t.source),e(a,{link:`children`,origin:t.origin})}};return addEventListener(`message`,a),{kind:`children`,post(e){for(let t of i){let r=t;if(r.closed){i.delete(t);continue}n.guard(`bus.send_failed`,`postMessage to child`,()=>{r.postMessage(d(e),`*`)})}},close(){removeEventListener(`message`,a),i.clear()}}}function ee(e,t,n){let r=globalThis.BroadcastChannel;if(r===void 0)return null;let i=n.guard(`bus.send_failed`,`opening BroadcastChannel`,()=>new r(e));return i?(i.onmessage=e=>{let n=f(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`BroadcastChannel.postMessage`,()=>{i.postMessage(d(e))})},close(){n.guard(`bus.send_failed`,`closing BroadcastChannel`,()=>{i.close()})}}):null}function te(e,t,n){let r=globalThis.fin?.InterApplicationBus;return r?(n.guardAsync(`bus.send_failed`,`InterApplicationBus.subscribe`,()=>r.subscribe({uuid:`*`},e,e=>{let n=f(e);n&&t(n,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(t){n.guardAsync(`bus.send_failed`,`InterApplicationBus.publish`,()=>r.publish(e,d(t)))},close(){}}):null}function ne(e,t){let n=globalThis,r=n.postMessage;return n.WorkerGlobalScope===void 0||!r?null:(n.addEventListener?.(`message`,t=>{let n=f(t.data);n&&e(n,{link:`owner`,origin:`same-origin`})}),{kind:`owner`,post(e){t.guard(`bus.send_failed`,`worker postMessage`,()=>{r(d(e))})},close(){}})}function re(e,t,n){let r=e=>{let n=f(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,r),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`postMessage to a worker`,()=>{e.postMessage(d(t))})},close(){e.removeEventListener(`message`,r)}}}var ie=[`children`,`direct`,`worker`],ae=class{config;diagnostics;platform;contextId;tabId;handlers;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;awaitingWelcome=null;constructor(e,t,n,r,i,a){this.config=e,this.diagnostics=t,this.platform=n,this.contextId=r,this.tabId=i,this.handlers=a}getRole(){return this.role}isResolved(){return this.resolved}async start(){let{bus:e}=this.config;if(e.mode===`off`)return this.role=`sender`,this.resolved=!0,this.role;if(this.isOpenFinProvider=this.resolveOpenFinProvider(),e.mode===`sender`||e.mode===`forwarder`)return this.role=e.mode,this.openControlLinks(),this.role===`forwarder`&&(this.upstream=this.candidateUpstream(),this.upstream||this.diagnostics.report(`bus.no_owner`,`bus.mode is "forwarder" but there is no owner to forward to. Records will be dropped.`)),this.resolved=!0,this.announce(),this.role;this.openControlLinks();let t=m(this.receive,this.diagnostics);if(t)return this.role=`forwarder`,this.upstream=t,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`attached directly to the same-origin parent runtime`,{role:`forwarder`,via:`direct`}),this.announce(),this.role;let n=this.candidateUpstream();if(!n)return this.role=`sender`,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`no owner to forward to, sending directly`,{role:`sender`}),this.announce(),this.role;let r=this.orphanPolicy()===`retry`?this.config.bus.maxHandshakeAttempts:1,i=!1;for(let e=0;e<r&&!i;e++)i=await this.handshake(n);return this.role=i?`forwarder`:`sender`,this.upstream=i?n:null,i||(n!==this.openFinLink&&n.close(),this.diagnostics.report(`bus.handshake_timeout`,`no owner answered after ${String(r)} attempt(s) of ${String(this.config.bus.handshakeTimeoutMs)}ms, promoting to sender`,{via:n.kind,crossOrigin:this.isCrossOriginFrame()})),this.diagnostics.report(`bus.role_resolved`,`role is ${this.role}`,{role:this.role,via:i?n.kind:`none`}),this.resolved=!0,this.announce(),this.role}sendRecords(e){this.upstream?.post({t:`records`,from:this.contextId,records:e})}acceptDirect(e,t){if(e.from===this.contextId)return;let n={link:`direct`,origin:`same-origin`};if(e.t===`hello`){this.canOwn(`direct`)&&t({t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId},n);return}if(e.t===`journey?`){let e=this.handlers.onJourneyRequest();e&&t({t:`journey`,from:this.contextId,journey:e},n);return}this.receive(e,n)}attachWorker(e){this.links.push(re(e,this.receive,this.diagnostics))}broadcastJourney(e){this.post({t:`journey`,from:this.contextId,journey:e})}destroy(){for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}post(e){for(let t of this.allLinks())t.post(e)}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}receive=(e,t)=>{if(e.from!==this.contextId)switch(e.t){case`hello`:this.canOwn(t.link)&&this.postOver(t.link,{t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId});break;case`welcome`:if(e.to!==this.contextId)break;this.awaitingWelcome?.link===t.link&&this.awaitingWelcome.settle(!0);break;case`records`:this.role===`sender`?this.handlers.onRecords(e.records):this.upstream&&t.link!==this.upstream.kind&&this.upstream.post(e);break;case`journey`:this.handlers.onJourney(e.journey);break;case`journey?`:{let e=this.handlers.onJourneyRequest();e&&this.postOver(t.link,{t:`journey`,from:this.contextId,journey:e});break}case`tab`:t.link===`broadcast`&&e.tabId===this.tabId&&this.contextId>e.from&&this.handlers.onTabConflict()}};canOwn(e){return this.role===`sender`?e===`openfin`?this.isOpenFinProvider:ie.includes(e):!1}resolveOpenFinProvider(){let e=this.config.bus.openFinRole;if(e!==`auto`)return e===`provider`;if(this.platform.platform!==`openfin`&&this.platform.platform!==`openfin_web`)return!1;let t=globalThis.fin?.me;return!t?.identity||t.isView?!1:!!(t.identity.name&&t.identity.name===t.identity.uuid)}orphanPolicy(){let e=this.config.bus.orphanPolicy;return e===`auto`?this.isCrossOriginFrame()?`retry`:`promote`:e}isCrossOriginFrame(){if(typeof window>`u`||window.parent===window)return!1;try{return window.parent.location,!1}catch{return!0}}candidateUpstream(){return this.platform.isWorker?ne(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&this.config.bus.openFinHost===`provider`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:h(this.receive,this.diagnostics)}openControlLinks(){let e=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(e(g(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),e(ee(this.config.bus.channelName,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&e(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=te(this.config.bus.channelName,this.receive,this.diagnostics),this.openFinLink}handshake(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,this.awaitingWelcome=null,clearTimeout(i),t(e))};this.awaitingWelcome={link:e.kind,settle:r};let i=setTimeout(()=>{r(!1)},this.config.bus.handshakeTimeoutMs);u(i),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.post({t:`journey?`,from:this.contextId})}},oe=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let t=e.target,n=t?.src??t?.href??``;if(t!==null&&t!==globalThis&&n!==``){if(!this.ctx.config.capture.resourceErrors)return;this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${n}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":n,"resource.tag":t.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let r=e,i=r.message===``?`unknown error`:r.message,a=r.error??Error(i);this.report(`window.onerror`,a,{"error.source":r.filename,"error.line":r.lineno,"error.column":r.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`more than 20 errors in ${String(e.F)}ms, suppressing the rest of this window`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
2
- `)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<this.ctx.config.capture.errorDedupeMs){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?t:a.message,a,{...r,"error.captured_by":t,"error.suppressed_count":l})}};function se(e){if(e===null)return`unknown`;let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function _(){return history}var ce=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(_().pushState=this.originalPushState),this.originalReplaceState&&(_().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let t=e.target,n=se(t instanceof Element?t:null),r=t instanceof HTMLElement?t.innerText.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:n,data:r===``?void 0:{text:r}})};onNavigate=()=>{let e=this.lastUrl,t=location.href;e!==t&&(this.lastUrl=t,this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${e} -> ${t}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":e}))};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=_(),t=e.pushState,n=e.replaceState;this.originalPushState=t,this.originalReplaceState=n;let r=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(r)},e.replaceState=function(...e){n.apply(this,e),queueMicrotask(r)}}};function v(e,t){return t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function y(){return XMLHttpRequest.prototype}var le=class{ctx;name=`network`;originalFetch=null;originalOpen=null;originalSend=null;constructor(e){this.ctx=e}install(){this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr()}uninstall(){this.originalFetch&&=(globalThis.fetch=this.originalFetch,null),this.originalOpen&&=(y().open=this.originalOpen,null),this.originalSend&&=(y().send=this.originalSend,null)}ignored(e){return v(e,this.ctx.config.capture.ignoreUrls)}installFetch(){if(typeof globalThis.fetch!=`function`||this.originalFetch)return;let e=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let t=this.ctx,n=e=>this.ignored(e),r=(e,t,n,r,i)=>{this.record(e,t,n,r,i)};globalThis.fetch=async function(i,a){let o=typeof i==`string`?i:i instanceof URL?i.href:i.url,s=(a?.method??(i instanceof Request?i.method:`GET`)).toUpperCase();if(n(o))return e(i,a);let c=i,l=a;if(v(o,t.config.capture.propagateTraceHeaderTo))try{let e=Object.entries(t.tracing.headers());if(i instanceof Request){let t=new Headers(i.headers);for(let[n,r]of e)t.set(n,r);c=new Request(i,{headers:t})}else{let t=new Headers(a?.headers);for(let[n,r]of e)t.set(n,r);l={...a,headers:t}}}catch(e){c=i,l=a,t.diagnostics.report(`capture.header_failed`,`could not attach traceparent, sending the request unchanged`,{url:o},e)}let u=performance.now();try{let t=await e(c,l);return r(s,o,t.status,performance.now()-u,void 0),t}catch(e){throw r(s,o,0,performance.now()-u,e),e}}}installXhr(){if(typeof XMLHttpRequest>`u`||this.originalOpen)return;let e=e=>this.ignored(e),t=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},n=y(),r=n.open,i=n.send;this.originalOpen=r,this.originalSend=i,n.open=function(e,t,...n){this.__uiobs={method:e.toUpperCase(),url:String(t),startedAt:0},r.apply(this,[e,t,...n])},n.send=function(...n){let r=this.__uiobs;r&&!e(r.url)&&(r.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{t(r.method,r.url,this.status,performance.now()-r.startedAt)})),i.apply(this,n)}}record(e,t,n,r,i){this.ctx.diagnostics.guard(`capture.record_failed`,`recording ${e} ${t}`,()=>{let a=Math.round(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${t} ${n===0?`failed`:String(n)}`,data:{durationMs:a}});let o={"http.request.method":e,"url.full":t,"http.response.status_code":n,"http.duration_ms":a};if(n===0){this.ctx.logger.error(`${e} ${t} failed`,i,o);return}if(n>=400){this.ctx.logger.warn(`${e} ${t} returned ${String(n)}`,o);return}this.ctx.logger.debug(`${e} ${t}`,o)})}};function ue(){return import(`web-vitals`)}var de=class{ctx;name=`web-vitals`;installed=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.reportNavigationTiming(),this.loadWebVitals())}uninstall(){this.installed=!1}async loadWebVitals(){let e=this.ctx.config.capture.webVitalsLoader??ue,t=await this.ctx.diagnostics.guardAsync(`capture.install_failed`,`loading web-vitals`,e);if(!t){this.ctx.diagnostics.report(`capture.install_failed`,`web-vitals is not available, so LCP, CLS and INP are unavailable. Navigation timing still works.`);return}let n=(e,t)=>n=>{this.ctx.logger.logMetric(`web_vitals.${e}`,Math.round(n.value*1e3)/1e3,t,`gauge`,{"metric.rating":n.rating,"metric.id":n.id})};t.onLCP(n(`lcp`,`ms`)),t.onCLS(n(`cls`,`1`)),t.onINP(n(`inp`,`ms`)),t.onFCP(n(`fcp`,`ms`)),t.onTTFB(n(`ttfb`,`ms`))}reportNavigationTiming(){this.ctx.diagnostics.guard(`capture.install_failed`,`reading navigation timing`,()=>{let e=performance.getEntriesByType(`navigation`)[0];if(!e)return;let t={"navigation.dns_ms":e.domainLookupEnd-e.domainLookupStart,"navigation.tcp_ms":e.connectEnd-e.connectStart,"navigation.ttfb_ms":e.responseStart-e.requestStart,"navigation.response_ms":e.responseEnd-e.responseStart,"navigation.dom_interactive_ms":e.domInteractive,"navigation.dom_complete_ms":e.domComplete,"navigation.load_ms":e.loadEventEnd};for(let[n,r]of Object.entries(t))Number.isFinite(r)&&r>=0&&this.ctx.logger.logMetric(n,Math.round(r),`ms`,`gauge`,{"navigation.type":e.type})})}};function b(){return`${String(Date.now())}000000`}function x(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 S(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 C(){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return S(16)}function w(e,t,n){return n.guard(`storage.unavailable`,`reading ${e}Storage`,()=>(e===`local`?localStorage:sessionStorage).getItem(t))??null}function T(e,t,n,r){r.guard(`storage.unavailable`,`writing ${e}Storage`,()=>{(e===`local`?localStorage:sessionStorage).setItem(t,n)})}function fe(t){let n=C(),r=Date.now(),i=C(),a=w(`local`,e.Tt,t);if(a)try{let e=JSON.parse(a);e.id&&r-(e.lastSeenAt??0)<18e5&&(i=e.id)}catch{t.report(`storage.degraded`,`session record was not JSON, starting a new session`)}let o=JSON.stringify({id:i,lastSeenAt:r});T(`local`,e.Tt,o,t);let s=w(`session`,`ui-observability.tab`,t)??``;return s||(s=C(),T(`session`,e.Pt,s,t)),{sessionId:i,tabId:s,contextId:n}}var pe=0;function me(t,n){let r=Date.now();if(r-pe<6e4)return;pe=r;let i=JSON.stringify({id:t,lastSeenAt:r});T(`local`,e.Tt,i,n)}function he(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`id`),n=Reflect.get(e,`createdAt`),r=Reflect.get(e,`attempts`),i=Reflect.get(e,`records`);return typeof t==`string`&&typeof n==`number`&&typeof r==`number`&&Array.isArray(i)}function ge(e){if(e.records.length<2)return null;let t=Math.floor(e.records.length/2),n=t=>({id:C(),records:t,createdAt:e.createdAt,attempts:e.attempts});return[n(e.records.slice(0,t)),n(e.records.slice(t))]}function _e(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`acquiring lock ${e}`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function E(e,t){let n=[];return t.guard(`storage.unavailable`,`enumerating localStorage`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function ve(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.N}${n}.${t.id}`}function ye(e,t){let n=t.guard(`storage.degraded`,`an emergency entry was not JSON and was dropped`,()=>JSON.parse(e));return n===void 0?null:he(n)?n:(t.report(`storage.degraded`,`an emergency entry was not a batch and was dropped`),null)}async function be(t,n){let r=0;for(let i of E(e.N,n)){let e=n.guard(`storage.unavailable`,`reading the emergency queue`,()=>{let e=localStorage.getItem(i);return localStorage.removeItem(i),e});if(!e)continue;let a=ye(e,n);if(a!==null)try{await t.save(a),r++}catch(e){n.report(`storage.degraded`,`an emergency batch could not be recovered`,{key:i},e)}}return r}function xe(t,n){let r=`writing the emergency queue, ${String(t.records.length)} records`;n.guard(`storage.quota_exceeded`,r,()=>{let r=E(e.N,n);for(let e of r.slice(0,Math.max(0,r.length-20+1)))localStorage.removeItem(e);localStorage.setItem(ve(t),JSON.stringify(t))})}async function Se(e,t){return await _e(`ui-observability.emergency`,t,()=>be(e,t),{skipIfBusy:!1})??0}function Ce(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.v}${n}.${t.id}`}var we=class{limits;diagnostics;onGap;name=e.At;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){if(this.diagnostics.guard(`storage.quota_exceeded`,`localStorage refused a batch, evicting the oldest`,()=>(localStorage.setItem(Ce(e),JSON.stringify(e)),!0))!==!0){let e=this.keys();this.evict(e.slice(0,Math.ceil(e.length/4)));return}await this.prune()}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);if(e===null){this.removeKey(n);continue}t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null?Promise.resolve():(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`updating attempts`,()=>{localStorage.setItem(n,JSON.stringify(r))}),Promise.resolve())}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=(e,n)=>{this.removeKey(e),t.batches++,t.records+=n},r=[];for(let t of this.keys()){let i=this.read(t);if(i===null){n(t,0);continue}if(i.createdAt<e){n(t,i.records.length);continue}r.push({key:t,records:i.records.length})}let i=r.length-this.limits.maxBatches;if(i>0){t.reason=`over_capacity`;for(let e of r.slice(0,i))n(e.key,e.records)}return t.batches>0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(t.batches)} stored batches (${String(t.records)} records)`,{...t}),this.onGap?.(t)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`reading a stored batch`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`a stored batch was corrupt and was removed`,()=>JSON.parse(t));return n===void 0?null:he(n)?n:(this.diagnostics.report(`storage.degraded`,`a stored entry was not a batch and was dropped`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`removing a stored batch`,()=>{localStorage.removeItem(e)})}keys(){return E(e.v,this.diagnostics)}};function Te(e){return e.reduce((e,t)=>e+t.records.length,0)}var D=class{limits;onGap;name=e.jt;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),t.batches+=n.length,t.records+=Te(n);let r=this.batches.length-this.limits.maxBatches;if(r>0){t.reason=`over_capacity`;let e=this.batches.slice(0,r);this.batches=this.batches.slice(r),t.batches+=e.length,t.records+=Te(e)}return t.batches>0&&this.onGap?.(t),Promise.resolve(t)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},Ee={name:e.Mt,save:()=>Promise.resolve(),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()};function De(e){return e.guard(`storage.unavailable`,`reading indexedDB`,()=>globalThis.indexedDB!=null)===!0}function Oe(t){return t.guard(`storage.unavailable`,`probing localStorage`,()=>(localStorage.setItem(e.Nt,`1`),localStorage.removeItem(e.Nt),!0))===!0}async function ke(e,t,n,r,i){if(e===`none`)return Ee;if(e===`memory`)return new D(n,i);if(e===`indexeddb`||e===`auto`){if(De(r)){let e=await r.guardAsync(`storage.unavailable`,`opening IndexedDB`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-BhMUPgyG.cjs"));return new e(t,n,r,i)});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB was asked for by name and is unavailable, using memory`),new D(n,i)}return Oe(r)?new we(n,r,i):(r.report(`storage.degraded`,`no persistent storage available, offline logs are memory only`),new D(n,i))}function O(e,t){if(e.length<=t)return e;let n=Ae(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function Ae(e){return e>=55296&&e<=56319}function je(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 k(e,t){let n={bytes:0};return{value:j(e,t,new WeakSet,0,n),bytes:n.bytes}}function A(e,t){return t.bytes+=M(e)+2,e}function j(e,t,n,r,i){if(e==null)return i.bytes+=4,e;if(typeof e==`string`)return A(O(e,t.maxAttributeChars),i);if(typeof e==`number`)return i.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return i.bytes+=5,e;if(typeof e==`bigint`)return A(`${e.toString()}n`,i);if(typeof e==`symbol`)return A(e.toString(),i);if(typeof e==`function`)return A(`[Function ${e.name===``?`anonymous`:e.name}]`,i);if(r>=t.maxDepth)return A(`[MaxDepth]`,i);if(n.has(e))return A(`[Circular]`,i);n.add(e),i.bytes+=2;try{if(e instanceof Error)return{name:A(e.name,i),message:A(O(e.message,t.maxAttributeChars),i),stack:e.stack?A(O(e.stack,t.maxStackChars),i):void 0,cause:e.cause?j(e.cause,t,n,r+1,i):void 0};if(e instanceof Date)return A(e.toISOString(),i);if(e instanceof RegExp)return A(e.toString(),i);if(e instanceof Map){let a=e,o={},s=0;for(let[e,c]of a){if(s>=t.maxArrayLength){o[`…`]=A(`[${String(a.size-t.maxArrayLength)} more entries]`,i);break}s++;let l=String(e);i.bytes+=M(l)+4,o[l]=j(c,t,n,r+1,i)}return o}if(e instanceof Set)return j([...e].slice(0,t.maxArrayLength),t,n,r,i);if(ArrayBuffer.isView(e)){let t=e.length??0;return A(`[${e.constructor.name}(${String(t)})]`,i)}if(e instanceof Promise)return A(`[Promise]`,i);if(typeof Node<`u`&&e instanceof Node)return A(je(e),i);if(Array.isArray(e)){let a=e,o=a.slice(0,t.maxArrayLength).map(e=>j(e,t,n,r+1,i));return a.length>t.maxArrayLength&&o.push(A(`[${String(a.length-t.maxArrayLength)} more items]`,i)),o}let a=e.toJSON;if(typeof a==`function`)return j(a.call(e),t,n,r+1,i);let o=e,s=Object.keys(o),c={},l=0;for(let e of s){if(l>=t.maxAttributeCount){c[`…`]=A(`[${String(s.length-l)} more keys]`,i);break}l++,i.bytes+=M(e)+4,c[e]=j(o[e],t,n,r+1,i)}return c}catch(e){return A(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,i)}finally{n.delete(e)}}function M(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 Me=class{deps;installed=!1;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`subscribing to close-requested`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`releasing close-requested`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(t){let{diagnostics:n}=this.deps,r=this.endpointUrl();if(r===null)return;let i=this.deps.drainPending();if(!i||i.records.length===0)return;let a=n.guard(`transport.serialize_failed`,`the ${t} exit flush could not serialize its batch`,()=>this.deps.config.serializer.serialize(i.records));if(!a)return;if(M(a.body)>6e4){xe(i,n);return}r.searchParams.set(e.at,i.id),r.searchParams.set(e.ot,t);let o=r.toString();this.beacon(o,a.body)||this.keepaliveFetch(o,a.body,t)}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`the exit flush cannot use endpoint ${e}`,()=>new URL(e))??null:null}beacon(t,n){return this.deps.diagnostics.guard(`transport.http_error`,`sendBeacon`,()=>{let r=globalThis.navigator;return r?.sendBeacon?r.sendBeacon(t,new Blob([n],{type:e.E})):!1})===!0}keepaliveFetch(t,n,r){let{config:i,diagnostics:a}=this.deps;a.guard(`transport.http_error`,`the keepalive fetch fallback`,()=>{fetch(t,{method:`POST`,body:n,headers:{[e.H]:e.E},credentials:i.credentials,keepalive:!0}).catch(e=>{a.report(`transport.http_error`,`the exit flush failed`,{reason:r},e)})})}};async function Ne(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.P)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var N=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i){super(t),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function Pe(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.Q);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var Fe=class{config;diagnostics;throttledUntil=0;constructor(e,t){this.config=e,this.diagnostics=t}async send(e){!this.config.endpoint||e.records.length===0||await this.post(e)}throttledForMs(){return Math.max(0,this.throttledUntil-Date.now())}async post(t){let{config:n}=this,r;try{r=n.serializer.serialize(t.records)}catch(e){this.diagnostics.report(`transport.serialize_failed`,`serializer threw, dropping the batch`,{batchId:t.id},e);return}let i=new Headers(await this.resolveHeaders());i.set(e.H,r.contentType),i.set(e.B,t.id),i.set(e.z,String(t.attempts));let a=await this.encodeBody(r.body);typeof a!=`string`&&i.set(e.V,e.P);let o=await this.dispatch(i,a);if(o.ok){this.throttledUntil=0;return}throw await this.classify(o,t.id)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||M(e)<t.compressionThresholdBytes?e:await this.diagnostics.guardAsync(`transport.http_error`,`gzipping the payload`,()=>Ne(e))??e}async dispatch(e,t){let{config:n}=this,r=new AbortController,i=setTimeout(()=>{r.abort()},n.requestTimeoutMs);u(i);try{return await fetch(n.endpoint,{method:`POST`,headers:e,body:t,credentials:n.credentials,signal:r.signal,cache:`no-store`})}catch{if(r.signal.aborted)throw new N(`timeout`,`request exceeded ${String(n.requestTimeoutMs)}ms`);let e=globalThis.navigator?.onLine;throw new N(e===!1?`offline`:`transient`,`network error`)}finally{clearTimeout(i)}}async classify(t,n){let r=t.status,i=Pe(t.headers.get(e.U));if(r===401||r===403)return this.diagnostics.report(`transport.rejected_credentials`,`server returned ${String(r)}. In a cross-origin iframe the session cookie is a third-party cookie and is very likely blocked. Forward to the platform document instead of promoting to sender, or issue the cookie with the Partitioned attribute.`,{status:r,endpoint:this.config.endpoint}),new N(`permanent`,`rejected with ${String(r)}`,r);if(r===413)return new N(`too_large`,`payload too large`,r,void 0,await this.readMaxBytes(t));if(r===429||r===503){let e=r===429;return this.throttledUntil=Date.now()+(i??this.config.retry.baseDelayMs),e&&this.diagnostics.report(`transport.throttled`,`server throttled us`,{retryAfterMs:i}),new N(`throttled`,e?`throttled`:`service unavailable`,r,i)}return r===408||r>=500?new N(`transient`,`server error ${String(r)}`,r):(this.diagnostics.report(`transport.dropped_permanent`,`server rejected the batch with ${String(r)}, dropping it`,{batchId:n,status:r}),new N(`permanent`,`rejected with ${String(r)}`,r))}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`reading the 413 body`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;return e?typeof e==`function`?await this.diagnostics.guardAsync(`transport.http_error`,`headers() threw`,()=>Promise.resolve(e()))??{}:e:{}}},Ie=class{storage;transport;diagnostics;config;batchesPerDrain;timer=null;attempt=0;draining=!1;stopped=!1;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(this.config.retry.idleDelayMs)}nudge(){this.draining||this.schedule(this.config.retry.baseDelayMs)}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,u(t)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let e=Math.min(this.config.retry.baseDelayMs*2**this.attempt,this.config.retry.maxDelayMs);return Math.random()*e}async drain(){if(!this.draining){this.draining=!0;try{await _e(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(this.config.retry.idleDelayMs)}finally{this.draining=!1}}}async drainLocked(){try{if(globalThis.navigator?.onLine===!1)return this.schedule(this.config.retry.idleDelayMs),!0;let e=await this.storage.take(this.batchesPerDrain);if(e.length===0)return this.schedule(this.config.retry.idleDelayMs),!0;for(let t of e)if(this.stopped||!await this.deliver(t))return!0;return this.schedule(e.length===this.batchesPerDrain?0:this.config.retry.idleDelayMs),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`the drain loop threw`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(e){if(e.attempts>=this.config.storage.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`giving up on a batch after ${e.attempts.toString()} attempts`,{batchId:e.id,records:e.records.length}),await this.storage.remove(e.id),!0;try{return await this.transport.send(e),await this.storage.remove(e.id),this.attempt=0,!0}catch(t){let n=t instanceof N?t:void 0;return n?.kind===`permanent`?(await this.storage.remove(e.id),!0):n?.kind===`too_large`?(await this.splitStored(e,n.maxBytes),!0):n?.kind===`offline`?(this.schedule(this.config.retry.idleDelayMs),!1):(await this.storage.bumpAttempts(e.id,e.attempts+1),this.attempt++,this.schedule(n?.retryAfterMs??this.backoffMs()),!1)}}async splitStored(e,t){let n=ge(e);if(await this.storage.remove(e.id),!n){this.diagnostics.report(`transport.dropped_permanent`,`a single record exceeds the server limit and was dropped`,{batchId:e.id,bodies:e.records.map(e=>e.body)});return}this.diagnostics.report(`transport.batch_split`,`the server refused the batch as too large`,{from:e.records.length,to:n[0].records.length,serverMaxBytes:t});for(let e of n)await this.storage.save(e)}},P={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},Le=class{enabled;minLevel;constructor(e,t){this.enabled=e,this.minLevel=t}update(e,t){this.enabled=e,this.minLevel=t}write(t,n,r){if(!this.enabled||e.J[t]<e.J[this.minLevel]||typeof console>`u`)return;let i=`%c${e.Y}%c ${t}`;if(r===void 0){console[P[t]](i,e.C,``,n);return}console[P[t]](i,e.C,``,n,r)}},F=null;function I(e,t){let n=e[t];return n!==void 0&&e instanceof n}function Re(t){if(F)return F;let n=globalThis,r=n.navigator?.userAgent??``,i=`browser`,a,o,s=!1,c=n.fin?.me;return I(n,`ServiceWorkerGlobalScope`)?(i=`service_worker`,s=!0):I(n,`SharedWorkerGlobalScope`)?(i=`shared_worker`,s=!0):I(n,`WorkerGlobalScope`)?(i=`web_worker`,s=!0):c===void 0?n.Capacitor!==void 0||n.Ionic!==void 0?i=`ionic`:n.cordova!==void 0||ze(r)?i=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(i=`node`):(i=e.it.test(r)?`openfin`:`openfin_web`,t.guard(`openfin.unavailable`,`reading fin.me.identity`,()=>{let e=c.identity;a=e?.uuid,o=e?.name})),F={platform:i,openfinUuid:a,openfinName:o,userAgent:r,isWorker:s,isTopLevelDocument:Be()},F}function ze(t){return e.t.test(t)?!0:(e.K.test(t)||e.Z.test(t)&&e.$.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function Be(){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return!1}}function Ve(){try{return typeof location<`u`?location.href:``}catch{return``}}var He=class{value=0;next(){return++this.value}reset(){this.value=0}};function Ue(){return S(16)}function We(){return S(8)}function L(){return{traceId:Ue(),spanId:We(),traceFlags:1,startedAt:Date.now()}}function R(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var Ge=class{diagnostics;maxAgeMs;ambient=L();constructor(t,n=e.Rt){this.diagnostics=t,this.maxAgeMs=n}resolve(){let e=this.diagnostics.guard(`trace.otel_failed`,`reading the active OpenTelemetry span`,()=>{let e=t.trace.getActiveSpan();if(e===void 0)return;let n=e.spanContext();if((0,t.isSpanContextValid)(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}});return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),R(this.ambient)):e}rotate(e){return this.ambient=L(),R(this.ambient)}headers(){let e={};if(this.diagnostics.guard(`trace.otel_failed`,`injecting OpenTelemetry headers`,()=>{t.propagation.inject(t.context.active(),e)}),!e.traceparent){let t=this.resolve(),n=(t.traceFlags&255).toString(16).padStart(2,`0`);e.traceparent=`00-${t.traceId}-${t.spanId}-${n}`}return e}},Ke=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}resize(e){let t=Math.max(e,1);if(t===this.capacity)return;let n=this.snapshot().slice(-t);this.capacity=t,this.clear();for(let e of n)this.push(e)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function qe(t){return e.et.test(t)?Number(BigInt(t)/e.tt):Date.now()}var Je={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=qe(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.mt],version:t.resource[e.ht],environment:t.resource[e.ut]},user_agent:{original:t.resource[e.ct]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...t.resource,...t.attributes}})}).join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-CeqjB0Aa.cjs");let t=require("@opentelemetry/api"),n=require("rxjs");function r(t){return Math.round((performance.now()-t)*e.j)/e.j}function i(e,t,n,i,a){e.logMetric(`${t}.duration`,r(n),`ms`,`histogram`,{status:i,...a})}function a(e,t,n,i,a){e.error(`${t} failed`,i,{"action.duration_ms":r(n),status:`FAILURE`,...a})}function o(e,t,n,r){let o=performance.now();try{let a=n();return i(e,t,o,`SUCCESS`,r),a}catch(n){throw a(e,t,o,n,r),n}}async function s(e,t,n,r){let o=performance.now();try{let a=await n();return i(e,t,o,`SUCCESS`,r),a}catch(n){throw a(e,t,o,n,r),n}}function c(e){return e instanceof Error?e:Error(String(e))}var l=class t{runtime;namespace;options;constructor(e,t,n={}){this.runtime=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.runtime,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.O,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>o(this,e,t,n);timeAsync=(e,t,n)=>s(this,e,t,n);write(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let i=this.runtime.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});i&&t!==`metric`&&this.runtime.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.runtime.console.write(e,n,i?.attributes),this.runtime.emit(i)}writeError(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let i=n===void 0?void 0:c(n),a=this.runtime.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...r,...i?{"error.type":i.name,"error.message":i.message,"error.stack_trace":i.stack}:{},breadcrumbs:this.runtime.breadcrumbs.snapshot()}});this.runtime.console.write(e,t,i??a?.attributes),this.runtime.emit(a)}};function u(e){typeof e!=`number`&&e.unref?.()}function d(t){return{p:e.b,m:t}}function f(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.p!==`ui-observability/1`||typeof t.m!=`object`||t.m===null)return null;let n=t.m;return typeof n.t==`string`?n:null}var p=Symbol.for(e.xt);function m(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[p]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`direct call into the parent runtime`,()=>{r.busAccept(n,e)})},close(){i=!1}}}function h(e,t){if(typeof window>`u`||window.parent===window)return null;let n=t=>{let n=f(t.data);n&&t.source===window.parent&&e(n,{link:`parent`,origin:t.origin})};return addEventListener(`message`,n),{kind:`parent`,post(e){t.guard(`bus.send_failed`,`postMessage to parent`,()=>{window.parent.postMessage(d(e),`*`)})},close(){removeEventListener(`message`,n)}}}function g(e,t,n){if(typeof window>`u`)return null;let r=new Set([window.location.origin,...t]),i=new Set,a=t=>{let a=f(t.data);if(a){if(!r.has(t.origin)){n.report(`bus.untrusted_origin`,`ignored a bus message from ${t.origin}. Add it to bus.trustedOrigins if it is yours.`,{origin:t.origin,type:a.t});return}t.source&&i.add(t.source),e(a,{link:`children`,origin:t.origin})}};return addEventListener(`message`,a),{kind:`children`,post(e){for(let t of i){let r=t;if(r.closed){i.delete(t);continue}n.guard(`bus.send_failed`,`postMessage to child`,()=>{r.postMessage(d(e),`*`)})}},close(){removeEventListener(`message`,a),i.clear()}}}function ee(e,t,n){let r=globalThis.BroadcastChannel;if(r===void 0)return null;let i=n.guard(`bus.send_failed`,`opening BroadcastChannel`,()=>new r(e));return i?(i.onmessage=e=>{let n=f(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`BroadcastChannel.postMessage`,()=>{i.postMessage(d(e))})},close(){n.guard(`bus.send_failed`,`closing BroadcastChannel`,()=>{i.close()})}}):null}function te(e,t,n){let r=globalThis.fin?.InterApplicationBus;return r?(n.guardAsync(`bus.send_failed`,`InterApplicationBus.subscribe`,()=>r.subscribe({uuid:`*`},e,e=>{let n=f(e);n&&t(n,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(t){n.guardAsync(`bus.send_failed`,`InterApplicationBus.publish`,()=>r.publish(e,d(t)))},close(){}}):null}function ne(e,t){let n=globalThis,r=n.postMessage;return n.WorkerGlobalScope===void 0||!r?null:(n.addEventListener?.(`message`,t=>{let n=f(t.data);n&&e(n,{link:`owner`,origin:`same-origin`})}),{kind:`owner`,post(e){t.guard(`bus.send_failed`,`worker postMessage`,()=>{r(d(e))})},close(){}})}function re(e,t,n){let r=e=>{let n=f(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,r),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`postMessage to a worker`,()=>{e.postMessage(d(t))})},close(){e.removeEventListener(`message`,r)}}}var ie=[`children`,`direct`,`worker`],ae=class{config;diagnostics;platform;contextId;tabId;handlers;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;awaitingWelcome=null;constructor(e,t,n,r,i,a){this.config=e,this.diagnostics=t,this.platform=n,this.contextId=r,this.tabId=i,this.handlers=a}getRole(){return this.role}isResolved(){return this.resolved}async start(){let{bus:e}=this.config;if(e.mode===`off`)return this.role=`sender`,this.resolved=!0,this.role;if(this.isOpenFinProvider=this.resolveOpenFinProvider(),e.mode===`sender`||e.mode===`forwarder`)return this.role=e.mode,this.openControlLinks(),this.role===`forwarder`&&(this.upstream=this.candidateUpstream(),this.upstream||this.diagnostics.report(`bus.no_owner`,`bus.mode is "forwarder" but there is no owner to forward to. Records will be dropped.`)),this.resolved=!0,this.announce(),this.role;this.openControlLinks();let t=m(this.receive,this.diagnostics);if(t)return this.role=`forwarder`,this.upstream=t,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`attached directly to the same-origin parent runtime`,{role:`forwarder`,via:`direct`}),this.announce(),this.role;let n=this.candidateUpstream();if(!n)return this.role=`sender`,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`no owner to forward to, sending directly`,{role:`sender`}),this.announce(),this.role;let r=this.orphanPolicy()===`retry`?this.config.bus.maxHandshakeAttempts:1,i=!1;for(let e=0;e<r&&!i;e++)i=await this.handshake(n);return this.role=i?`forwarder`:`sender`,this.upstream=i?n:null,i||(n!==this.openFinLink&&n.close(),this.diagnostics.report(`bus.handshake_timeout`,`no owner answered after ${String(r)} attempt(s) of ${String(this.config.bus.handshakeTimeoutMs)}ms, promoting to sender`,{via:n.kind,crossOrigin:this.isCrossOriginFrame()})),this.diagnostics.report(`bus.role_resolved`,`role is ${this.role}`,{role:this.role,via:i?n.kind:`none`}),this.resolved=!0,this.announce(),this.role}sendRecords(e){this.upstream?.post({t:`records`,from:this.contextId,records:e})}acceptDirect(e,t){if(e.from===this.contextId)return;let n={link:`direct`,origin:`same-origin`};if(e.t===`hello`){this.canOwn(`direct`)&&t({t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId},n);return}if(e.t===`journey?`){let e=this.handlers.onJourneyRequest();e&&t({t:`journey`,from:this.contextId,journey:e},n);return}this.receive(e,n)}attachWorker(e){this.links.push(re(e,this.receive,this.diagnostics))}broadcastJourney(e){this.post({t:`journey`,from:this.contextId,journey:e})}destroy(){for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}post(e){for(let t of this.allLinks())t.post(e)}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}receive=(e,t)=>{if(e.from!==this.contextId)switch(e.t){case`hello`:this.canOwn(t.link)&&this.postOver(t.link,{t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId});break;case`welcome`:if(e.to!==this.contextId)break;this.awaitingWelcome?.link===t.link&&this.awaitingWelcome.settle(!0);break;case`records`:this.role===`sender`?this.handlers.onRecords(e.records):this.upstream&&t.link!==this.upstream.kind&&this.upstream.post(e);break;case`journey`:this.handlers.onJourney(e.journey);break;case`journey?`:{let e=this.handlers.onJourneyRequest();e&&this.postOver(t.link,{t:`journey`,from:this.contextId,journey:e});break}case`tab`:t.link===`broadcast`&&e.tabId===this.tabId&&this.contextId>e.from&&this.handlers.onTabConflict()}};canOwn(e){return this.role===`sender`?e===`openfin`?this.isOpenFinProvider:ie.includes(e):!1}resolveOpenFinProvider(){let e=this.config.bus.openFinRole;if(e!==`auto`)return e===`provider`;if(this.platform.platform!==`openfin`&&this.platform.platform!==`openfin_web`)return!1;let t=globalThis.fin?.me;return!t?.identity||t.isView?!1:!!(t.identity.name&&t.identity.name===t.identity.uuid)}orphanPolicy(){let e=this.config.bus.orphanPolicy;return e===`auto`?this.isCrossOriginFrame()?`retry`:`promote`:e}isCrossOriginFrame(){if(typeof window>`u`||window.parent===window)return!1;try{return window.parent.location,!1}catch{return!0}}candidateUpstream(){return this.platform.isWorker?ne(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&this.config.bus.openFinHost===`provider`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:h(this.receive,this.diagnostics)}openControlLinks(){let e=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(e(g(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),e(ee(this.config.bus.channelName,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&e(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=te(this.config.bus.channelName,this.receive,this.diagnostics),this.openFinLink}handshake(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,this.awaitingWelcome=null,clearTimeout(i),t(e))};this.awaitingWelcome={link:e.kind,settle:r};let i=setTimeout(()=>{r(!1)},this.config.bus.handshakeTimeoutMs);u(i),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.post({t:`journey?`,from:this.contextId})}},oe=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let t=e.target,n=t?.src??t?.href??``;if(t!==null&&t!==globalThis&&n!==``){if(!this.ctx.config.capture.resourceErrors)return;this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${n}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":n,"resource.tag":t.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let r=e,i=r.message===``?`unknown error`:r.message,a=r.error??Error(i);this.report(`window.onerror`,a,{"error.source":r.filename,"error.line":r.lineno,"error.column":r.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`more than 20 errors in ${String(e.F)}ms, suppressing the rest of this window`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
2
+ `)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<this.ctx.config.capture.errorDedupeMs){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?t:a.message,a,{...r,"error.captured_by":t,"error.suppressed_count":l})}};function se(e){if(e===null)return`unknown`;let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function _(){return history}var ce=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(_().pushState=this.originalPushState),this.originalReplaceState&&(_().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let t=e.target,n=se(t instanceof Element?t:null),r=t instanceof HTMLElement?t.innerText.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:n,data:r===``?void 0:{text:r}})};onNavigate=()=>{let e=this.lastUrl,t=location.href;e!==t&&(this.lastUrl=t,this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${e} -> ${t}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":e}))};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=_(),t=e.pushState,n=e.replaceState;this.originalPushState=t,this.originalReplaceState=n;let r=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(r)},e.replaceState=function(...e){n.apply(this,e),queueMicrotask(r)}}};function v(e,t){return t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function y(){return XMLHttpRequest.prototype}var le=class{ctx;name=`network`;originalFetch=null;originalOpen=null;originalSend=null;constructor(e){this.ctx=e}install(){this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr()}uninstall(){this.originalFetch&&=(globalThis.fetch=this.originalFetch,null),this.originalOpen&&=(y().open=this.originalOpen,null),this.originalSend&&=(y().send=this.originalSend,null)}ignored(e){return v(e,this.ctx.config.capture.ignoreUrls)}installFetch(){if(typeof globalThis.fetch!=`function`||this.originalFetch)return;let e=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let t=this.ctx,n=e=>this.ignored(e),r=(e,t,n,r,i)=>{this.record(e,t,n,r,i)};globalThis.fetch=async function(i,a){let o=typeof i==`string`?i:i instanceof URL?i.href:i.url,s=(a?.method??(i instanceof Request?i.method:`GET`)).toUpperCase();if(n(o))return e(i,a);let c=i,l=a;if(v(o,t.config.capture.propagateTraceHeaderTo))try{let e=Object.entries(t.tracing.headers());if(i instanceof Request){let t=new Headers(i.headers);for(let[n,r]of e)t.set(n,r);c=new Request(i,{headers:t})}else{let t=new Headers(a?.headers);for(let[n,r]of e)t.set(n,r);l={...a,headers:t}}}catch(e){c=i,l=a,t.diagnostics.report(`capture.header_failed`,`could not attach traceparent, sending the request unchanged`,{url:o},e)}let u=performance.now();try{let t=await e(c,l);return r(s,o,t.status,performance.now()-u,void 0),t}catch(e){throw r(s,o,0,performance.now()-u,e),e}}}installXhr(){if(typeof XMLHttpRequest>`u`||this.originalOpen)return;let e=e=>this.ignored(e),t=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},n=y(),r=n.open,i=n.send;this.originalOpen=r,this.originalSend=i,n.open=function(e,t,...n){this.__uiobs={method:e.toUpperCase(),url:String(t),startedAt:0},r.apply(this,[e,t,...n])},n.send=function(...n){let r=this.__uiobs;r&&!e(r.url)&&(r.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{t(r.method,r.url,this.status,performance.now()-r.startedAt)})),i.apply(this,n)}}record(e,t,n,r,i){this.ctx.diagnostics.guard(`capture.record_failed`,`recording ${e} ${t}`,()=>{let a=Math.round(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${t} ${n===0?`failed`:String(n)}`,data:{durationMs:a}});let o={"http.request.method":e,"url.full":t,"http.response.status_code":n,"http.duration_ms":a};if(n===0){this.ctx.logger.error(`${e} ${t} failed`,i,o);return}if(n>=400){this.ctx.logger.warn(`${e} ${t} returned ${String(n)}`,o);return}this.ctx.logger.debug(`${e} ${t}`,o)})}};function ue(){return import(`web-vitals`)}var de=class{ctx;name=`web-vitals`;installed=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.reportNavigationTiming(),this.loadWebVitals())}uninstall(){this.installed=!1}async loadWebVitals(){let e=this.ctx.config.capture.webVitalsLoader??ue,t=await this.ctx.diagnostics.guardAsync(`capture.install_failed`,`loading web-vitals`,e);if(!t){this.ctx.diagnostics.report(`capture.install_failed`,`web-vitals is not available, so LCP, CLS and INP are unavailable. Navigation timing still works.`);return}let n=(e,t)=>n=>{this.ctx.logger.logMetric(`web_vitals.${e}`,Math.round(n.value*1e3)/1e3,t,`gauge`,{"metric.rating":n.rating,"metric.id":n.id})};t.onLCP(n(`lcp`,`ms`)),t.onCLS(n(`cls`,`1`)),t.onINP(n(`inp`,`ms`)),t.onFCP(n(`fcp`,`ms`)),t.onTTFB(n(`ttfb`,`ms`))}reportNavigationTiming(){this.ctx.diagnostics.guard(`capture.install_failed`,`reading navigation timing`,()=>{let e=performance.getEntriesByType(`navigation`)[0];if(!e)return;let t={"navigation.dns_ms":e.domainLookupEnd-e.domainLookupStart,"navigation.tcp_ms":e.connectEnd-e.connectStart,"navigation.ttfb_ms":e.responseStart-e.requestStart,"navigation.response_ms":e.responseEnd-e.responseStart,"navigation.dom_interactive_ms":e.domInteractive,"navigation.dom_complete_ms":e.domComplete,"navigation.load_ms":e.loadEventEnd};for(let[n,r]of Object.entries(t))Number.isFinite(r)&&r>=0&&this.ctx.logger.logMetric(n,Math.round(r),`ms`,`gauge`,{"navigation.type":e.type})})}};function b(){return`${String(Date.now())}000000`}function x(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 S(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 C(){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return S(16)}function w(e,t,n){return n.guard(`storage.unavailable`,`reading ${e}Storage`,()=>(e===`local`?localStorage:sessionStorage).getItem(t))??null}function T(e,t,n,r){r.guard(`storage.unavailable`,`writing ${e}Storage`,()=>{(e===`local`?localStorage:sessionStorage).setItem(t,n)})}function fe(t){let n=C(),r=Date.now(),i=C(),a=w(`local`,e.Tt,t);if(a)try{let e=JSON.parse(a);e.id&&r-(e.lastSeenAt??0)<18e5&&(i=e.id)}catch{t.report(`storage.degraded`,`session record was not JSON, starting a new session`)}let o=JSON.stringify({id:i,lastSeenAt:r});T(`local`,e.Tt,o,t);let s=w(`session`,`ui-observability.tab`,t)??``;return s||(s=C(),T(`session`,e.Pt,s,t)),{sessionId:i,tabId:s,contextId:n}}var pe=0;function me(t,n){let r=Date.now();if(r-pe<6e4)return;pe=r;let i=JSON.stringify({id:t,lastSeenAt:r});T(`local`,e.Tt,i,n)}function he(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`id`),n=Reflect.get(e,`createdAt`),r=Reflect.get(e,`attempts`),i=Reflect.get(e,`records`);return typeof t==`string`&&typeof n==`number`&&typeof r==`number`&&Array.isArray(i)}function ge(e){if(e.records.length<2)return null;let t=Math.floor(e.records.length/2),n=t=>({id:C(),records:t,createdAt:e.createdAt,attempts:e.attempts});return[n(e.records.slice(0,t)),n(e.records.slice(t))]}function _e(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`acquiring lock ${e}`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function E(e,t){let n=[];return t.guard(`storage.unavailable`,`enumerating localStorage`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function ve(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.N}${n}.${t.id}`}function ye(e,t){let n=t.guard(`storage.degraded`,`an emergency entry was not JSON and was dropped`,()=>JSON.parse(e));return n===void 0?null:he(n)?n:(t.report(`storage.degraded`,`an emergency entry was not a batch and was dropped`),null)}async function be(t,n){let r=0;for(let i of E(e.N,n)){let e=n.guard(`storage.unavailable`,`reading the emergency queue`,()=>{let e=localStorage.getItem(i);return localStorage.removeItem(i),e});if(!e)continue;let a=ye(e,n);if(a!==null)try{await t.save(a),r++}catch(e){n.report(`storage.degraded`,`an emergency batch could not be recovered`,{key:i},e)}}return r}function xe(t,n){let r=`writing the emergency queue, ${String(t.records.length)} records`;n.guard(`storage.quota_exceeded`,r,()=>{let r=E(e.N,n);for(let e of r.slice(0,Math.max(0,r.length-20+1)))localStorage.removeItem(e);localStorage.setItem(ve(t),JSON.stringify(t))})}async function Se(e,t){return await _e(`ui-observability.emergency`,t,()=>be(e,t),{skipIfBusy:!1})??0}function Ce(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.v}${n}.${t.id}`}var we=class{limits;diagnostics;onGap;name=e.At;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){if(this.diagnostics.guard(`storage.quota_exceeded`,`localStorage refused a batch, evicting the oldest`,()=>(localStorage.setItem(Ce(e),JSON.stringify(e)),!0))!==!0){let e=this.keys();this.evict(e.slice(0,Math.ceil(e.length/4)));return}await this.prune()}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);if(e===null){this.removeKey(n);continue}t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null?Promise.resolve():(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`updating attempts`,()=>{localStorage.setItem(n,JSON.stringify(r))}),Promise.resolve())}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=(e,n)=>{this.removeKey(e),t.batches++,t.records+=n},r=[];for(let t of this.keys()){let i=this.read(t);if(i===null){n(t,0);continue}if(i.createdAt<e){n(t,i.records.length);continue}r.push({key:t,records:i.records.length})}let i=r.length-this.limits.maxBatches;if(i>0){t.reason=`over_capacity`;for(let e of r.slice(0,i))n(e.key,e.records)}return t.batches>0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(t.batches)} stored batches (${String(t.records)} records)`,{...t}),this.onGap?.(t)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`reading a stored batch`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`a stored batch was corrupt and was removed`,()=>JSON.parse(t));return n===void 0?null:he(n)?n:(this.diagnostics.report(`storage.degraded`,`a stored entry was not a batch and was dropped`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`removing a stored batch`,()=>{localStorage.removeItem(e)})}keys(){return E(e.v,this.diagnostics)}};function Te(e){return e.reduce((e,t)=>e+t.records.length,0)}var D=class{limits;onGap;name=e.jt;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),t.batches+=n.length,t.records+=Te(n);let r=this.batches.length-this.limits.maxBatches;if(r>0){t.reason=`over_capacity`;let e=this.batches.slice(0,r);this.batches=this.batches.slice(r),t.batches+=e.length,t.records+=Te(e)}return t.batches>0&&this.onGap?.(t),Promise.resolve(t)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},Ee={name:e.Mt,save:()=>Promise.resolve(),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()};function De(e){return e.guard(`storage.unavailable`,`reading indexedDB`,()=>globalThis.indexedDB!=null)===!0}function Oe(t){return t.guard(`storage.unavailable`,`probing localStorage`,()=>(localStorage.setItem(e.Nt,`1`),localStorage.removeItem(e.Nt),!0))===!0}async function ke(e,t,n,r,i){if(e===`none`)return Ee;if(e===`memory`)return new D(n,i);if(e===`indexeddb`||e===`auto`){if(De(r)){let e=await r.guardAsync(`storage.unavailable`,`opening IndexedDB`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-K3DhJWgu.cjs"));return new e(t,n,r,i)});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB was asked for by name and is unavailable, using memory`),new D(n,i)}return Oe(r)?new we(n,r,i):(r.report(`storage.degraded`,`no persistent storage available, offline logs are memory only`),new D(n,i))}function O(e,t){if(e.length<=t)return e;let n=Ae(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function Ae(e){return e>=55296&&e<=56319}function je(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 k(e,t){let n={bytes:0};return{value:j(e,t,new WeakSet,0,n),bytes:n.bytes}}function A(e,t){return t.bytes+=M(e)+2,e}function j(e,t,n,r,i){if(e==null)return i.bytes+=4,e;if(typeof e==`string`)return A(O(e,t.maxAttributeChars),i);if(typeof e==`number`)return i.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return i.bytes+=5,e;if(typeof e==`bigint`)return A(`${e.toString()}n`,i);if(typeof e==`symbol`)return A(e.toString(),i);if(typeof e==`function`)return A(`[Function ${e.name===``?`anonymous`:e.name}]`,i);if(r>=t.maxDepth)return A(`[MaxDepth]`,i);if(n.has(e))return A(`[Circular]`,i);n.add(e),i.bytes+=2;try{if(e instanceof Error)return{name:A(e.name,i),message:A(O(e.message,t.maxAttributeChars),i),stack:e.stack?A(O(e.stack,t.maxStackChars),i):void 0,cause:e.cause?j(e.cause,t,n,r+1,i):void 0};if(e instanceof Date)return A(e.toISOString(),i);if(e instanceof RegExp)return A(e.toString(),i);if(e instanceof Map){let a=e,o={},s=0;for(let[e,c]of a){if(s>=t.maxArrayLength){o[`…`]=A(`[${String(a.size-t.maxArrayLength)} more entries]`,i);break}s++;let l=String(e);i.bytes+=M(l)+4,o[l]=j(c,t,n,r+1,i)}return o}if(e instanceof Set)return j([...e].slice(0,t.maxArrayLength),t,n,r,i);if(ArrayBuffer.isView(e)){let t=e.length??0;return A(`[${e.constructor.name}(${String(t)})]`,i)}if(e instanceof Promise)return A(`[Promise]`,i);if(typeof Node<`u`&&e instanceof Node)return A(je(e),i);if(Array.isArray(e)){let a=e,o=a.slice(0,t.maxArrayLength).map(e=>j(e,t,n,r+1,i));return a.length>t.maxArrayLength&&o.push(A(`[${String(a.length-t.maxArrayLength)} more items]`,i)),o}let a=e.toJSON;if(typeof a==`function`)return j(a.call(e),t,n,r+1,i);let o=e,s=Object.keys(o),c={},l=0;for(let e of s){if(l>=t.maxAttributeCount){c[`…`]=A(`[${String(s.length-l)} more keys]`,i);break}l++,i.bytes+=M(e)+4,c[e]=j(o[e],t,n,r+1,i)}return c}catch(e){return A(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,i)}finally{n.delete(e)}}function M(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 Me=class{deps;installed=!1;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`subscribing to close-requested`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`releasing close-requested`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(t){let{diagnostics:n}=this.deps,r=this.endpointUrl();if(r===null)return;let i=this.deps.drainPending();if(!i||i.records.length===0)return;let a=n.guard(`transport.serialize_failed`,`the ${t} exit flush could not serialize its batch`,()=>this.deps.config.serializer.serialize(i.records));if(!a)return;if(M(a.body)>6e4){xe(i,n);return}r.searchParams.set(e.at,i.id),r.searchParams.set(e.ot,t);let o=r.toString();this.beacon(o,a.body)||this.keepaliveFetch(o,a.body,t)}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`the exit flush cannot use endpoint ${e}`,()=>new URL(e))??null:null}beacon(t,n){return this.deps.diagnostics.guard(`transport.http_error`,`sendBeacon`,()=>{let r=globalThis.navigator;return r?.sendBeacon?r.sendBeacon(t,new Blob([n],{type:e.E})):!1})===!0}keepaliveFetch(t,n,r){let{config:i,diagnostics:a}=this.deps;a.guard(`transport.http_error`,`the keepalive fetch fallback`,()=>{fetch(t,{method:`POST`,body:n,headers:{[e.H]:e.E},credentials:i.credentials,keepalive:!0}).catch(e=>{a.report(`transport.http_error`,`the exit flush failed`,{reason:r},e)})})}};async function Ne(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.P)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var N=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i){super(t),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function Pe(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.Q);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var Fe=class{config;diagnostics;throttledUntil=0;constructor(e,t){this.config=e,this.diagnostics=t}async send(e){!this.config.endpoint||e.records.length===0||await this.post(e)}throttledForMs(){return Math.max(0,this.throttledUntil-Date.now())}async post(t){let{config:n}=this,r;try{r=n.serializer.serialize(t.records)}catch(e){this.diagnostics.report(`transport.serialize_failed`,`serializer threw, dropping the batch`,{batchId:t.id},e);return}let i=new Headers(await this.resolveHeaders());i.set(e.H,r.contentType),i.set(e.B,t.id),i.set(e.z,String(t.attempts));let a=await this.encodeBody(r.body);typeof a!=`string`&&i.set(e.V,e.P);let o=await this.dispatch(i,a);if(o.ok){this.throttledUntil=0;return}throw await this.classify(o,t.id)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||M(e)<t.compressionThresholdBytes?e:await this.diagnostics.guardAsync(`transport.http_error`,`gzipping the payload`,()=>Ne(e))??e}async dispatch(e,t){let{config:n}=this,r=new AbortController,i=setTimeout(()=>{r.abort()},n.requestTimeoutMs);u(i);try{return await fetch(n.endpoint,{method:`POST`,headers:e,body:t,credentials:n.credentials,signal:r.signal,cache:`no-store`})}catch{if(r.signal.aborted)throw new N(`timeout`,`request exceeded ${String(n.requestTimeoutMs)}ms`);let e=globalThis.navigator?.onLine;throw new N(e===!1?`offline`:`transient`,`network error`)}finally{clearTimeout(i)}}async classify(t,n){let r=t.status,i=Pe(t.headers.get(e.U));if(r===401||r===403)return this.diagnostics.report(`transport.rejected_credentials`,`server returned ${String(r)}. In a cross-origin iframe the session cookie is a third-party cookie and is very likely blocked. Forward to the platform document instead of promoting to sender, or issue the cookie with the Partitioned attribute.`,{status:r,endpoint:this.config.endpoint}),new N(`permanent`,`rejected with ${String(r)}`,r);if(r===413)return new N(`too_large`,`payload too large`,r,void 0,await this.readMaxBytes(t));if(r===429||r===503){let e=r===429;return this.throttledUntil=Date.now()+(i??this.config.retry.baseDelayMs),e&&this.diagnostics.report(`transport.throttled`,`server throttled us`,{retryAfterMs:i}),new N(`throttled`,e?`throttled`:`service unavailable`,r,i)}return r===408||r>=500?new N(`transient`,`server error ${String(r)}`,r):(this.diagnostics.report(`transport.dropped_permanent`,`server rejected the batch with ${String(r)}, dropping it`,{batchId:n,status:r}),new N(`permanent`,`rejected with ${String(r)}`,r))}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`reading the 413 body`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;return e?typeof e==`function`?await this.diagnostics.guardAsync(`transport.http_error`,`headers() threw`,()=>Promise.resolve(e()))??{}:e:{}}},Ie=class{storage;transport;diagnostics;config;batchesPerDrain;timer=null;attempt=0;draining=!1;stopped=!1;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(this.config.retry.idleDelayMs)}nudge(){this.draining||this.schedule(this.config.retry.baseDelayMs)}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,u(t)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let e=Math.min(this.config.retry.baseDelayMs*2**this.attempt,this.config.retry.maxDelayMs);return Math.random()*e}async drain(){if(!this.draining){this.draining=!0;try{await _e(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(this.config.retry.idleDelayMs)}finally{this.draining=!1}}}async drainLocked(){try{if(globalThis.navigator?.onLine===!1)return this.schedule(this.config.retry.idleDelayMs),!0;let e=await this.storage.take(this.batchesPerDrain);if(e.length===0)return this.schedule(this.config.retry.idleDelayMs),!0;for(let t of e)if(this.stopped||!await this.deliver(t))return!0;return this.schedule(e.length===this.batchesPerDrain?0:this.config.retry.idleDelayMs),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`the drain loop threw`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(e){if(e.attempts>=this.config.storage.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`giving up on a batch after ${e.attempts.toString()} attempts`,{batchId:e.id,records:e.records.length}),await this.storage.remove(e.id),!0;try{return await this.transport.send(e),await this.storage.remove(e.id),this.attempt=0,!0}catch(t){let n=t instanceof N?t:void 0;return n?.kind===`permanent`?(await this.storage.remove(e.id),!0):n?.kind===`too_large`?(await this.splitStored(e,n.maxBytes),!0):n?.kind===`offline`?(this.schedule(this.config.retry.idleDelayMs),!1):(await this.storage.bumpAttempts(e.id,e.attempts+1),this.attempt++,this.schedule(n?.retryAfterMs??this.backoffMs()),!1)}}async splitStored(e,t){let n=ge(e);if(await this.storage.remove(e.id),!n){this.diagnostics.report(`transport.dropped_permanent`,`a single record exceeds the server limit and was dropped`,{batchId:e.id,bodies:e.records.map(e=>e.body)});return}this.diagnostics.report(`transport.batch_split`,`the server refused the batch as too large`,{from:e.records.length,to:n[0].records.length,serverMaxBytes:t});for(let e of n)await this.storage.save(e)}},P={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},Le=class{enabled;minLevel;constructor(e,t){this.enabled=e,this.minLevel=t}update(e,t){this.enabled=e,this.minLevel=t}write(t,n,r){if(!this.enabled||e.J[t]<e.J[this.minLevel]||typeof console>`u`)return;let i=`%c${e.Y}%c ${t}`;if(r===void 0){console[P[t]](i,e.C,``,n);return}console[P[t]](i,e.C,``,n,r)}},F=null;function I(e,t){let n=e[t];return n!==void 0&&e instanceof n}function Re(t){if(F)return F;let n=globalThis,r=n.navigator?.userAgent??``,i=`browser`,a,o,s=!1,c=n.fin?.me;return I(n,`ServiceWorkerGlobalScope`)?(i=`service_worker`,s=!0):I(n,`SharedWorkerGlobalScope`)?(i=`shared_worker`,s=!0):I(n,`WorkerGlobalScope`)?(i=`web_worker`,s=!0):c===void 0?n.Capacitor!==void 0||n.Ionic!==void 0?i=`ionic`:n.cordova!==void 0||ze(r)?i=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(i=`node`):(i=e.it.test(r)?`openfin`:`openfin_web`,t.guard(`openfin.unavailable`,`reading fin.me.identity`,()=>{let e=c.identity;a=e?.uuid,o=e?.name})),F={platform:i,openfinUuid:a,openfinName:o,userAgent:r,isWorker:s,isTopLevelDocument:Be()},F}function ze(t){return e.t.test(t)?!0:(e.K.test(t)||e.Z.test(t)&&e.$.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function Be(){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return!1}}function Ve(){try{return typeof location<`u`?location.href:``}catch{return``}}var He=class{value=0;next(){return++this.value}reset(){this.value=0}};function Ue(){return S(16)}function We(){return S(8)}function L(){return{traceId:Ue(),spanId:We(),traceFlags:1,startedAt:Date.now()}}function R(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var Ge=class{diagnostics;maxAgeMs;ambient=L();constructor(t,n=e.Rt){this.diagnostics=t,this.maxAgeMs=n}resolve(){let e=this.diagnostics.guard(`trace.otel_failed`,`reading the active OpenTelemetry span`,()=>{let e=t.trace.getActiveSpan();if(e===void 0)return;let n=e.spanContext();if((0,t.isSpanContextValid)(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}});return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),R(this.ambient)):e}rotate(e){return this.ambient=L(),R(this.ambient)}headers(){let e={};if(this.diagnostics.guard(`trace.otel_failed`,`injecting OpenTelemetry headers`,()=>{t.propagation.inject(t.context.active(),e)}),!e.traceparent){let t=this.resolve(),n=(t.traceFlags&255).toString(16).padStart(2,`0`);e.traceparent=`00-${t.traceId}-${t.spanId}-${n}`}return e}},Ke=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}resize(e){let t=Math.max(e,1);if(t===this.capacity)return;let n=this.snapshot().slice(-t);this.capacity=t,this.clear();for(let e of n)this.push(e)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function qe(t){return e.et.test(t)?Number(BigInt(t)/e.tt):Date.now()}var Je={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=qe(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.mt],version:t.resource[e.ht],environment:t.resource[e.ut]},user_agent:{original:t.resource[e.ct]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...t.resource,...t.attributes}})}).join(`
3
3
  `)}\n`,contentType:e.T}}};function z(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(z).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:B(e)}}:null}function B(e){let t=[];for(let[n,r]of Object.entries(e)){let e=z(r);e&&t.push({key:n,value:e})}return t}var V=new WeakMap;function Ye(e){let t=V.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return V.set(e,n),n}var H={name:e.Ct,serialize(t){let n=new Map;for(let e of t){let t=Ye(e.resource),r=n.get(t);if(r){r.records.push(e);continue}n.set(t,{resource:e.resource,records:[e]})}let r=[...n.values()].map(t=>({resource:{attributes:B(t.resource)},scopeLogs:[{scope:{name:e.It,version:e.Lt},logRecords:t.records.map(e=>({timeUnixNano:e.timeUnixNano,observedTimeUnixNano:e.observedTimeUnixNano??e.timeUnixNano,severityNumber:e.severityNumber,severityText:e.severityText,body:{stringValue:e.body},traceId:e.traceId,spanId:e.spanId,flags:e.traceFlags,attributes:B(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:r}),contentType:e.w}}};function Xe(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function Ze(t,n,r){return t===void 0?n??H:t===`otlp`?H:t===`ecs`?Je:Xe(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Ct}", "ecs" or an implementation`),H)}function U(t,n,r){let i=r??e.D,a={...i,...t,serializer:Ze(t.serializer,r?.serializer,n),streams:{logs:{...i.streams.logs,...t.streams?.logs},metrics:{...i.streams.metrics,...t.streams?.metrics}},storage:{...i.storage,...t.storage},retry:{...i.retry,...t.retry},sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},journey:{...i.journey,...t.journey},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture},limits:{...i.limits,...t.limits},console:{...i.console,...t.console}};if(!a.endpoint)n.report(`config.invalid`,`endpoint is missing. Records will be built and dropped, never sent.`);else try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record will report service.name as '${e.Vt}'.`),e.Vt);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1, got ${String(o)}`),a.sampling.defaultRate=1);let s=Object.entries(a.sampling.rates);for(let[e,t]of s)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1, got ${String(t)}`),a.sampling.rates[e]=1);a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]);let c=new Set([...Object.keys(e.D),...e.Bt]);for(let e of Object.keys(t))c.has(e)||n.report(`config.invalid`,`unknown config key "${e}", ignored. Typo?`);return a}function Qe(t,n){for(let r of Object.keys(n))e.S.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.S)Object.assign(t[r],n[r])}var $e=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},et=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.k){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a};if(this.handler)try{this.handler(s)}catch(t){this.count(`handler.threw`),typeof console<`u`&&console.warn(`${e.Y} onDiagnostic handler threw`,t)}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}};function W(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function G(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function tt(e){if(typeof e!=`object`||!e)return null;let t=W(e,`id`),n=W(e,`name`),r=G(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:W(e,`parentId`),ownerContextId:W(e,`ownerContextId`)??``}}function nt(e){if(typeof e!=`object`||!e)return null;let t=W(e,`i`),n=W(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:G(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function rt(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.g,`-`).replace(e._,`_`).replace(e.h,``)}function it(e,t){let n=new Promise((e,n)=>{u(setTimeout(()=>{n(Error(`timed out after ${String(t)}ms`))},t))});return Promise.race([e,n])}var at=class{options;diagnostics;contextId;onLocalChange;journey=null;expiryTimer=null;constructor(e,t,n,r){this.options=e,this.diagnostics=t,this.contextId=n,this.onLocalChange=r}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`reading the persisted journey`,()=>sessionStorage.getItem(e.q));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,t={}){let n={id:t.id??C(),name:e,startedAt:Date.now(),parentId:t.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(n),this.onLocalChange(n),n}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=rt(e);if(t.length>256){this.diagnostics.report(`journey.token_too_large`,`journey token exceeded the size cap and was not issued`,{length:t.length});return}return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`discarded a seeded journey older than maxAgeMs`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`adopted journey "${r.name}"`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=tt(this.diagnostics.guard(`storage.degraded`,`parsing the persisted journey`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`discarded a persisted journey older than maxAgeMs`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`resumed journey "${t.name}"`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`decoding a seeded journey token`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return nt(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`persisting the journey`,()=>{t===null?sessionStorage.removeItem(e.q):sessionStorage.setItem(e.q,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),r=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`journey "${t.name}" hit maxAgeMs and was ended automatically`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=r,u(r)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`clearing the persisted journey`,()=>{sessionStorage.removeItem(e.q)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`reading the journey token from the URL`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let t=globalThis.fin?.me,n=t?.getOptions;if(n===void 0)return null;let r=(await this.diagnostics.guardAsync(`openfin.unavailable`,`reading fin.me.getOptions()`,()=>it(n.call(t),e.rt)))?.customData?.[e.nt];return typeof r==`string`?r:null}};function ot(t){let n=e.I;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.L);return n>>>0}function K(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function st(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 ct(t,n){if(t.severityText===`ERROR`||t.severityText===`FATAL`||n.sampling.alwaysSampleTypes.includes(K(t,`log.type`)))return!0;let r=st(K(t,e.n),n);return r>=1?!0:r<=0?!1:ot(K(t,`journey.id`)||t.traceId)/e.zt<r}function lt(t){return t.attributes[e.l]===e.X}var q=class{config;name;diagnostics;pending=[];constructor(e,t,n){this.config=e,this.name=t,this.diagnostics=n}get options(){return this.config.streams[this.name]}get capacity(){return Math.max(this.options.batchSize,1)*10}add(e){this.pending.length>=this.capacity&&(this.pending.shift(),this.diagnostics.count(`record.dropped_pending_full`)),this.pending.push(e)}take(){let e=this.pending;return this.pending=[],e}},ut=class{config;transport;storage;retry;diagnostics;records$=new n.Subject;streams;subscription=null;unconfirmed=new Map;stopped=!1;constructor(e,t,n,r,i){this.config=e,this.transport=t,this.storage=n,this.retry=r,this.diagnostics=i,this.streams={logs:new q(e,`logs`,i),metrics:new q(e,`metrics`,i)},this.subscribe()}push(e){this.stopped||(e.observedTimeUnixNano=b(),this.records$.next(e))}drainPending(){let e=[...[...this.unconfirmed.values()].flatMap(e=>e.records),...this.streams.metrics.take(),...this.streams.logs.take()];return this.unconfirmed.clear(),e.length===0?null:{id:C(),records:e,createdAt:Date.now(),attempts:0}}refresh(){this.subscription?.unsubscribe(),this.subscribe()}destroy(){this.stopped=!0,this.subscription?.unsubscribe(),this.subscription=null,this.records$.complete()}subscribe(){if(this.stopped)return;let[e,t]=(0,n.partition)(this.records$,lt);this.subscription=(0,n.merge)(this.batches(e,this.streams.metrics),this.batches(t,this.streams.logs)).pipe((0,n.catchError)(e=>(this.diagnostics.report(`pipeline.crashed`,`the pipeline errored and was restarted`,void 0,e),this.subscribe(),n.EMPTY)),(0,n.observeOn)(n.asapScheduler),(0,n.mergeMap)(e=>(0,n.from)(this.dispatch(e)).pipe((0,n.catchError)(t=>(this.diagnostics.report(`pipeline.crashed`,`dispatch rejected, which it is written never to do`,{batchId:e.id},t),n.EMPTY))),this.config.maxConcurrentRequests)).subscribe()}batches(e,t){return e.pipe((0,n.filter)(e=>ct(e,this.config)?!0:(this.diagnostics.count(`record.dropped_by_sampling`),!1)),(0,n.tap)(e=>{t.add(e)}),(0,n.bufferTime)(t.options.flushIntervalMs,null,t.options.batchSize),(0,n.map)(()=>this.claim(t)),(0,n.filter)(e=>e!==null))}claim(e){let t=e.take();if(t.length===0)return null;let n={id:C(),records:t,createdAt:Date.now(),attempts:0};return this.unconfirmed.set(n.id,n),n}async dispatch(e){try{let t=this.transport.throttledForMs();if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`stored the batch rather than sending it`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e)}catch(t){await this.store({...e,attempts:e.attempts+1}),this.diagnostics.report(`transport.http_error`,`batch was stored for retry instead of being delivered`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async store(e){await this.diagnostics.guardAsync(`storage.degraded`,`persisting an undelivered batch`,async()=>{await this.storage.save(e),this.retry.nudge()})}};function J(e){return e}var dt=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;return n.enabled?e.J[t]>=e.J[n.minLevel]:!1}build(t){let{config:n,diagnostics:r,tracing:i,journey:a,sequence:o}=this.deps;if(!this.isEnabled(t.level))return r.count(`record.dropped_by_level`),null;let s=n.limits,c=i.resolve(),l=a.current(),u=o.next(),d=Ve(),f,p=0;try{let e=k(this.deps.context.getAll(),s),n=k(t.scoped??{},s),r=k(t.payload??{},s);p=e.bytes+n.bytes+r.bytes,f={...J(e.value),...J(n.value),...J(r.value)}}catch(t){r.report(`record.sanitize_failed`,`attributes could not be sanitized`,void 0,t),f={[e.d]:!0}}f[e.l]=t.type,f[e.c]=u,f[e.n]=t.namespace,f[e.u]=d,l&&(f[e.a]=l.id,f[e.o]=l.name,l.parentId!==void 0&&(f[e.s]=l.parentId));let m=O(t.body,s.maxBodyChars);m!==t.body&&r.count(`record.truncated`);let h={timeUnixNano:b(),traceId:c.traceId,spanId:c.spanId,traceFlags:c.traceFlags,severityNumber:e.Dt[t.level],severityText:t.level,body:m,attributes:f,resource:this.resource()},g=n.redact;if(g){let e=r.guard(`record.sanitize_failed`,`redact hook threw`,()=>g(h));if(e===null)return r.count(`record.dropped_by_redact`),null;if(e!==void 0&&e!==h){if(x(e)){let t=k(e.attributes,s);h={...e,attributes:J(t.value)},p=t.bytes}else r.report(`record.sanitize_failed`,`redact hook returned something that is not a record, keeping the original`)}}if(p>s.maxRecordBytes){r.report(`record.truncated`,`attributes exceeded the size budget and were dropped`,{bytes:p,body:h.body});let n={[e.l]:t.type,[e.c]:u,[e.n]:t.namespace,[e.u]:d,[e.i]:!0,[e.r]:p};l&&(n[e.a]=l.id,n[e.o]=l.name),h.attributes=n}return h}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.mt]:t.serviceName,[e.ht]:t.serviceVersion,[e.ut]:t.environment,[e.yt]:e.It,[e.bt]:e.Lt,[e.vt]:e.Ft,[e.dt]:r.platform,[e.gt]:n.sessionId,[e._t]:n.tabId,[e.lt]:n.contextId,[e.ct]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.pt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.ft]:r.openfinName}},this.resourceCache}},Y=Symbol.for(e.xt),X=class t{diagnostics;config;platform;identity;context=new $e;breadcrumbs;tracing;sequence=new He;journey;builder;console;bus;storage;transport;retry;pipeline;exitFlush;captures=[];bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;ready=!1;destroyed=!1;lastGapAt=0;constructor(e){this.diagnostics=new et(e.onDiagnostic),this.platform=Re(this.diagnostics),this.config=U(e,this.diagnostics),this.identity=fe(this.diagnostics),this.breadcrumbs=new Ke(this.config.capture.maxBreadcrumbs),this.tracing=new Ge(this.diagnostics),this.console=new Le(this.config.console.enabled,this.config.console.level),this.journey=new at(this.config.journey,this.diagnostics,this.identity.contextId,e=>{this.bus.broadcastJourney(e)}),this.builder=new dt({config:this.config,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform}),this.bus=new ae(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()}})}busAccept=(e,t)=>{this.destroyed||this.diagnostics.guard(`bus.send_failed`,`accepting a direct message from a child`,()=>{this.bus.acceptDirect(e,t)})};static current(){return globalThis[Y]??null}static configure(e){let n=t.current();if(n&&!n.destroyed)return n.reconfigure(e),n;let r=new t(e);return globalThis[Y]=r,r.init(),r}reconfigure(e){Qe(this.config,U(e,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console.enabled,this.config.console.level),this.breadcrumbs.resize(this.config.capture.maxBreadcrumbs),this.pipeline?.refresh(),this.ready&&this.reinstallCaptures(),this.diagnostics.report(`config.reconfigured`,`configure() was called again, the existing runtime was updated`)}async init(){try{let e=this.journey.bootstrap();await this.bus.start()===`sender`&&await this.becomeSender(),await e,this.installCaptures()}catch(e){this.diagnostics.report(`pipeline.crashed`,`startup failed, continuing in a degraded state`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}}async becomeSender(){this.storage=await ke(this.config.storage.strategy,this.config.storage.dbName,this.config.storage,this.diagnostics,this.reportGap),this.transport=new Fe(this.config,this.diagnostics),this.retry=new Ie(this.storage,this.transport,this.diagnostics,this.config),this.pipeline=new ut(this.config,this.transport,this.storage,this.retry,this.diagnostics),this.exitFlush=new Me({config:this.config,diagnostics:this.diagnostics,drainPending:()=>this.pipeline?.drainPending()??null}),await Se(this.storage,this.diagnostics),this.retry.start(),this.exitFlush.install()}installCaptures(){let t={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new l(this,e.x)},n=this.config.capture;(n.errors||n.rejections||n.resourceErrors)&&this.captures.push(new oe(t)),(n.fetch||n.xhr)&&this.captures.push(new le(t)),(n.interactions||n.navigation)&&this.captures.push(new ce(t)),n.webVitals&&this.captures.push(new de(t));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`installing ${e.name}`,()=>{e.install()})}reinstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`uninstalling ${e.name}`,()=>{e.uninstall()});this.captures.length=0,this.installCaptures()}registerWorker(e){this.destroyed||this.diagnostics.guard(`bus.send_failed`,`registering a worker`,()=>{this.bus.attachWorker(e)})}async destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.captures)e.uninstall();this.captures.length=0,this.exitFlush?.flush(`shutdown`),this.exitFlush?.uninstall(),this.retry?.stop(),this.pipeline?.destroy(),this.journey.destroy(),this.bus.destroy(),this.forwardBuffer=[],await this.storage?.close(),t.current()===this&&Reflect.deleteProperty(globalThis,Y)}}emit(e){if(!(!e||this.destroyed)){if(me(this.identity.sessionId,this.diagnostics),!this.ready){this.bootBuffer.length>=this.config.bus.maxBootBufferRecords&&(this.bootBuffer.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),this.bootBuffer.push(e);return}this.route(e)}}route(e){if(this.bus.getRole()===`forwarder`){this.forward(e);return}this.pipeline?.push(e)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e)){this.diagnostics.count(`record.dropped_malformed`);return}for(let t of e){if(!x(t)){this.diagnostics.count(`record.dropped_malformed`);continue}this.pipeline?.push(t)}}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new l(this,e.Ot).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let t=C();this.diagnostics.report(`bus.role_resolved`,`another context claimed this tab id, most likely a duplicated tab. Regenerating.`,{was:this.identity.tabId,now:t}),this.identity.tabId=t,this.diagnostics.guard(`storage.unavailable`,`persisting the new tab id`,()=>{sessionStorage.setItem(e.Pt,t)}),this.builder.invalidateResource()}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting the batches waiting in storage`,()=>this.storage?.count()??Promise.resolve(0))??0}async flush(){if(this.bus.getRole()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus.sendRecords(e);return}let e=this.pipeline?.drainPending();if(!(!e||!this.transport))try{await this.transport.send(e)}catch(t){await this.diagnostics.guardAsync(`storage.degraded`,`persisting the batch drained by flush()`,async()=>{await this.storage?.save({...e,attempts:1}),this.retry?.nudge()}),this.diagnostics.report(`transport.http_error`,`the batch drained by flush() was stored for retry instead of being delivered`,{batchId:e.id,records:e.records.length},t)}}},Z=new Map;function Q(){return X.current()||X.configure({})}function ft(e){X.configure(e),Z.clear()}function pt(e,t){let n=t?`${e}::${JSON.stringify(t)}`:e,r=Z.get(n);return r||(r=new l(Q(),e,t),Z.set(n,r)),r}function $(){return pt(`app`)}function mt(e,t){$().trace(e,t)}function ht(e,t){$().debug(e,t)}function gt(e,t){$().info(e,t)}function _t(e,t){$().warn(e,t)}function vt(e,t,n){$().error(e,t,n)}function yt(e,t){$().logAction(e,t)}function bt(e,t){$().logEvent(e,t)}function xt(e,t,n,r,i){$().logMetric(e,t,n,r,i)}function St(e,t,n){return $().timeSync(e,t,n)}function Ct(e,t,n){return $().timeAsync(e,t,n)}function wt(e,t){Q().context.set(e,t)}function Tt(e){Q().context.setMany(e)}function Et(e){Q().context.remove(e)}function Dt(e,t){return Q().journey.start(e,t)}function Ot(){Q().journey.end()}function kt(){return Q().journey.current()}function At(){return Q().journey.getToken()}function jt(e){return Q().journey.adopt(e,`manual`,!0)}function Mt(e){Q().registerWorker(e)}function Nt(){Q().tracing.rotate(`explicit`)}function Pt(){return Q().tracing.headers()}function Ft(){return Q().flush()}function It(){return Q().queueDepth()}function Lt(){return Q().diagnostics.snapshot()}async function Rt(){let e=X.current();Z.clear(),await e?.destroy()}exports.OneLogger=l,exports.adoptJourney=jt,exports.configure=ft,exports.currentJourney=kt,exports.debug=ht,exports.endJourney=Ot,exports.error=vt,exports.flush=Ft,exports.getDiagnosticCounters=Lt,exports.getJourneyToken=At,exports.getLogger=pt,exports.getQueueDepth=It,exports.getTraceHeaders=Pt,exports.info=gt,exports.logAction=yt,exports.logEvent=bt,exports.logMetric=xt,exports.registerWorker=Mt,exports.removeContext=Et,exports.setContext=wt,exports.setContextMap=Tt,exports.shutdown=Rt,exports.startJourney=Dt,exports.startTrace=Nt,exports.timeAsync=Ct,exports.timeSync=St,exports.trace=mt,exports.warn=_t;
4
4
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as e, At as t, B as n, Bt as r, C as i, Ct as a, D as o, Dt as s, E as c, F as l, Ft as u, H as d, I as f, It as p, J as m, K as h, L as g, Lt as ee, Mt as te, N as _, Nt as ne, O as re, Ot as ie, P as ae, Pt as oe, Q as se, Rt as ce, S as le, T as ue, Tt as v, U as de, V as fe, Vt as pe, X as me, Y as he, Z as ge, _ as _e, _t as ve, a as ye, at as be, b as xe, bt as Se, c as Ce, ct as we, d as Te, dt as Ee, et as De, ft as Oe, g as ke, gt as Ae, h as je, ht as Me, i as Ne, it as Pe, j as Fe, jt as Ie, k as Le, l as y, lt as Re, m as ze, mt as Be, n as b, nt as Ve, o as He, ot as Ue, p as We, pt as Ge, q as x, r as Ke, rt as qe, s as Je, t as Ye, tt as Xe, u as Ze, ut as Qe, v as $e, vt as et, w as tt, x as nt, xt as rt, yt as it, z as at, zt as ot } from "./constants-4eu3x1qw.js";
1
+ import { $ as e, At as t, B as n, Bt as r, C as i, Ct as a, D as o, Dt as s, E as c, F as l, Ft as u, H as d, I as f, It as p, J as m, K as h, L as g, Lt as ee, Mt as te, N as _, Nt as ne, O as re, Ot as ie, P as ae, Pt as oe, Q as se, Rt as ce, S as le, T as ue, Tt as v, U as de, V as fe, Vt as pe, X as me, Y as he, Z as ge, _ as _e, _t as ve, a as ye, at as be, b as xe, bt as Se, c as Ce, ct as we, d as Te, dt as Ee, et as De, ft as Oe, g as ke, gt as Ae, h as je, ht as Me, i as Ne, it as Pe, j as Fe, jt as Ie, k as Le, l as y, lt as Re, m as ze, mt as Be, n as b, nt as Ve, o as He, ot as Ue, p as We, pt as Ge, q as x, r as Ke, rt as qe, s as Je, t as Ye, tt as Xe, u as Ze, ut as Qe, v as $e, vt as et, w as tt, x as nt, xt as rt, yt as it, z as at, zt as ot } from "./constants-CYedFKrL.js";
2
2
  import { context as st, isSpanContextValid as ct, propagation as lt, trace as ut } from "@opentelemetry/api";
3
3
  import { EMPTY as dt, Subject as ft, asapScheduler as pt, bufferTime as mt, catchError as ht, filter as S, from as gt, map as _t, merge as vt, mergeMap as yt, observeOn as bt, partition as xt, tap as St } from "rxjs";
4
4
  //#region src/utils/timer.ts
@@ -1121,7 +1121,7 @@ async function dn(e, t, n, r, i) {
1121
1121
  if (e === "indexeddb" || e === "auto") {
1122
1122
  if (ln(r)) {
1123
1123
  let e = await r.guardAsync("storage.unavailable", "opening IndexedDB", async () => {
1124
- let { IndexedDbStorage: e } = await import("./indexeddb-storage-2PCdF5Ji.js");
1124
+ let { IndexedDbStorage: e } = await import("./indexeddb-storage-3oT4si-p.js");
1125
1125
  return new e(t, n, r, i);
1126
1126
  });
1127
1127
  if (e) return e;
@@ -1,4 +1,4 @@
1
- import { kt as e } from "./constants-4eu3x1qw.js";
1
+ import { kt as e } from "./constants-CYedFKrL.js";
2
2
  import t from "dexie";
3
3
  //#region src/storage/indexeddb-storage.ts
4
4
  function n(e) {
@@ -85,4 +85,4 @@ var r = class extends t {
85
85
  //#endregion
86
86
  export { i as IndexedDbStorage };
87
87
 
88
- //# sourceMappingURL=indexeddb-storage-2PCdF5Ji.js.map
88
+ //# sourceMappingURL=indexeddb-storage-3oT4si-p.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb-storage-2PCdF5Ji.js","names":[],"sources":["../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB and Dexie with time-ordered indexing.\n\nimport Dexie, { type Table } from \"dexie\";\nimport {\n INDEXEDDB_SCHEMA_VERSION,\n QUOTA_EVICTION_DIVISOR,\n QUOTA_EXCEEDED_ERROR,\n STORAGE_NAME_INDEXEDDB,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Dexie database instance schema definition for log batch storage. */\nclass ObservabilityDb extends Dexie {\n /** Table storing LogBatch entities keyed by id and indexed by createdAt. */\n batches!: Table<LogBatch, string>;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(name: string) {\n super(name);\n this.version(INDEXEDDB_SCHEMA_VERSION).stores({ batches: \"id, createdAt\" });\n }\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Underlying Dexie database instance. */\n private readonly db: ObservabilityDb;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new ObservabilityDb(dbName);\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.batches.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.batches.orderBy(\"createdAt\").limit(limit).toArray(),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.batches.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.batches.update(id, { attempts }),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.batches.where(\"createdAt\").below(cutoff).toArray();\n if (expired.length > 0) {\n await this.db.batches.bulkDelete(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.batches.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.batches.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () =>\n this.db.batches.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n close(): Promise<void> {\n this.diagnostics.guard(\"storage.degraded\", \"closing the database\", () => {\n this.db.close();\n });\n return Promise.resolve();\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.batches.orderBy(\"createdAt\").limit(howMany).toArray();\n await this.db.batches.bulkDelete(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"indexeddb-storage-3oT4si-p.js","names":[],"sources":["../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB and Dexie with time-ordered indexing.\n\nimport Dexie, { type Table } from \"dexie\";\nimport {\n INDEXEDDB_SCHEMA_VERSION,\n QUOTA_EVICTION_DIVISOR,\n QUOTA_EXCEEDED_ERROR,\n STORAGE_NAME_INDEXEDDB,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Dexie database instance schema definition for log batch storage. */\nclass ObservabilityDb extends Dexie {\n /** Table storing LogBatch entities keyed by id and indexed by createdAt. */\n batches!: Table<LogBatch, string>;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(name: string) {\n super(name);\n this.version(INDEXEDDB_SCHEMA_VERSION).stores({ batches: \"id, createdAt\" });\n }\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Underlying Dexie database instance. */\n private readonly db: ObservabilityDb;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new ObservabilityDb(dbName);\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.batches.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.batches.orderBy(\"createdAt\").limit(limit).toArray(),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.batches.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.batches.update(id, { attempts }),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.batches.where(\"createdAt\").below(cutoff).toArray();\n if (expired.length > 0) {\n await this.db.batches.bulkDelete(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.batches.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.batches.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () =>\n this.db.batches.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n close(): Promise<void> {\n this.diagnostics.guard(\"storage.degraded\", \"closing the database\", () => {\n this.db.close();\n });\n return Promise.resolve();\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.batches.orderBy(\"createdAt\").limit(howMany).toArray();\n await this.db.batches.bulkDelete(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));const c=require("./constants-Daya7Mc-.cjs");let l=require("dexie");l=s(l,1);function u(e){return e.reduce((e,t)=>e+t.records.length,0)}var d=class extends l.default{batches;constructor(e){super(e),this.version(1).stores({batches:`id, createdAt`})}},f=class{limits;diagnostics;onGap;name=c.kt;db;constructor(e,t,n,r){this.limits=t,this.diagnostics=n,this.onGap=r,this.db=new d(e)}async save(e){try{await this.db.batches.put(e),await this.prune()}catch(t){if(t instanceof Error&&t.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full, evicting the oldest`);let e=await this.diagnostics.guardAsync(`storage.degraded`,`evicting after a full disk`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));e&&this.reportGap({...e,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`could not persist a batch`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`reading stored batches`,()=>this.db.batches.orderBy(`createdAt`).limit(e).toArray())??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`deleting a batch`,()=>this.db.batches.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`updating attempts`,()=>this.db.batches.update(e,{attempts:t}))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`pruning`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.batches.where(`createdAt`).below(t).toArray();n.length>0&&(await this.db.batches.bulkDelete(n.map(e=>e.id)),e.batches+=n.length,e.records+=u(n));let r=await this.db.batches.count();if(r>this.limits.maxBatches){e.reason=`over_capacity`;let t=await this.evictOldest(r-this.limits.maxBatches);e.batches+=t.batches,e.records+=t.records}}),this.reportGap(e),e}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting`,()=>this.db.batches.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`clearing`,()=>this.db.batches.clear())}close(){return this.diagnostics.guard(`storage.degraded`,`closing the database`,()=>{this.db.close()}),Promise.resolve()}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(e.batches)} stored batches (${String(e.records)} records)`,{...e}),this.onGap?.(e))}async evictOldest(e){let t=await this.db.batches.orderBy(`createdAt`).limit(e).toArray();return await this.db.batches.bulkDelete(t.map(e=>e.id)),{batches:t.length,records:u(t)}}};exports.IndexedDbStorage=f;
2
- //# sourceMappingURL=indexeddb-storage-BhMUPgyG.cjs.map
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));const c=require("./constants-CeqjB0Aa.cjs");let l=require("dexie");l=s(l,1);function u(e){return e.reduce((e,t)=>e+t.records.length,0)}var d=class extends l.default{batches;constructor(e){super(e),this.version(1).stores({batches:`id, createdAt`})}},f=class{limits;diagnostics;onGap;name=c.kt;db;constructor(e,t,n,r){this.limits=t,this.diagnostics=n,this.onGap=r,this.db=new d(e)}async save(e){try{await this.db.batches.put(e),await this.prune()}catch(t){if(t instanceof Error&&t.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full, evicting the oldest`);let e=await this.diagnostics.guardAsync(`storage.degraded`,`evicting after a full disk`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));e&&this.reportGap({...e,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`could not persist a batch`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`reading stored batches`,()=>this.db.batches.orderBy(`createdAt`).limit(e).toArray())??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`deleting a batch`,()=>this.db.batches.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`updating attempts`,()=>this.db.batches.update(e,{attempts:t}))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`pruning`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.batches.where(`createdAt`).below(t).toArray();n.length>0&&(await this.db.batches.bulkDelete(n.map(e=>e.id)),e.batches+=n.length,e.records+=u(n));let r=await this.db.batches.count();if(r>this.limits.maxBatches){e.reason=`over_capacity`;let t=await this.evictOldest(r-this.limits.maxBatches);e.batches+=t.batches,e.records+=t.records}}),this.reportGap(e),e}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting`,()=>this.db.batches.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`clearing`,()=>this.db.batches.clear())}close(){return this.diagnostics.guard(`storage.degraded`,`closing the database`,()=>{this.db.close()}),Promise.resolve()}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(e.batches)} stored batches (${String(e.records)} records)`,{...e}),this.onGap?.(e))}async evictOldest(e){let t=await this.db.batches.orderBy(`createdAt`).limit(e).toArray();return await this.db.batches.bulkDelete(t.map(e=>e.id)),{batches:t.length,records:u(t)}}};exports.IndexedDbStorage=f;
2
+ //# sourceMappingURL=indexeddb-storage-K3DhJWgu.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb-storage-BhMUPgyG.cjs","names":[],"sources":["../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB and Dexie with time-ordered indexing.\n\nimport Dexie, { type Table } from \"dexie\";\nimport {\n INDEXEDDB_SCHEMA_VERSION,\n QUOTA_EVICTION_DIVISOR,\n QUOTA_EXCEEDED_ERROR,\n STORAGE_NAME_INDEXEDDB,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Dexie database instance schema definition for log batch storage. */\nclass ObservabilityDb extends Dexie {\n /** Table storing LogBatch entities keyed by id and indexed by createdAt. */\n batches!: Table<LogBatch, string>;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(name: string) {\n super(name);\n this.version(INDEXEDDB_SCHEMA_VERSION).stores({ batches: \"id, createdAt\" });\n }\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Underlying Dexie database instance. */\n private readonly db: ObservabilityDb;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new ObservabilityDb(dbName);\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.batches.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.batches.orderBy(\"createdAt\").limit(limit).toArray(),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.batches.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.batches.update(id, { attempts }),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.batches.where(\"createdAt\").below(cutoff).toArray();\n if (expired.length > 0) {\n await this.db.batches.bulkDelete(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.batches.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.batches.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () =>\n this.db.batches.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n close(): Promise<void> {\n this.diagnostics.guard(\"storage.degraded\", \"closing the database\", () => {\n this.db.close();\n });\n return Promise.resolve();\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.batches.orderBy(\"createdAt\").limit(howMany).toArray();\n await this.db.batches.bulkDelete(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"indexeddb-storage-K3DhJWgu.cjs","names":[],"sources":["../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB and Dexie with time-ordered indexing.\n\nimport Dexie, { type Table } from \"dexie\";\nimport {\n INDEXEDDB_SCHEMA_VERSION,\n QUOTA_EVICTION_DIVISOR,\n QUOTA_EXCEEDED_ERROR,\n STORAGE_NAME_INDEXEDDB,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Dexie database instance schema definition for log batch storage. */\nclass ObservabilityDb extends Dexie {\n /** Table storing LogBatch entities keyed by id and indexed by createdAt. */\n batches!: Table<LogBatch, string>;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(name: string) {\n super(name);\n this.version(INDEXEDDB_SCHEMA_VERSION).stores({ batches: \"id, createdAt\" });\n }\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Underlying Dexie database instance. */\n private readonly db: ObservabilityDb;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new ObservabilityDb(dbName);\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.batches.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.batches.orderBy(\"createdAt\").limit(limit).toArray(),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.batches.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.batches.update(id, { attempts }),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.batches.where(\"createdAt\").below(cutoff).toArray();\n if (expired.length > 0) {\n await this.db.batches.bulkDelete(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.batches.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.batches.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () =>\n this.db.batches.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n close(): Promise<void> {\n this.diagnostics.guard(\"storage.degraded\", \"closing the database\", () => {\n this.db.close();\n });\n return Promise.resolve();\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.batches.orderBy(\"createdAt\").limit(howMany).toArray();\n await this.db.batches.bulkDelete(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@utk09/ui-observability",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "UI observability and logging for browser, OpenFin and webview applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [