@utk09/ui-observability 0.9.1 → 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +75 -64
- package/dist/batch-D5qvsMQ_.cjs +2 -0
- package/dist/batch-D5qvsMQ_.cjs.map +1 -0
- package/dist/{batch-DEK4bv9N.js → batch-DDgxg16_.js} +7 -4
- package/dist/batch-DDgxg16_.js.map +1 -0
- package/dist/bus/bus.d.ts +0 -4
- package/dist/{bus-HVQ8E72V.js → bus-C6RwKzPW.js} +63 -66
- package/dist/bus-C6RwKzPW.js.map +1 -0
- package/dist/bus-WPVDFw2y.cjs +2 -0
- package/dist/bus-WPVDFw2y.cjs.map +1 -0
- package/dist/capture/network.d.ts +2 -0
- package/dist/capture/storm.d.ts +2 -7
- package/dist/capture/types.d.ts +3 -0
- package/dist/{console-DssDxq1B.cjs → console-BSusX_M-.cjs} +2 -2
- package/dist/{console-DssDxq1B.cjs.map → console-BSusX_M-.cjs.map} +1 -1
- package/dist/{console-C9Y639mn.js → console-Dv5GfaNn.js} +3 -3
- package/dist/{console-C9Y639mn.js.map → console-Dv5GfaNn.js.map} +1 -1
- package/dist/constants-Cb92egPS.cjs +2 -0
- package/dist/constants-Cb92egPS.cjs.map +1 -0
- package/dist/{constants-N99w84xy.js → constants-DhH6VI5a.js} +39 -12
- package/dist/constants-DhH6VI5a.js.map +1 -0
- package/dist/constants.d.ts +28 -3
- package/dist/core/breadcrumbs.d.ts +1 -3
- package/dist/core/context.d.ts +0 -8
- package/dist/core/diagnostics.d.ts +1 -3
- package/dist/core/meter.d.ts +45 -0
- package/dist/core/pipeline.d.ts +5 -12
- package/dist/core/record.d.ts +7 -0
- package/dist/core/runtime.d.ts +17 -0
- package/dist/core/sampling.d.ts +3 -3
- package/dist/core/sender.d.ts +2 -0
- package/dist/deadline-CUrH0Hd8.cjs +2 -0
- package/dist/deadline-CUrH0Hd8.cjs.map +1 -0
- package/dist/deadline-DeqXEliN.js +31 -0
- package/dist/deadline-DeqXEliN.js.map +1 -0
- package/dist/{errors-CQusIGWJ.js → errors-DCZWcHkd.js} +4 -4
- package/dist/{errors-CQusIGWJ.js.map → errors-DCZWcHkd.js.map} +1 -1
- package/dist/{errors-BTWuVnHZ.cjs → errors-ERu-su8m.cjs} +3 -3
- package/dist/{errors-BTWuVnHZ.cjs.map → errors-ERu-su8m.cjs.map} +1 -1
- package/dist/fixed-window-BR0bu32Y.cjs +2 -0
- package/dist/fixed-window-BR0bu32Y.cjs.map +1 -0
- package/dist/fixed-window-Re7jIRJH.js +9 -0
- package/dist/fixed-window-Re7jIRJH.js.map +1 -0
- package/dist/{identity-B1GDS1Tb.cjs → identity-C1WLItSl.cjs} +2 -2
- package/dist/{identity-B1GDS1Tb.cjs.map → identity-C1WLItSl.cjs.map} +1 -1
- package/dist/{identity-D4DPjTM9.js → identity-Di-QXGCC.js} +2 -2
- package/dist/{identity-D4DPjTM9.js.map → identity-Di-QXGCC.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +18 -0
- package/dist/index.js +522 -369
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-DX18p39D.cjs +2 -0
- package/dist/indexeddb-storage-DX18p39D.cjs.map +1 -0
- package/dist/{indexeddb-storage-B8SGUzSV.js → indexeddb-storage-T9YIYVYC.js} +48 -59
- package/dist/indexeddb-storage-T9YIYVYC.js.map +1 -0
- package/dist/{interactions-CnjfQgw3.js → interactions-BLH_tX87.js} +2 -2
- package/dist/{interactions-CnjfQgw3.js.map → interactions-BLH_tX87.js.map} +1 -1
- package/dist/{interactions-CcxrVzpg.cjs → interactions-_hfOerfC.cjs} +2 -2
- package/dist/{interactions-CcxrVzpg.cjs.map → interactions-_hfOerfC.cjs.map} +1 -1
- package/dist/journey-BRUj0hqD.cjs +2 -0
- package/dist/journey-BRUj0hqD.cjs.map +1 -0
- package/dist/{journey-DjvDzHyp.js → journey-yALMEWF7.js} +39 -38
- package/dist/journey-yALMEWF7.js.map +1 -0
- package/dist/library-request-BcAxuwsf.cjs +2 -0
- package/dist/library-request-BcAxuwsf.cjs.map +1 -0
- package/dist/library-request-CQD4HUiP.js +25 -0
- package/dist/library-request-CQD4HUiP.js.map +1 -0
- package/dist/{long-frames-BGik_Yhy.cjs → long-frames-D4Bm3Zkz.cjs} +2 -2
- package/dist/{long-frames-BGik_Yhy.cjs.map → long-frames-D4Bm3Zkz.cjs.map} +1 -1
- package/dist/{long-frames-CZk3XOkH.js → long-frames-DD_Um9_4.js} +3 -3
- package/dist/{long-frames-CZk3XOkH.js.map → long-frames-DD_Um9_4.js.map} +1 -1
- package/dist/models/batch.d.ts +6 -0
- package/dist/models/config.d.ts +23 -0
- package/dist/models/metric.d.ts +50 -0
- package/dist/network--GoE7_Or.js +211 -0
- package/dist/network--GoE7_Or.js.map +1 -0
- package/dist/network-DcuS2H1P.cjs +2 -0
- package/dist/network-DcuS2H1P.cjs.map +1 -0
- package/dist/openfin-BwEN0uj4.js +8 -0
- package/dist/openfin-BwEN0uj4.js.map +1 -0
- package/dist/openfin-DtH2f7zX.cjs +2 -0
- package/dist/openfin-DtH2f7zX.cjs.map +1 -0
- package/dist/platform-GaM6h7XM.js +52 -0
- package/dist/platform-GaM6h7XM.js.map +1 -0
- package/dist/platform-kIL5AZB7.cjs +2 -0
- package/dist/platform-kIL5AZB7.cjs.map +1 -0
- package/dist/{remote-rules-M-XZ1xbe.js → remote-rules-6ePq8CrI.js} +23 -25
- package/dist/remote-rules-6ePq8CrI.js.map +1 -0
- package/dist/remote-rules-CI3gbRCL.cjs +2 -0
- package/dist/remote-rules-CI3gbRCL.cjs.map +1 -0
- package/dist/sampling-C-M8p3FK.cjs +2 -0
- package/dist/sampling-C-M8p3FK.cjs.map +1 -0
- package/dist/sampling-Ud_WiuU9.js +65 -0
- package/dist/sampling-Ud_WiuU9.js.map +1 -0
- package/dist/{sanitize-DKp5MRsa.cjs → sanitize--_e4oOPX.cjs} +2 -2
- package/dist/{sanitize-DKp5MRsa.cjs.map → sanitize--_e4oOPX.cjs.map} +1 -1
- package/dist/{sanitize-Dwj9JCkI.js → sanitize-DP0xDPrt.js} +2 -2
- package/dist/{sanitize-Dwj9JCkI.js.map → sanitize-DP0xDPrt.js.map} +1 -1
- package/dist/sender-BESHz6my.cjs +3 -0
- package/dist/sender-BESHz6my.cjs.map +1 -0
- package/dist/{sender-BBY0IcUo.js → sender-BUBWLn5i.js} +425 -290
- package/dist/sender-BUBWLn5i.js.map +1 -0
- package/dist/storage/gap.d.ts +20 -0
- package/dist/storage/indexeddb-storage.d.ts +1 -7
- package/dist/storage/keys.d.ts +9 -0
- package/dist/storage/local-storage.d.ts +0 -6
- package/dist/storage/memory-storage.d.ts +1 -1
- package/dist/storm-DhHGHhOc.cjs +2 -0
- package/dist/storm-DhHGHhOc.cjs.map +1 -0
- package/dist/storm-OD5J6Ylm.js +10 -0
- package/dist/storm-OD5J6Ylm.js.map +1 -0
- package/dist/transport/custom-transport.d.ts +3 -2
- package/dist/transport/exit-flush.d.ts +13 -2
- package/dist/transport/http-transport.d.ts +6 -4
- package/dist/transport/retry-engine.d.ts +3 -1
- package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
- package/dist/transport/serializers/otlp.d.ts +30 -0
- package/dist/transport/serializers/select.d.ts +20 -4
- package/dist/transport/status-transport.d.ts +19 -11
- package/dist/utils/fixed-window.d.ts +15 -0
- package/dist/utils/guards.d.ts +6 -0
- package/dist/utils/library-request.d.ts +12 -0
- package/dist/utils/openfin.d.ts +48 -0
- package/dist/utils/platform.d.ts +5 -0
- package/package.json +2 -3
- package/dist/batch-DEK4bv9N.js.map +0 -1
- package/dist/batch-DEVFs28i.cjs +0 -2
- package/dist/batch-DEVFs28i.cjs.map +0 -1
- package/dist/bus-DNFvTkif.cjs +0 -2
- package/dist/bus-DNFvTkif.cjs.map +0 -1
- package/dist/bus-HVQ8E72V.js.map +0 -1
- package/dist/constants-N99w84xy.js.map +0 -1
- package/dist/constants-X86IDwkC.cjs +0 -2
- package/dist/constants-X86IDwkC.cjs.map +0 -1
- package/dist/deadline-5_PecIl5.js +0 -26
- package/dist/deadline-5_PecIl5.js.map +0 -1
- package/dist/deadline-XSnm95pg.cjs +0 -2
- package/dist/deadline-XSnm95pg.cjs.map +0 -1
- package/dist/indexeddb-storage-B8SGUzSV.js.map +0 -1
- package/dist/indexeddb-storage-ukzC82dm.cjs +0 -2
- package/dist/indexeddb-storage-ukzC82dm.cjs.map +0 -1
- package/dist/journey-DjvDzHyp.js.map +0 -1
- package/dist/journey-DxlfdFJV.cjs +0 -2
- package/dist/journey-DxlfdFJV.cjs.map +0 -1
- package/dist/library-request-BZ1ekVtl.cjs +0 -2
- package/dist/library-request-BZ1ekVtl.cjs.map +0 -1
- package/dist/library-request-C8kc5YWv.js +0 -14
- package/dist/library-request-C8kc5YWv.js.map +0 -1
- package/dist/network-51iicpLl.js +0 -174
- package/dist/network-51iicpLl.js.map +0 -1
- package/dist/network-jBbjyAJP.cjs +0 -2
- package/dist/network-jBbjyAJP.cjs.map +0 -1
- package/dist/platform-Cjts-8k8.js +0 -48
- package/dist/platform-Cjts-8k8.js.map +0 -1
- package/dist/platform-DW3GFIUE.cjs +0 -2
- package/dist/platform-DW3GFIUE.cjs.map +0 -1
- package/dist/remote-rules-ByS34k4e.cjs +0 -2
- package/dist/remote-rules-ByS34k4e.cjs.map +0 -1
- package/dist/remote-rules-M-XZ1xbe.js.map +0 -1
- package/dist/sampling-BN3Oi6SV.js +0 -63
- package/dist/sampling-BN3Oi6SV.js.map +0 -1
- package/dist/sampling-b2ck5X98.cjs +0 -2
- package/dist/sampling-b2ck5X98.cjs.map +0 -1
- package/dist/sender-BBY0IcUo.js.map +0 -1
- package/dist/sender-BXoAZKum.cjs +0 -3
- package/dist/sender-BXoAZKum.cjs.map +0 -1
- package/dist/storm-CKuaBp7i.cjs +0 -2
- package/dist/storm-CKuaBp7i.cjs.map +0 -1
- package/dist/storm-DhtL2eVr.js +0 -10
- package/dist/storm-DhtL2eVr.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sender-BUBWLn5i.js","names":["items","nested","HEADER_RETRY_AFTER","ECS_LEVEL_NAMES","NANOS_PER_MILLI","QUERY_PARAM_BATCH_ID","RESOURCE_BROWSER_USER_AGENT","EMERGENCY_STORAGE_KEY_PREFIX","RESOURCE_SERVICE_VERSION","RETRY_BASE_DELAY_MS","RESOURCE_DEPLOYMENT_ENVIRONMENT","CONTENT_TYPE_JSON","CONTENT_TYPE_NDJSON","QUERY_PARAM_EXIT_REASON","CONTENT_TYPE_TEXT_PLAIN","REQUEST_TIMEOUT_MS","HEADER_CONTENT_TYPE","NANOS_PATTERN","ENCODING_GZIP","RESOURCE_SERVICE_NAME","HEADER_BATCH_ID","RETRY_MAX_DELAY_MS","HEADER_ATTEMPT","RETRY_IDLE_DELAY_MS","HEADER_CONTENT_ENCODING","STORAGE_DB_NAME","MILLIS_PER_SECOND","ATTR_LOG_TYPE","STORAGE_NAME_NONE","SERIALIZER_NAME_OTLP","HEADER_SAMPLING","STORAGE_PROBE_KEY","TELEMETRY_SDK_VERSION","TELEMETRY_SDK_NAME","LOG_TYPE_METRIC","STORAGE_NAME_LOCAL","STORAGE_DEADLINE_MS","STORAGE_NAME_MEMORY","METRIC_KEYS","BATCH_STORAGE_KEY_PREFIX","withDeadline","unrefTimer","DeadlineError","nowUnixNano","ErrorCeiling","runAsLibraryConsole","estimateBytes","newId","getFin","isOnline","splitBatch","isLogBatch","countRecords","isActionRecord","attributeOf","trackTransportCall","runAsLibraryRequest","parseRemoteRules","applyRemote","storageLimits","retention","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","batchKey","prefix","batch","keysWithPrefix","out","i","key","readBatch","parsed","raw","importAll","moved","value","storage","error","saveToEmergencyQueue","context","evicted","saved","keys","old","dropped","records","one","onLoss","drainEmergencyQueue","hasAction","EvictionPick","howMany","isAudit","item","pickEvictable","pick","items","addDrop","batches","reason","reportEviction","gap","onGap","createdAtOf","start","at","LocalStorageStorage","limits","limit","id","attempts","cutoff","result","expired","alive","createdAt","excess","entry","entries","MemoryStorage","found","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","IndexedDbStorage","dbName","TransportError","message","cause","kind","status","retryAfterMs","maxBytes","parseRetryAfter","header","seconds","date","toMillis","timeUnixNano","toLabelValue","pushLabel","existing","labels","flattenLabel","scalar","seen","toLabels","source","ecsSerializer","millis","record","toAnyValue","toKeyValues","resourceKeys","resourceKey","cached","resource","groupByResource","groups","group","otlpSerializer","resourceLogs","DELTA","numberOf","isNumbers","pointAttributes","histogramOf","count","bounds","buckets","min","numberPointOf","pointOf","values","field","metricOf","points","data","point","otlpMetricsSerializer","resourceMetrics","type","named","unit","serializerFor","choice","batchKind","config","endpointFor","serializeBatch","StatusTransport","onSampling","serialized","sampling","code","advice","hints","throttled","toTransportRequest","isResponse","finiteHint","CustomTransport","transport","request","response","deadline","ExitFlush","deps","me","url","target","custom","headers","outcome","onExit","endpoint","nav","body","park","bytes","gzip","CS","stream","text","buffer","CREDENTIAL_ADVICE","HttpTransport","onKeepalive","keepalive","work","controller","timer","hidden","resolved","RetryEngine","batchesPerDrain","parts","part","delayMs","exponential","blocked","failure","halves","isMetric","RecordStream","options","onFlush","LogPipeline","retry","flush","streamOptions","inFlight","metrics","logs","pending","resolve","settle","throttledMs","Sender","pipeline","exitFlush","update","http","batching","started","sender"],"sources":["../src/models/storage.ts","../src/utils/lock.ts","../src/storage/keys.ts","../src/storage/emergency-queue.ts","../src/storage/eviction.ts","../src/storage/gap.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts","../src/transport/errors.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp.ts","../src/transport/serializers/otlp-metrics.ts","../src/transport/serializers/select.ts","../src/transport/status-transport.ts","../src/transport/custom-transport.ts","../src/transport/exit-flush.ts","../src/transport/compression.ts","../src/transport/http-transport.ts","../src/transport/retry-engine.ts","../src/core/pipeline.ts","../src/core/sender.ts"],"sourcesContent":["// src/models/storage.ts\n//\n// Storage interface for undelivered batches, with adapters for IndexedDB,\n// localStorage, memory, and a fallback that does nothing.\n\nimport type { LogBatch } from \"./batch\";\nimport type { RetentionOptions } from \"./config\";\n\n/** Persistent batch storage interface. All methods must resolve and never throw. */\nexport interface StorageAdapter {\n /** Adapter identifier name. */\n readonly name: string;\n\n /**\n * Persists a batch to storage.\n * @param batch The batch to store.\n */\n save(batch: LogBatch): Promise<void>;\n\n /**\n * Reads up to `limit` batches in FIFO order without removing them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Oldest persisted batches.\n */\n take(limit: number): Promise<LogBatch[]>;\n\n /**\n * Removes a batch by ID. A call with an unknown ID resolves without error.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void>;\n\n /**\n * Updates the total delivery attempts for a batch.\n * @param id Batch identifier.\n * @param attempts Absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void>;\n\n /**\n * Deletes expired and over-capacity batches.\n * @returns Prune summary metrics.\n */\n prune(): Promise<PruneResult>;\n\n /** Returns the total number of stored batches. */\n count(): Promise<number>;\n\n /** Deletes all batches in storage. */\n clear(): Promise<void>;\n\n /** Closes storage connections and releases resources. */\n close(): Promise<void>;\n}\n\n/** Capacity and retention thresholds enforced by a storage adapter. */\nexport interface StorageLimits {\n /** Maximum batch capacity before FIFO eviction. */\n maxBatches: number;\n /** Maximum time-to-live for a stored batch in milliseconds. */\n maxAgeMs: number;\n /** Maximum delivery attempts before dead-letter drop. */\n maxAttempts: number;\n}\n\n/**\n * Gives the storage limits of a retention setting. \"until-delivered\" has no age limit and no\n * attempt limit. The batch cap still applies.\n * @param retention Retention setting from the config.\n * @returns The limits for the storage adapters and the retry engine.\n */\nexport function storageLimits(retention: RetentionOptions): StorageLimits {\n const { maxBatches } = retention;\n\n if (retention.mode === \"until-delivered\") {\n return { maxBatches, maxAgeMs: Infinity, maxAttempts: Infinity };\n }\n\n return { maxBatches, maxAgeMs: retention.maxAgeMs, maxAttempts: retention.maxAttempts };\n}\n\n/** Metrics for batches and records dropped during storage pruning. */\nexport interface PruneResult {\n /** Total batches dropped. */\n batches: number;\n /** Total records dropped within evicted batches. */\n records: number;\n /**\n * Cause of the drop. If more than one rule applies, this is the last rule. \"not_stored\" means\n * that storage did not keep a batch after a failed send.\n */\n reason: \"expired\" | \"over_capacity\" | \"quota\" | \"not_stored\";\n}\n\n/**\n * Callback invoked when dropped records create a telemetry gap.\n * @param result Summary of evicted data.\n * @param dropped The dropped batches. A corrupt entry has no batch. The list then has none for it.\n */\nexport type GapReporter = (result: PruneResult, dropped: readonly LogBatch[]) => void;\n","// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without the lock, 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 when the lock is not available. */\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 that runs with the 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 * It runs the task directly when the Web Locks API is not available.\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 When true, the task does not run if another context holds the lock.\n * @returns Promise of the task result. It resolves to undefined when another context holds the\n * lock. A caller that reads undefined as a task result 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 // Run the task without a lock when the Web Locks API is not available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n","// src/storage/keys.ts\n//\n// This module builds the localStorage key of a batch. It also returns the sorted keys that start\n// with a prefix. A sandboxed frame and private mode throw on first access. They do not return null.\n\nimport { BATCH_KEY_TIME_WIDTH } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Formats a storage key with a zero-padded creation time. The keys sort in FIFO order. Always use\n * batch.createdAt, never Date.now(). A key from Date.now() does not match the written key.\n * @param prefix Storage key prefix.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nexport function batchKey(prefix: string, batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${prefix}${at}.${batch.id}`;\n}\n\n/**\n * Returns all localStorage keys that start with the prefix, in sorted order.\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(\n \"storage.unavailable\",\n \"The library could not list the localStorage keys.\",\n () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) has the type string | null. It cannot be null below length. A\n // null check here adds a branch that 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\n return out.sort();\n}\n","// src/storage/emergency-queue.ts\n//\n// This module keeps a synchronous localStorage queue. It holds oversized batches during unload.\n// Startup recovers them. The code is synchronous and never throws. It runs while the browser\n// destroys the document. No promise settles at that time.\n\nimport {\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 { LossReporter } from \"../models/drop\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\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 is not valid JSON. The library dropped it.\",\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(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target 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 // Read and remove the key in one synchronous step, before the async save. A second window\n // that imports at the same time cannot take the same batch.\n const raw = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n () => {\n const value = localStorage.getItem(key);\n localStorage.removeItem(key);\n return value;\n },\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 // Set a deadline. This code runs during startup. A save that does not settle keeps the\n // runtime not ready. 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 \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Writes an unsent batch to the emergency queue synchronously during unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n * @param onLoss Receives the records of the old entries that the queue drops, and of a\n * batch that the store refuses.\n */\nexport function saveToEmergencyQueue(\n batch: LogBatch,\n diagnostics: Diagnostics,\n onLoss?: LossReporter,\n): void {\n // Name the record count. A full localStorage drops this batch permanently. Removal of\n // emergency keys cannot free quota that the keys of other applications use.\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n const evicted: LogBatch[] = [];\n\n const saved = diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n // A key that another window removed gives null. readBatch then rejects it.\n const dropped = readBatch(String(localStorage.getItem(old)), diagnostics);\n if (dropped !== null) {\n evicted.push(dropped);\n }\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(batchKey(EMERGENCY_STORAGE_KEY_PREFIX, batch), JSON.stringify(batch));\n return true;\n });\n\n // The exit flush calls this function. A throw here skips the shutdown of the sender.\n diagnostics.guard(\"pipeline.crashed\", \"The loss report of the emergency queue failed.\", () => {\n if (evicted.length > 0) {\n const records = evicted.flatMap((one) => one.records);\n onLoss?.(\n \"exit_queue_full\",\n records,\n evicted.map((one) => one.id),\n );\n }\n\n if (saved !== true) {\n onLoss?.(\"quota\", batch.records, [batch.id]);\n }\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise that resolves 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/eviction.ts\n//\n// This module selects the stored batches to evict. An action is an audit fact. The batches without\n// an action go first. The walk stops early. A read of the full store at each save blocks the page.\n\nimport { isActionRecord, type LogBatch } from \"../models/batch\";\n\n/**\n * Tests if a batch holds an action. An eviction removes such a batch last.\n * @param batch Batch to test.\n * @returns True if one record of the batch is an action.\n */\nexport function hasAction(batch: LogBatch): boolean {\n // Another script on the origin can write to the database. A throw in a cursor handler stops\n // the eviction walk. The walk then never settles.\n return Array.isArray(batch.records) && batch.records.some(isActionRecord);\n}\n\n/** Collects the items to evict from a walk in age order, oldest first. */\nexport class EvictionPick<T> {\n /** Items without an audit fact. */\n private readonly plain: T[] = [];\n\n /** Oldest items with an audit fact. The pick uses them only when too few plain items exist. */\n private readonly audit: T[] = [];\n\n /**\n * @param howMany Number of items to evict.\n * @param isAudit Tests if an item holds an audit fact.\n */\n constructor(\n private readonly howMany: number,\n private readonly isAudit: (item: T) => boolean,\n ) {}\n\n /**\n * Adds the next item of the walk.\n * @param item Next oldest item.\n * @returns False when the pick has enough items without an audit fact. The walk then stops.\n */\n add(item: T): boolean {\n if (!this.isAudit(item)) {\n this.plain.push(item);\n } else if (this.audit.length < this.howMany) {\n this.audit.push(item);\n }\n\n return this.plain.length < this.howMany;\n }\n\n /**\n * Gives the items to evict. The items without an audit fact come first.\n * @returns The picked items.\n */\n picked(): T[] {\n return [...this.plain, ...this.audit].slice(0, this.howMany);\n }\n}\n\n/**\n * Picks the items to evict from a walk in age order. It stops the walk early.\n * @param items Items, oldest first. A generator reads each item only when the walk needs it.\n * @param howMany Number of items to evict.\n * @param isAudit Tests if an item holds an audit fact.\n * @returns The picked items. The items without an audit fact come first.\n */\nexport function pickEvictable<T>(\n items: Iterable<T>,\n howMany: number,\n isAudit: (item: T) => boolean,\n): T[] {\n const pick = new EvictionPick(howMany, isAudit);\n\n for (const item of items) {\n if (!pick.add(item)) {\n break;\n }\n }\n\n return pick.picked();\n}\n","// src/storage/gap.ts\n//\n// This module counts and reports the batches that a storage adapter drops. Each dropped batch is a\n// loss. The gap handler gives it to onDrop.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult } from \"../models/storage\";\n\n/**\n * Adds the drop of one rule to the prune result.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param batches Number of dropped batches.\n * @param records Number of dropped records.\n * @returns The counts of this rule alone, for the gap report.\n */\nexport function addDrop(\n result: PruneResult,\n reason: PruneResult[\"reason\"],\n batches: number,\n records: number,\n): PruneResult {\n result.batches += batches;\n result.records += records;\n result.reason = reason;\n return { batches, records, reason };\n}\n\n/**\n * Reports dropped batches to diagnostics and to the gap handler. An empty drop reports nothing.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Gap handler of the adapter.\n * @param gap Counts and reason of the drop.\n * @param dropped The dropped batches that the adapter could read.\n */\nexport function reportEviction(\n diagnostics: Diagnostics,\n onGap: GapReporter | undefined,\n gap: PruneResult,\n dropped: readonly LogBatch[],\n): void {\n if (gap.batches === 0) {\n return;\n }\n\n diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(gap.batches)} stored batches (${String(gap.records)} records).`,\n { ...gap },\n );\n onGap?.(gap, dropped);\n}\n","// src/storage/local-storage.ts\n//\n// This module stores batches in localStorage with time-ordered keys. The padding makes\n// keys().sort() a sort by creation time. Without padding, the sort uses hex order. take()\n// then does not return 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 { countRecords, isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/** A stored entry. A corrupt entry has no batch. */\ninterface Entry {\n key: string;\n batch: LogBatch | null;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after each save. A\n * read from the batch parses the full store for each save.\n * @param key Prefixed storage key.\n * @returns Creation time in epoch milliseconds, or null for a malformed key.\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/** This StorageAdapter keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** This field holds the storage 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 * Writes a batch to localStorage. It removes the oldest entries on a quota error.\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 makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\n if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n }\n\n /**\n * Returns up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves 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 // The entry is corrupt. The library cannot recover it. Remove it without a gap count. It has\n // no readable record count.\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 the batch with the given ID from localStorage.\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 * Sets the delivery attempt count of a stored batch. It does not change the 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(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => {\n localStorage.setItem(key, JSON.stringify(batch));\n },\n );\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise that resolves 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 const expired: string[] = [];\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 expired.push(key);\n continue;\n }\n alive.push(key);\n }\n\n // The record count is the one field that the key does not contain. Parse only the\n // deleted batches.\n this.drop(result, \"expired\", [...this.entries(expired)]);\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n this.drop(result, \"over_capacity\", this.evictable(alive, excess));\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns the number of stored batch keys. It does not deserialize the batches.\n * @returns Promise that resolves to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** This method deletes all batch keys from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** This method does nothing. localStorage has no connection to close. */\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 Text that diagnostics reports when the write fails.\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(batchKey(BATCH_STORAGE_KEY_PREFIX, batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** This method removes a quarter of the store to free quota. It counts the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n const howMany = Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR);\n\n this.drop(result, \"quota\", this.evictable(keys, howMany));\n }\n\n /**\n * Picks the entries to evict. Entries without an action go first. An action is an audit fact.\n * A corrupt entry has no action. It goes first.\n * @param keys Batch keys, oldest first.\n * @param howMany Number of entries to evict.\n * @returns The picked entries.\n */\n private evictable(keys: string[], howMany: number): Entry[] {\n return pickEvictable(\n this.entries(keys),\n howMany,\n (entry) => entry.batch !== null && hasAction(entry.batch),\n );\n }\n\n /**\n * Reads the entries one at a time. The eviction walk stops early. The later entries then stay\n * unparsed.\n * @param keys Batch keys.\n * @yields Each key with its batch.\n */\n private *entries(keys: string[]): Generator<Entry> {\n for (const key of keys) {\n yield { key, batch: this.read(key) };\n }\n }\n\n /**\n * Removes entries. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that removes the entries.\n * @param entries Entries to remove.\n */\n private drop(result: PruneResult, reason: PruneResult[\"reason\"], entries: Entry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const dropped: LogBatch[] = [];\n\n for (const { key, batch } of entries) {\n this.removeKey(key);\n if (batch) {\n dropped.push(batch);\n }\n }\n\n // A corrupt entry counts as a batch with no records.\n const gap = addDrop(result, reason, entries.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Reads and validates the stored batch at 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(\n \"storage.unavailable\",\n \"The library could not read 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 is corrupt. The library removed it.\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. A second report counts one corrupt\n // entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"A stored entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Finds the storage key that ends with the batch ID.\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 a list 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 one storage key inside a guard.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not remove a stored batch.\",\n () => {\n localStorage.removeItem(key);\n },\n );\n }\n\n /**\n * Returns all batch storage keys in sorted order.\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// This module keeps batches in volatile memory during offline periods. A reload loses all of\n// them. This adapter is the last fallback.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop } from \"./gap\";\n\n/** This StorageAdapter keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** This array holds the batches in 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 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 * Returns up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves 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 the batch with the given 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 * Sets the delivery attempt count of 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. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise that resolves 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 this.report(result, \"expired\", expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n // An action is an audit fact. Evict each batch without an action first.\n const evicted = pickEvictable(this.batches, excess, hasAction);\n this.batches = this.batches.filter((batch) => !evicted.includes(batch));\n this.report(result, \"over_capacity\", evicted);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Adds dropped batches to the prune result. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private report(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n if (dropped.length === 0) {\n return;\n }\n\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n this.onGap?.(gap, dropped);\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Promise that resolves to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** This method deletes all stored batches. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** This method deletes all stored batches when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// This module selects a storage adapter. It falls back from IndexedDB to localStorage to memory.\n// It falls back and does not throw. IndexedDB is unavailable in private mode and sandboxed\n// 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 * Builds the adapter that keeps nothing. The factory returns it for the \"none\" strategy. Each\n * method resolves. A sender that calls close() on shutdown must not crash.\n * @param onGap Receives each batch that the adapter does not keep. That batch is a loss.\n * @returns The adapter.\n */\nconst noop = (onGap?: GapReporter): StorageAdapter => ({\n name: STORAGE_NAME_NONE,\n save: (batch) => {\n onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return Promise.resolve();\n },\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 * Checks if IndexedDB is available in the current context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read indexedDB.\",\n () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n },\n );\n\n return available === true;\n}\n\n/**\n * Checks if localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if localStorage probe write succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write a test key to localStorage.\",\n () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n },\n );\n\n return usable === true;\n}\n\n/**\n * Creates the requested storage adapter. It falls back to the next adapter when\n * a dependency is 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 that resolves 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(onGap);\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 // Import IndexedDbStorage dynamically. This keeps the driver out of the main bundle. A\n // chunk that does not load falls back to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The library could not open IndexedDB.\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Open the database here, not on first use. Private mode, a corrupt profile and\n // some WebViews define indexedDB but reject open(). Only a rejection in this\n // 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 is not available. The library uses memory storage instead.\",\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 is available. The library keeps undelivered records in memory only.\",\n );\n return new MemoryStorage(limits, onGap);\n}\n","// src/transport/errors.ts\n//\n// This module classifies HTTP transport failures. It also parses the Retry-After header.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * The failure kind sets the retry, backoff or drop behavior. The engine retries transient,\n * offline and timeout failures with backoff. A throttled failure waits for the server delay.\n * A too_large failure splits the batch. The engine drops a permanent failure. The server\n * never accepts that batch.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** This error records a failed transport attempt, its failure kind and its 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 * @param cause Error that caused this failure.\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 cause?: unknown,\n ) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = \"TransportError\";\n }\n}\n\n/**\n * Parses an HTTP Retry-After value into a delay in milliseconds. The value\n * can be a number of seconds or an HTTP date. The function clamps a negative delay to zero.\n * A date in the past gives a negative delay.\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/serializers/ecs.ts\n//\n// This module serializes log batches as Elastic Common Schema (ECS) 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 from the\n * bus has passed only a shape check. BigInt throws a SyntaxError on a non-numeric string.\n * That error loses the whole batch, not 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/** Elasticsearch maps these value types under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value to 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. That error 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. It folds a repeated key into an array. Elasticsearch reads\n * a repeated leaf as one multi-valued field. An array of objects maps the same way.\n * @param labels Label map that the function builds.\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\n * nested object under it causes an Elasticsearch dynamic mapping conflict.\n * @param labels Label map that the function builds.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects. This set stops infinite recursion on a cycle.\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 passed only a shape check. Its attributes can contain 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 // Remove the object on unwind. If not, a repeated sibling reads 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 // Use a 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/** This serializer writes log records as Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** This field holds the format name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes 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 // Use the request URL of a captured network event before the page URL.\n url: {\n full: record.attributes[ATTR_URL_FULL] ?? record.attributes[ATTR_PAGE_URL],\n },\n // Spread the attributes last. A record attribute overrides a resource key with the same\n // 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// This module serializes log batches as OTLP/JSON log records. It groups the records by resource.\n// The OTLP metrics serializer uses its value encoding and its resource grouping.\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/** This type holds an OTLP AnyValue with typed value wrappers. */\ntype AnyValue = Record<string, unknown>;\n\n/** This interface holds an OTLP KeyValue pair. */\nexport interface KeyValue {\n /** This field holds the attribute key. */\n key: string;\n /** This field holds the typed AnyValue. */\n value: AnyValue;\n}\n\n/** This interface holds the records that share resource attributes. */\nexport interface ResourceGroup {\n /** This field holds the resource attribute map. */\n resource: Record<string, unknown>;\n /** This field holds the log records of the resource. */\n records: LogRecord[];\n}\n\n/**\n * Wraps a JavaScript value in an OTLP AnyValue.\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 // Encode int64 as a decimal string. The OTLP protobuf JSON mapping requires it. A conforming\n // collector returns a 400 status for a number. The response does not give the cause.\n // An integer above MAX_SAFE_INTEGER goes to doubleValue. Its text can be \"1e+21\" or overflow int64.\n if (typeof value === \"number\") {\n return Number.isSafeInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n }\n\n // Convert a BigInt to a decimal string. JSON.stringify throws on a BigInt and loses the\n // 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 to an array of OTLP KeyValue pairs.\n * @param source Key-value attribute object.\n * @returns Array of valid KeyValue pairs.\n */\nexport function 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/** This map caches the JSON key of each resource object. It prevents a repeated stringify. */\nconst resourceKeys = new WeakMap<object, string>();\n\n/**\n * Returns the stable JSON key of a resource object. It caches the key.\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/**\n * Groups records by their resource attributes. It keeps the record order in each group.\n * @param records Records to group.\n * @returns One group for each resource.\n */\nexport function groupByResource(records: LogRecord[]): ResourceGroup[] {\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 return [...groups.values()];\n}\n\n/** This serializer writes log records as OTLP/JSON payloads. */\nexport const otlpSerializer: LogSerializer = {\n /** This field holds the format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups records by resource. It encodes them as an OTLP\n * 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 resourceLogs = groupByResource(records).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 // Use timeUnixNano when observedTimeUnixNano is not set.\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/otlp-metrics.ts\n//\n// This module serializes metric records as an OTLP/JSON ExportMetricsServiceRequest. The transport\n// uses it only for a batch of metric records when metricsEndpoint is set.\n\nimport {\n CONTENT_TYPE_JSON,\n METRIC_KEYS,\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\";\nimport { groupByResource, toKeyValues } from \"./otlp\";\n\n/** OTLP AggregationTemporality DELTA. Each point holds the change since the previous point. */\nconst DELTA = 1;\n\n/** OTLP field of each metric type. A type that is not a counter or a histogram is a gauge. */\ntype MetricField = \"sum\" | \"histogram\" | \"gauge\";\n\n/** One OTLP data point. */\ntype DataPoint = Record<string, unknown>;\n\n/** Data points of one metric name, type and unit. */\ninterface MetricEntry {\n /** Metric name. */\n name: string;\n /** Unit of the values. */\n unit: string;\n /** OTLP field of the type. */\n field: MetricField;\n /** Data points. */\n points: DataPoint[];\n}\n\n/**\n * Reads a finite number attribute.\n * @param record Metric record.\n * @param key Attribute key.\n * @returns The number, or undefined.\n */\nfunction numberOf(record: LogRecord, key: string): number | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Tests if a value is a list of finite numbers.\n * @param value Attribute value.\n * @returns True for a list of finite numbers.\n */\nfunction isNumbers(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.every((item: unknown) => typeof item === \"number\" && Number.isFinite(item))\n );\n}\n\n/**\n * Reads the point attributes that the call of the app gave. The context attributes of the record\n * stay out. A session id on each point makes a new series for each session.\n * @param record Metric record.\n * @returns The string, number and boolean attributes that `metric.attribute_keys` names.\n */\nfunction pointAttributes(record: LogRecord): Record<string, unknown> {\n const keys: unknown = record.attributes[METRIC_KEYS.attributeKeys];\n const out: Record<string, unknown> = {};\n\n if (!Array.isArray(keys)) {\n return out;\n }\n\n for (const key of keys as unknown[]) {\n // A key of the call can have the name of a metric field. That field holds the value of\n // the library.\n const named = typeof key === \"string\" && !key.startsWith(\"metric.\");\n const value: unknown = named ? record.attributes[key] : undefined;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[key as string] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Builds the histogram fields of a point.\n * @param record Metric record.\n * @returns The fields, or null for a point that a record limit cut.\n */\nfunction histogramOf(record: LogRecord): DataPoint | null {\n const count = numberOf(record, METRIC_KEYS.count);\n\n // A logMetric histogram holds one value. It has one bucket and no boundaries.\n if (count === undefined) {\n const value = numberOf(record, \"metric.value\");\n return value === undefined\n ? null\n : {\n count: \"1\",\n sum: value < 0 ? undefined : value,\n min: value,\n max: value,\n bucketCounts: [\"1\"],\n explicitBounds: [],\n };\n }\n\n const bounds: unknown = record.attributes[METRIC_KEYS.bounds];\n const buckets: unknown = record.attributes[METRIC_KEYS.buckets];\n\n // maxArrayLength can cut a list. A point with a cut list gives false buckets.\n if (!isNumbers(bounds) || !isNumbers(buckets) || buckets.length !== bounds.length + 1) {\n return null;\n }\n\n // OTLP: a histogram with a negative value sets no sum. A backend reads the sum as a total.\n const min = numberOf(record, METRIC_KEYS.min);\n\n return {\n count: String(count),\n sum: min !== undefined && min < 0 ? undefined : numberOf(record, METRIC_KEYS.sum),\n min,\n max: numberOf(record, METRIC_KEYS.max),\n // OTLP JSON encodes an int64 as a decimal string.\n bucketCounts: buckets.map(String),\n explicitBounds: bounds,\n };\n}\n\n/**\n * Builds the value field of a sum or gauge point.\n * @param record Metric record.\n * @returns The field, or null for a record without a valid value.\n */\nfunction numberPointOf(record: LogRecord): DataPoint | null {\n const value = numberOf(record, \"metric.value\");\n return value === undefined ? null : { asDouble: value };\n}\n\n/**\n * Builds one OTLP data point.\n * @param record Metric record.\n * @param field OTLP field of the type.\n * @returns The point, or null for a record without a valid value.\n */\nfunction pointOf(record: LogRecord, field: MetricField): DataPoint | null {\n const start: unknown = record.attributes[METRIC_KEYS.start];\n const values = field === \"histogram\" ? histogramOf(record) : numberPointOf(record);\n\n if (values === null) {\n return null;\n }\n\n return {\n attributes: toKeyValues(pointAttributes(record)),\n // A logMetric record has no interval. Its point starts and ends at its time.\n startTimeUnixNano: typeof start === \"string\" ? start : record.timeUnixNano,\n timeUnixNano: record.timeUnixNano,\n ...values,\n };\n}\n\n/**\n * Builds the OTLP metric of an entry.\n * @param entry Data points of one name, type and unit.\n * @returns The OTLP metric.\n */\nfunction metricOf({ name, unit, field, points }: MetricEntry): Record<string, unknown> {\n if (field === \"gauge\") {\n return { name, unit, gauge: { dataPoints: points } };\n }\n\n const data: Record<string, unknown> = { aggregationTemporality: DELTA, dataPoints: points };\n\n // A logMetric counter can hold a negative value. A monotonic sum must not decrease.\n if (field === \"sum\") {\n data.isMonotonic = points.every((point) => (point.asDouble as number) >= 0);\n }\n\n return { name, unit, [field]: data };\n}\n\n/** This serializer writes metric records as an OTLP/JSON ExportMetricsServiceRequest. */\nexport const otlpMetricsSerializer: LogSerializer = {\n /** This field holds the format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource, then by metric name, type and unit. It drops a record\n * without a valid value.\n * @param records Metric records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceMetrics = groupByResource(records).map((group) => {\n const entries = new Map<string, MetricEntry>();\n\n for (const record of group.records) {\n const type: unknown = record.attributes[\"metric.type\"];\n const field: MetricField =\n type === \"counter\" ? \"sum\" : type === \"histogram\" ? \"histogram\" : \"gauge\";\n const point = pointOf(record, field);\n\n if (point === null) {\n continue;\n }\n\n const named: unknown = record.attributes[\"metric.name\"];\n const unit: unknown = record.attributes[\"metric.unit\"];\n const entry: MetricEntry = {\n name: typeof named === \"string\" ? named : record.body,\n unit: typeof unit === \"string\" ? unit : \"\",\n field,\n points: [],\n };\n const key = JSON.stringify([entry.field, entry.name, entry.unit]);\n const found = entries.get(key) ?? entry;\n\n found.points.push(point);\n entries.set(key, found);\n }\n\n return {\n resource: { attributes: toKeyValues(group.resource) },\n scopeMetrics: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n metrics: [...entries.values()].map(metricOf),\n },\n ],\n };\n });\n\n return {\n body: JSON.stringify({ resourceMetrics }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// This module maps the serializer option to an implementation. Only transport code imports\n// this module. config.ts keeps only the name. The main chunk then contains no serializer.\n\nimport { ATTR_LOG_TYPE } from \"../../constants\";\nimport type { Diagnostics } from \"../../core/diagnostics\";\nimport { attributeOf, type LogBatch } from \"../../models/batch\";\nimport type { BatchKind, ResolvedConfig, SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\nimport { otlpMetricsSerializer } from \"./otlp-metrics\";\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\n/**\n * Gives the kind of a batch. Only a batch of metric records goes to metricsEndpoint. A stored\n * record can be corrupt. It then is not a metric.\n * @param batch Batch to test.\n * @param config Active configuration.\n * @returns \"metrics\" with metricsEndpoint set and only metric records, else \"logs\".\n */\nexport function batchKind(batch: LogBatch, config: ResolvedConfig): BatchKind {\n const metrics =\n config.metricsEndpoint !== \"\" &&\n batch.records.length > 0 &&\n batch.records.every((record) => attributeOf(record, ATTR_LOG_TYPE) === \"metric\");\n\n return metrics ? \"metrics\" : \"logs\";\n}\n\n/**\n * Gives the endpoint of a batch kind.\n * @param kind Kind of the batch.\n * @param config Active configuration.\n * @returns metricsEndpoint for a metrics batch, else endpoint.\n */\nexport function endpointFor(kind: BatchKind, config: ResolvedConfig): string | null {\n return kind === \"metrics\" ? config.metricsEndpoint : config.endpoint;\n}\n\n/**\n * Serializes a batch. It reports a serializer that throws, and the caller drops the batch.\n * A metrics batch gets the OTLP metrics format.\n * @param config Active configuration.\n * @param batch Batch to serialize.\n * @param diagnostics Diagnostics reporter.\n * @param message ASD-STE100 sentence for the report.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\nexport function serializeBatch(\n config: ResolvedConfig,\n batch: LogBatch,\n diagnostics: Diagnostics,\n message: string,\n): SerializedBatch | undefined {\n try {\n const serializer =\n batchKind(batch, config) === \"metrics\"\n ? otlpMetricsSerializer\n : serializerFor(config.serializer);\n return serializer.serialize(batch.records);\n } catch (error) {\n diagnostics.report(\"transport.serialize_failed\", message, { batchId: batch.id }, error);\n return undefined;\n }\n}\n","// src/transport/status-transport.ts\n//\n// Holds the parts that the HTTP transport and the custom transport share. A status code then\n// has the same meaning on both paths. 2xx accepts the batch. 413 splits it. 429 and 503 throttle.\n// 408 and 5xx retry. Each other code drops the batch.\n\nimport {\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 RETRY_BASE_DELAY_MS,\n RETRY_MAX_DELAY_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { TransportError } from \"./errors\";\nimport { batchKind, endpointFor, serializeBatch } from \"./serializers/select\";\n\n/** The two operations that the pipeline and the retry engine use. */\nexport interface BatchTransport {\n /**\n * Sends one batch.\n * @param batch Batch to send.\n * @param onKeepalive Runs when a request of the batch starts with keepalive.\n * @throws TransportError when the batch is not accepted.\n */\n send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;\n /**\n * Returns the remaining throttle delay of the endpoint of a batch.\n * @param batch Batch to send.\n * @returns Milliseconds until the throttle ends, or 0.\n */\n throttledForMs(batch: LogBatch): number;\n}\n\n/** Hints that come with a rejected batch. */\nexport interface RejectHints {\n /** Delay that the server asks for, in milliseconds. */\n retryAfterMs?: number;\n /** Largest payload that the server accepts, from a 413 answer. */\n maxBytes?: number;\n /** Extra advice for a 401 or a 403 answer. */\n advice?: string;\n}\n\n/** Base class of the HTTP transport and the custom transport. */\nexport abstract class StatusTransport implements BatchTransport {\n /**\n * Epoch time in milliseconds when the server throttle ends, for each endpoint. A 429 from\n * metricsEndpoint must not stop the log batches.\n */\n private readonly throttledUntil: Record<BatchKind, number> = { logs: 0, metrics: 0 };\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param onSampling Receives the sampling rules of an accepted batch, before validation.\n * @param onLoss Receives the records of a batch that the serializer cannot encode.\n */\n constructor(\n protected readonly config: ResolvedConfig,\n protected readonly diagnostics: Diagnostics,\n private readonly onSampling: (raw: unknown) => void = () => undefined,\n private readonly onLoss: LossReporter = () => undefined,\n ) {}\n\n /**\n * Sends one batch.\n * @param batch Batch to send.\n * @param onKeepalive Runs when a request of the batch starts with keepalive.\n * @throws TransportError when the batch is not accepted.\n */\n abstract send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;\n\n /**\n * Returns the remaining throttle delay of the endpoint of a batch, in milliseconds.\n * @param batch Batch to send.\n * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.\n */\n throttledForMs(batch: LogBatch): number {\n return Math.max(0, this.throttledUntil[batchKind(batch, this.config)] - Date.now());\n }\n\n /**\n * Serializes a batch with the configured serializer. A metrics batch gets the OTLP metrics\n * format. It reports a serializer that throws.\n * @param batch Batch to serialize.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n protected serialize(batch: LogBatch): SerializedBatch | undefined {\n const serialized = serializeBatch(\n this.config,\n batch,\n this.diagnostics,\n \"The serializer threw an error. The library dropped the batch.\",\n );\n\n if (!serialized) {\n this.onLoss(\"unserializable\", batch.records, [batch.id]);\n }\n\n return serialized;\n }\n\n /**\n * Records an accepted batch. It ends the server throttle of the endpoint of the batch.\n * @param kind Kind of the accepted batch.\n * @param sampling Sampling rules of the answer, as text or as an object.\n */\n protected accept(kind: BatchKind, sampling: unknown): void {\n this.throttledUntil[kind] = 0;\n\n // Trust only the answer to a batch that the library sent. A null header means no rules.\n if (this.config.sampling.remote && sampling !== undefined && sampling !== null) {\n this.onSampling(sampling);\n }\n }\n\n /**\n * Converts a status code that is not 2xx into a classified TransportError.\n * @param status Status code of the answer.\n * @param batchId Identifier of the rejected batch.\n * @param kind Kind of the rejected batch. A throttle applies only to its endpoint.\n * @param hints Delay, size limit and advice that come with the answer.\n * @returns Classified TransportError instance.\n */\n protected reject(\n status: number,\n batchId: string,\n kind: BatchKind,\n hints: RejectHints,\n ): TransportError {\n const code = String(status);\n\n if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) {\n const advice = hints.advice === undefined ? \"\" : ` ${hints.advice}`;\n\n this.diagnostics.report(\n \"transport.rejected_credentials\",\n `The server returned ${code}.${advice}`,\n { status, endpoint: endpointFor(kind, this.config) },\n );\n // Classify as permanent. A retry loop on a rejected credential blocks each batch after it.\n return new TransportError(\"permanent\", `The server rejected the batch with ${code}.`, status);\n }\n\n if (status === HTTP_PAYLOAD_TOO_LARGE) {\n return new TransportError(\n \"too_large\",\n \"The payload is too large.\",\n status,\n undefined,\n hints.maxBytes,\n );\n }\n\n if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_SERVICE_UNAVAILABLE) {\n const throttled = status === HTTP_TOO_MANY_REQUESTS;\n // Cap the server delay. Without the cap, a large Retry-After stops delivery for hours.\n const retryAfterMs =\n hints.retryAfterMs === undefined\n ? undefined\n : Math.min(hints.retryAfterMs, RETRY_MAX_DELAY_MS);\n this.throttledUntil[kind] = Date.now() + (retryAfterMs ?? RETRY_BASE_DELAY_MS);\n\n if (throttled) {\n this.diagnostics.report(\"transport.throttled\", \"The server throttles the requests.\", {\n retryAfterMs,\n });\n }\n\n return new TransportError(\n \"throttled\",\n throttled ? \"The server throttles the requests.\" : \"The service is not available.\",\n status,\n retryAfterMs,\n );\n }\n\n if (status === HTTP_REQUEST_TIMEOUT || status >= HTTP_SERVER_ERROR_MIN) {\n return new TransportError(\"transient\", `The server returned the error ${code}.`, status);\n }\n\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The server rejected the batch with ${code}. The library dropped it.`,\n { batchId, status },\n );\n return new TransportError(\"permanent\", `The server rejected the batch with ${code}.`, status);\n }\n}\n","// src/transport/custom-transport.ts\n//\n// Sends batches through the transport function that the consumer supplies. The status codes\n// have the same meaning as on the HTTP path. Retry, storage and the exit flush do not change.\n\nimport {\n HTTP_STATUS_MAX,\n HTTP_STATUS_MIN,\n HTTP_SUCCESS_END,\n HTTP_SUCCESS_MIN,\n REQUEST_TIMEOUT_MS,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { DeadlineError, withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest, trackTransportCall } from \"../utils/library-request\";\nimport { TransportError } from \"./errors\";\nimport { batchKind } from \"./serializers/select\";\nimport { StatusTransport } from \"./status-transport\";\n\n/**\n * Builds the request that a custom transport and its exit hook receive.\n * @param batch Batch to send.\n * @param serialized Serialized form of the batch.\n * @param kind Kind of the batch.\n * @returns The transport request.\n */\nexport function toTransportRequest(\n batch: LogBatch,\n serialized: SerializedBatch,\n kind: BatchKind,\n): TransportRequest {\n return {\n kind,\n body: serialized.body,\n contentType: serialized.contentType,\n batchId: batch.id,\n attempt: batch.attempts,\n records: batch.records,\n };\n}\n\n/**\n * Tests if a value is a usable transport response.\n * @param value Value that the transport resolved to.\n * @returns True if the value has an integer status from 100 to 599.\n */\nfunction isResponse(value: unknown): value is TransportResponse {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const status: unknown = Reflect.get(value, \"status\");\n return (\n typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= HTTP_STATUS_MIN &&\n status <= HTTP_STATUS_MAX\n );\n}\n\n/**\n * Gives a number hint that the server can use. A string, NaN or Infinity breaks the throttle.\n * @param value Hint that the transport returned.\n * @returns The value, 0 or more, or undefined if it is not a finite number.\n */\nfunction finiteHint(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : undefined;\n}\n\n/** Sends batches through the consumer's transport function. */\nexport class CustomTransport extends StatusTransport {\n /**\n * Sends one batch through the configured transport function.\n * @param batch Batch to send.\n * @throws TransportError when the batch is not accepted.\n */\n async send(batch: LogBatch): Promise<void> {\n const { transport } = this.config;\n\n if (!transport || batch.records.length === 0) {\n return;\n }\n\n const serialized = this.serialize(batch);\n\n if (!serialized) {\n return;\n }\n\n const kind = batchKind(batch, this.config);\n const request = toTransportRequest(batch, serialized, kind);\n\n let response: unknown;\n\n try {\n // A transport that never settles holds a dispatch slot. The deadline frees the slot.\n response = await withDeadline(\n // The capture modules skip a request or a console line inside these scopes. Network\n // capture warns about a request after an await, which is outside the scopes.\n trackTransportCall(() =>\n runAsLibraryRequest(() => runAsLibraryConsole(() => transport(request))),\n ),\n REQUEST_TIMEOUT_MS,\n );\n } catch (error) {\n // The pipeline reports the thrown error. Classify it here.\n const deadline = error instanceof DeadlineError ? error : undefined;\n const kind = deadline ? \"timeout\" : \"transient\";\n const message = deadline?.message ?? \"The custom transport failed.\";\n\n throw new TransportError(kind, message, undefined, undefined, undefined, error);\n }\n\n if (!isResponse(response)) {\n this.diagnostics.report(\n \"transport.http_error\",\n \"The custom transport returned no valid status. The library sends the batch again later.\",\n { batchId: batch.id },\n );\n throw new TransportError(\"transient\", \"The custom transport returned no valid status.\");\n }\n\n const { status } = response;\n\n if (status >= HTTP_SUCCESS_MIN && status < HTTP_SUCCESS_END) {\n this.accept(kind, response.sampling);\n return;\n }\n\n throw this.reject(status, batch.id, kind, {\n retryAfterMs: finiteHint(response.retryAfterMs),\n maxBytes: finiteHint(response.maxBytes),\n });\n }\n}\n","// src/transport/exit-flush.ts\n//\n// This module flushes buffered batches on exit. It uses sendBeacon, a keepalive fetch or\n// emergency storage. It runs during unload. No code in it awaits. A hidden document\n// still runs. It gets a normal flush.\n\nimport {\n BEACON_LIMIT_BYTES,\n CONTENT_TYPE_TEXT_PLAIN,\n HEADER_BATCH_ID,\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 { ExitTransport, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { saveToEmergencyQueue } from \"../storage/emergency-queue\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { getFin } from \"../utils/openfin\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { toTransportRequest } from \"./custom-transport\";\nimport { batchKind, serializeBatch } from \"./serializers/select\";\n\n/** This type names the lifecycle event or manual action that starts an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/**\n * This type holds the answer of the browser to a beacon. `refused` means that the in-flight\n * budget is full. `unavailable` means that the host has no usable sendBeacon.\n */\ntype BeaconOutcome = \"sent\" | \"refused\" | \"unavailable\";\n\n/** This type reads navigator.sendBeacon without global DOM type assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** This interface lists the dependencies of ExitFlush. */\nexport interface ExitFlushDeps {\n /** This field holds the active configuration. */\n config: ResolvedConfig;\n /** This field holds the diagnostics reporter. */\n diagnostics: Diagnostics;\n /** This callback drains all buffered and unconfirmed records into one batch for each kind. */\n drainForExit: () => LogBatch[];\n /**\n * This callback runs a normal flush with headers, gzip and retry. A hidden document uses it.\n * It does not touch an in-flight batch.\n */\n flushAlive: () => void | Promise<void>;\n /**\n * This callback gives the headers that the HTTP transport sent last, or undefined.\n * sendBeacon cannot set a header. With headers, the exit flush uses a keepalive fetch.\n */\n exitHeaders: () => Record<string, string> | undefined;\n /** This callback receives the records that the exit flush loses. */\n onLoss?: LossReporter;\n /** This callback sends the points of the open metric interval into the buffers. */\n beforeExit?: () => void;\n}\n\n/**\n * This class flushes pending telemetry on document unload. It uses sendBeacon, a keepalive\n * fetch or emergency storage.\n */\nexport class ExitFlush {\n /** This flag is true while the library listens for the unload events. */\n private installed = false;\n\n /** Bytes of the keepalive fetches of the current exit flush. All batches share one budget. */\n private keepaliveBytes = 0;\n\n /** This listener flushes on visibilitychange when the document becomes hidden. */\n private readonly onVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n this.flush(\"hidden\");\n }\n };\n\n /** This listener flushes on the window pagehide event. */\n private readonly onPageHide = (): void => {\n this.flush(\"pagehide\");\n };\n\n /** This listener flushes on the document freeze event. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** This listener flushes on the OpenFin close-requested event. */\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 /** This method attaches the unload listeners to the document, the window and OpenFin. */\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 fire on the document. pagehide fires on the window.\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n document.addEventListener(\"freeze\", this.onFreeze);\n }\n\n addEventListener(\"pagehide\", this.onPageHide);\n\n const me = getFin()?.me;\n this.deps.diagnostics.guard(\n \"openfin.unavailable\",\n \"The library could not subscribe to close-requested.\",\n () => {\n me?.on?.(\"close-requested\", this.onOpenFinClose);\n },\n );\n }\n\n /** This method removes all 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 = getFin()?.me;\n this.deps.diagnostics.guard(\n \"openfin.unavailable\",\n \"The library could not unsubscribe from close-requested.\",\n () => {\n me?.removeListener?.(\"close-requested\", this.onOpenFinClose);\n },\n );\n }\n\n /**\n * Drains pending records synchronously. It sends them with a beacon, a\n * keepalive fetch or emergency storage. A hidden document gets a normal flush. It never\n * awaits and never throws. The caller is an unload listener.\n * @param reason Reason code of the flush.\n */\n flush(reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n // The drain below then takes the points of the open metric interval.\n diagnostics.guard(\"pipeline.crashed\", \"The metric points before the exit flush failed.\", () => {\n this.deps.beforeExit?.();\n });\n\n // hidden fires at each tab switch. The document keeps running. A normal flush keeps the\n // headers, gzip and the retry. A beacon has none of them. The in-flight batches complete\n // by themselves. A take of them here sends the records again under a new id.\n if (reason === \"hidden\") {\n this.flushAlive();\n return;\n }\n\n if (config.transport) {\n this.flushCustom(reason, config.transportOnExit);\n return;\n }\n\n const url = this.endpointUrl();\n if (url === null) {\n return;\n }\n\n // The fetches of an earlier flush are complete or lost. They do not use this budget.\n this.keepaliveBytes = 0;\n\n for (const batch of this.deps.drainForExit()) {\n // resolveConfig keeps only a valid absolute metricsEndpoint.\n const target = batchKind(batch, config) === \"metrics\" ? config.metricsEndpoint : url.href;\n this.flushBatch(batch, reason, new URL(target));\n }\n }\n\n /**\n * Sends one exit batch with a beacon, a keepalive fetch or emergency storage.\n * @param batch Batch to send.\n * @param reason Reason code of the flush.\n * @param url Endpoint of the batch.\n */\n private flushBatch(batch: LogBatch, reason: ExitReason, url: URL): void {\n const { config, diagnostics } = this.deps;\n\n if (batch.records.length === 0) {\n return;\n }\n\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n return;\n }\n\n // Save an oversized payload to the synchronous localStorage queue. localStorage is the\n // only storage that accepts a write without await.\n if (estimateBytes(serialized.body) > BEACON_LIMIT_BYTES) {\n saveToEmergencyQueue(batch, diagnostics, this.deps.onLoss);\n return;\n }\n\n // Send the batch ID and the reason as query parameters. sendBeacon cannot set 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\n // sendBeacon cannot set a header. An ingest server that needs the authorization header\n // drops a beacon. Send the last headers with a keepalive fetch.\n const custom = this.deps.exitHeaders();\n if (custom) {\n this.keepaliveFetch(target, batch, serialized.body, reason, () => {\n const headers = new Headers(custom);\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n return headers;\n });\n return;\n }\n\n // A headers function has no cached result until a call gives one. The server refuses a\n // beacon without the headers. The next page load sends the batch with them.\n if (config.headers) {\n saveToEmergencyQueue(batch, diagnostics, this.deps.onLoss);\n return;\n }\n\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. No code retries the send.\n if (outcome === \"refused\") {\n saveToEmergencyQueue(batch, diagnostics, this.deps.onLoss);\n return;\n }\n\n const plain = (): Headers => new Headers({ [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN });\n this.keepaliveFetch(target, batch, serialized.body, reason, plain);\n }\n\n /** Runs the normal flush of a hidden document. It reports a flush that throws or rejects. */\n private flushAlive(): void {\n const { diagnostics } = this.deps;\n const message = \"The flush of the hidden document failed.\";\n\n diagnostics.guard(\"pipeline.crashed\", message, () => {\n void Promise.resolve(this.deps.flushAlive()).catch((error: unknown) => {\n diagnostics.report(\"pipeline.crashed\", message, undefined, error);\n });\n });\n }\n\n /**\n * Gives the pending records to the exit hook of a custom transport. A page that closes cannot\n * wait for the async transport. Without a hook, or when the hook refuses the batch, the batch\n * goes to the emergency queue. The next page load sends it.\n * @param reason Reason code of the flush.\n * @param onExit Synchronous exit hook of the custom transport.\n */\n private flushCustom(reason: ExitReason, onExit: ExitTransport | undefined): void {\n const { config, diagnostics } = this.deps;\n\n for (const batch of this.deps.drainForExit()) {\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n continue;\n }\n\n const request = toTransportRequest(batch, serialized, batchKind(batch, config));\n const accepted =\n onExit !== undefined &&\n diagnostics.guard(\"transport.http_error\", \"The transportOnExit hook threw an error.\", () =>\n runAsLibraryRequest(() => onExit(request)),\n ) === true;\n\n if (!accepted) {\n saveToEmergencyQueue(batch, diagnostics, this.deps.onLoss);\n }\n }\n }\n\n /**\n * Serializes the exit batch. It reports a serializer that throws.\n * @param batch Batch to serialize.\n * @param reason Reason code of the flush.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n private serialize(batch: LogBatch, reason: ExitReason): SerializedBatch | undefined {\n const serialized = serializeBatch(\n this.deps.config,\n batch,\n this.deps.diagnostics,\n `The ${reason} exit flush could not serialize its batch.`,\n );\n\n if (!serialized) {\n this.deps.onLoss?.(\"unserializable\", batch.records, [batch.id]);\n }\n\n return serialized;\n }\n\n /**\n * Parses the configured 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 the endpoint ${endpoint}.`,\n () => new URL(endpoint),\n );\n\n return url ?? null;\n }\n\n /**\n * Sends the payload as text/plain with navigator.sendBeacon.\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 \"The sendBeacon call failed.\",\n () => {\n // Call sendBeacon on navigator to keep its receiver. A detached sendBeacon throws when\n // called.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return \"unavailable\";\n }\n\n // Use text/plain to prevent a CORS preflight during unload. A preflight during unload\n // usually does not complete. The browser then drops the beacon without an error.\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 fetch can\n // still succeed.\n return outcome ?? \"unavailable\";\n }\n\n /**\n * Sends a fallback POST with fetch and `keepalive: true`. A keepalive request\n * continues after the document closes. The browser cancels a plain fetch at page close.\n * A failed fetch parks the batch in the emergency queue. The server drops a second copy by\n * its batch id.\n * @param url Target endpoint URL.\n * @param batch Batch in the payload.\n * @param body Serialized payload string.\n * @param reason Reason code of the flush.\n * @param headers Builds the request headers. Without custom headers, only a text/plain\n * content type. A header value outside ISO-8859-1 makes the Headers constructor throw.\n */\n private keepaliveFetch(\n url: string,\n batch: LogBatch,\n body: string,\n reason: ExitReason,\n headers: () => Headers,\n ): void {\n const { config, diagnostics } = this.deps;\n // A rejection arrives only while the document is alive. The next page load sends the batch.\n const park = (): void => {\n saveToEmergencyQueue(batch, diagnostics, this.deps.onLoss);\n };\n\n // The browser rejects a fetch over the budget after the document closes. park() then does\n // not run, and the batch is lost.\n const bytes = estimateBytes(body);\n if (this.keepaliveBytes + bytes > BEACON_LIMIT_BYTES) {\n park();\n return;\n }\n this.keepaliveBytes += bytes;\n\n const started = diagnostics.guard(\"transport.http_error\", \"The keepalive fetch failed.\", () => {\n void fetch(url, {\n method: \"POST\",\n body,\n headers: headers(),\n credentials: config.credentials,\n keepalive: true,\n }).catch((error: unknown) => {\n diagnostics.report(\"transport.http_error\", \"The exit flush failed.\", { reason }, error);\n park();\n });\n return true;\n });\n\n if (started !== true) {\n park();\n }\n }\n}\n","// src/transport/compression.ts\n//\n// This module compresses payloads with the native CompressionStream API. It returns null\n// when the API is absent. It does not return raw text. The server rejects a non-gzip body\n// that has a \"Content-Encoding: gzip\" header with a 400 status.\n\nimport { ENCODING_GZIP } from \"../constants\";\n\n/**\n * Compresses a string to gzip bytes with CompressionStream. The result is a\n * Uint8Array on a non-shared ArrayBuffer. fetch accepts this result as BodyInit.\n * @param text Raw serialized payload to compress.\n * @returns Promise that resolves to the gzip bytes, or null without CompressionStream.\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/http-transport.ts\n//\n// This module serializes, compresses and sends log batches over HTTP. It classifies each\n// failure, reports it and throws it. The caller that owns storage decides what happens to a\n// rejected batch.\n\nimport {\n BEACON_LIMIT_BYTES,\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 HEADER_SAMPLING,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_UNAUTHORIZED,\n REQUEST_TIMEOUT_MS,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { isOnline } from \"../utils/platform\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { gzip } from \"./compression\";\nimport { parseRetryAfter, TransportError } from \"./errors\";\nimport { batchKind, endpointFor } from \"./serializers/select\";\nimport { StatusTransport } from \"./status-transport\";\n\n/** Advice for a 401 or a 403 answer on the HTTP path. */\nconst CREDENTIAL_ADVICE =\n \"In a cross-origin iframe, the session cookie is a third-party cookie. The browser \" +\n \"often blocks it. Forward the records to the platform document. As an alternative, \" +\n \"issue the cookie with the Partitioned attribute.\";\n\n/** Body of one request. It is text or gzip bytes. */\ntype RequestBody = string | Uint8Array<ArrayBuffer>;\n\n/** Headers that a headers() function gave, that function and the endpoint of the send. */\ninterface CachedHeaders {\n /** The headers() function that gave the headers. */\n source: unknown;\n /** The endpoint in force when headers() ran. */\n endpoint: string | null;\n /** The metricsEndpoint in force when headers() ran. */\n metricsEndpoint: string;\n /** The headers. */\n headers: Record<string, string>;\n}\n\n/** This type reads document.visibilityState without global DOM type assertions. */\ninterface DocumentGlobal {\n document?: { visibilityState?: string };\n}\n\n/**\n * This class sends serialized log batches over HTTP. It resolves headers, applies gzip\n * compression and classifies errors.\n */\nexport class HttpTransport extends StatusTransport {\n /**\n * Headers that the headers() function gave last. The exit flush sends them only while that\n * function and the two endpoints are in force. A tenant switch must not send the old token to\n * the new endpoint.\n */\n private cachedHeaders: CachedHeaders | undefined;\n\n /**\n * Sends one log batch over HTTP. A metrics batch goes to metricsEndpoint.\n * @param batch Batch to send.\n * @param onKeepalive Runs when a request of the batch starts with keepalive.\n * @throws TransportError on transient, throttled, 413, or permanent network failures.\n */\n async send(batch: LogBatch, onKeepalive?: () => void): Promise<void> {\n const { config } = this;\n const kind = batchKind(batch, config);\n const endpoint = endpointFor(kind, config);\n\n if (!endpoint || batch.records.length === 0) {\n return;\n }\n\n await this.post(batch, kind, endpoint, onKeepalive);\n }\n\n /**\n * Gives the headers for the exit flush. A closing document cannot await headers().\n * @returns The static headers, the headers that the function in force gave last, or undefined.\n */\n lastHeaders(): Record<string, string> | undefined {\n const { headers } = this.config;\n if (!headers) {\n return undefined;\n }\n\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n // The headers apply to both endpoints. A change of either endpoint can be a tenant switch.\n const cached = this.cachedHeaders;\n const current =\n cached?.source === headers &&\n cached.endpoint === this.config.endpoint &&\n cached.metricsEndpoint === this.config.metricsEndpoint;\n\n return current ? cached.headers : undefined;\n }\n\n /**\n * Serializes, encodes and sends a batch. It throws a classified TransportError\n * on failure.\n * @param batch Batch to deliver.\n * @param kind Kind of the batch. The caller reads it with the endpoint.\n * @param endpoint Ingest URL. The caller reads it one time. A reconfigure during the send\n * cannot change it.\n * @param onKeepalive Runs when a request of the batch starts with keepalive.\n */\n private async post(\n batch: LogBatch,\n kind: BatchKind,\n endpoint: string,\n onKeepalive: (() => void) | undefined,\n ): Promise<void> {\n const serialized = this.serialize(batch);\n\n if (!serialized) {\n return;\n }\n\n let response = await this.attempt(batch, endpoint, serialized, onKeepalive);\n\n // A token can expire between two calls of headers(). Send one time more with new\n // headers. A second 401 or 403 drops the batch.\n if (this.rejectsCredentials(response.status) && typeof this.config.headers === \"function\") {\n this.cachedHeaders = undefined;\n response = await this.attempt(batch, endpoint, serialized, onKeepalive);\n }\n\n if (response.ok) {\n // The server must list the header in Access-Control-Expose-Headers. If not, it is null.\n this.accept(kind, response.headers.get(HEADER_SAMPLING));\n return;\n }\n\n const status = response.status;\n const retryAfterMs = parseRetryAfter(response.headers.get(HEADER_RETRY_AFTER));\n const maxBytes =\n status === HTTP_PAYLOAD_TOO_LARGE ? await this.readMaxBytes(response) : undefined;\n\n throw this.reject(status, batch.id, kind, {\n retryAfterMs,\n maxBytes,\n advice: CREDENTIAL_ADVICE,\n });\n }\n\n /**\n * Tests if a status rejects the credentials.\n * @param status HTTP status code.\n * @returns True for 401 and 403.\n */\n private rejectsCredentials(status: number): boolean {\n return status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN;\n }\n\n /**\n * Resolves the headers, encodes the body and sends one request. One deadline covers the\n * three steps. Without it, a headers() that never settles holds a dispatch slot forever.\n * @param batch Batch to deliver.\n * @param endpoint Ingest URL.\n * @param serialized Serialized batch.\n * @param onKeepalive Runs when the request starts with keepalive.\n * @returns Promise that resolves to the HTTP Response.\n * @throws TransportError on timeout or network failure.\n */\n private async attempt(\n batch: LogBatch,\n endpoint: string,\n serialized: SerializedBatch,\n onKeepalive: (() => void) | undefined,\n ): Promise<Response> {\n const deadline = Date.now() + REQUEST_TIMEOUT_MS;\n\n // Headers ignores the case of header names. A config header cannot duplicate a header below.\n const headers = new Headers(await this.before(this.resolveHeaders(), deadline, endpoint));\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.before(this.encodeBody(serialized.body), deadline, endpoint);\n if (typeof body !== \"string\") {\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n\n // A keepalive request continues after unload. The exit flush must not send the batch again.\n const keepalive = this.keepalive(body);\n if (keepalive) {\n onKeepalive?.();\n }\n\n return this.dispatch(endpoint, headers, body, deadline, keepalive);\n }\n\n /**\n * Waits for a step until the deadline.\n * @param work Step to wait for. It does not reject. Only the deadline rejects here.\n * @param deadline Epoch time in milliseconds at which the request times out.\n * @param endpoint Ingest URL of the request, for the timeout report.\n * @returns Promise that resolves to the value of the step.\n * @throws TransportError of kind \"timeout\" at the deadline.\n */\n private async before<T>(work: Promise<T>, deadline: number, endpoint: string): Promise<T> {\n try {\n return await withDeadline(work, Math.max(0, deadline - Date.now()));\n } catch {\n throw this.timeout(endpoint);\n }\n }\n\n /**\n * Reports a timeout and builds its error.\n * @param endpoint Ingest URL of the request.\n * @returns TransportError of kind \"timeout\".\n */\n private timeout(endpoint: string): TransportError {\n const waited = String(REQUEST_TIMEOUT_MS);\n const message = `The request took longer than ${waited} ms.`;\n\n this.diagnostics.report(\"transport.timeout\", message, { endpoint });\n return new TransportError(\"timeout\", message);\n }\n\n /**\n * Compresses the serialized payload when the config sets gzip. The payload size must\n * be at or above the threshold.\n * @param text Serialized payload string.\n * @returns Promise that resolves to original string or compressed byte array.\n */\n private async encodeBody(text: string): Promise<RequestBody> {\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 \"The library could not compress the payload.\",\n () => gzip(text),\n );\n\n return compressed ?? text;\n }\n\n /**\n * Sends the HTTP POST request with a timeout. It maps network errors to\n * TransportError.\n * @param endpoint Ingest URL.\n * @param headers HTTP request headers.\n * @param body Request body string or byte array.\n * @param deadline Epoch time in milliseconds at which the request times out.\n * @param keepalive True if the request continues after unload.\n * @returns Promise that resolves 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: RequestBody,\n deadline: number,\n keepalive: boolean,\n ): Promise<Response> {\n const { config } = this;\n const controller = new AbortController();\n // The fetch gets the rest of the time after the headers and the encoding.\n const timer = setTimeout(\n () => {\n controller.abort();\n },\n Math.max(0, deadline - Date.now()),\n );\n unrefTimer(timer);\n\n try {\n return await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n signal: controller.signal,\n cache: \"no-store\",\n keepalive,\n }),\n );\n } catch {\n if (controller.signal.aborted) {\n throw this.timeout(endpoint);\n }\n throw new TransportError(isOnline() ? \"transient\" : \"offline\", \"A network error occurred.\");\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Tests if a send uses keepalive. A mobile OS can stop a hidden page with no pagehide.\n * A keepalive request continues after that. The browser limits the keepalive bodies in flight.\n * @param body Request body string or byte array.\n * @returns True for a hidden document and a body of BEACON_LIMIT_BYTES or less.\n */\n private keepalive(body: RequestBody): boolean {\n const hidden = (globalThis as DocumentGlobal).document?.visibilityState === \"hidden\";\n const bytes = typeof body === \"string\" ? estimateBytes(body) : body.byteLength;\n\n return hidden && bytes <= BEACON_LIMIT_BYTES;\n }\n\n /**\n * Reads the optional maxBytes limit from a 413 response body.\n * @param response HTTP 413 Response instance.\n * @returns Promise that resolves to maximum byte limit or undefined.\n */\n private async readMaxBytes(response: Response): Promise<number | undefined> {\n return this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not read the body of the 413 response.\",\n 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 /**\n * Resolves the configured static or dynamic request headers. It keeps the headers that\n * headers() gave, for the exit flush.\n * @returns Promise that resolves 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 // Read the endpoints before the call. A configure() during the call then ends the cache.\n const { endpoint, metricsEndpoint } = this.config;\n const resolved = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"The headers() function threw an error.\",\n () => Promise.resolve(headers()),\n );\n\n if (resolved) {\n this.cachedHeaders = { source: headers, endpoint, metricsEndpoint, headers: resolved };\n }\n\n return resolved ?? {};\n }\n}\n","// src/transport/retry-engine.ts\n//\n// This module sends stored log batches again in the background. It uses exponential\n// backoff with jitter. It keeps one timer, never a chain of timers. Each scheduling path\n// clears the pending 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} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type LogBatch, splitBatch } from \"../models/batch\";\nimport type { BatchKind, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport { type StorageAdapter, storageLimits } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { isOnline } from \"../utils/platform\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { TransportError } from \"./errors\";\nimport { batchKind } from \"./serializers/select\";\nimport type { BatchTransport } from \"./status-transport\";\n\n/** Result of one delivery. A number is the delay before the next try of a failed batch. */\ntype Outcome = \"next\" | \"stop\" | number;\n\n/**\n * This class sends persisted offline batches again on a timer. It uses backoff, a cross-tab\n * drain lock and batch splitting.\n */\nexport class RetryEngine {\n /** This field holds the active retry timer handle. It is null when no timer runs. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** This field counts consecutive failed deliveries. The backoff calculation uses it. */\n private attempt = 0;\n\n /** This flag is true while a storage drain runs. */\n private draining = false;\n\n /** This flag is true after stop(). */\n private stopped = false;\n\n /** Attempt limit of a stored batch. Retention cannot change after the delivery stack loads. */\n private readonly maxAttempts: number;\n\n /** This listener runs on the online event. It resets the attempt count and starts a 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 * @param onLoss Receives the records of each batch that the engine drops.\n */\n constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: BatchTransport,\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n private readonly batchesPerDrain = BATCHES_PER_DRAIN,\n private readonly onLoss: LossReporter = () => undefined,\n ) {\n this.maxAttempts = storageLimits(config.retention).maxAttempts;\n }\n\n /** This method starts the engine. It listens for online events and arms the first 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 /** This method schedules an earlier retry when storage receives a new offline batch. */\n nudge(): void {\n if (!this.draining) {\n this.schedule(RETRY_BASE_DELAY_MS);\n }\n }\n\n /**\n * Stores a batch that failed outside the drain loop. It applies the same rules\n * as the drain. It does not store a refused batch whole. A whole batch causes another request\n * with a payload that the server 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 /** This method stops the engine. It removes the listener and clears the pending timer. */\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 the pending timer. It then schedules a drain after the 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 * Sets a deadline on a storage call. A call that does not settle keeps\n * `draining` true. 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 /** This method clears the pending timer when a timer is active. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Calculates the exponential backoff delay from consecutive failures. It applies\n * full jitter, not a fixed offset. With a fixed offset, tabs that reconnect together send\n * their requests at the same time.\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 /** This method runs a drain under 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 // The value is undefined when another window holds the lock. Without this reschedule,\n // one lost lock race stops all drains in 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 it holds the Web Lock. It schedules the next tick.\n * It always resolves. A throw leaves the engine idle with no armed timer.\n * @returns Promise that resolves to true on completion.\n */\n private async drainLocked(): Promise<true> {\n try {\n if (!isOnline()) {\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 // A failure blocks only the kind of its batch. The other endpoint can accept its batches.\n const blocked = new Set<BatchKind>();\n let delayMs = 0;\n\n for (const batch of batches) {\n if (this.stopped) {\n return true;\n }\n\n const kind = batchKind(batch, this.config);\n if (blocked.has(kind)) {\n continue;\n }\n\n const outcome = await this.deliver(batch);\n if (outcome === \"stop\") {\n return true;\n }\n\n if (outcome !== \"next\") {\n blocked.add(kind);\n // Keep the longest delay. A shorter one sends before the Retry-After of the other server.\n delayMs = Math.max(delayMs, outcome);\n }\n }\n\n if (blocked.size > 0) {\n this.schedule(delayMs);\n } else {\n this.schedule(batches.length === this.batchesPerDrain ? 0 : RETRY_IDLE_DELAY_MS);\n }\n return true;\n } catch (error) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"The drain loop threw an error.\",\n undefined,\n error,\n );\n this.attempt++;\n this.schedule(this.backoffMs());\n return true;\n }\n }\n\n /**\n * Tries to deliver one batch. It removes the batch on success. On failure, it applies the\n * rule for the failure kind.\n * @param batch Log batch to deliver.\n * @returns \"next\" to continue with the next batch. \"stop\" to stop the current drain. A delay\n * in milliseconds blocks the kind of the batch until the next drain.\n */\n private async deliver(batch: LogBatch): Promise<Outcome> {\n if (batch.attempts >= this.maxAttempts) {\n this.diagnostics.report(\n \"storage.dead_lettered\",\n `The library dropped a batch after ${batch.attempts.toString()} attempts.`,\n { batchId: batch.id, records: batch.records.length },\n );\n this.onLoss(\"max_attempts\", batch.records, [batch.id]);\n await this.bounded(this.storage.remove(batch.id));\n return \"next\";\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 \"next\";\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 \"next\";\n }\n\n // Offline stops both kinds. The other endpoint is not reachable either.\n if (failure?.kind === \"offline\") {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return \"stop\";\n }\n\n // A throttle rejects no records. The server asks for the batch later. Do not bump the\n // stored attempts here. A bump dead-letters the batch after five throttled responses.\n if (failure?.kind === \"throttled\") {\n this.attempt++;\n return failure.retryAfterMs ?? this.backoffMs();\n }\n\n await this.bounded(this.storage.bumpAttempts(batch.id, batch.attempts + 1));\n this.attempt++;\n return failure?.retryAfterMs ?? this.backoffMs();\n }\n }\n\n /**\n * Replaces a stored batch with the parts that survive its failure. The parts\n * are the split halves, or nothing after a permanent refusal.\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 * Selects the batches to keep after a failure. A 413 response splits the batch\n * in two. A permanent refusal keeps nothing. Each 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. The array is empty when the engine drops the records.\n */\n private toStorable(batch: LogBatch, error: unknown): LogBatch[] {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\") {\n this.onLoss(\"rejected\", batch.records, [batch.id]);\n return [];\n }\n\n if (failure?.kind !== \"too_large\") {\n return [batch];\n }\n\n const halves = splitBatch(batch, this.diagnostics);\n\n if (!halves) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n \"One record is larger than the server limit. The library dropped it.\",\n {\n batchId: batch.id,\n bodies: batch.records.map((record) => record.body),\n },\n );\n this.onLoss(\"rejected\", batch.records, [batch.id]);\n return [];\n }\n\n this.diagnostics.report(\n \"transport.batch_split\",\n \"The server refused the batch because it is too large.\",\n {\n from: batch.records.length,\n to: halves[0].records.length,\n serverMaxBytes: failure.maxBytes,\n },\n );\n\n return halves;\n }\n}\n","// src/core/pipeline.ts\n//\n// This module buffers the log and metric streams. It makes batches. It delivers them.\n//\n// Each stream has its own buffer and flush timer. Thus the exit flush can take each\n// record that is not yet at the transport.\n\nimport {\n ATTR_LOG_TYPE,\n LOG_TYPE_METRIC,\n MAX_CONCURRENT_REQUESTS,\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 { BatchTransport } from \"../transport/status-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/** Name of a pipeline stream. */\nexport type StreamName = \"logs\" | \"metrics\";\n\n/**\n * Checks if a log record is 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 /** Maximum time in milliseconds that a partial batch waits before the pipeline sends it. */\n flushIntervalMs: number;\n /** Maximum records in a batch. At this count, the pipeline sends the batch early. */\n batchSize: number;\n}\n\n/** A closed batch in the queue or in flight. */\ninterface Pending {\n /** Batch to deliver. */\n batch: LogBatch;\n /** Resolves when the dispatch of the batch ends, or on destroy. */\n done: Promise<void>;\n /** Resolves `done`. */\n resolve: () => void;\n}\n\n/** One stream's pending records and the timer that closes a partial batch. */\nclass RecordStream {\n /** Pending records in time 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 * Adds a record to the buffer. At batchSize records, it closes the batch.\n * Below batchSize, it starts the interval timer. Without the timer, a small batch\n * waits for the next record. On a quiet page, the next record does not come.\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 * Removes and returns all buffered records. It also stops 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 /** Stops the flush timer. The buffered records stay 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/** Buffers the log and metric streams. It makes batches. It sends them over HTTP. */\nexport class LogPipeline {\n /** Buffer instances for logs and metrics streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** In-flight batches without delivery confirmation. The exit flush sends them again. */\n private readonly unconfirmed = new Map<string, LogBatch>();\n\n /** Closed batches waiting for a free dispatch slot. */\n private readonly queue: Pending[] = [];\n\n /** Each batch in the queue or in flight. flushPending waits for them. destroy() resolves them. */\n private readonly open = new Set<Pending>();\n\n /** Ceiling on the ERROR and FATAL records that bypass sampling. */\n private readonly ceiling = new ErrorCeiling();\n\n /** Number of dispatches in flight. MAX_CONCURRENT_REQUESTS is the limit. */\n private inFlight = 0;\n\n /** It is true when a pump is in the queue. One microtask then drains a burst. */\n private pumpScheduled = false;\n\n /** True after destroy() stops the pipeline. */\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, from the batching config.\n */\n constructor(\n private readonly transport: BatchTransport,\n private readonly storage: StorageAdapter,\n private readonly retry: RetryEngine,\n private readonly diagnostics: Diagnostics,\n streamOptions: Record<StreamName, StreamOptions>,\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 * Sets the observed timestamp and adds a record to 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 all buffered and unconfirmed in-flight records into exit batches in one step.\n * Records already given to fetch go again under a new batch ID. The server cannot\n * deduplicate them. Thus the exit flush can deliver duplicates. This is intentional.\n * A closing document cannot confirm delivery.\n * @returns One batch of metric records and one batch of other records. A kind with no\n * records has no batch. A mixed batch sends a metric to the endpoint of the logs.\n */\n drainForExit(): LogBatch[] {\n const inFlight = [...this.unconfirmed.values()].flatMap((batch) => batch.records);\n this.unconfirmed.clear();\n\n const metrics = [...inFlight.filter(isMetric), ...this.streams.metrics.take()];\n const logs = [...inFlight.filter((record) => !isMetric(record)), ...this.streams.logs.take()];\n\n return [this.toBatch(metrics), this.toBatch(logs)].filter((batch) => batch !== null);\n }\n\n /**\n * Sends the buffered records through the normal dispatch path. Then it waits for each\n * batch in the queue and in flight. The throttle check and the concurrency limit apply.\n * A direct send goes around both.\n * @returns Promise that resolves when the pipeline sends or stores each batch, or on destroy.\n */\n async flushPending(): Promise<void> {\n // One batch for each stream. A mixed batch sends a metric to the endpoint of the logs.\n // The claim does not take an in-flight batch. A second copy under a new ID is a duplicate\n // that the server cannot remove.\n if (!this.stopped) {\n this.claim(this.streams.metrics);\n this.claim(this.streams.logs);\n }\n\n // A batch in the queue counts too. If not, the exit flush sends it again under a new id.\n await Promise.all([...this.open].map((pending) => pending.done));\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 // destroy() drops each queued batch. Release each flushPending that waits for one.\n for (const pending of this.open) {\n pending.resolve();\n }\n this.open.clear();\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 the drain takes nothing.\n */\n private toBatch(records: LogRecord[]): LogBatch | null {\n if (records.length === 0) {\n return null;\n }\n\n return { id: newId(this.diagnostics), records, createdAt: Date.now(), attempts: 0 };\n }\n\n /**\n * Sorts a record into its stream. Sampling already ran. RecordBuilder samples a local\n * record. The runtime samples a forwarded record. This method catches each fault.\n * A record without `attributes` makes isMetric throw. An uncaught throw goes into the\n * log call of the caller.\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 records bypass sampling upstream. This ceiling is their only\n // limit.\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 \"The pipeline dropped a record before it reached a stream.\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Drains a stream buffer into a new batch and queues the batch for dispatch.\n * A timer or a flush calls it. An empty buffer gives no batch.\n * Each `take` stops the timer that calls this method.\n * @param stream Stream buffer to drain.\n */\n private claim(stream: RecordStream): void {\n this.enqueue(this.toBatch(stream.take()));\n }\n\n /**\n * Queues a batch and schedules the pump on a microtask. An inline dispatch starts\n * a fetch inside the log call of the application.\n * @param batch Batch ready for delivery, or null when the drain found no records.\n */\n private enqueue(batch: LogBatch | null): void {\n if (!batch) {\n return;\n }\n\n let resolve!: () => void;\n const done = new Promise<void>((settle) => {\n resolve = settle;\n });\n const pending: Pending = { batch, done, resolve };\n\n this.unconfirmed.set(batch.id, batch);\n this.open.add(pending);\n this.queue.push(pending);\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 pending = this.queue.shift();\n if (!pending) {\n return;\n }\n\n this.inFlight++;\n void this.run(pending);\n }\n }\n\n /**\n * Delivers one batch. It then frees the concurrency slot. It resolves the promise of the batch.\n * @param pending Batch to deliver.\n */\n private async run(pending: Pending): Promise<void> {\n const { batch } = pending;\n\n try {\n await this.dispatch(batch);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"A dispatch rejected its promise. This must not occur.\",\n { batchId: batch.id },\n error,\n );\n } finally {\n this.inFlight--;\n this.open.delete(pending);\n pending.resolve();\n this.pump();\n }\n }\n\n /**\n * Sends a batch over the HTTP transport. If the transport throttles or fails, it stores\n * the batch.\n * @param batch Batch to deliver.\n */\n private async dispatch(batch: LogBatch): Promise<void> {\n try {\n // Store the batch while the transport throttles. A send here posts a batch each\n // flush interval through the throttle. Do not change the attempt count.\n // The pipeline sent nothing.\n const throttledMs = this.transport.throttledForMs(batch);\n if (throttledMs > 0) {\n await this.store(batch);\n this.diagnostics.report(\n \"transport.throttled\",\n \"The server throttles requests. The pipeline stored the batch and did not send it.\",\n {\n batchId: batch.id,\n records: batch.records.length,\n throttledMs,\n },\n );\n return;\n }\n\n try {\n // A keepalive request continues after unload. The exit flush must not send it again.\n // A failed send still goes to the retry engine from this batch reference.\n await this.transport.send(batch, () => {\n this.unconfirmed.delete(batch.id);\n });\n } catch (error) {\n // Increment the attempt count before the store. At 0, the batch exceeds\n // STORAGE_LIMITS.maxAttempts by one. The attempt headers then report one too few.\n await this.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n this.diagnostics.report(\n \"transport.http_error\",\n \"The send failed. The pipeline stored the batch for a retry.\",\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 * Stores a batch that the transport refused. The retry engine splits a 413 and\n * drops a batch that the server does not 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 \"The library could not store an undelivered batch.\",\n async () => {\n await this.retry.storeFailed(batch, error);\n },\n );\n }\n\n /**\n * Stores an undelivered batch. Then it starts the retry engine. A deadline limits the\n * wait. A storage call that does not settle holds this dispatch slot. Two such calls\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 \"The library could not store 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// This module builds the delivery stack of the sender role.\n// The stack has storage, transport, retry, pipeline and exit flush.\n// The runtime imports this module dynamically only when the config sets an endpoint.\n// Console-only mode does not download this module.\n\nimport { BATCHES_PER_DRAIN, STORAGE_DB_NAME } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { type GapReporter, type StorageAdapter, storageLimits } from \"../models/storage\";\nimport { drainEmergencyQueue } from \"../storage/emergency-queue\";\nimport { createStorage } from \"../storage/factory\";\nimport { ExitFlush } from \"../transport/exit-flush\";\nimport { CustomTransport } from \"../transport/custom-transport\";\nimport { HttpTransport } from \"../transport/http-transport\";\nimport { RetryEngine } from \"../transport/retry-engine\";\nimport type { BatchTransport } from \"../transport/status-transport\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { LogPipeline } from \"./pipeline\";\nimport { applyRemote, parseRemoteRules } from \"./remote-rules\";\nimport type { RemoteSlot } from \"./remote-sampling\";\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 /** Receives the records that the transport, the retry engine and the exit flush lose. */\n onLoss: LossReporter;\n /** Slot of the runtime for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Sends the points of the open metric interval before the exit flush drains the buffers. */\n beforeExit?: () => void;\n}\n\n/** Delivery stack for one sender runtime. */\nexport class Sender {\n /**\n * @param storage Storage adapter for undelivered batches.\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 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 and starts the retry loop. The emergency queue import runs\n * after the start. A slow IndexedDB open then does not hold the boot buffer.\n * @param deps Configuration, diagnostics and gap reporter.\n * @returns Promise that resolves 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 storageLimits(config.retention),\n diagnostics,\n deps.onGap,\n );\n const onSampling = (raw: unknown): void => {\n const update = parseRemoteRules(raw, diagnostics);\n\n if (update) {\n applyRemote(deps.remote, config, update);\n }\n };\n\n // The stack keeps one transport for its life. The runtime refuses a later change.\n // The exit flush reads the last headers from the HTTP transport.\n const { onLoss } = deps;\n const http = config.transport\n ? undefined\n : new HttpTransport(config, diagnostics, onSampling, onLoss);\n const transport: BatchTransport =\n http ?? new CustomTransport(config, diagnostics, onSampling, onLoss);\n const retry = new RetryEngine(\n storage,\n transport,\n diagnostics,\n config,\n BATCHES_PER_DRAIN,\n onLoss,\n );\n const { batching } = config;\n const pipeline = new LogPipeline(transport, storage, retry, diagnostics, {\n logs: { flushIntervalMs: batching.logFlushIntervalMs, batchSize: batching.logBatchSize },\n metrics: {\n flushIntervalMs: batching.metricFlushIntervalMs,\n batchSize: batching.metricBatchSize,\n },\n });\n\n const exitFlush = new ExitFlush({\n config,\n diagnostics,\n drainForExit: () => pipeline.drainForExit(),\n flushAlive: () => pipeline.flushPending(),\n exitHeaders: () => http?.lastHeaders(),\n onLoss,\n beforeExit: deps.beforeExit,\n });\n\n // If one step fails, stop both. A retry loop with no owner sends after load reports 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 const sender = new Sender(storage, retry, pipeline, exitFlush, diagnostics);\n void sender.importEmergency();\n return sender;\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 in the stream buffers. Then it waits for each batch in flight.\n * @returns Promise that resolves when the pipeline sends or stores each batch.\n */\n async flush(): Promise<void> {\n await this.pipeline.flushPending();\n }\n\n /**\n * Counts the batches held in storage.\n * @returns Promise that resolves 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 \"The library could not count the batches in storage.\",\n () => this.storage.count(),\n );\n\n return count ?? 0;\n }\n\n /**\n * Sends pending records with a normal flush, then with the exit flush. Then it stops all\n * timers and listeners. Then it closes storage. The normal flush keeps the headers, gzip\n * and the retry. The exit flush takes the records that the normal flush did not confirm.\n * @returns Promise that resolves when storage closes.\n */\n async destroy(): Promise<void> {\n await this.diagnostics.guardAsync(\"pipeline.crashed\", \"The flush before shutdown failed.\", () =>\n this.flush(),\n );\n\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 /**\n * Moves the batches of the emergency queue into storage, then wakes the retry engine.\n * The previous page load parked them during its unload.\n */\n private async importEmergency(): Promise<void> {\n const moved = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The emergency import failed.\",\n () => drainEmergencyQueue(this.storage, this.diagnostics),\n );\n\n if (moved !== undefined && moved > 0) {\n this.retry.nudge();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAuEA,SAAgB2D,EAAc,GAA4C;CACxE,IAAM,EAAE,kBAAeC;CAMvB,OAJIA,EAAU,SAAS,oBACd;EAAE;EAAY,UAAU;EAAU,aAAa;CAAS,IAG1D;EAAE;EAAY,UAAUA,EAAU;EAAU,aAAaA,EAAU;CAAY;AACxF;;;AC3CA,SAAgBC,EACd,GACA,GACA,GACA,EAAE,gBAAa,OAAmC,CAAC,GAC3B;CACxB,IAAMC,IAAS,WAA2D,WAAW;CAOrF,OAJKA,GAAO,UAILC,EAAY,WACjB,oBACA,sCAAsCC,EAAK,UAEzCF,EAAM,QAAQE,GAAM,EAAE,aAAaC,EAAW,IAAI,MAChDC,IAAOC,EAAG,IAAI,QAAQ,QAAQ,KAAA,CAAS,CACzC,CACJ,IAVSA,EAAG;AAWd;;;ACzCA,SAAgBC,EAAS,GAAgB,GAAyB;CAEhE,OAAO,GAAGC,IADC,OAAOC,EAAM,SAAS,CAAC,CAAC,SAAA,IAA+B,GAC/C,EAAG,GAAGA,EAAM;AACjC;A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WACnC,oBACA,6DACM,KAAK,QAAQ,MAAM,CAC3B,KAEgB;CAClB;CAQA,MAAM,UAAyB;EAU7B,AATA,MAAM,KAAK,YAAY,WAAW,oBAAoB,2CACpD,KAAK,MAAM,CACb,GAEA,KAAK,UAAU,MAAM,UAAU,GAC/B,KAAK,UAAU,UAAU,GACzB,KAAK,MAAM,KAAK,GAChB,KAAK,SAAS,QAAQ,GAEtB,MAAM,KAAK,QAAQ,MAAM;CAC3B;CAMA,MAAc,kBAAiC;EAC7C,IAAM/E,IAAQ,MAAM,KAAK,YAAY,WACnC,oBACA,sCACMc,GAAoB,KAAK,SAAS,KAAK,WAAW,CAC1D;EAEA,AAAId,MAAU,KAAA,KAAaA,IAAQ,KACjC,KAAK,MAAM,MAAM;CAErB;AACF"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Diagnostics } from "../core/diagnostics";
|
|
2
|
+
import type { LogBatch } from "../models/batch";
|
|
3
|
+
import type { GapReporter, PruneResult } from "../models/storage";
|
|
4
|
+
/**
|
|
5
|
+
* Adds the drop of one rule to the prune result.
|
|
6
|
+
* @param result Prune result of all rules.
|
|
7
|
+
* @param reason Rule that dropped the batches.
|
|
8
|
+
* @param batches Number of dropped batches.
|
|
9
|
+
* @param records Number of dropped records.
|
|
10
|
+
* @returns The counts of this rule alone, for the gap report.
|
|
11
|
+
*/
|
|
12
|
+
export declare function addDrop(result: PruneResult, reason: PruneResult["reason"], batches: number, records: number): PruneResult;
|
|
13
|
+
/**
|
|
14
|
+
* Reports dropped batches to diagnostics and to the gap handler. An empty drop reports nothing.
|
|
15
|
+
* @param diagnostics Diagnostics reporter.
|
|
16
|
+
* @param onGap Gap handler of the adapter.
|
|
17
|
+
* @param gap Counts and reason of the drop.
|
|
18
|
+
* @param dropped The dropped batches that the adapter could read.
|
|
19
|
+
*/
|
|
20
|
+
export declare function reportEviction(diagnostics: Diagnostics, onGap: GapReporter | undefined, gap: PruneResult, dropped: readonly LogBatch[]): void;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Diagnostics } from "../core/diagnostics";
|
|
2
|
-
import type
|
|
2
|
+
import { type LogBatch } from "../models/batch";
|
|
3
3
|
import type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from "../models/storage";
|
|
4
4
|
/** This StorageAdapter keeps batches in IndexedDB. */
|
|
5
5
|
export declare class IndexedDbStorage implements StorageAdapter {
|
|
@@ -66,12 +66,6 @@ export declare class IndexedDbStorage implements StorageAdapter {
|
|
|
66
66
|
* @param dropped The dropped batches.
|
|
67
67
|
*/
|
|
68
68
|
private addGap;
|
|
69
|
-
/**
|
|
70
|
-
* Reports dropped records to diagnostics and to the gap handler.
|
|
71
|
-
* @param result Prune result metrics.
|
|
72
|
-
* @param dropped The dropped batches.
|
|
73
|
-
*/
|
|
74
|
-
private reportGap;
|
|
75
69
|
/**
|
|
76
70
|
* Deletes the given number of stored batches. Batches without an action go first, oldest
|
|
77
71
|
* first. An action is an audit fact. It has no guard. Both callers guard it. A guard here
|
package/dist/storage/keys.d.ts
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import type { Diagnostics } from "../core/diagnostics";
|
|
2
|
+
import type { LogBatch } from "../models/batch";
|
|
3
|
+
/**
|
|
4
|
+
* Formats a storage key with a zero-padded creation time. The keys sort in FIFO order. Always use
|
|
5
|
+
* batch.createdAt, never Date.now(). A key from Date.now() does not match the written key.
|
|
6
|
+
* @param prefix Storage key prefix.
|
|
7
|
+
* @param batch Target log batch.
|
|
8
|
+
* @returns Prefixed, timestamp-ordered storage key.
|
|
9
|
+
*/
|
|
10
|
+
export declare function batchKey(prefix: string, batch: LogBatch): string;
|
|
2
11
|
/**
|
|
3
12
|
* Returns all localStorage keys that start with the prefix, in sorted order.
|
|
4
13
|
* @param prefix Storage key prefix to filter by.
|
|
@@ -82,12 +82,6 @@ export declare class LocalStorageStorage implements StorageAdapter {
|
|
|
82
82
|
* @param entries Entries to remove.
|
|
83
83
|
*/
|
|
84
84
|
private drop;
|
|
85
|
-
/**
|
|
86
|
-
* Reports dropped records to diagnostics and to the gap handler.
|
|
87
|
-
* @param result Eviction metrics.
|
|
88
|
-
* @param dropped The dropped batches that the adapter could read.
|
|
89
|
-
*/
|
|
90
|
-
private reportGap;
|
|
91
85
|
/**
|
|
92
86
|
* Reads and validates the stored batch at a key.
|
|
93
87
|
* @param key Storage key to read.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type LogBatch } from "../models/batch";
|
|
2
2
|
import type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from "../models/storage";
|
|
3
3
|
/** This StorageAdapter keeps batches in volatile memory. */
|
|
4
4
|
export declare class MemoryStorage implements StorageAdapter {
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-Cb92egPS.cjs"),t=require("./fixed-window-BR0bu32Y.cjs");function n(n,r,i,a){return t.t(n,r,1e4)?!0:(i.report(`capture.rate_limited`,`More than ${String(r)} ${a} occurred in ${String(e.G)} ms. The library ignores the other ${a} in this window.`),!1)}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
|
|
2
|
+
//# sourceMappingURL=storm-DhHGHhOc.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storm-DhHGHhOc.cjs","names":["countInWindow","ERROR_STORM_WINDOW_MS","require_constants","require_fixed_window","allowInWindow","window","limit","diagnostics","what"],"sources":["../src/capture/storm.ts"],"sourcesContent":["// src/capture/storm.ts\n//\n// Fixed-window rate limit for the capture modules. A render loop that throws or freezes\n// makes thousands of events each second. Sending all of them floods the ingest endpoint.\n\nimport { ERROR_STORM_WINDOW_MS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\n\nexport type { StormWindow } from \"../utils/fixed-window\";\n\n/**\n * Counts one event in a fixed window. It reports each event over the limit.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param diagnostics Diagnostics reporter.\n * @param what Plural name of the events, for the diagnostic message.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function allowInWindow(\n window: StormWindow,\n limit: number,\n diagnostics: Diagnostics,\n what: string,\n): boolean {\n if (countInWindow(window, limit, ERROR_STORM_WINDOW_MS)) {\n return true;\n }\n\n diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(limit)} ${what} occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other ${what} in this window.`,\n );\n return false;\n}\n"],"mappings":"qFAmBA,SAAgBI,EACd,EACA,EACA,EACA,EACS,CAST,OARIJ,EAAAA,EAAcK,EAAQC,EAAA,GAA4B,EAC7C,IAGTC,EAAY,OACV,uBACA,aAAa,OAAOD,CAAK,EAAE,GAAGE,EAAK,eAAe,OAAOP,EAAAA,CAAqB,EAAE,qCAAqCO,EAAK,iBAC5H,EACO,GACT"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { G as e } from "./constants-DhH6VI5a.js";
|
|
2
|
+
import { t } from "./fixed-window-Re7jIRJH.js";
|
|
3
|
+
//#region src/capture/storm.ts
|
|
4
|
+
function n(n, r, i, a) {
|
|
5
|
+
return t(n, r, 1e4) ? !0 : (i.report("capture.rate_limited", `More than ${String(r)} ${a} occurred in ${String(e)} ms. The library ignores the other ${a} in this window.`), !1);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
export { n as t };
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=storm-OD5J6Ylm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storm-OD5J6Ylm.js","names":["ERROR_STORM_WINDOW_MS","allowInWindow","countInWindow","window","limit","diagnostics","what"],"sources":["../src/capture/storm.ts"],"sourcesContent":["// src/capture/storm.ts\n//\n// Fixed-window rate limit for the capture modules. A render loop that throws or freezes\n// makes thousands of events each second. Sending all of them floods the ingest endpoint.\n\nimport { ERROR_STORM_WINDOW_MS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\n\nexport type { StormWindow } from \"../utils/fixed-window\";\n\n/**\n * Counts one event in a fixed window. It reports each event over the limit.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param diagnostics Diagnostics reporter.\n * @param what Plural name of the events, for the diagnostic message.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function allowInWindow(\n window: StormWindow,\n limit: number,\n diagnostics: Diagnostics,\n what: string,\n): boolean {\n if (countInWindow(window, limit, ERROR_STORM_WINDOW_MS)) {\n return true;\n }\n\n diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(limit)} ${what} occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other ${what} in this window.`,\n );\n return false;\n}\n"],"mappings":";;;AAmBA,SAAgBC,EACd,GACA,GACA,GACA,GACS;CAST,OARIC,EAAcC,GAAQC,GAAA,GAA4B,IAC7C,MAGTC,EAAY,OACV,wBACA,aAAa,OAAOD,CAAK,EAAE,GAAGE,EAAK,eAAe,OAAON,CAAqB,EAAE,qCAAqCM,EAAK,iBAC5H,GACO;AACT"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import type { LogBatch } from "../models/batch";
|
|
2
|
-
import type { TransportRequest } from "../models/config";
|
|
2
|
+
import type { BatchKind, TransportRequest } from "../models/config";
|
|
3
3
|
import type { SerializedBatch } from "../models/serializer";
|
|
4
4
|
import { StatusTransport } from "./status-transport";
|
|
5
5
|
/**
|
|
6
6
|
* Builds the request that a custom transport and its exit hook receive.
|
|
7
7
|
* @param batch Batch to send.
|
|
8
8
|
* @param serialized Serialized form of the batch.
|
|
9
|
+
* @param kind Kind of the batch.
|
|
9
10
|
* @returns The transport request.
|
|
10
11
|
*/
|
|
11
|
-
export declare function toTransportRequest(batch: LogBatch, serialized: SerializedBatch): TransportRequest;
|
|
12
|
+
export declare function toTransportRequest(batch: LogBatch, serialized: SerializedBatch, kind: BatchKind): TransportRequest;
|
|
12
13
|
/** Sends batches through the consumer's transport function. */
|
|
13
14
|
export declare class CustomTransport extends StatusTransport {
|
|
14
15
|
/**
|