@utk09/ui-observability 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +119 -60
- package/dist/bus/bus.d.ts +10 -10
- package/dist/bus/links.d.ts +1 -1
- package/dist/bus-DeZzr2bx.cjs +2 -0
- package/dist/bus-DeZzr2bx.cjs.map +1 -0
- package/dist/{bus-D3OO0OcL.js → bus-DfAbg_pg.js} +19 -19
- package/dist/bus-DfAbg_pg.js.map +1 -0
- package/dist/capture/network.d.ts +2 -2
- package/dist/capture/types.d.ts +10 -10
- package/dist/capture/web-vitals.d.ts +3 -3
- package/dist/constants-C8nZQBmQ.js +86 -0
- package/dist/constants-C8nZQBmQ.js.map +1 -0
- package/dist/constants-IBL_jd5R.cjs +2 -0
- package/dist/constants-IBL_jd5R.cjs.map +1 -0
- package/dist/constants.d.ts +56 -43
- package/dist/core/breadcrumbs.d.ts +14 -14
- package/dist/core/config.d.ts +5 -4
- package/dist/core/context.d.ts +2 -2
- package/dist/core/diagnostics.d.ts +10 -9
- package/dist/core/journey.d.ts +23 -20
- package/dist/core/logger.d.ts +7 -7
- package/dist/core/pipeline.d.ts +34 -29
- package/dist/core/record.d.ts +6 -6
- package/dist/core/runtime.d.ts +20 -18
- package/dist/core/sampling.d.ts +15 -16
- package/dist/core/sender.d.ts +1 -1
- package/dist/{errors-Dme9tz-6.js → errors-4MQyjZVj.js} +4 -4
- package/dist/errors-4MQyjZVj.js.map +1 -0
- package/dist/{errors-DPju_xSI.cjs → errors-CUdShXe7.cjs} +2 -2
- package/dist/errors-CUdShXe7.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.js +136 -115
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-nxs_rxGx.js → indexeddb-storage-0LtUALBg.js} +16 -16
- package/dist/indexeddb-storage-0LtUALBg.js.map +1 -0
- package/dist/indexeddb-storage-CcEJlq2l.cjs +2 -0
- package/dist/indexeddb-storage-CcEJlq2l.cjs.map +1 -0
- package/dist/{interactions-DP0-rIPJ.cjs → interactions-BMNPQ3WH.cjs} +2 -2
- package/dist/interactions-BMNPQ3WH.cjs.map +1 -0
- package/dist/{interactions-C1romMpE.js → interactions-BaCmoGLB.js} +2 -2
- package/dist/interactions-BaCmoGLB.js.map +1 -0
- package/dist/models/batch.d.ts +12 -9
- package/dist/models/bus.d.ts +12 -13
- package/dist/models/config.d.ts +85 -44
- package/dist/models/log-record.d.ts +12 -10
- package/dist/models/serializer.d.ts +3 -2
- package/dist/models/storage.d.ts +2 -2
- package/dist/network-DBNvxCE3.cjs +2 -0
- package/dist/network-DBNvxCE3.cjs.map +1 -0
- package/dist/{network-au-Tqt1n.js → network-jQ2t8rU4.js} +4 -4
- package/dist/network-jQ2t8rU4.js.map +1 -0
- package/dist/platform-ByQllE_W.cjs +2 -0
- package/dist/platform-ByQllE_W.cjs.map +1 -0
- package/dist/{platform-DMYo3AX3.js → platform-YuByH8A5.js} +8 -8
- package/dist/platform-YuByH8A5.js.map +1 -0
- package/dist/{sampling-ByI5H44E.js → sampling-CbYySsZ1.js} +21 -18
- package/dist/sampling-CbYySsZ1.js.map +1 -0
- package/dist/sampling-Cs50xsZl.cjs +2 -0
- package/dist/sampling-Cs50xsZl.cjs.map +1 -0
- package/dist/{sender-R7lOpyNc.js → sender-BIob8eZz.js} +60 -60
- package/dist/sender-BIob8eZz.js.map +1 -0
- package/dist/sender-iOjzcueM.cjs +3 -0
- package/dist/sender-iOjzcueM.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.ts +2 -2
- package/dist/storage/factory.d.ts +2 -1
- package/dist/storage/idb-driver.d.ts +19 -19
- package/dist/storage/indexeddb-storage.d.ts +18 -17
- package/dist/storage/keys.d.ts +1 -1
- package/dist/storage/local-storage.d.ts +19 -18
- package/dist/storage/memory-storage.d.ts +12 -11
- package/dist/transport/compression.d.ts +2 -2
- package/dist/transport/errors.d.ts +8 -7
- package/dist/transport/exit-flush.d.ts +27 -24
- package/dist/transport/http-transport.d.ts +18 -11
- package/dist/transport/retry-engine.d.ts +33 -28
- package/dist/transport/serializers/ecs.d.ts +1 -1
- package/dist/transport/serializers/otlp.d.ts +1 -1
- package/dist/unref-16maCyKA.js.map +1 -1
- package/dist/unref-CU9Nyz_9.cjs.map +1 -1
- package/dist/utils/console.d.ts +7 -6
- package/dist/utils/identity.d.ts +6 -5
- package/dist/utils/lock.d.ts +4 -4
- package/dist/utils/platform.d.ts +5 -3
- package/dist/utils/sanitize.d.ts +5 -2
- package/dist/utils/sequence.d.ts +2 -2
- package/dist/utils/tracing.d.ts +8 -7
- package/dist/web-vitals-B2FYsEAU.cjs +2 -0
- package/dist/web-vitals-B2FYsEAU.cjs.map +1 -0
- package/dist/{web-vitals-DwWdLBq6.js → web-vitals-DHZ0yA_H.js} +4 -4
- package/dist/web-vitals-DHZ0yA_H.js.map +1 -0
- package/package.json +4 -2
- package/dist/bus-D3OO0OcL.js.map +0 -1
- package/dist/bus-OdRJVUzr.cjs +0 -2
- package/dist/bus-OdRJVUzr.cjs.map +0 -1
- package/dist/constants-B6kdsCzF.js +0 -75
- package/dist/constants-B6kdsCzF.js.map +0 -1
- package/dist/constants-DZH04585.cjs +0 -2
- package/dist/constants-DZH04585.cjs.map +0 -1
- package/dist/errors-DPju_xSI.cjs.map +0 -1
- package/dist/errors-Dme9tz-6.js.map +0 -1
- package/dist/indexeddb-storage-lGdoHGHy.cjs +0 -2
- package/dist/indexeddb-storage-lGdoHGHy.cjs.map +0 -1
- package/dist/indexeddb-storage-nxs_rxGx.js.map +0 -1
- package/dist/interactions-C1romMpE.js.map +0 -1
- package/dist/interactions-DP0-rIPJ.cjs.map +0 -1
- package/dist/network-DDVIJSHd.cjs +0 -2
- package/dist/network-DDVIJSHd.cjs.map +0 -1
- package/dist/network-au-Tqt1n.js.map +0 -1
- package/dist/platform-DMYo3AX3.js.map +0 -1
- package/dist/platform-g99Kn755.cjs +0 -2
- package/dist/platform-g99Kn755.cjs.map +0 -1
- package/dist/sampling-ByI5H44E.js.map +0 -1
- package/dist/sampling-Dui-Fp3u.cjs +0 -2
- package/dist/sampling-Dui-Fp3u.cjs.map +0 -1
- package/dist/sender-R7lOpyNc.js.map +0 -1
- package/dist/sender-vLcbQhiB.cjs +0 -3
- package/dist/sender-vLcbQhiB.cjs.map +0 -1
- package/dist/web-vitals-DM2nvcMJ.cjs +0 -2
- package/dist/web-vitals-DM2nvcMJ.cjs.map +0 -1
- package/dist/web-vitals-DwWdLBq6.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-ByI5H44E.js","names":["set","toJson","FNV_OFFSET_BASIS","FNV_PRIME","SESSION_ID_KEY","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","UINT32_MAX","TAB_ID_KEY","unrefTimer","nowUnixNano","isLogRecord","value","record","truncate","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","keys","count","error","bytes","i","BROWSER_STORES","memoryStores","wrap","localStore","sessionStore","randomHex","byteLength","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","withDeadline","expire","deadline","timer","ms","work","hash","h","readAttr","rateFor","config","best","bestLength","prefix","rate","rates","namespace","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/sanitize.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// Severity tables live in `src/constants.ts`.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape, converted to wire format by a serializer. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /** Time this library received the event, if different from `timeUnixNano` (e.g. on a forwarded record). */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. Only the sampled bit is used. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * Concatenates rather than multiplies: `Date.now() * 1e6` overflows\n * `Number.MAX_SAFE_INTEGER` and silently corrupts digits. Trailing zeros are\n * unknown precision, not real.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Used to validate records arriving from another realm, since a malformed\n * one throws during serialization. `severityText` is checked as a string,\n * not a known level, so an unrecognised level from a newer version still\n * passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Widened to `unknown` rather than asserted as `Partial<LogRecord>`, which\n // would tell the compiler these fields are never null and make the checks\n // below look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/sanitize.ts\n//\n// Sanitizes arbitrary data into JSON-safe structures with cycle detection and byte-size estimation.\n// Never throws. Never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(value: unknown, limits: SanitizeLimits): unknown {\n return sanitizeWithSize(value, limits).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(value: unknown, limits: SanitizeLimits): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0 };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Recursively walks object trees, replacing cyclic references, hostile getters, and invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits cannot bound a wide tree: 128 keys over 6 levels is\n // 128^6 values, all walked synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catches hostile getters and throwing proxies. One costs an attribute, not the\n // record.\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Removes object from ancestor set on unwind. Left in, a repeated sibling reads\n // as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. Storage\n// throws rather than returning null in a sandboxed iframe and in private mode. An\n// unguarded read takes the library down at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * Uses crypto.getRandomValues when available, falling back to Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @returns UUID or random hex identifier.\n */\nexport function newId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // Catches sandbox SecurityError throws when crypto.randomUUID is blocked. The\n // method is present; only the call fails.\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `reading ${store}Storage`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\"storage.unavailable\", `writing ${store}Storage`, () => {\n stores[store]().setItem(key, value);\n });\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId();\n const now = Date.now();\n\n let sessionId = newId();\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\"storage.degraded\", \"session record was not JSON, starting a new session\");\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId();\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`.\n * The throttle is instance state, not module state: two runtimes in one document\n * must not silence each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event, so its caller waits with it and holds the slot it took.\n\nimport { unrefTimer } from \"./unref\";\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`timed out after ${String(ms)}ms`));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Cleared on both paths. One armed timer for each storage call is waste.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// Deterministic record sampling based on namespace rules, journey IDs, and trace\n// IDs. Keyed on the journey, so one journey is kept or dropped whole. Stable\n// across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/**\n * Computes 32-bit FNV-1a hash of a string value. Not a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Safely extracts a string attribute value from a log record. Absent and non-string\n * both read as empty. A forwarded record has only passed a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * Resolves sampling rate for a namespace using longest-prefix matching, so\n * trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig): number {\n const { rates, defaultRate } = config.sampling;\n let best: number | undefined;\n let bestLength = -1;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > bestLength) {\n best = rate;\n bestLength = prefix.length;\n }\n }\n\n return best ?? defaultRate;\n}\n\n/** Everything sampling reads, all of it known before a record is built. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey id, empty when no journey is running. */\n journeyId: string;\n /** Trace id, the sampling key when no journey is running. */\n traceId: string;\n}\n\n/**\n * Evaluates whether an entry should be sampled for retention. Takes the fields\n * rather than a record, so the verdict is available before the attribute walk\n * a dropped entry must not pay for.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @returns True if the entry should be retained and transmitted.\n */\nexport function shouldSampleInput(input: SampleInput, config: ResolvedConfig): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n const rate = rateFor(input.namespace, config);\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Falls back to trace ID when journey ID is absent. The trace still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Evaluates whether a built log record should be sampled for retention. Used on\n * records that arrive already built, from a child context over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @returns True if the record should be retained and transmitted.\n */\nexport function shouldSample(record: LogRecord, config: ResolvedConfig): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n );\n}\n\n/**\n * Fixed-window ceiling on the ERROR and FATAL records that bypass sampling.\n *\n * Auto-captured errors are already limited inside ErrorCapture. This covers the\n * case nothing else does: application code calling logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the window currently counting, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Admits a record against the ceiling, counting only ERROR and FATAL.\n * @param record Record about to enter a stream.\n * @returns False when the window is spent and the record must be dropped.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Fixed window, not a sliding one: a quiet spell banks no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":";;;AAqDA,SAAgBW,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAWA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOC,KAAU,aAAYA,GAC/B,OAAO;CAKT,IAAMC,IAASD;CACf,OACE,OAAOC,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB;;;AC1CA,SAAgBC,EAAS,GAAe,GAAqB;CAC3D,IAAIF,EAAM,UAAUG,GAClB,OAAOH;CAKT,IAAMI,IAAMC,EAAgBL,EAAM,WAAWG,IAAM,CAAC,CAAC,IAAIA,IAAM,IAAIA;CACnE,OAAO,GAAGH,EAAM,MAAM,GAAGI,CAAG,EAAE,eAAe,OAAOJ,EAAM,SAASI,CAAG,EAAE;AAC1E;AAOA,SAASC,EAAgB,GAAuB;CAC9C,OAAOC,KAAA,SAA8BA,KAAA;AACvC;AAcA,SAASC,EAAa,GAAwB;CAO5C,OAAO,aANMC,EAAK,YAAY,OAAA,CAAQ,YAMnB,IALRA,EAAK,KAAK,IAAIA,EAAK,OAAO,KAEnC,OAAOA,EAAK,aAAc,YAAYA,EAAK,YACvC,IAAIA,EAAK,UAAU,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,GAAA,CAAuB,CAAC,CAAC,KAAK,GAAG,MAC9E,GAC4B;AACpC;AAwBA,SAAgBC,EAAS,GAAgB,GAAiC;CACxE,OAAOC,EAAiBV,GAAOW,CAAM,CAAC,CAAC;AACzC;AAQA,SAAgBD,EAA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EAAM,aAAaA,EAAM,OAEtB,IAAIlF,IAAa6E;AAClC;AASA,SAAgBM,EAAa,GAAmB,GAAiC;CAC/E,OAAOF,EACL;EACE,OAAO3E,EAAO;EACd,MAAMiE,EAASjE,GAAQR,CAAa;EACpC,WAAWyE,EAASjE,GAAQP,CAAkB;EAC9C,WAAWwE,EAASjE,GAAQT,CAAe;EAC3C,SAASS,EAAO;CAClB,GACAmE,CACF;AACF;AAQA,IAAaW,IAAb,MAA0B;CAExB,cAAsB;CAGtB,QAAgB;CAOhB,MAAM,GAA4B;EAChC,IAAI9E,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,SAC7D,OAAO;EAGT,IAAMiD,IAAM,KAAK,IAAI;EASrB,OAPIA,IAAM,KAAK,cAAA,QACb,KAAK,cAAcA,GACnB,KAAK,QAAQ,IAGf,KAAK,SAEE,KAAK,SAAA;CACd;AACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-DZH04585.cjs"),t=require("./unref-CU9Nyz_9.cjs");function n(){return`${String(Date.now())}000000`}function r(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}function i(e,t){if(e.length<=t)return e;let n=a(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function a(e){return e>=55296&&e<=56319}function o(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function s(e,t){return c(e,t).value}function c(e,t){let n={bytes:0,nodes:0};return{value:u(e,t,new WeakSet,0,n),bytes:n.bytes}}function l(e,t){return t.bytes+=d(e)+2,e}function u(e,t,n,r,a){if(a.nodes++,a.nodes>t.maxNodes)return l(`[MaxNodes]`,a);if(e==null)return a.bytes+=4,e;if(typeof e==`string`)return l(i(e,t.maxAttributeChars),a);if(typeof e==`number`)return a.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return a.bytes+=5,e;if(typeof e==`bigint`)return l(`${e.toString()}n`,a);if(typeof e==`symbol`)return l(e.toString(),a);if(typeof e==`function`)return l(`[Function ${e.name===``?`anonymous`:e.name}]`,a);if(r>=t.maxDepth)return l(`[MaxDepth]`,a);if(n.has(e))return l(`[Circular]`,a);n.add(e),a.bytes+=2;try{if(e instanceof Error)return{name:l(e.name,a),message:l(i(e.message,t.maxAttributeChars),a),stack:e.stack?l(i(e.stack,t.maxStackChars),a):void 0,cause:e.cause?u(e.cause,t,n,r+1,a):void 0};if(e instanceof Date)return l(e.toISOString(),a);if(e instanceof RegExp)return l(e.toString(),a);if(e instanceof Map){let i=e,o={},s=0;for(let[e,c]of i){if(s>=t.maxArrayLength){o[`…`]=l(`[${String(i.size-t.maxArrayLength)} more entries]`,a);break}s++;let f=String(e);a.bytes+=d(f)+4,o[f]=u(c,t,n,r+1,a)}return o}if(e instanceof Set)return u([...e].slice(0,t.maxArrayLength),t,n,r,a);if(ArrayBuffer.isView(e)){let t=e.length??0;return l(`[${e.constructor.name}(${String(t)})]`,a)}if(e instanceof Promise)return l(`[Promise]`,a);if(typeof Node<`u`&&e instanceof Node)return l(o(e),a);if(Array.isArray(e)){let i=e,o=i.slice(0,t.maxArrayLength).map(e=>u(e,t,n,r+1,a));return i.length>t.maxArrayLength&&o.push(l(`[${String(i.length-t.maxArrayLength)} more items]`,a)),o}let s=e.toJSON;if(typeof s==`function`)return u(s.call(e),t,n,r+1,a);let c=e,f=Object.keys(c),p={},m=0;for(let e of f){if(m>=t.maxAttributeCount){p[`…`]=l(`[${String(f.length-m)} more keys]`,a);break}m++,a.bytes+=d(e)+4,p[e]=u(c[e],t,n,r+1,a)}return p}catch(e){return l(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,a)}finally{n.delete(e)}}function d(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}var f={local:()=>localStorage,session:()=>sessionStorage};function p(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function m(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function h(){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return m(16)}function g(e,t,n,r){return r.guard(`storage.unavailable`,`reading ${t}Storage`,()=>e[t]().getItem(n))??null}function _(e,t,n,r,i){i.guard(`storage.unavailable`,`writing ${t}Storage`,()=>{e[t]().setItem(n,r)})}function v(t,n=f){let r=h(),i=Date.now(),a=h(),o=g(n,`local`,e.Ut,t);if(o)try{let e=JSON.parse(o);e.id&&i-(e.lastSeenAt??0)<18e5&&(a=e.id)}catch{t.report(`storage.degraded`,`session record was not JSON, starting a new session`)}let s=JSON.stringify({id:a,lastSeenAt:i});_(n,`local`,e.Ut,s,t);let c=g(n,`session`,`ui-observability.tab`,t)??``;return c||(c=h(),_(n,`session`,e.tn,c,t)),{sessionId:a,tabId:c,contextId:r}}function y(t,n,r){_(r,`session`,e.tn,t,n)}var b=class{diagnostics;stores;lastTouchAt=0;constructor(e,t=f){this.diagnostics=e,this.stores=t}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});_(this.stores,`local`,e.Ut,r,this.diagnostics)}};function x(e,n){let r,i=new Promise((e,i)=>{let a=setTimeout(()=>{i(Error(`timed out after ${String(n)}ms`))},n);r=a,t.t(a)});return Promise.race([e,i]).finally(()=>{clearTimeout(r)})}function S(t){let n=e.H;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.U);return n>>>0}function C(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function w(e,t){let{rates:n,defaultRate:r}=t.sampling,i,a=-1;for(let[t,r]of Object.entries(n))(e===t||e.startsWith(`${t}.`))&&t.length>a&&(i=r,a=t.length);return i??r}function T(t,n){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let r=w(t.namespace,n);return r>=1?!0:r<=0?!1:S(t.journeyId||t.traceId)/e.sn<r}function E(t,n){return T({level:t.severityText,type:C(t,e.l),namespace:C(t,e.n),journeyId:C(t,e.a),traceId:t.traceId},n)}var D=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return m}});
|
|
2
|
-
//# sourceMappingURL=sampling-Dui-Fp3u.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-Dui-Fp3u.cjs","names":["set","toJson","SESSION_ID_KEY","TAB_ID_KEY","FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","require_constants","require_unref","nowUnixNano","isLogRecord","value","record","truncate","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","keys","count","error","bytes","i","BROWSER_STORES","memoryStores","wrap","localStore","sessionStore","randomHex","byteLength","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","withDeadline","expire","deadline","timer","reject","ms","work","hash","h","readAttr","rateFor","config","best","bestLength","prefix","rate","rates","namespace","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/sanitize.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// Severity tables live in `src/constants.ts`.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape, converted to wire format by a serializer. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /** Time this library received the event, if different from `timeUnixNano` (e.g. on a forwarded record). */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. Only the sampled bit is used. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * Concatenates rather than multiplies: `Date.now() * 1e6` overflows\n * `Number.MAX_SAFE_INTEGER` and silently corrupts digits. Trailing zeros are\n * unknown precision, not real.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Used to validate records arriving from another realm, since a malformed\n * one throws during serialization. `severityText` is checked as a string,\n * not a known level, so an unrecognised level from a newer version still\n * passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Widened to `unknown` rather than asserted as `Partial<LogRecord>`, which\n // would tell the compiler these fields are never null and make the checks\n // below look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/sanitize.ts\n//\n// Sanitizes arbitrary data into JSON-safe structures with cycle detection and byte-size estimation.\n// Never throws. Never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(value: unknown, limits: SanitizeLimits): unknown {\n return sanitizeWithSize(value, limits).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(value: unknown, limits: SanitizeLimits): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0 };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Recursively walks object trees, replacing cyclic references, hostile getters, and invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits cannot bound a wide tree: 128 keys over 6 levels is\n // 128^6 values, all walked synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catches hostile getters and throwing proxies. One costs an attribute, not the\n // record.\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Removes object from ancestor set on unwind. Left in, a repeated sibling reads\n // as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. Storage\n// throws rather than returning null in a sandboxed iframe and in private mode. An\n// unguarded read takes the library down at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * Uses crypto.getRandomValues when available, falling back to Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @returns UUID or random hex identifier.\n */\nexport function newId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // Catches sandbox SecurityError throws when crypto.randomUUID is blocked. The\n // method is present; only the call fails.\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `reading ${store}Storage`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\"storage.unavailable\", `writing ${store}Storage`, () => {\n stores[store]().setItem(key, value);\n });\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId();\n const now = Date.now();\n\n let sessionId = newId();\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\"storage.degraded\", \"session record was not JSON, starting a new session\");\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId();\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`.\n * The throttle is instance state, not module state: two runtimes in one document\n * must not silence each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event, so its caller waits with it and holds the slot it took.\n\nimport { unrefTimer } from \"./unref\";\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`timed out after ${String(ms)}ms`));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Cleared on both paths. One armed timer for each storage call is waste.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// Deterministic record sampling based on namespace rules, journey IDs, and trace\n// IDs. Keyed on the journey, so one journey is kept or dropped whole. Stable\n// across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/**\n * Computes 32-bit FNV-1a hash of a string value. Not a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Safely extracts a string attribute value from a log record. Absent and non-string\n * both read as empty. A forwarded record has only passed a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * Resolves sampling rate for a namespace using longest-prefix matching, so\n * trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig): number {\n const { rates, defaultRate } = config.sampling;\n let best: number | undefined;\n let bestLength = -1;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > bestLength) {\n best = rate;\n bestLength = prefix.length;\n }\n }\n\n return best ?? defaultRate;\n}\n\n/** Everything sampling reads, all of it known before a record is built. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey id, empty when no journey is running. */\n journeyId: string;\n /** Trace id, the sampling key when no journey is running. */\n traceId: string;\n}\n\n/**\n * Evaluates whether an entry should be sampled for retention. Takes the fields\n * rather than a record, so the verdict is available before the attribute walk\n * a dropped entry must not pay for.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @returns True if the entry should be retained and transmitted.\n */\nexport function shouldSampleInput(input: SampleInput, config: ResolvedConfig): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n const rate = rateFor(input.namespace, config);\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Falls back to trace ID when journey ID is absent. The trace still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Evaluates whether a built log record should be sampled for retention. Used on\n * records that arrive already built, from a child context over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @returns True if the record should be retained and transmitted.\n */\nexport function shouldSample(record: LogRecord, config: ResolvedConfig): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n );\n}\n\n/**\n * Fixed-window ceiling on the ERROR and FATAL records that bypass sampling.\n *\n * Auto-captured errors are already limited inside ErrorCapture. This covers the\n * case nothing else does: application code calling logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the window currently counting, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Admits a record against the ceiling, counting only ERROR and FATAL.\n * @param record Record about to enter a stream.\n * @returns False when the window is spent and the record must be dropped.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Fixed window, not a sliding one: a quiet spell banks no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":"8EAqDA,SAAgBY,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAWA,SAAgBC,EAAY,EAAoC,CAC9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A,IAAaW,EAAb,KAA0B,CAExB,YAAsB,EAGtB,MAAgB,EAOhB,MAAM,EAA4B,CAChC,GAAI/E,EAAO,eAAiB,SAAWA,EAAO,eAAiB,QAC7D,MAAO,GAGT,IAAMiD,EAAM,KAAK,IAAI,EASrB,OAPIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,MAAQ,GAGf,KAAK,QAEE,KAAK,OAAA,GACd,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sender-R7lOpyNc.js","names":["keyFor","items","nested","STORAGE_NAME_NONE","CONTENT_TYPE_TEXT_PLAIN","RETRY_BASE_DELAY_MS","HEADER_ATTEMPT","ECS_LEVEL_NAMES","RETRY_IDLE_DELAY_MS","HEADER_CONTENT_TYPE","STORAGE_LIMITS","HEADER_BATCH_ID","STORAGE_DB_NAME","RETRY_MAX_DELAY_MS","CONTENT_TYPE_JSON","RESOURCE_SERVICE_NAME","STORAGE_NAME_MEMORY","EMERGENCY_STORAGE_KEY_PREFIX","RESOURCE_BROWSER_USER_AGENT","SERIALIZER_NAME_OTLP","HEADER_RETRY_AFTER","STORAGE_NAME_LOCAL","QUERY_PARAM_BATCH_ID","STORAGE_PROBE_KEY","NANOS_PATTERN","TELEMETRY_SDK_VERSION","CONTENT_TYPE_NDJSON","RESOURCE_SERVICE_VERSION","ATTR_LOG_TYPE","METRIC_FLUSH_INTERVAL_MS","LOG_FLUSH_INTERVAL_MS","NANOS_PER_MILLI","HEADER_CONTENT_ENCODING","STORAGE_DEADLINE_MS","TELEMETRY_SDK_NAME","LOG_TYPE_METRIC","MILLIS_PER_SECOND","BATCH_STORAGE_KEY_PREFIX","QUERY_PARAM_EXIT_REASON","RESOURCE_DEPLOYMENT_ENVIRONMENT","REQUEST_TIMEOUT_MS","ENCODING_GZIP","nowUnixNano","newId","estimateBytes","withDeadline","ErrorCeiling","unrefTimer","isLogBatch","value","id","createdAt","attempts","records","splitBatch","batch","middle","halve","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","keysWithPrefix","out","i","key","prefix","keyFor$1","at","readBatch","parsed","raw","importAll","moved","storage","error","saveToEmergencyQueue","context","keys","old","drainEmergencyQueue","keyFor","createdAtOf","start","LocalStorageStorage","limits","onGap","limit","cutoff","result","drop","alive","excess","stored","countRecords","batches","total","MemoryStorage","found","expired","evicted","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","IndexedDbStorage","dbName","toMillis","timeUnixNano","toLabelValue","pushLabel","existing","labels","flattenLabel","scalar","seen","item","entry","toLabels","source","ecsSerializer","millis","record","toAnyValue","toKeyValues","resourceKeys","resourceKey","cached","resource","otlpSerializer","groups","group","resourceLogs","serializerFor","choice","ExitFlush","deps","me","url","reason","serialized","target","outcome","endpoint","nav","body","config","gzip","CS","stream","text","buffer","TransportError","message","kind","status","retryAfterMs","maxBytes","parseRetryAfter","header","seconds","date","HttpTransport","headers","response","controller","timer","online","throttled","RetryEngine","transport","batchesPerDrain","parts","part","delayMs","work","exponential","failure","halves","isMetric","STREAM_OPTIONS","RecordStream","options","onFlush","LogPipeline","retry","flush","streamOptions","inFlight","throttledMs","Sender","pipeline","exitFlush","started"],"sources":["../src/models/batch.ts","../src/utils/lock.ts","../src/storage/keys.ts","../src/storage/emergency-queue.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp.ts","../src/transport/serializers/select.ts","../src/transport/exit-flush.ts","../src/transport/compression.ts","../src/transport/errors.ts","../src/transport/http-transport.ts","../src/transport/retry-engine.ts","../src/core/pipeline.ts","../src/core/sender.ts"],"sourcesContent":["// src/models/batch.ts\n//\n// A batch of log records for delivery to the ingest endpoint.\n\nimport { newId } from \"../utils/identity\";\nimport type { LogRecord } from \"./log-record\";\n\n/**\n * A batch of records with a stable id used for server-side deduplication across retries.\n * @see {@link splitBatch}\n */\nexport interface LogBatch {\n /** Deduplication key. Stable across retries and reloads. */\n id: string;\n /** Records to deliver, in log order. */\n records: LogRecord[];\n /** Batch creation time, in epoch milliseconds. */\n createdAt: number;\n /** Delivery attempts so far. */\n attempts: number;\n}\n\n/**\n * Whether a value parsed out of storage carries the whole batch contract. An entry\n * missing `id` is never matched by `keyOf` after delivery, so it is retried forever\n * and blocks every batch behind it. One missing `attempts` counts as NaN, never\n * reaches `maxAttempts`, and is never dead-lettered.\n * @param value Parsed storage entry.\n * @returns True when every required field is present and correctly typed.\n */\nexport function isLogBatch(value: unknown): value is LogBatch {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const id: unknown = Reflect.get(value, \"id\");\n const createdAt: unknown = Reflect.get(value, \"createdAt\");\n const attempts: unknown = Reflect.get(value, \"attempts\");\n const records: unknown = Reflect.get(value, \"records\");\n\n return (\n typeof id === \"string\" &&\n typeof createdAt === \"number\" &&\n typeof attempts === \"number\" &&\n Array.isArray(records)\n );\n}\n\n/**\n * Splits a batch the server rejected as too large into two halves.\n * Each half gets a fresh id; age and attempts carry over unchanged.\n * @param batch The rejected batch.\n * @returns Two batches, or `null` if a single record is already over the limit.\n */\nexport function splitBatch(batch: LogBatch): [LogBatch, LogBatch] | null {\n if (batch.records.length < 2) {\n return null;\n }\n\n const middle = Math.floor(batch.records.length / 2);\n const halve = (records: LogRecord[]): LogBatch => ({\n id: newId(),\n records,\n createdAt: batch.createdAt,\n attempts: batch.attempts,\n });\n\n return [halve(batch.records.slice(0, middle)), halve(batch.records.slice(middle))];\n}\n","// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without it every window on the origin drains and sends the same batches\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object or null if lock acquisition was unavailable. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback executed with lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * Falls back to direct execution in environments without Web Locks support.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy Skips execution if lock is currently held by another context.\n * @returns Promise resolving to the task result, or undefined if the lock was held\n * and nothing ran. A caller that conflates the two stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Falls back to unguarded execution if Web Locks API is unavailable.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\"storage.degraded\", `acquiring lock ${name}`, () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n","// src/storage/keys.ts\n//\n// Enumerates and filters sorted localStorage keys matching a prefix. A sandboxed\n// frame and private mode throw on first access rather than returning null.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/**\n * Returns all sorted localStorage keys matching the specified prefix.\n * @param prefix Storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns Sorted array of matching storage keys.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\"storage.unavailable\", \"enumerating localStorage\", () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) is typed string | null but cannot be null below length.\n // A null check here is a branch no test can reach.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n });\n\n return out.sort();\n}\n","// src/storage/emergency-queue.ts\n//\n// Synchronous localStorage queue parking oversized batches during unload for startup recovery.\n// Synchronous and never throws. Runs while the document is being destroyed, where\n// no promise settles.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with zero-padded creation time for FIFO sorting.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${EMERGENCY_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/**\n * Parses and validates a raw storage string into a LogBatch object.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"an emergency entry was not JSON and was dropped\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\"storage.degraded\", \"an emergency entry was not a batch and was dropped\");\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target storage adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(storage: StorageAdapter, diagnostics: Diagnostics): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics)) {\n // Atomically removes key before async persistence to prevent duplicate recovery.\n // A second window importing at the same time cannot take the same batch.\n const raw = diagnostics.guard(\"storage.unavailable\", \"reading the emergency queue\", () => {\n const value = localStorage.getItem(key);\n localStorage.removeItem(key);\n return value;\n });\n\n if (!raw) {\n continue;\n }\n\n const batch = readBatch(raw, diagnostics);\n if (batch === null) {\n continue;\n }\n\n try {\n // Bounded: this runs during startup. A save that does not settle keeps the\n // runtime not ready, and each record then goes to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"an emergency batch could not be recovered\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Synchronously writes an unsent batch to the emergency queue during document unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n */\nexport function saveToEmergencyQueue(batch: LogBatch, diagnostics: Diagnostics): void {\n // Names the record count, because a full localStorage drops this batch for good:\n // evicting emergency keys cannot free quota another application's keys are using.\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n\n diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics);\n\n // Evicts oldest entries to enforce capacity ceiling.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n });\n}\n\n/**\n * Recovers batches parked in emergency storage during prior shutdowns.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise resolving to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n): Promise<number> {\n const moved = await withDrainLock(\n EMERGENCY_LOCK_NAME,\n diagnostics,\n () => importAll(storage, diagnostics),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n","// src/storage/local-storage.ts\n//\n// Persistent synchronous storage adapter backed by localStorage using time-ordered\n// keys. The padding makes keys().sort() a sort by creation time. Unpadded it sorts\n// by hex and take() stops returning the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with zero-padded creation time for FIFO key sorting. Always\n * from batch.createdAt, never Date.now(). A rebuilt key does not match the one\n * written.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${BATCH_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after each save. Read\n * from the batch, this field costs one parse of the full store for each save.\n * @param key Prefixed storage key.\n * @returns Creation time in epoch milliseconds, or null if the key is malformed.\n */\nfunction createdAtOf(key: string): number | null {\n const start = BATCH_STORAGE_KEY_PREFIX.length;\n const at = Number(key.slice(start, start + BATCH_KEY_TIME_WIDTH));\n\n return Number.isFinite(at) ? at : null;\n}\n\n/** Persistent StorageAdapter implementation backed by localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\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 private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Persists a batch to localStorage, evicting oldest entries on quota errors.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n if (this.write(batch, \"localStorage refused a batch, evicting the oldest\")) {\n await this.prune();\n return;\n }\n\n this.evictForQuota();\n\n // The eviction exists to make room for this batch. Without a second attempt\n // save() resolves while the batch is gone and uncounted.\n if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n }\n\n /**\n * Retrieves up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // Corrupt and unrecoverable. Dropped without counting a gap: no record count\n // can be read from it.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Deletes a batch from localStorage by batch ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Updates delivery attempt count for a stored batch without changing its key.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\"storage.degraded\", \"updating attempts\", () => {\n localStorage.setItem(key, JSON.stringify(batch));\n });\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches and evicts oldest entries exceeding capacity limits.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n // Parses only the batches it deletes. The record count is the one field the\n // key does not carry.\n const drop = (key: string): void => {\n const batch = this.read(key);\n this.removeKey(key);\n result.batches++;\n result.records += batch?.records.length ?? 0;\n };\n\n const alive: string[] = [];\n\n for (const key of this.keys()) {\n const createdAt = createdAtOf(key);\n // A key with no readable time also has no position in the sort order.\n if (createdAt === null || createdAt < cutoff) {\n drop(key);\n continue;\n }\n alive.push(key);\n }\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n for (const key of alive.slice(0, excess)) {\n drop(key);\n }\n }\n\n this.reportGap(result);\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns total count of stored batch keys without deserialization.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** Deletes all matching batch keys from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** No-op storage teardown method. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Writes a batch to localStorage.\n * @param batch Batch to store.\n * @param context Description reported if the write is refused.\n * @returns True if the write succeeded.\n */\n private write(batch: LogBatch, context: string): boolean {\n const written = this.diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** Drops the oldest quarter of the store to free quota, counting the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n\n for (const key of keys.slice(0, Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR))) {\n const stored = this.read(key);\n this.removeKey(key);\n result.batches++;\n result.records += stored?.records.length ?? 0;\n }\n\n this.reportGap(result);\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Eviction 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 * Deserializes and validates a stored batch from a key.\n * @param key Storage key to read.\n * @returns Validated LogBatch or null if missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\"storage.unavailable\", \"reading a stored batch\", () =>\n localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"a stored batch was corrupt and was removed\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. Reporting again here would\n // count one corrupt entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\"storage.degraded\", \"a stored entry was not a batch and was dropped\");\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Resolves storage key containing the specified batch ID suffix.\n * @param id Batch identifier.\n * @returns Matching storage key string or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes an array of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes a single storage key with error guarding.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\"storage.degraded\", \"removing a stored batch\", () => {\n localStorage.removeItem(key);\n });\n }\n\n /**\n * Returns all sorted batch storage keys matching prefix.\n * @returns Sorted array of storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(BATCH_STORAGE_KEY_PREFIX, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// In-memory fallback storage adapter for volatile batch retention during offline\n// periods. A reload loses everything here. Last resort adapter.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\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/** In-memory StorageAdapter implementation retaining batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** Internal array holding batches in chronological FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch to memory storage and applies retention pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n this.batches.push(batch);\n await this.prune();\n }\n\n /**\n * Retrieves up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Deletes a batch from memory storage by batch ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\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 bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity limits.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n result.batches += expired.length;\n result.records += countRecords(expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n const evicted = this.batches.slice(0, excess);\n this.batches = this.batches.slice(excess);\n result.batches += evicted.length;\n result.records += countRecords(evicted);\n }\n\n if (result.batches > 0) {\n this.onGap?.(result);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** Clears all stored batches from memory. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** Clears stored batches on storage teardown. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// Factory resolving storage adapters with graceful degradation from IndexedDB to localStorage to memory.\n// Degrades rather than throwing. IndexedDB is unavailable in private mode and\n// sandboxed frames.\n\nimport {\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * No-op storage adapter returned when persistence strategy is \"none\". Every method\n * resolves. A sender calling close() on shutdown must not crash.\n */\nconst noop: StorageAdapter = {\n name: STORAGE_NAME_NONE,\n save: () => Promise.resolve(),\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n};\n\n/**\n * Evaluates whether IndexedDB is accessible in the current execution context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\"storage.unavailable\", \"reading indexedDB\", () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n });\n\n return available === true;\n}\n\n/**\n * Tests whether localStorage is accessible and accepts write operations.\n * @param diagnostics Diagnostics reporter.\n * @returns True if localStorage probe write succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\"storage.unavailable\", \"probing localStorage\", () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n });\n\n return usable === true;\n}\n\n/**\n * Instantiates the requested storage adapter, degrading gracefully if dependencies are unavailable.\n * @param strategy Configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns Promise resolving to the selected StorageAdapter instance.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop;\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // Dynamically imports IndexedDbStorage to omit storage drivers from main\n // bundle. A chunk that fails to load degrades to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"opening IndexedDB\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Opened here, not on first use. Private mode, a corrupt profile and\n // some WebViews define indexedDB and then reject open(). Only a\n // rejection in this block selects the next adapter.\n await storage.open();\n return storage;\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB was asked for by name and is unavailable, using memory\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(limits, diagnostics, onGap);\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"no persistent storage available, offline logs are memory only\",\n );\n return new MemoryStorage(limits, onGap);\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches into Elastic Common Schema (ECS) formatted newline-delimited JSON.\n\nimport {\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record forwarded over\n * the bus has only passed a shape check, and BigInt throws a SyntaxError on a\n * non-numeric string, which loses the whole batch instead of one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input is not numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Value forms Elasticsearch maps under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value into its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt, which loses the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label, folding a repeated key into an array. Elasticsearch reads a\n * repeated leaf as one multi-valued field, which is how an array of objects maps.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map; a nested\n * object under it trips Elasticsearch dynamic mapping.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects, so a cycle cannot recurse forever.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has only passed a shape check, so its attributes can hold a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Removes the object on unwind, so a repeated sibling does not read as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Null prototype: an attribute named `__proto__` must become a key, not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/** Serializer formatting log records into Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** Format identifier name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes an array of log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n log: { level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase() },\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // Prefers request URL over ambient page URL for captured network events.\n url: {\n full: record.attributes[ATTR_URL_FULL] ?? record.attributes[ATTR_PAGE_URL],\n },\n // Attributes last: a record attribute overrides the resource key of the same name.\n labels: { ...toLabels(record.resource), ...toLabels(record.attributes) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp.ts\n//\n// Serializes log batches into OpenTelemetry (OTLP/JSON) formatted log records grouped by resource.\n\nimport {\n CONTENT_TYPE_JSON,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** OTLP AnyValue container with typed value wrappers. */\ntype AnyValue = Record<string, unknown>;\n\n/** OTLP KeyValue pair container. */\ninterface KeyValue {\n /** Attribute key. */\n key: string;\n /** Typed AnyValue container. */\n value: AnyValue;\n}\n\n/** Records grouped by shared resource attributes. */\ninterface ResourceGroup {\n /** Resource attribute map. */\n resource: Record<string, unknown>;\n /** Log records associated with the resource. */\n records: LogRecord[];\n}\n\n/**\n * Wraps a JavaScript value in an OTLP AnyValue container.\n * @param value Raw attribute or resource value.\n * @returns Typed AnyValue object or null if unsupported.\n */\nfunction toAnyValue(value: unknown): AnyValue | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\") {\n return { stringValue: value };\n }\n\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n\n // Encodes int64 as decimal strings per OTLP protobuf JSON specification. A number\n // is a silent 400 from a conforming collector.\n if (typeof value === \"number\") {\n return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n }\n\n // Converts BigInt to decimal string representation for JSON serialization.\n // JSON.stringify throws on a BigInt and loses the batch.\n if (typeof value === \"bigint\") {\n return { intValue: value.toString() };\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const values = items.map(toAnyValue).filter((item): item is AnyValue => item !== null);\n\n return { arrayValue: { values } };\n }\n\n if (typeof value === \"object\") {\n const nested = value as Record<string, unknown>;\n return { kvlistValue: { values: toKeyValues(nested) } };\n }\n\n return null;\n}\n\n/**\n * Converts a plain object into an array of OTLP KeyValue pairs.\n * @param source Key-value attribute object.\n * @returns Array of valid KeyValue pairs.\n */\nfunction toKeyValues(source: Record<string, unknown>): KeyValue[] {\n const out: KeyValue[] = [];\n\n for (const [key, raw] of Object.entries(source)) {\n const value = toAnyValue(raw);\n if (value) {\n out.push({ key, value });\n }\n }\n\n return out;\n}\n\n/** Memoized JSON string keys per resource object to avoid redundant stringification. */\nconst resourceKeys = new WeakMap<object, string>();\n\n/**\n * Computes or retrieves a stable serialization key for a resource object.\n * @param resource Resource attribute object.\n * @returns JSON key string.\n */\nfunction resourceKey(resource: Record<string, unknown>): string {\n const cached = resourceKeys.get(resource);\n if (cached !== undefined) {\n return cached;\n }\n\n const key = JSON.stringify(resource);\n resourceKeys.set(resource, key);\n\n return key;\n}\n\n/** Serializer formatting log records into OTLP/JSON payloads. */\nexport const otlpSerializer: LogSerializer = {\n /** Format identifier name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups records by resource and encodes them into an OTLP ExportLogsServiceRequest JSON payload.\n * @param records Array of log records to serialize.\n * @returns Serialized JSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const groups = new Map<string, ResourceGroup>();\n\n for (const record of records) {\n const key = resourceKey(record.resource);\n const group = groups.get(key);\n\n if (group) {\n group.records.push(record);\n continue;\n }\n\n groups.set(key, { resource: record.resource, records: [record] });\n }\n\n const resourceLogs = [...groups.values()].map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeLogs: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n logRecords: group.records.map((record) => ({\n timeUnixNano: record.timeUnixNano,\n // Falls back to timeUnixNano if observedTimeUnixNano is unset.\n observedTimeUnixNano: record.observedTimeUnixNano ?? record.timeUnixNano,\n severityNumber: record.severityNumber,\n severityText: record.severityText,\n body: { stringValue: record.body },\n traceId: record.traceId,\n spanId: record.spanId,\n flags: record.traceFlags,\n attributes: toKeyValues(record.attributes),\n })),\n },\n ],\n }));\n\n return {\n body: JSON.stringify({ resourceLogs }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// Maps the serializer option to an implementation. Only transport code imports this\n// module. config.ts keeps the name, so the main chunk holds no serializer.\n\nimport type { SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n","// src/transport/exit-flush.ts\n//\n// Synchronous exit-flush handler delivering buffered batches via sendBeacon, keepalive fetch, or emergency storage.\n// Runs during unload. Nothing awaits.\n\nimport {\n BEACON_LIMIT_BYTES,\n CONTENT_TYPE_TEXT_PLAIN,\n HEADER_CONTENT_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport { saveToEmergencyQueue } from \"../storage/emergency-queue\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { serializerFor } from \"./serializers/select\";\n\n/** Document lifecycle event or manual action that triggered an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/**\n * The answer of the browser to a beacon. `refused` means the in-flight budget is\n * full. `unavailable` means the host has no usable sendBeacon.\n */\ntype BeaconOutcome = \"sent\" | \"refused\" | \"unavailable\";\n\n/** Structural interface for OpenFin window event subscription. */\ninterface FinMeLike {\n on?: (event: string, listener: () => void) => void;\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** Global environment extended with optional OpenFin runtime APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: { me?: FinMeLike } };\n\n/** Structural type for inspecting navigator.sendBeacon without restoring global DOM assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** Injected dependencies required by ExitFlush. */\nexport interface ExitFlushDeps {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Callback draining all pending buffered and unconfirmed batches into a single LogBatch. */\n drainForExit: () => LogBatch | null;\n /** Callback draining the buffered records only. An in-flight batch stays where it is. */\n drainPending: () => LogBatch | null;\n}\n\n/** Flushes pending telemetry on document unload using sendBeacon, keepalive fetch, or emergency storage. */\nexport class ExitFlush {\n /** Indicates whether unload listeners are currently active. */\n private installed = false;\n\n /** Handles visibilitychange events when the document becomes hidden. */\n private readonly onVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n this.flush(\"hidden\");\n }\n };\n\n /** Handles window pagehide events. */\n private readonly onPageHide = (): void => {\n this.flush(\"pagehide\");\n };\n\n /** Handles document freeze events. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** Handles OpenFin close-requested events. */\n private readonly onOpenFinClose = (): void => {\n this.flush(\"openfin-close\");\n };\n\n /**\n * @param deps Injected configuration, diagnostics, and drain callback.\n */\n constructor(private readonly deps: ExitFlushDeps) {}\n\n /** Attaches unload listeners across document, window, and OpenFin environments. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n if (typeof document !== \"undefined\") {\n // visibilitychange and freeze target the document; pagehide targets window.\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n document.addEventListener(\"freeze\", this.onFreeze);\n }\n\n addEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\"openfin.unavailable\", \"subscribing to close-requested\", () => {\n me?.on?.(\"close-requested\", this.onOpenFinClose);\n });\n }\n\n /** Removes all registered unload listeners and subscriptions. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", this.onVisibility);\n document.removeEventListener(\"freeze\", this.onFreeze);\n }\n\n removeEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\"openfin.unavailable\", \"releasing close-requested\", () => {\n me?.removeListener?.(\"close-requested\", this.onOpenFinClose);\n });\n }\n\n /**\n * Synchronously drains pending records and transmits via beacon, keepalive, or\n * emergency storage. Never awaits and never throws. The caller is an unload\n * listener.\n * @param reason Trigger reason code.\n */\n flush(reason: ExitReason): void {\n const { diagnostics } = this.deps;\n\n const url = this.endpointUrl();\n if (url === null) {\n return;\n }\n\n const batch = this.drain(reason);\n if (!batch || batch.records.length === 0) {\n return;\n }\n\n const serialized = diagnostics.guard(\n \"transport.serialize_failed\",\n `the ${reason} exit flush could not serialize its batch`,\n () => serializerFor(this.deps.config.serializer).serialize(batch.records),\n );\n if (!serialized) {\n return;\n }\n\n // Parks oversized payloads in synchronous localStorage queue. localStorage is\n // the only storage writable without awaiting.\n if (estimateBytes(serialized.body) > BEACON_LIMIT_BYTES) {\n saveToEmergencyQueue(batch, diagnostics);\n return;\n }\n\n // Passes batch ID and reason via query parameters. sendBeacon cannot set\n // headers.\n url.searchParams.set(QUERY_PARAM_BATCH_ID, batch.id);\n url.searchParams.set(QUERY_PARAM_EXIT_REASON, reason);\n\n const target = url.toString();\n const outcome = this.beacon(target, serialized.body);\n if (outcome === \"sent\") {\n return;\n }\n\n // A refusal means the in-flight budget is full. A keepalive fetch uses the\n // same budget and fails the same way. The document closes, so nothing retries.\n if (outcome === \"refused\") {\n saveToEmergencyQueue(batch, diagnostics);\n return;\n }\n\n this.keepaliveFetch(target, serialized.body, reason);\n }\n\n /**\n * Selects the drain for the reason. `hidden` occurs at each tab switch, and the\n * document continues to run. Taken here, an in-flight batch goes out a second\n * time under a new id, which the server cannot deduplicate.\n * @param reason Trigger reason code.\n * @returns Combined LogBatch, or null if no records are pending.\n */\n private drain(reason: ExitReason): LogBatch | null {\n return reason === \"hidden\" ? this.deps.drainPending() : this.deps.drainForExit();\n }\n\n /**\n * Resolves and parses the destination endpoint URL.\n * @returns URL instance or null if missing or invalid.\n */\n private endpointUrl(): URL | null {\n const { endpoint } = this.deps.config;\n if (!endpoint) {\n return null;\n }\n\n const url = this.deps.diagnostics.guard(\n \"config.invalid\",\n `the exit flush cannot use endpoint ${endpoint}`,\n () => new URL(endpoint),\n );\n\n return url ?? null;\n }\n\n /**\n * Attempts transmission via navigator.sendBeacon with text/plain payload.\n * @param url Target endpoint URL with query parameters.\n * @param body Serialized payload string.\n * @returns The answer of the browser.\n */\n private beacon(url: string, body: string): BeaconOutcome {\n const outcome = this.deps.diagnostics.guard<BeaconOutcome>(\n \"transport.http_error\",\n \"sendBeacon\",\n () => {\n // Invokes sendBeacon directly on navigator to preserve receiver context. A\n // detached sendBeacon throws on invocation.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return \"unavailable\";\n }\n\n // Uses text/plain to avoid CORS preflights during document unload. A preflight\n // started during unload rarely completes, dropping the beacon silently.\n const accepted = nav.sendBeacon(url, new Blob([body], { type: CONTENT_TYPE_TEXT_PLAIN }));\n return accepted ? \"sent\" : \"refused\";\n },\n );\n\n // A throw is not a refusal: the method is present but unusable. The keepalive\n // fetch can still succeed.\n return outcome ?? \"unavailable\";\n }\n\n /**\n * Fallback POST delivery using fetch with keepalive: true. keepalive outlives the\n * document. A plain fetch is cancelled as the page goes.\n * @param url Target endpoint URL.\n * @param body Serialized payload string.\n * @param reason Trigger reason code.\n */\n private keepaliveFetch(url: string, body: string, reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n diagnostics.guard(\"transport.http_error\", \"the keepalive fetch fallback\", () => {\n void fetch(url, {\n method: \"POST\",\n body,\n headers: { [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n credentials: config.credentials,\n keepalive: true,\n }).catch((error: unknown) => {\n diagnostics.report(\"transport.http_error\", \"the exit flush failed\", { reason }, error);\n });\n });\n }\n}\n","// src/transport/compression.ts\n//\n// Compresses payloads using the native CompressionStream API when available.\n// Returns null rather than raw text. A non-gzip body under Content-Encoding: gzip\n// is a 400 the server cannot explain.\n\nimport { ENCODING_GZIP } from \"../constants\";\n\n/**\n * Compresses a string into a gzip-encoded byte array using CompressionStream.\n * Returns non-shared ArrayBuffer backed Uint8Array compatible with fetch BodyInit.\n * @param text Raw serialized payload to compress.\n * @returns Promise resolving to compressed Uint8Array, or null if CompressionStream is unsupported.\n */\nexport async function gzip(text: string): Promise<Uint8Array<ArrayBuffer> | null> {\n const CS = (globalThis as { CompressionStream?: typeof CompressionStream }).CompressionStream;\n if (CS === undefined) {\n return null;\n }\n\n const stream = new Blob([text]).stream().pipeThrough(new CS(ENCODING_GZIP));\n const buffer = await new Response(stream).arrayBuffer();\n\n return new Uint8Array(buffer);\n}\n","// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses server Retry-After backoff headers.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * Failure classification determining retry, backoff, or drop behavior. transient,\n * offline and timeout retry with backoff. throttled waits the server's delay.\n * too_large splits the batch. permanent drops it: it will never be accepted.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** Error representing a failed transport attempt with failure classification and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n ) {\n super(message);\n this.name = \"TransportError\";\n }\n}\n\n/**\n * Parses HTTP Retry-After header value (seconds or HTTP date) into millisecond\n * delay. Both forms are legal. A date already past clamps to zero.\n * Clamps negative delays to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/http-transport.ts\n//\n// Serializes, compresses, and delivers log batches over HTTP with error\n// classification. Classifies, reports and throws. What happens to a rejected batch\n// belongs to the caller that owns storage.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_RETRY_AFTER,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REQUEST_TIMEOUT,\n HTTP_SERVER_ERROR_MIN,\n HTTP_SERVICE_UNAVAILABLE,\n HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED,\n REQUEST_TIMEOUT_MS,\n RETRY_BASE_DELAY_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { gzip } from \"./compression\";\nimport { parseRetryAfter, TransportError } from \"./errors\";\nimport { serializerFor } from \"./serializers/select\";\n\n/** HTTP transport delivering serialized log batches with header resolution, gzip compression, and error classification. */\nexport class HttpTransport {\n /** Timestamp in epoch milliseconds until which requests are throttled. */\n private throttledUntil = 0;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Delivers a single log batch over HTTP.\n * @param batch Batch to send.\n * @throws TransportError on transient, throttled, 413, or permanent network failures.\n */\n async send(batch: LogBatch): Promise<void> {\n const { endpoint } = this.config;\n\n if (!endpoint || batch.records.length === 0) {\n return;\n }\n\n await this.post(batch, endpoint);\n }\n\n /**\n * Returns the remaining throttle backoff duration in milliseconds.\n * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.\n */\n throttledForMs(): number {\n return Math.max(0, this.throttledUntil - Date.now());\n }\n\n /**\n * Serializes, encodes, and dispatches a batch, throwing a classified TransportError on failure.\n * @param batch Batch to deliver.\n * @param endpoint Ingest URL. The caller reads it one time. A reconfigure during the send cannot change it.\n */\n private async post(batch: LogBatch, endpoint: string): Promise<void> {\n const { config } = this;\n\n let serialized: SerializedBatch;\n try {\n serialized = serializerFor(config.serializer).serialize(batch.records);\n } catch (error) {\n this.diagnostics.report(\n \"transport.serialize_failed\",\n \"serializer threw, dropping the batch\",\n { batchId: batch.id },\n error,\n );\n return;\n }\n\n // Headers normalizes header names case-insensitively.\n const headers = new Headers(await this.resolveHeaders());\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n headers.set(HEADER_ATTEMPT, String(batch.attempts));\n\n const body = await this.encodeBody(serialized.body);\n if (typeof body !== \"string\") {\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n\n const response = await this.dispatch(endpoint, headers, body);\n if (response.ok) {\n this.throttledUntil = 0;\n return;\n }\n\n throw await this.classify(response, batch.id);\n }\n\n /**\n * Compresses the serialized payload if gzip compression is enabled and size exceeds threshold.\n * @param text Serialized payload string.\n * @returns Promise resolving to original string or compressed byte array.\n */\n private async encodeBody(text: string): Promise<string | Uint8Array<ArrayBuffer>> {\n const { config } = this;\n if (config.compression !== ENCODING_GZIP || estimateBytes(text) < COMPRESSION_THRESHOLD_BYTES) {\n return text;\n }\n\n const compressed = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"gzipping the payload\",\n () => gzip(text),\n );\n\n return compressed ?? text;\n }\n\n /**\n * Executes the HTTP POST request with timeout and network error mapping.\n * @param endpoint Ingest URL.\n * @param headers HTTP request headers.\n * @param body Request body string or byte array.\n * @returns Promise resolving to the HTTP Response.\n * @throws TransportError on network failure, timeout, or offline status.\n */\n private async dispatch(\n endpoint: string,\n headers: Headers,\n body: string | Uint8Array<ArrayBuffer>,\n ): Promise<Response> {\n const { config } = this;\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, REQUEST_TIMEOUT_MS);\n unrefTimer(timer);\n\n try {\n return await fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n signal: controller.signal,\n cache: \"no-store\",\n });\n } catch {\n if (controller.signal.aborted) {\n const waited = String(REQUEST_TIMEOUT_MS);\n throw new TransportError(\"timeout\", `request exceeded ${waited}ms`);\n }\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n throw new TransportError(online === false ? \"offline\" : \"transient\", \"network error\");\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Classifies an HTTP error response into a structured TransportError.\n * @param response Unsuccessful HTTP response.\n * @param batchId Identifier of the rejected batch.\n * @returns Classified TransportError instance.\n */\n private async classify(response: Response, batchId: string): Promise<TransportError> {\n const status = response.status;\n const retryAfterMs = parseRetryAfter(response.headers.get(HEADER_RETRY_AFTER));\n\n if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) {\n const advice =\n \"In a cross-origin iframe the session cookie is a third-party cookie and is very \" +\n \"likely blocked. Forward to the platform document instead of promoting to sender, \" +\n \"or issue the cookie with the Partitioned attribute.\";\n\n this.diagnostics.report(\n \"transport.rejected_credentials\",\n `server returned ${String(status)}. ${advice}`,\n { status, endpoint: this.config.endpoint },\n );\n // Permanent. Retrying a rejected credential forever blocks every batch behind\n // it.\n return new TransportError(\"permanent\", `rejected with ${String(status)}`, status);\n }\n\n if (status === HTTP_PAYLOAD_TOO_LARGE) {\n const maxBytes = await this.readMaxBytes(response);\n return new TransportError(\"too_large\", \"payload too large\", status, undefined, maxBytes);\n }\n\n if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_SERVICE_UNAVAILABLE) {\n const throttled = status === HTTP_TOO_MANY_REQUESTS;\n this.throttledUntil = Date.now() + (retryAfterMs ?? RETRY_BASE_DELAY_MS);\n\n if (throttled) {\n this.diagnostics.report(\"transport.throttled\", \"server throttled us\", {\n retryAfterMs,\n });\n }\n\n return new TransportError(\n \"throttled\",\n throttled ? \"throttled\" : \"service unavailable\",\n status,\n retryAfterMs,\n );\n }\n\n if (status === HTTP_REQUEST_TIMEOUT || status >= HTTP_SERVER_ERROR_MIN) {\n return new TransportError(\"transient\", `server error ${String(status)}`, status);\n }\n\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `server rejected the batch with ${String(status)}, dropping it`,\n { batchId, status },\n );\n return new TransportError(\"permanent\", `rejected with ${String(status)}`, status);\n }\n\n /**\n * Extracts optional maxBytes payload limit from a 413 response body.\n * @param response HTTP 413 Response instance.\n * @returns Promise resolving to maximum byte limit or undefined.\n */\n private async readMaxBytes(response: Response): Promise<number | undefined> {\n return this.diagnostics.guardAsync(\"transport.http_error\", \"reading the 413 body\", async () => {\n const parsed = JSON.parse(await response.text()) as {\n maxBytes?: unknown;\n };\n return typeof parsed.maxBytes === \"number\" ? parsed.maxBytes : undefined;\n });\n }\n\n /**\n * Evaluates configured static or dynamic request headers.\n * @returns Promise resolving to resolved header map.\n */\n private async resolveHeaders(): Promise<Record<string, string>> {\n const { headers } = this.config;\n if (!headers) {\n return {};\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const resolved = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"headers() threw\",\n () => Promise.resolve(headers()),\n );\n return resolved ?? {};\n }\n}\n","// src/transport/retry-engine.ts\n//\n// Scheduled background redelivery of stored log batches using jittered exponential\n// backoff. One timer, never a chain. Every scheduling path clears the pending\n// timer first.\n\nimport {\n BATCHES_PER_DRAIN,\n DRAIN_LOCK_NAME,\n RETRY_BASE_DELAY_MS,\n RETRY_IDLE_DELAY_MS,\n RETRY_MAX_DELAY_MS,\n STORAGE_DEADLINE_MS,\n STORAGE_LIMITS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type LogBatch, splitBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { TransportError } from \"./errors\";\nimport type { HttpTransport } from \"./http-transport\";\n\n/** Manages timed redelivery of persisted offline batches with backoff, lock coordination, and batch splitting. */\nexport class RetryEngine {\n /** Active retry timer handle or null if unreserved. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Consecutive failed delivery attempts for exponential backoff calculation. */\n private attempt = 0;\n\n /** Indicates whether a storage drain operation is actively executing. */\n private draining = false;\n\n /** Indicates whether the engine is stopped. */\n private stopped = false;\n\n /** Online event listener resetting attempts and scheduling immediate drain. */\n private readonly onOnline = (): void => {\n this.attempt = 0;\n this.schedule(0);\n };\n\n /**\n * @param storage Storage adapter holding undelivered batches.\n * @param transport HTTP transport for batch delivery.\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration instance.\n * @param batchesPerDrain Maximum batches processed per drain tick.\n */\n constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: HttpTransport,\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n private readonly batchesPerDrain = BATCHES_PER_DRAIN,\n ) {}\n\n /** Starts the retry engine, listens for online events, and arms the initial timer. */\n start(): void {\n this.stopped = false;\n\n if (typeof addEventListener !== \"undefined\") {\n addEventListener(\"online\", this.onOnline);\n }\n\n this.schedule(RETRY_IDLE_DELAY_MS);\n }\n\n /** Triggers an accelerated retry schedule when a new batch is stored offline. */\n nudge(): void {\n if (!this.draining) {\n this.schedule(RETRY_BASE_DELAY_MS);\n }\n }\n\n /**\n * Persists a batch that failed outside the drain loop, under the same rules the\n * drain applies. Storing it whole would spend another request on a payload the\n * server already refused.\n * @param batch Rejected batch, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n\n if (parts.length > 0) {\n this.nudge();\n }\n }\n\n /** Halts retry execution, removes listeners, and clears pending timers. */\n stop(): void {\n this.stopped = true;\n\n if (typeof removeEventListener !== \"undefined\") {\n removeEventListener(\"online\", this.onOnline);\n }\n\n this.clearTimer();\n }\n\n /**\n * Clears existing timers and schedules a new drain execution after a delay.\n * @param delayMs Delay duration in milliseconds.\n */\n private schedule(delayMs: number): void {\n if (this.stopped) {\n return;\n }\n\n this.clearTimer();\n\n const timer = setTimeout(() => {\n void this.drain();\n }, delayMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /**\n * Bounds a storage call. A call that does not settle keeps `draining` set, and\n * this window then runs no more drains.\n * @param work Storage promise to bound.\n * @returns The value of the promise, or a rejection after the deadline.\n */\n private bounded<T>(work: Promise<T>): Promise<T> {\n return withDeadline(work, STORAGE_DEADLINE_MS);\n }\n\n /** Clears the pending timer handle if active. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Computes jittered exponential backoff delay based on consecutive failures. Full\n * jitter, not a fixed offset. Tabs reconnecting together stampede otherwise.\n * @returns Backoff duration in milliseconds.\n */\n private backoffMs(): number {\n const exponential = Math.min(RETRY_BASE_DELAY_MS * 2 ** this.attempt, RETRY_MAX_DELAY_MS);\n\n return Math.random() * exponential;\n }\n\n /** Executes a drain operation protected by the origin-wide Web Lock. */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n const ran = await withDrainLock(DRAIN_LOCK_NAME, this.diagnostics, () => this.drainLocked());\n\n // undefined means the lock was held elsewhere. Without the reschedule, one\n // lost race retires this window.\n if (ran !== true) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n }\n } finally {\n this.draining = false;\n }\n }\n\n /**\n * Processes batches while holding the Web Lock and schedules subsequent ticks.\n * Always resolves. A throw leaves the engine idle with no timer armed.\n * @returns Promise resolving to true on completion.\n */\n private async drainLocked(): Promise<true> {\n try {\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n if (online === false) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return true;\n }\n\n const batches = await this.bounded(this.storage.take(this.batchesPerDrain));\n\n if (batches.length === 0) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return true;\n }\n\n for (const batch of batches) {\n if (this.stopped) {\n return true;\n }\n\n const done = await this.deliver(batch);\n if (!done) {\n return true;\n }\n }\n\n this.schedule(batches.length === this.batchesPerDrain ? 0 : RETRY_IDLE_DELAY_MS);\n return true;\n } catch (error) {\n this.diagnostics.report(\"storage.degraded\", \"the drain loop threw\", undefined, error);\n this.attempt++;\n this.schedule(this.backoffMs());\n return true;\n }\n }\n\n /**\n * Attempts delivery of a single batch, removing it on success or handling errors.\n * @param batch Log batch to deliver.\n * @returns True to continue processing next batch; false to halt current drain.\n */\n private async deliver(batch: LogBatch): Promise<boolean> {\n if (batch.attempts >= STORAGE_LIMITS.maxAttempts) {\n this.diagnostics.report(\n \"storage.dead_lettered\",\n `giving up on a batch after ${batch.attempts.toString()} attempts`,\n { batchId: batch.id, records: batch.records.length },\n );\n await this.bounded(this.storage.remove(batch.id));\n return true;\n }\n\n try {\n await this.transport.send(batch);\n await this.bounded(this.storage.remove(batch.id));\n this.attempt = 0;\n return true;\n } catch (error) {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\" || failure?.kind === \"too_large\") {\n await this.replaceStored(batch, error);\n return true;\n }\n\n if (failure?.kind === \"offline\") {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return false;\n }\n\n // A throttle rejects no records: the server asks for the batch later. An\n // attempt counted here dead-letters the batch after five throttled answers.\n if (failure?.kind === \"throttled\") {\n this.attempt++;\n this.schedule(failure.retryAfterMs ?? this.backoffMs());\n return false;\n }\n\n await this.bounded(this.storage.bumpAttempts(batch.id, batch.attempts + 1));\n this.attempt++;\n this.schedule(failure?.retryAfterMs ?? this.backoffMs());\n return false;\n }\n }\n\n /**\n * Replaces a stored batch with what survives its failure: the split halves, or\n * nothing when the server refuses the records for good.\n * @param batch Rejected log batch, already held in storage.\n * @param error Failure thrown by the transport.\n */\n private async replaceStored(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n await this.bounded(this.storage.remove(batch.id));\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n }\n\n /**\n * Decides what a failed batch leaves behind. A 413 splits in two, a permanent\n * refusal keeps nothing, and every other failure keeps the batch whole.\n * @param batch Rejected log batch.\n * @param error Failure thrown by the transport.\n * @returns Batches to persist, empty when the records are dropped.\n */\n private toStorable(batch: LogBatch, error: unknown): LogBatch[] {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\") {\n return [];\n }\n\n if (failure?.kind !== \"too_large\") {\n return [batch];\n }\n\n const halves = splitBatch(batch);\n\n if (!halves) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n \"a single record exceeds the server limit and was dropped\",\n {\n batchId: batch.id,\n bodies: batch.records.map((record) => record.body),\n },\n );\n return [];\n }\n\n this.diagnostics.report(\"transport.batch_split\", \"the server refused the batch as too large\", {\n from: batch.records.length,\n to: halves[0].records.length,\n serverMaxBytes: failure.maxBytes,\n });\n\n return halves;\n }\n}\n","// src/core/pipeline.ts\n//\n// Stream buffering, batch formation, and delivery for logs and metrics.\n//\n// Each stream owns its buffer and its own flush timer, so the exit flush can\n// take every record that has not reached the transport yet.\n\nimport {\n ATTR_LOG_TYPE,\n LOG_BATCH_SIZE,\n LOG_FLUSH_INTERVAL_MS,\n LOG_TYPE_METRIC,\n MAX_CONCURRENT_REQUESTS,\n METRIC_BATCH_SIZE,\n METRIC_FLUSH_INTERVAL_MS,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport { type LogRecord, nowUnixNano } from \"../models/log-record\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport type { HttpTransport } from \"../transport/http-transport\";\nimport type { RetryEngine } from \"../transport/retry-engine\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { ErrorCeiling } from \"./sampling\";\n\n/** Pipeline stream classification for logs versus metrics. */\nexport type StreamName = \"logs\" | \"metrics\";\n\n/**\n * Evaluates whether a log record is classified as a metric.\n * @param record Record to evaluate.\n * @returns True if the record log type attribute equals metric.\n */\nfunction isMetric(record: LogRecord): boolean {\n return record.attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC;\n}\n\n/** Batching policy for one record stream. */\nexport interface StreamOptions {\n /** Max time a partial batch waits before it is sent, in milliseconds. */\n flushIntervalMs: number;\n /** Max records per batch before it is sent early. */\n batchSize: number;\n}\n\n/** Batching policy per stream. Metrics batch harder: higher volume, nothing waits on them. */\nexport const STREAM_OPTIONS: Record<StreamName, StreamOptions> = {\n logs: { flushIntervalMs: LOG_FLUSH_INTERVAL_MS, batchSize: LOG_BATCH_SIZE },\n metrics: { flushIntervalMs: METRIC_FLUSH_INTERVAL_MS, batchSize: METRIC_BATCH_SIZE },\n};\n\n/** One stream's pending records and the timer that closes a partial batch. */\nclass RecordStream {\n /** Pending records waiting in chronological order. */\n private pending: LogRecord[] = [];\n\n /** Handle of the armed flush timer, or null when none is pending. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Batching policy for this stream.\n * @param onFlush Called with this stream when a batch is ready to close.\n */\n constructor(\n readonly options: StreamOptions,\n private readonly onFlush: (stream: RecordStream) => void,\n ) {}\n\n /**\n * Buffers a record, closing the batch at once on the batchSize-th and arming\n * the interval timer on the first. Without the timer a batch below batchSize\n * waits for the next record, which on a quiet page never comes.\n * @param record Record to enqueue.\n */\n add(record: LogRecord): void {\n this.pending.push(record);\n\n if (this.pending.length >= this.options.batchSize) {\n this.onFlush(this);\n return;\n }\n\n this.arm();\n }\n\n /**\n * Drains and returns all buffered records, disarming the flush timer.\n * @returns Array of buffered records.\n */\n take(): LogRecord[] {\n this.clearTimer();\n\n const records = this.pending;\n this.pending = [];\n\n return records;\n }\n\n /** Disarms the flush timer, leaving buffered records in place. */\n stop(): void {\n this.clearTimer();\n }\n\n /** Arms the flush timer unless one is already pending. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n const timer = setTimeout(() => {\n this.timer = null;\n this.onFlush(this);\n }, this.options.flushIntervalMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /** Clears the pending timer handle if armed. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n\n/** Pipeline orchestrating log and metric stream buffering, batch creation, and HTTP dispatch. */\nexport class LogPipeline {\n /** Buffer instances for logs and metrics streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** Unconfirmed in-flight batches tracked for exit flush recovery. */\n private readonly unconfirmed = new Map<string, LogBatch>();\n\n /** Closed batches waiting for a free dispatch slot. */\n private readonly queue: LogBatch[] = [];\n\n /** Ceiling on the ERROR and FATAL records that bypass sampling. */\n private readonly ceiling = new ErrorCeiling();\n\n /** Dispatches currently in flight, capped at MAX_CONCURRENT_REQUESTS. */\n private inFlight = 0;\n\n /** Indicates a pump is already queued, so one microtask drains a burst. */\n private pumpScheduled = false;\n\n /** Indicates whether the pipeline has been destroyed. */\n private stopped = false;\n\n /**\n * @param transport HTTP transport for live batch delivery.\n * @param storage Storage adapter for offline batch persistence.\n * @param retry Retry engine for redelivering persisted batches.\n * @param diagnostics Diagnostics reporter.\n * @param streamOptions Batching policy per stream.\n */\n constructor(\n private readonly transport: HttpTransport,\n private readonly storage: StorageAdapter,\n private readonly retry: RetryEngine,\n private readonly diagnostics: Diagnostics,\n streamOptions: Record<StreamName, StreamOptions> = STREAM_OPTIONS,\n ) {\n const flush = (stream: RecordStream): void => {\n this.claim(stream);\n };\n\n this.streams = {\n logs: new RecordStream(streamOptions.logs, flush),\n metrics: new RecordStream(streamOptions.metrics, flush),\n };\n }\n\n /**\n * Stamps observed timestamp and enqueues a record into the pipeline.\n * @param record Record to push.\n */\n push(record: LogRecord): void {\n if (this.stopped) {\n return;\n }\n\n record.observedTimeUnixNano = nowUnixNano();\n this.route(record);\n }\n\n /**\n * Drains the stream buffers into one batch. In-flight batches stay where they\n * are. They carry their own ids and are still on their way, so taking them here\n * resends every record under an id the server cannot deduplicate against.\n * @returns Combined LogBatch or null if no records are buffered.\n */\n drainPending(): LogBatch | null {\n return this.toBatch([...this.streams.metrics.take(), ...this.streams.logs.take()]);\n }\n\n /**\n * Atomically drains all buffered and unconfirmed in-flight records into a single\n * exit batch. Records already handed to fetch go out again under a new batch id,\n * so the server cannot deduplicate them and the exit flush can deliver duplicates.\n * A document being closed cannot confirm delivery, so this is by design.\n * @returns Combined LogBatch or null if no records are pending.\n */\n drainForExit(): LogBatch | null {\n const inFlight = [...this.unconfirmed.values()].flatMap((batch) => batch.records);\n this.unconfirmed.clear();\n\n return this.toBatch([...inFlight, ...this.streams.metrics.take(), ...this.streams.logs.take()]);\n }\n\n /** Stops the flush timers and refuses further records. */\n destroy(): void {\n this.stopped = true;\n this.streams.logs.stop();\n this.streams.metrics.stop();\n this.queue.length = 0;\n }\n\n /**\n * Wraps drained records in a batch.\n * @param records Records taken from the buffers, in delivery order.\n * @returns New LogBatch, or null when nothing was drained.\n */\n private toBatch(records: LogRecord[]): LogBatch | null {\n if (records.length === 0) {\n return null;\n }\n\n return { id: newId(), records, createdAt: Date.now(), attempts: 0 };\n }\n\n /**\n * Sorts a record into its stream. Sampling already ran, in RecordBuilder for a\n * local record and in the runtime for a forwarded one. Every fault is contained\n * here: a record carrying no `attributes` makes isMetric throw, and a throw\n * escaping this method would surface inside the caller's own log call.\n * @param record Record to sort.\n */\n private route(record: LogRecord): void {\n try {\n const stream = isMetric(record) ? this.streams.metrics : this.streams.logs;\n\n // ERROR and FATAL bypass sampling upstream, so this is the only limit\n // on them.\n if (!this.ceiling.allow(record)) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n\n stream.add(record);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"a record was dropped on its way into a stream\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Drains a stream buffer into a new batch and queues it for dispatch. The\n * buffer always holds at least one record here: a timer is armed only by a\n * push, and every `take` disarms the timer that would have called this.\n * @param stream Stream buffer to drain.\n */\n private claim(stream: RecordStream): void {\n const records = stream.take();\n\n const batch: LogBatch = {\n id: newId(),\n records,\n createdAt: Date.now(),\n attempts: 0,\n };\n this.unconfirmed.set(batch.id, batch);\n this.enqueue(batch);\n }\n\n /**\n * Queues a batch and schedules the pump on a microtask. Dispatching inline\n * would start a fetch inside the application's own log call.\n * @param batch Batch ready for delivery.\n */\n private enqueue(batch: LogBatch): void {\n this.queue.push(batch);\n\n if (this.pumpScheduled) {\n return;\n }\n\n this.pumpScheduled = true;\n queueMicrotask(() => {\n this.pumpScheduled = false;\n this.pump();\n });\n }\n\n /** Starts queued dispatches up to the concurrency limit. */\n private pump(): void {\n while (this.inFlight < MAX_CONCURRENT_REQUESTS) {\n const batch = this.queue.shift();\n if (!batch) {\n return;\n }\n\n this.inFlight++;\n void this.run(batch);\n }\n }\n\n /**\n * Delivers one batch and frees its concurrency slot.\n * @param batch Batch to deliver.\n */\n private async run(batch: LogBatch): Promise<void> {\n try {\n await this.dispatch(batch);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"dispatch rejected, which it is written never to do\",\n { batchId: batch.id },\n error,\n );\n } finally {\n this.inFlight--;\n this.pump();\n }\n }\n\n /**\n * Sends a batch over HTTP transport or persists it to offline storage if throttled or failed.\n * @param batch Batch to deliver.\n */\n private async dispatch(batch: LogBatch): Promise<void> {\n try {\n // Persists directly to storage while transport is throttled. Sending here\n // posts a batch every flush interval straight through the throttle.\n // Attempt count unchanged: nothing was sent.\n const throttledMs = this.transport.throttledForMs();\n if (throttledMs > 0) {\n await this.store(batch);\n this.diagnostics.report(\"transport.throttled\", \"stored the batch rather than sending it\", {\n batchId: batch.id,\n records: batch.records.length,\n throttledMs,\n });\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n // Increments attempt count before storing failed live send. Stored at 0,\n // the batch exceeds STORAGE_LIMITS.maxAttempts by one and attempt headers\n // under-report.\n await this.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n this.diagnostics.report(\n \"transport.http_error\",\n \"batch was stored for retry instead of being delivered\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n } finally {\n this.unconfirmed.delete(batch.id);\n }\n }\n\n /**\n * Persists a batch the transport refused, letting the retry engine split a 413\n * and drop what the server will never accept.\n * @param batch Batch to persist, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n private async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting an undelivered batch\",\n async () => {\n await this.retry.storeFailed(batch, error);\n },\n );\n }\n\n /**\n * Persists an undelivered batch to storage and triggers retry engine. Bounded:\n * a storage call that does not settle holds this dispatch slot. Two of them\n * stop the pipeline.\n * @param batch Batch to persist.\n */\n private async store(batch: LogBatch): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting an undelivered batch\",\n async () => {\n await withDeadline(this.storage.save(batch), STORAGE_DEADLINE_MS);\n this.retry.nudge();\n },\n );\n }\n}\n","// src/core/sender.ts\n//\n// Delivery stack of the sender role: storage, transport, retry, pipeline and exit flush.\n// The runtime imports this module dynamically, and only when an endpoint is set.\n// Console-only mode does not download it.\n\nimport { STORAGE_DB_NAME, STORAGE_LIMITS } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { GapReporter, StorageAdapter } from \"../models/storage\";\nimport { drainEmergencyQueue } from \"../storage/emergency-queue\";\nimport { createStorage } from \"../storage/factory\";\nimport { ExitFlush } from \"../transport/exit-flush\";\nimport { HttpTransport } from \"../transport/http-transport\";\nimport { RetryEngine } from \"../transport/retry-engine\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { LogPipeline } from \"./pipeline\";\n\n/** Inputs to build the delivery stack. */\nexport interface SenderDeps {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** Receives a report when storage drops batches before delivery. */\n onGap: GapReporter;\n}\n\n/** Delivery stack for one sender runtime. */\nexport class Sender {\n /**\n * @param storage Storage adapter for undelivered batches.\n * @param transport HTTP transport for live delivery.\n * @param retry Retry engine for stored batches.\n * @param pipeline Pipeline that batches records.\n * @param exitFlush Handler that sends pending records on unload.\n * @param diagnostics Diagnostics reporter.\n */\n private constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: HttpTransport,\n private readonly retry: RetryEngine,\n private readonly pipeline: LogPipeline,\n private readonly exitFlush: ExitFlush,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Builds the delivery stack, drains the emergency queue and starts the retry loop.\n * @param deps Configuration, diagnostics and gap reporter.\n * @returns Promise resolving to the started sender.\n */\n static async create(deps: SenderDeps): Promise<Sender> {\n const { config, diagnostics } = deps;\n\n const storage = await createStorage(\n config.storage,\n STORAGE_DB_NAME,\n STORAGE_LIMITS,\n diagnostics,\n deps.onGap,\n );\n const transport = new HttpTransport(config, diagnostics);\n const retry = new RetryEngine(storage, transport, diagnostics, config);\n const pipeline = new LogPipeline(transport, storage, retry, diagnostics);\n\n const exitFlush = new ExitFlush({\n config,\n diagnostics,\n drainForExit: () => pipeline.drainForExit(),\n drainPending: () => pipeline.drainPending(),\n });\n\n await drainEmergencyQueue(storage, diagnostics);\n\n // Stop both if one fails. A retry loop with no owner sends after the load reports a failure.\n let started = false;\n\n try {\n exitFlush.install();\n retry.start();\n started = true;\n } finally {\n if (!started) {\n exitFlush.uninstall();\n retry.stop();\n }\n }\n\n return new Sender(storage, transport, retry, pipeline, exitFlush, diagnostics);\n }\n\n /**\n * Adds a record to the pipeline.\n * @param record Record to deliver.\n */\n push(record: LogRecord): void {\n this.pipeline.push(record);\n }\n\n /**\n * Sends the records held in the stream buffers.\n * @returns Promise resolving when the batch is sent or stored for retry.\n */\n async flush(): Promise<void> {\n const batch = this.pipeline.drainPending();\n\n if (!batch) {\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting the batch drained by flush()\",\n // The retry engine classifies the failure. A 413 splits the batch here, as in the drain.\n async () => {\n await this.retry.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n },\n );\n this.diagnostics.report(\n \"transport.http_error\",\n \"the batch drained by flush() was stored for retry instead of being delivered\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n }\n\n /**\n * Counts the batches held in storage.\n * @returns Promise resolving to the batch count, or 0 if storage fails.\n */\n async queueDepth(): Promise<number> {\n const count = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"counting the batches waiting in storage\",\n () => this.storage.count(),\n );\n\n return count ?? 0;\n }\n\n /**\n * Sends pending records, stops every timer and listener, then closes storage.\n * The synchronous steps run before the first await. The runtime relies on this order.\n * @returns Promise resolving when storage is closed.\n */\n async destroy(): Promise<void> {\n this.exitFlush.flush(\"shutdown\");\n this.exitFlush.uninstall();\n this.retry.stop();\n this.pipeline.destroy();\n\n await this.storage.close();\n }\n}\n"],"mappings":";;;;AA8BA,SAAgBgD,EAAW,GAAmC;CAC5D,IAAI,OAAOC,KAAU,aAAYA,GAC/B,OAAO;CAGT,IAAMC,IAAc,QAAQ,IAAID,GAAO,IAAI,GACrCE,IAAqB,QAAQ,IAAIF,GAAO,WAAW,GACnDG,IAAoB,QAAQ,IAAIH,GAAO,UAAU,GACjDI,IAAmB,QAAQ,IAAIJ,GAAO,SAAS;CAErD,OACE,OAAOC,KAAO,YACd,OAAOC,KAAc,YACrB,OAAOC,KAAa,YACpB,MAAM,QAAQC,CAAO;AAEzB;AAQA,SAAgBC,EAAW,GAA8C;CACvE,IAAIC,EAAM,QAAQ,SAAS,GACzB,OAAO;CAGT,IAAMC,IAAS,KAAK,MAAMD,EAAM,QAAQ,SAAS,CAAC,GAC5CE,KAAS,OAAoC;EACjD,IAAId,EAAM;EACV;EACA,WAAWY,EAAM;EACjB,UAAUA,EAAM;CAClB;CAEA,OAA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KAAKA,CAAK;EACjC,SAASuB,GAAO;GASd,AARA,MAAM,KAAK,YAAY,WACrB,oBACA,2CAEA,YAAY;IACV,MAAM,KAAK,MAAM,YAAY;KAAE,GAAGvB;KAAO,UAAUA,EAAM,WAAW;IAAE,GAAGuB,CAAK;GAChF,CACF,GACA,KAAK,YAAY,OACf,wBACA,gFACA;IAAE,SAASvB,EAAM;IAAI,SAASA,EAAM,QAAQ;GAAO,GACnDuB,CACF;EACF;CACF;CAMA,MAAM,aAA8B;EAOlC,OAAO,MANa,KAAK,YAAY,WACnC,oBACA,iDACM,KAAK,QAAQ,MAAM,CAC3B,KAEgB;CAClB;CAOA,MAAM,UAAyB;EAM7B,AALA,KAAK,UAAU,MAAM,UAAU,GAC/B,KAAK,UAAU,UAAU,GACzB,KAAK,MAAM,KAAK,GAChB,KAAK,SAAS,QAAQ,GAEtB,MAAM,KAAK,QAAQ,MAAM;CAC3B;AACF"}
|
package/dist/sender-vLcbQhiB.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-DZH04585.cjs"),t=require("./sampling-Dui-Fp3u.cjs"),n=require("./unref-CU9Nyz_9.cjs");function r(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 i(e){if(e.records.length<2)return null;let n=Math.floor(e.records.length/2),r=n=>({id:t.c(),records:n,createdAt:e.createdAt,attempts:e.attempts});return[r(e.records.slice(0,n)),r(e.records.slice(n))]}function a(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 o(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 s(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.R}${n}.${t.id}`}function c(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:r(n)?n:(t.report(`storage.degraded`,`an emergency entry was not a batch and was dropped`),null)}async function l(n,r){let i=0;for(let a of o(e.R,r)){let o=r.guard(`storage.unavailable`,`reading the emergency queue`,()=>{let e=localStorage.getItem(a);return localStorage.removeItem(a),e});if(!o)continue;let s=c(o,r);if(s!==null)try{await t.i(n.save(s),e.qt),i++}catch(e){r.report(`storage.degraded`,`an emergency batch could not be recovered`,{key:a},e)}}return i}function u(t,n){let r=`writing the emergency queue, ${String(t.records.length)} records`;n.guard(`storage.quota_exceeded`,r,()=>{let r=o(e.R,n);for(let e of r.slice(0,Math.max(0,r.length-20+1)))localStorage.removeItem(e);localStorage.setItem(s(t),JSON.stringify(t))})}async function d(e,t){return await a(`ui-observability.emergency`,t,()=>l(e,t),{skipIfBusy:!1})??0}function f(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.v}${n}.${t.id}`}function p(t){let n=e.v.length,r=Number(t.slice(n,n+14));return Number.isFinite(r)?r:null}var m=class{limits;diagnostics;onGap;name=e.Zt;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){this.write(e,`localStorage refused a batch, evicting the oldest`)?await this.prune():(this.evictForQuota(),this.write(e,`localStorage refused a batch even after evicting`)||this.reportGap({batches:1,records:e.records.length,reason:`quota`}))}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);e===null?this.removeKey(n):t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null||(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`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=>{let n=this.read(e);this.removeKey(e),t.batches++,t.records+=n?.records.length??0},r=[];for(let t of this.keys()){let i=p(t);i===null||i<e?n(t):r.push(t)}let i=r.length-this.limits.maxBatches;if(i>0){t.reason=`over_capacity`;for(let e of r.slice(0,i))n(e)}return this.reportGap(t),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(e,t){return this.diagnostics.guard(`storage.quota_exceeded`,t,()=>(localStorage.setItem(f(e),JSON.stringify(e)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`};for(let n of e.slice(0,Math.ceil(e.length/4))){let e=this.read(n);this.removeKey(n),t.batches++,t.records+=e?.records.length??0}this.reportGap(t)}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(e.batches)} stored batches (${String(e.records)} records)`,{...e}),this.onGap?.(e))}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:r(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 o(e.v,this.diagnostics)}};function h(e){return e.reduce((e,t)=>e+t.records.length,0)}var g=class{limits;onGap;name=e.Qt;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+=h(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+=h(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()}},_={name:e.$t,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 v(e){return e.guard(`storage.unavailable`,`reading indexedDB`,()=>globalThis.indexedDB!=null)===!0}function y(t){return t.guard(`storage.unavailable`,`probing localStorage`,()=>(localStorage.setItem(e.en,`1`),localStorage.removeItem(e.en),!0))===!0}async function b(e,t,n,r,i){if(e===`none`)return _;if(e===`memory`)return new g(n,i);if(e===`indexeddb`||e===`auto`){if(v(r)){let e=await r.guardAsync(`storage.unavailable`,`opening IndexedDB`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-lGdoHGHy.cjs")),a=new e(t,n,r,i);return await a.open(),a});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB was asked for by name and is unavailable, using memory`),new g(n,i)}return y(r)?new m(n,r,i):(r.report(`storage.degraded`,`no persistent storage available, offline logs are memory only`),new g(n,i))}function x(t){return e.ft.test(t)?Number(BigInt(t)/e.pt):Date.now()}function S(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function C(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function w(e,t,n,r){let i=S(n);if(i!==null)C(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)w(e,t,i,r);else for(let[i,a]of Object.entries(n))w(e,`${t}.${i}`,a,r);r.delete(n)}}function T(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))w(t,r,i,n);return t}var E={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=x(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:e.I[t.severityText]??t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Ot],version:t.resource[e.kt],environment:t.resource[e.wt]},user_agent:{original:t.resource[e.St]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...T(t.resource),...T(t.attributes)}})}).join(`
|
|
2
|
-
`)}\n`,contentType:e.k}}};function D(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(D).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:O(e)}}:null}function O(e){let t=[];for(let[n,r]of Object.entries(e)){let e=D(r);e&&t.push({key:n,value:e})}return t}var k=new WeakMap;function A(e){let t=k.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return k.set(e,n),n}var j={name:e.Vt,serialize(t){let n=new Map;for(let e of t){let t=A(e.resource),r=n.get(t);r?r.records.push(e):n.set(t,{resource:e.resource,records:[e]})}let r=[...n.values()].map(t=>({resource:{attributes:O(t.resource)},scopeLogs:[{scope:{name:e.rn,version:e.in},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:O(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:r}),contentType:e.O}}};function M(e){return e===`otlp`?j:e===`ecs`?E:e}var N=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(n){let{diagnostics:r}=this.deps,i=this.endpointUrl();if(i===null)return;let a=this.drain(n);if(!a||a.records.length===0)return;let o=r.guard(`transport.serialize_failed`,`the ${n} exit flush could not serialize its batch`,()=>M(this.deps.config.serializer).serialize(a.records));if(!o)return;if(t.f(o.body)>6e4){u(a,r);return}i.searchParams.set(e._t,a.id),i.searchParams.set(e.vt,n);let s=i.toString(),c=this.beacon(s,o.body);c!==`sent`&&(c===`refused`?u(a,r):this.keepaliveFetch(s,o.body,n))}drain(e){return e===`hidden`?this.deps.drainPending():this.deps.drainForExit()}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(e,t){return this.deps.diagnostics.guard(`transport.http_error`,`sendBeacon`,()=>{let n=globalThis.navigator;return n?.sendBeacon?n.sendBeacon(e,new Blob([t],{type:`text/plain;charset=UTF-8`}))?`sent`:`refused`:`unavailable`})??`unavailable`}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.J]:e.A},credentials:i.credentials,keepalive:!0}).catch(e=>{a.report(`transport.http_error`,`the exit flush failed`,{reason:r},e)})})}};async function P(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.z)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var F=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 I(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.ut);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var L=class{config;diagnostics;throttledUntil=0;constructor(e,t){this.config=e,this.diagnostics=t}async send(e){let{endpoint:t}=this.config;t&&e.records.length!==0&&await this.post(e,t)}throttledForMs(){return Math.max(0,this.throttledUntil-Date.now())}async post(t,n){let{config:r}=this,i;try{i=M(r.serializer).serialize(t.records)}catch(e){this.diagnostics.report(`transport.serialize_failed`,`serializer threw, dropping the batch`,{batchId:t.id},e);return}let a=new Headers(await this.resolveHeaders());a.set(e.J,i.contentType),a.set(e.K,t.id),a.set(e.G,String(t.attempts));let o=await this.encodeBody(i.body);typeof o!=`string`&&a.set(e.q,e.z);let s=await this.dispatch(n,a,o);if(s.ok)this.throttledUntil=0;else throw await this.classify(s,t.id)}async encodeBody(e){let{config:n}=this;return n.compression!==`gzip`||t.f(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`gzipping the payload`,()=>P(e))??e}async dispatch(t,r,i){let{config:a}=this,o=new AbortController,s=setTimeout(()=>{o.abort()},e.xt);n.t(s);try{return await fetch(t,{method:`POST`,headers:r,body:i,credentials:a.credentials,signal:o.signal,cache:`no-store`})}catch{if(o.signal.aborted)throw new F(`timeout`,`request exceeded ${String(e.xt)}ms`);let t=globalThis.navigator?.onLine;throw new F(t===!1?`offline`:`transient`,`network error`)}finally{clearTimeout(s)}}async classify(t,n){let r=t.status,i=I(t.headers.get(e.Y));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 F(`permanent`,`rejected with ${String(r)}`,r);if(r===413)return new F(`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??2e3),e&&this.diagnostics.report(`transport.throttled`,`server throttled us`,{retryAfterMs:i}),new F(`throttled`,e?`throttled`:`service unavailable`,r,i)}return r===408||r>=500?new F(`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 F(`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:{}}},R=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(e.It)}nudge(){this.draining||this.schedule(e.Ft)}async storeFailed(e,t){let n=this.toStorable(e,t);for(let e of n)await this.bounded(this.storage.save(e));n.length>0&&this.nudge()}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,n.t(t)}bounded(n){return t.i(n,e.qt)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Ft*2**this.attempt,e.Lt);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await a(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.It)}finally{this.draining=!1}}}async drainLocked(){try{if(globalThis.navigator?.onLine===!1)return this.schedule(e.It),!0;let t=await this.bounded(this.storage.take(this.batchesPerDrain));if(t.length===0)return this.schedule(e.It),!0;for(let e of t)if(this.stopped||!await this.deliver(e))return!0;return this.schedule(t.length===this.batchesPerDrain?0:e.It),!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(t){if(t.attempts>=e.Jt.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`giving up on a batch after ${t.attempts.toString()} attempts`,{batchId:t.id,records:t.records.length}),await this.bounded(this.storage.remove(t.id)),!0;try{return await this.transport.send(t),await this.bounded(this.storage.remove(t.id)),this.attempt=0,!0}catch(n){let r=n instanceof F?n:void 0;return r?.kind===`permanent`||r?.kind===`too_large`?(await this.replaceStored(t,n),!0):r?.kind===`offline`?(this.schedule(e.It),!1):r?.kind===`throttled`?(this.attempt++,this.schedule(r.retryAfterMs??this.backoffMs()),!1):(await this.bounded(this.storage.bumpAttempts(t.id,t.attempts+1)),this.attempt++,this.schedule(r?.retryAfterMs??this.backoffMs()),!1)}}async replaceStored(e,t){let n=this.toStorable(e,t);await this.bounded(this.storage.remove(e.id));for(let e of n)await this.bounded(this.storage.save(e))}toStorable(e,t){let n=t instanceof F?t:void 0;if(n?.kind===`permanent`)return[];if(n?.kind!==`too_large`)return[e];let r=i(e);return r?(this.diagnostics.report(`transport.batch_split`,`the server refused the batch as too large`,{from:e.records.length,to:r[0].records.length,serverMaxBytes:n.maxBytes}),r):(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)}),[])}};function z(t){return t.attributes[e.l]===e.st}var B={logs:{flushIntervalMs:e.ot,batchSize:100},metrics:{flushIntervalMs:e.lt,batchSize:500}},V=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){this.pending.push(e),this.pending.length>=this.options.batchSize?this.onFlush(this):this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,n.t(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},H=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];ceiling=new t.t;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i=B){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new V(i.logs,a),metrics:new V(i.metrics,a)}}push(e){this.stopped||(e.observedTimeUnixNano=t._(),this.route(e))}drainPending(){return this.toBatch([...this.streams.metrics.take(),...this.streams.logs.take()])}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.toBatch([...e,...this.streams.metrics.take(),...this.streams.logs.take()])}destroy(){this.stopped=!0,this.streams.logs.stop(),this.streams.metrics.stop(),this.queue.length=0}toBatch(e){return e.length===0?null:{id:t.c(),records:e,createdAt:Date.now(),attempts:0}}route(e){try{let t=z(e)?this.streams.metrics:this.streams.logs;if(!this.ceiling.allow(e)){this.diagnostics.count(`record.dropped_by_ceiling`);return}t.add(e)}catch(e){this.diagnostics.report(`pipeline.crashed`,`a record was dropped on its way into a stream`,void 0,e)}}claim(e){let n=e.take(),r={id:t.c(),records:n,createdAt:Date.now(),attempts:0};this.unconfirmed.set(r.id,r),this.enqueue(r)}enqueue(e){this.queue.push(e),!this.pumpScheduled&&(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){for(;this.inFlight<2;){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){try{await this.dispatch(e)}catch(t){this.diagnostics.report(`pipeline.crashed`,`dispatch rejected, which it is written never to do`,{batchId:e.id},t)}finally{this.inFlight--,this.pump()}}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.storeFailed({...e,attempts:e.attempts+1},t),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 storeFailed(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`persisting an undelivered batch`,async()=>{await this.retry.storeFailed(e,t)})}async store(n){await this.diagnostics.guardAsync(`storage.degraded`,`persisting an undelivered batch`,async()=>{await t.i(this.storage.save(n),e.qt),this.retry.nudge()})}},U=class t{storage;transport;retry;pipeline;exitFlush;diagnostics;constructor(e,t,n,r,i,a){this.storage=e,this.transport=t,this.retry=n,this.pipeline=r,this.exitFlush=i,this.diagnostics=a}static async create(n){let{config:r,diagnostics:i}=n,a=await b(r.storage,e.Kt,e.Jt,i,n.onGap),o=new L(r,i),s=new R(a,o,i,r),c=new H(o,a,s,i),l=new N({config:r,diagnostics:i,drainForExit:()=>c.drainForExit(),drainPending:()=>c.drainPending()});await d(a,i);let u=!1;try{l.install(),s.start(),u=!0}finally{u||(l.uninstall(),s.stop())}return new t(a,o,s,c,l,i)}push(e){this.pipeline.push(e)}async flush(){let e=this.pipeline.drainPending();if(e)try{await this.transport.send(e)}catch(t){await this.diagnostics.guardAsync(`storage.degraded`,`persisting the batch drained by flush()`,async()=>{await this.retry.storeFailed({...e,attempts:e.attempts+1},t)}),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)}}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting the batches waiting in storage`,()=>this.storage.count())??0}async destroy(){this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.pipeline.destroy(),await this.storage.close()}};exports.Sender=U;
|
|
3
|
-
//# sourceMappingURL=sender-vLcbQhiB.cjs.map
|