@utk09/ui-observability 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -15
- package/README.md +94 -82
- package/dist/bus/links.d.ts +5 -4
- package/dist/capture/network.d.ts +1 -1
- package/dist/constants-BpFlszME.cjs +2 -0
- package/dist/constants-BpFlszME.cjs.map +1 -0
- package/dist/constants-CrU3IUyy.js +74 -0
- package/dist/constants-CrU3IUyy.js.map +1 -0
- package/dist/constants.d.ts +20 -2
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/logger.d.ts +7 -5
- package/dist/core/pipeline.d.ts +19 -6
- package/dist/core/record.d.ts +11 -2
- package/dist/core/runtime.d.ts +13 -1
- package/dist/core/sampling.d.ts +42 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +728 -565
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-DAoHV_oL.js → indexeddb-storage-CSaDuHGk.js} +19 -15
- package/dist/indexeddb-storage-CSaDuHGk.js.map +1 -0
- package/dist/indexeddb-storage-DIJIbFnp.cjs +2 -0
- package/dist/indexeddb-storage-DIJIbFnp.cjs.map +1 -0
- package/dist/models/config.d.ts +69 -2
- package/dist/storage/local-storage.d.ts +14 -0
- package/dist/transport/exit-flush.d.ts +1 -1
- package/dist/utils/console.d.ts +4 -1
- package/dist/utils/identity.d.ts +17 -6
- package/dist/utils/platform.d.ts +7 -0
- package/dist/utils/sanitize.d.ts +2 -0
- package/dist/utils/tracing.d.ts +17 -1
- package/package.json +10 -8
- package/dist/constants-DkrpC_xK.cjs +0 -2
- package/dist/constants-DkrpC_xK.cjs.map +0 -1
- package/dist/constants-NJNXpfPi.js +0 -67
- package/dist/constants-NJNXpfPi.js.map +0 -1
- package/dist/indexeddb-storage-CH9NocOC.cjs +0 -2
- package/dist/indexeddb-storage-CH9NocOC.cjs.map +0 -1
- package/dist/indexeddb-storage-DAoHV_oL.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $ as e, Jt as t, Q as n } from "./constants-CrU3IUyy.js";
|
|
2
2
|
//#region src/storage/idb-driver.ts
|
|
3
3
|
function r(e) {
|
|
4
4
|
return e.error ?? /* @__PURE__ */ Error("the IndexedDB request failed");
|
|
@@ -22,11 +22,11 @@ var a = class {
|
|
|
22
22
|
await i((await this.store("readwrite")).put(e));
|
|
23
23
|
}
|
|
24
24
|
async takeOldest(e) {
|
|
25
|
-
return i((await this.store("readonly")).index(
|
|
25
|
+
return i((await this.store("readonly")).index(n).getAll(null, e));
|
|
26
26
|
}
|
|
27
27
|
async takeBefore(e) {
|
|
28
|
-
let
|
|
29
|
-
return i(
|
|
28
|
+
let t = await this.store("readonly"), r = IDBKeyRange.upperBound(e, !0);
|
|
29
|
+
return i(t.index(n).getAll(r));
|
|
30
30
|
}
|
|
31
31
|
async delete(e) {
|
|
32
32
|
await i((await this.store("readwrite")).delete(e));
|
|
@@ -56,15 +56,15 @@ var a = class {
|
|
|
56
56
|
return (await this.open()).transaction(e, t).objectStore(e);
|
|
57
57
|
}
|
|
58
58
|
open() {
|
|
59
|
-
let
|
|
60
|
-
if (
|
|
61
|
-
let i = new Promise((
|
|
59
|
+
let t = this.connection;
|
|
60
|
+
if (t !== null) return t;
|
|
61
|
+
let i = new Promise((t, i) => {
|
|
62
62
|
let a = indexedDB.open(this.name, 11);
|
|
63
63
|
a.onupgradeneeded = () => {
|
|
64
|
-
let
|
|
65
|
-
|
|
64
|
+
let t = a.result;
|
|
65
|
+
t.objectStoreNames.contains("batches") || t.createObjectStore(e, { keyPath: "id" }).createIndex(n, n);
|
|
66
66
|
}, a.onsuccess = () => {
|
|
67
|
-
|
|
67
|
+
t(a.result);
|
|
68
68
|
}, a.onerror = () => {
|
|
69
69
|
i(r(a));
|
|
70
70
|
};
|
|
@@ -81,7 +81,7 @@ var s = class {
|
|
|
81
81
|
limits;
|
|
82
82
|
diagnostics;
|
|
83
83
|
onGap;
|
|
84
|
-
name =
|
|
84
|
+
name = t;
|
|
85
85
|
db;
|
|
86
86
|
constructor(e, t, n, r) {
|
|
87
87
|
this.limits = t, this.diagnostics = n, this.onGap = r, this.db = new a(e);
|
|
@@ -92,9 +92,13 @@ var s = class {
|
|
|
92
92
|
} catch (t) {
|
|
93
93
|
if (t instanceof Error && t.name === "QuotaExceededError") {
|
|
94
94
|
this.diagnostics.report("storage.quota_exceeded", "IndexedDB is full, evicting the oldest");
|
|
95
|
-
let
|
|
96
|
-
|
|
97
|
-
...
|
|
95
|
+
let t = await this.diagnostics.guardAsync("storage.degraded", "evicting after a full disk", () => this.evictOldest(Math.ceil(this.limits.maxBatches / 4)));
|
|
96
|
+
t && this.reportGap({
|
|
97
|
+
...t,
|
|
98
|
+
reason: "quota"
|
|
99
|
+
}), await this.diagnostics.guardAsync("storage.degraded", "writing a batch after evicting", async () => (await this.db.put(e), !0)) !== !0 && this.reportGap({
|
|
100
|
+
batches: 1,
|
|
101
|
+
records: e.records.length,
|
|
98
102
|
reason: "quota"
|
|
99
103
|
});
|
|
100
104
|
return;
|
|
@@ -151,4 +155,4 @@ var s = class {
|
|
|
151
155
|
//#endregion
|
|
152
156
|
export { s as IndexedDbStorage };
|
|
153
157
|
|
|
154
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
158
|
+
//# sourceMappingURL=indexeddb-storage-CSaDuHGk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-CSaDuHGk.js","names":[],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// Raw IndexedDB mechanics for the batch store: opening, request promises, and the\n// createdAt-ordered reads. Everything above this file works in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Reads the failure off a request that has errored. A host whose request reports\n * no error gets a stand-in: rejecting with null makes the instanceof Error test\n * in save() false, and a full disk is then reported as an ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"the IndexedDB request failed\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with its error. The\n * request is read as IDBRequest<any>, so every caller names the type it expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** One IndexedDB database holding undelivered batches keyed by id. */\nexport class IdbDriver {\n /** Open in progress or completed, reused so one database is opened per driver. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any batch already stored under the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Reads every batch created strictly before a cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction, so a partial failure leaves none\n * of them deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Rewrites the attempt count of a stored batch. An id that is not stored is\n * left alone: a batch already delivered and deleted must not be resurrected.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const read = await this.store(\"readonly\");\n const batch = await promisify<LogBatch | undefined>(read.get(id));\n if (batch === undefined) {\n return;\n }\n\n const write = await this.store(\"readwrite\");\n await promisify(write.put({ ...batch, attempts }));\n }\n\n /**\n * Counts stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /** Closes the connection, if one was ever opened. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a fresh transaction. A transaction is only valid\n * until control returns to the event loop, so every call takes a new one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database once and hands the same connection to every later call.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database written by an earlier release already carries the store.\n // Creating it again throws ConstraintError and the upgrade aborts.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n };\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n\n this.connection = opening;\n return opening;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB with time-ordered indexing.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** IndexedDB mechanics for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction exists to make room for this batch. Without a second\n // attempt save() resolves while the batch is gone and uncounted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"writing a batch after evicting\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () => this.db.clear());\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"closing the database\", () =>\n this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":";;AAmBA,SAAS,EAAU,GAA4B;CAC7C,OAAO,EAAQ,SAAS,gBA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promise((n,r)=>{e.onsuccess=()=>{n(e.result)},e.onerror=()=>{r(t(e))}})}var r=class{name;connection=null;constructor(e){this.name=e}async put(e){await n((await this.store(`readwrite`)).put(e))}async takeOldest(t){return n((await this.store(`readonly`)).index(e.Q).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.Q).getAll(i))}async delete(e){await n((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>n(t.delete(e))))}async bumpAttempts(e,t){let r=await n((await this.store(`readonly`)).get(e));r!==void 0&&await n((await this.store(`readwrite`)).put({...r,attempts:t}))}async count(){return n((await this.store(`readonly`)).count())}async clear(){await n((await this.store(`readwrite`)).clear())}async close(){let e=this.connection;e!==null&&(this.connection=null,(await e).close())}async store(t){return(await this.open()).transaction(e.$,t).objectStore(e.$)}open(){let n=this.connection;if(n!==null)return n;let r=new Promise((n,r)=>{let i=indexedDB.open(this.name,11);i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.$,{keyPath:`id`}).createIndex(e.Q,e.Q)},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(t(i))}});return this.connection=r,r}};function i(e){return e.reduce((e,t)=>e+t.records.length,0)}var a=class{limits;diagnostics;onGap;name=e.Jt;db;constructor(e,t,n,i){this.limits=t,this.diagnostics=n,this.onGap=i,this.db=new r(e)}async save(e){try{await this.db.put(e),await this.prune()}catch(t){if(t instanceof Error&&t.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full, evicting the oldest`);let t=await this.diagnostics.guardAsync(`storage.degraded`,`evicting after a full disk`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));t&&this.reportGap({...t,reason:`quota`}),await this.diagnostics.guardAsync(`storage.degraded`,`writing a batch after evicting`,async()=>(await this.db.put(e),!0))!==!0&&this.reportGap({batches:1,records:e.records.length,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`could not persist a batch`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`reading stored batches`,()=>this.db.takeOldest(e))??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`deleting a batch`,()=>this.db.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`updating attempts`,()=>this.db.bumpAttempts(e,t))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`pruning`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.takeBefore(t);n.length>0&&(await this.db.deleteMany(n.map(e=>e.id)),e.batches+=n.length,e.records+=i(n));let r=await this.db.count();if(r>this.limits.maxBatches){e.reason=`over_capacity`;let t=await this.evictOldest(r-this.limits.maxBatches);e.batches+=t.batches,e.records+=t.records}}),this.reportGap(e),e}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting`,()=>this.db.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`clearing`,()=>this.db.clear())}async close(){await this.diagnostics.guardAsync(`storage.degraded`,`closing the database`,()=>this.db.close())}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(e.batches)} stored batches (${String(e.records)} records)`,{...e}),this.onGap?.(e))}async evictOldest(e){let t=await this.db.takeOldest(e);return await this.db.deleteMany(t.map(e=>e.id)),{batches:t.length,records:i(t)}}};exports.IndexedDbStorage=a;
|
|
2
|
+
//# sourceMappingURL=indexeddb-storage-DIJIbFnp.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-DIJIbFnp.cjs","names":[],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// Raw IndexedDB mechanics for the batch store: opening, request promises, and the\n// createdAt-ordered reads. Everything above this file works in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Reads the failure off a request that has errored. A host whose request reports\n * no error gets a stand-in: rejecting with null makes the instanceof Error test\n * in save() false, and a full disk is then reported as an ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"the IndexedDB request failed\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with its error. The\n * request is read as IDBRequest<any>, so every caller names the type it expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** One IndexedDB database holding undelivered batches keyed by id. */\nexport class IdbDriver {\n /** Open in progress or completed, reused so one database is opened per driver. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any batch already stored under the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Reads every batch created strictly before a cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction, so a partial failure leaves none\n * of them deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Rewrites the attempt count of a stored batch. An id that is not stored is\n * left alone: a batch already delivered and deleted must not be resurrected.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const read = await this.store(\"readonly\");\n const batch = await promisify<LogBatch | undefined>(read.get(id));\n if (batch === undefined) {\n return;\n }\n\n const write = await this.store(\"readwrite\");\n await promisify(write.put({ ...batch, attempts }));\n }\n\n /**\n * Counts stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /** Closes the connection, if one was ever opened. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a fresh transaction. A transaction is only valid\n * until control returns to the event loop, so every call takes a new one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database once and hands the same connection to every later call.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database written by an earlier release already carries the store.\n // Creating it again throws ConstraintError and the upgrade aborts.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n };\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n\n this.connection = opening;\n return opening;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB with time-ordered indexing.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** IndexedDB mechanics for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction exists to make room for this batch. Without a second\n // attempt save() resolves while the batch is gone and uncounted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"writing a batch after evicting\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () => this.db.clear());\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"closing the database\", () =>\n this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mapp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ule {
|
|
|
47
47
|
*/
|
|
48
48
|
onTTFB: (report: WebVitalsReporter) => void;
|
|
49
49
|
}
|
|
50
|
+
/** W3C context an active OpenTelemetry span reports. */
|
|
51
|
+
export interface OtelSpanContext {
|
|
52
|
+
/** Hexadecimal 32-character W3C trace identifier. */
|
|
53
|
+
traceId: string;
|
|
54
|
+
/** Hexadecimal 16-character W3C span identifier. */
|
|
55
|
+
spanId: string;
|
|
56
|
+
/** Bitfield byte containing W3C trace flags. */
|
|
57
|
+
traceFlags: number;
|
|
58
|
+
}
|
|
59
|
+
/** The span the host has made active. */
|
|
60
|
+
export interface OtelSpan {
|
|
61
|
+
/**
|
|
62
|
+
* Reads this span's W3C context.
|
|
63
|
+
* @returns Trace and span ids with their flags.
|
|
64
|
+
*/
|
|
65
|
+
spanContext(): OtelSpanContext;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The three `@opentelemetry/api` entry points this library uses, typed
|
|
69
|
+
* structurally so the package stays an optional peer.
|
|
70
|
+
*/
|
|
71
|
+
export interface OtelApi {
|
|
72
|
+
/** Span lookup. */
|
|
73
|
+
trace: {
|
|
74
|
+
/**
|
|
75
|
+
* Reads the span the host has made active.
|
|
76
|
+
* @returns Active span, or undefined when there is none.
|
|
77
|
+
*/
|
|
78
|
+
getActiveSpan(): OtelSpan | undefined;
|
|
79
|
+
};
|
|
80
|
+
/** Ambient context lookup. */
|
|
81
|
+
context: {
|
|
82
|
+
/**
|
|
83
|
+
* Reads the active context.
|
|
84
|
+
* @returns Context, opaque to this library, understood by the propagator.
|
|
85
|
+
*/
|
|
86
|
+
active(): unknown;
|
|
87
|
+
};
|
|
88
|
+
/** Header propagation. */
|
|
89
|
+
propagation: {
|
|
90
|
+
/**
|
|
91
|
+
* Writes the host's trace headers into a carrier.
|
|
92
|
+
* @param context Context to propagate.
|
|
93
|
+
* @param carrier Header map written in place.
|
|
94
|
+
*/
|
|
95
|
+
inject(context: unknown, carrier: Record<string, string>): void;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Supplies the `@opentelemetry/api` module without a hard dependency on it.
|
|
100
|
+
* @returns A promise resolving to the module.
|
|
101
|
+
*/
|
|
102
|
+
export type OtelLoader = () => Promise<OtelApi>;
|
|
50
103
|
/** Sampling policy: which records survive. */
|
|
51
104
|
export interface SamplingOptions {
|
|
52
105
|
/**
|
|
@@ -128,6 +181,12 @@ export interface CaptureOptions {
|
|
|
128
181
|
* @default false
|
|
129
182
|
*/
|
|
130
183
|
webVitals: boolean;
|
|
184
|
+
/**
|
|
185
|
+
* Keep the query string and fragment on every URL the library records.
|
|
186
|
+
* Off strips them from page URLs, request targets and failed resource URLs.
|
|
187
|
+
* @default false
|
|
188
|
+
*/
|
|
189
|
+
fullUrls: boolean;
|
|
131
190
|
/**
|
|
132
191
|
* URLs excluded from logging. The ingest endpoint is always included.
|
|
133
192
|
* @default []
|
|
@@ -186,8 +245,8 @@ export interface ObservabilityConfig {
|
|
|
186
245
|
*/
|
|
187
246
|
serializer?: "otlp" | "ecs" | LogSerializer;
|
|
188
247
|
/**
|
|
189
|
-
* Passed to `fetch`.
|
|
190
|
-
* @default "
|
|
248
|
+
* Passed to `fetch`. Set "include" for an ingest endpoint that authenticates with cookies.
|
|
249
|
+
* @default "omit"
|
|
191
250
|
*/
|
|
192
251
|
credentials?: RequestCredentials;
|
|
193
252
|
/** Extra request headers, or a function returning them. */
|
|
@@ -217,6 +276,12 @@ export interface ObservabilityConfig {
|
|
|
217
276
|
* @default false
|
|
218
277
|
*/
|
|
219
278
|
console?: ConsoleOption;
|
|
279
|
+
/**
|
|
280
|
+
* Supplies the `@opentelemetry/api` module. Omit it and the library imports
|
|
281
|
+
* the package itself when it is installed.
|
|
282
|
+
* @see {@link OtelLoader}
|
|
283
|
+
*/
|
|
284
|
+
otelLoader?: OtelLoader;
|
|
220
285
|
/**
|
|
221
286
|
* Rewrites or drops a record before it's sent.
|
|
222
287
|
* @param record The record about to be sent.
|
|
@@ -270,6 +335,8 @@ export interface ResolvedConfig {
|
|
|
270
335
|
serializer: LogSerializer;
|
|
271
336
|
/** Extra request headers, or a function returning them. */
|
|
272
337
|
headers?: ObservabilityConfig["headers"];
|
|
338
|
+
/** Supplies the `@opentelemetry/api` module in place of importing it. */
|
|
339
|
+
otelLoader?: OtelLoader;
|
|
273
340
|
/**
|
|
274
341
|
* Rewrites or drops a record before it's sent.
|
|
275
342
|
* @param record The record about to be sent.
|
|
@@ -50,6 +50,20 @@ export declare class LocalStorageStorage implements StorageAdapter {
|
|
|
50
50
|
clear(): Promise<void>;
|
|
51
51
|
/** No-op storage teardown method. */
|
|
52
52
|
close(): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Writes a batch to localStorage.
|
|
55
|
+
* @param batch Batch to store.
|
|
56
|
+
* @param context Description reported if the write is refused.
|
|
57
|
+
* @returns True if the write succeeded.
|
|
58
|
+
*/
|
|
59
|
+
private write;
|
|
60
|
+
/** Drops the oldest quarter of the store to free quota, counting the loss. */
|
|
61
|
+
private evictForQuota;
|
|
62
|
+
/**
|
|
63
|
+
* Reports dropped records to diagnostics and registered gap handlers.
|
|
64
|
+
* @param result Eviction metrics.
|
|
65
|
+
*/
|
|
66
|
+
private reportGap;
|
|
53
67
|
/**
|
|
54
68
|
* Deserializes and validates a stored batch from a key.
|
|
55
69
|
* @param key Storage key to read.
|
|
@@ -10,7 +10,7 @@ export interface ExitFlushDeps {
|
|
|
10
10
|
/** Diagnostics reporter instance. */
|
|
11
11
|
diagnostics: Diagnostics;
|
|
12
12
|
/** Callback draining all pending buffered and unconfirmed batches into a single LogBatch. */
|
|
13
|
-
|
|
13
|
+
drainForExit: () => LogBatch | null;
|
|
14
14
|
}
|
|
15
15
|
/** Flushes pending telemetry on document unload using sendBeacon, keepalive fetch, or emergency storage. */
|
|
16
16
|
export declare class ExitFlush {
|
package/dist/utils/console.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import type { Diagnostics } from "../core/diagnostics";
|
|
1
2
|
import type { LogLevel } from "../models/log-record";
|
|
2
3
|
/** Mirrors log records directly to browser or Node console methods based on severity. */
|
|
3
4
|
export declare class ConsoleSink {
|
|
4
5
|
private minLevel;
|
|
6
|
+
private diagnostics;
|
|
5
7
|
/**
|
|
6
8
|
* @param minLevel Minimum log level required to emit, or null to mirror nothing.
|
|
9
|
+
* @param diagnostics Diagnostics reporter.
|
|
7
10
|
*/
|
|
8
|
-
constructor(minLevel: LogLevel | null);
|
|
11
|
+
constructor(minLevel: LogLevel | null, diagnostics: Diagnostics);
|
|
9
12
|
/**
|
|
10
13
|
* Updates the console mirroring threshold.
|
|
11
14
|
* @param minLevel Minimum log level required to emit, or null to mirror nothing.
|
package/dist/utils/identity.d.ts
CHANGED
|
@@ -27,10 +27,21 @@ export declare function newId(): string;
|
|
|
27
27
|
*/
|
|
28
28
|
export declare function resolveIdentity(diagnostics: Diagnostics): Identity;
|
|
29
29
|
/**
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
30
|
+
* Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`.
|
|
31
|
+
* The throttle is instance state, not module state: two runtimes in one document
|
|
32
|
+
* must not silence each other's session writes.
|
|
33
33
|
*/
|
|
34
|
-
export declare
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
export declare class SessionTouch {
|
|
35
|
+
private diagnostics;
|
|
36
|
+
/** Epoch milliseconds of the last write this instance made. */
|
|
37
|
+
private lastTouchAt;
|
|
38
|
+
/**
|
|
39
|
+
* @param diagnostics Diagnostics reporter.
|
|
40
|
+
*/
|
|
41
|
+
constructor(diagnostics: Diagnostics);
|
|
42
|
+
/**
|
|
43
|
+
* Updates the session activity timestamp in localStorage, at most once per window.
|
|
44
|
+
* @param sessionId Active session identifier.
|
|
45
|
+
*/
|
|
46
|
+
touch(sessionId: string): void;
|
|
47
|
+
}
|
package/dist/utils/platform.d.ts
CHANGED
|
@@ -32,5 +32,12 @@ export declare function isTopLevel(): boolean;
|
|
|
32
32
|
* @returns Current location.href or empty string.
|
|
33
33
|
*/
|
|
34
34
|
export declare function currentUrl(): string;
|
|
35
|
+
/**
|
|
36
|
+
* Drops the query string and fragment from a URL.
|
|
37
|
+
* A string cut, not a URL parse: a relative request target has no base to parse against.
|
|
38
|
+
* @param url Absolute or relative URL.
|
|
39
|
+
* @returns The URL up to the first "?" or "#".
|
|
40
|
+
*/
|
|
41
|
+
export declare function stripUrlQuery(url: string): string;
|
|
35
42
|
/** Resets the cached platform metadata for testing. */
|
|
36
43
|
export declare function resetPlatformCache(): void;
|
package/dist/utils/sanitize.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export interface SanitizeLimits {
|
|
|
10
10
|
maxAttributeCount: number;
|
|
11
11
|
/** Maximum error stack trace length in characters. */
|
|
12
12
|
maxStackChars: number;
|
|
13
|
+
/** Maximum values visited in one pass, across the whole tree. */
|
|
14
|
+
maxNodes: number;
|
|
13
15
|
}
|
|
14
16
|
/**
|
|
15
17
|
* Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.
|
package/dist/utils/tracing.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Diagnostics } from "../core/diagnostics";
|
|
2
|
+
import type { OtelLoader } from "../models/config";
|
|
2
3
|
/** W3C trace context fields attached to log records and network headers. */
|
|
3
4
|
export interface TraceContext {
|
|
4
5
|
/** Hexadecimal 32-character W3C trace identifier. */
|
|
@@ -26,21 +27,36 @@ export declare function newSpanId(): string;
|
|
|
26
27
|
export declare class TraceEngine {
|
|
27
28
|
private readonly diagnostics;
|
|
28
29
|
private readonly maxAgeMs;
|
|
30
|
+
private readonly load;
|
|
29
31
|
/**
|
|
30
32
|
* Active ambient trace context. Instance state, never module state. Two runtimes
|
|
31
33
|
* in one document must not share a trace id.
|
|
32
34
|
*/
|
|
33
35
|
private ambient;
|
|
36
|
+
/** The optional peer once loaded. Undefined while it loads, and forever if it is absent. */
|
|
37
|
+
private otel;
|
|
34
38
|
/**
|
|
35
39
|
* @param diagnostics Diagnostics reporter.
|
|
36
40
|
* @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.
|
|
41
|
+
* @param load Supplies the OpenTelemetry API.
|
|
37
42
|
*/
|
|
38
|
-
constructor(diagnostics: Diagnostics, maxAgeMs?: number);
|
|
43
|
+
constructor(diagnostics: Diagnostics, maxAgeMs?: number, load?: OtelLoader);
|
|
44
|
+
/**
|
|
45
|
+
* Loads the OpenTelemetry API. Records built before this resolves, and every
|
|
46
|
+
* record when the package is absent, carry the ambient trace instead.
|
|
47
|
+
* @returns Promise resolving once the attempt has settled.
|
|
48
|
+
*/
|
|
49
|
+
loadOtel(): Promise<void>;
|
|
39
50
|
/**
|
|
40
51
|
* Resolves trace context, prioritizing active OpenTelemetry spans over the ambient trace.
|
|
41
52
|
* @returns Active TraceContext.
|
|
42
53
|
*/
|
|
43
54
|
resolve(): TraceContext;
|
|
55
|
+
/**
|
|
56
|
+
* Reads the host's active span, if the peer is loaded and a span is running.
|
|
57
|
+
* @returns Trace context of the active span, or undefined.
|
|
58
|
+
*/
|
|
59
|
+
private activeSpanContext;
|
|
44
60
|
/**
|
|
45
61
|
* Rotates the ambient trace context to mark the start of a new logical operation.
|
|
46
62
|
* @param _reason Event reason triggering the rotation.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@utk09/ui-observability",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "UI observability and logging for browser, OpenFin and webview applications",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"keywords": [
|
|
@@ -75,32 +75,34 @@
|
|
|
75
75
|
"verify": "npm run format:check && npm run check:version && npm run typecheck && npm run lint && npm run build && npm run test:coverage",
|
|
76
76
|
"prepublishOnly": "npm run verify"
|
|
77
77
|
},
|
|
78
|
-
"dependencies": {
|
|
79
|
-
"@opentelemetry/api": "1.9.1"
|
|
80
|
-
},
|
|
81
78
|
"peerDependencies": {
|
|
79
|
+
"@opentelemetry/api": "^1",
|
|
82
80
|
"web-vitals": "^4 || ^5 || ^6"
|
|
83
81
|
},
|
|
84
82
|
"peerDependenciesMeta": {
|
|
83
|
+
"@opentelemetry/api": {
|
|
84
|
+
"optional": true
|
|
85
|
+
},
|
|
85
86
|
"web-vitals": {
|
|
86
87
|
"optional": true
|
|
87
88
|
}
|
|
88
89
|
},
|
|
89
90
|
"devDependencies": {
|
|
90
91
|
"@eslint/js": "10.0.1",
|
|
92
|
+
"@opentelemetry/api": "1.9.1",
|
|
91
93
|
"@types/node": "26.2.0",
|
|
92
94
|
"@vitest/coverage-istanbul": "4.1.11",
|
|
93
95
|
"concurrently": "10.0.5",
|
|
94
|
-
"eslint": "10.
|
|
96
|
+
"eslint": "10.10.0",
|
|
95
97
|
"eslint-config-prettier": "10.1.8",
|
|
96
98
|
"fake-indexeddb": "6.2.5",
|
|
97
|
-
"happy-dom": "20.
|
|
99
|
+
"happy-dom": "20.14.0",
|
|
98
100
|
"prettier": "3.9.6",
|
|
99
101
|
"rimraf": "6.1.3",
|
|
100
102
|
"typescript": "~5.9.3",
|
|
101
|
-
"typescript-eslint": "8.
|
|
103
|
+
"typescript-eslint": "8.70.0",
|
|
102
104
|
"vite": "8.2.2",
|
|
103
105
|
"vitest": "4.1.11",
|
|
104
|
-
"web-vitals": "6.
|
|
106
|
+
"web-vitals": "6.2.1"
|
|
105
107
|
}
|
|
106
108
|
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var ee=/OpenFin/i,e=/\bwv\b/,t=/\b(iPhone|iPad|iPod)\b/,n=/\bMacintosh\b/,r=/\bMobile\b/,i={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17,FATAL:21},a=i,o=`log.type`,s=`log.seq`,c=`app.namespace`,l=`page.url`,u=`url.full`,d=`journey.id`,f=`journey.name`,p=`journey.parent_id`,m=`uiobs.sanitize_failed`,h=`uiobs.attributes_dropped`,g=`uiobs.attributes_bytes`,_=`service.name`,v=`service.version`,y=`deployment.environment`,b=`telemetry.sdk.name`,x=`telemetry.sdk.version`,S=`telemetry.sdk.language`,C=`host.platform`,w=`session.id`,T=`tab.id`,E=`context.id`,D=`browser.user_agent`,O=`openfin.uuid`,k=`openfin.name`,A=`@utk09/ui-observability`,j=`0.2.0`,M=`webjs`,N=`otlp`,P=`application/json`,F=`application/x-ndjson`,I=1000000n,L=/^\d+$/,R=`Content-Type`,z=`Content-Encoding`,B=`Retry-After`,V=`X-UiObs-Batch-Id`,H=`X-UiObs-Attempt`,U=`gzip`,W=1e3,G=6e4,K=`text/plain;charset=UTF-8`,q=`uiobs_batch_id`,J=`uiobs_exit`,Y=`ui-observability.batch.`,X=`ui-observability.emergency.`,Z=`ui-observability.probe`,Q=`QuotaExceededError`,te=`batches`,ne=`createdAt`,$=`indexeddb`,re=`localstorage`,ie=`memory`,ae=`none`,oe=`ui-observability.drain`,se=`ui-observability.emergency`,ce=`ui-observability.journey`,le=2e3,ue=`uiObsJourney`,de=/\+/g,fe=/\//g,pe=/=+$/,me=/-/g,he=/_/g,ge=3e5,_e=`traceparent`,ve=2166136261,ye=16777619,be=4294967295,xe=`metric`,Se=`ui-observability/1`,Ce=`ui-observability.runtime`,we=1e4,Te=`color:#888`,Ee=1e3,De=6e4,Oe=`uiobs.capture`,ke=`uiobs.storage`,Ae=`count`,je=`unknown-service`,Me=[`redact`,`onDiagnostic`,`headers`,`serializer`],Ne=[`sampling`,`bus`,`capture`],Pe={endpoint:``,serviceName:``,serviceVersion:``,environment:``,enabled:!0,minLevel:`INFO`,compression:`gzip`,credentials:`include`,storage:`auto`,sampling:{defaultRate:1,rates:{},alwaysSampleTypes:[`action`]},bus:{mode:`auto`,trustedOrigins:[],openFinRole:`auto`},capture:{errors:!0,rejections:!0,resourceErrors:!1,fetch:!1,xhr:!1,interactions:!1,navigation:!1,webVitals:!1,ignoreUrls:[],propagateTraceHeaderTo:[]},console:null},Fe=`DEBUG`,Ie=2e3,Le=1e4,Re=15e3,ze=1024,Be=`UiObservability`,Ve={maxBatches:500,maxAgeMs:864e5,maxAttempts:5},He=2e3,Ue=6e4,We=3e4,Ge=18e5,Ke=`__uiobs_journey`,qe=`ui_observability_control`,Je=1500,Ye=5e3,Xe={maxBodyChars:4096,maxAttributeChars:8192,maxAttributeCount:128,maxStackChars:8192,maxDepth:6,maxArrayLength:100,maxRecordBytes:32768};Object.defineProperty(exports,"$",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"$t",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"At",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return we}}),Object.defineProperty(exports,"Bt",{enumerable:!0,get:function(){return 18e5}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,"Ct",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,"Dt",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return Fe}}),Object.defineProperty(exports,"Et",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,"Ft",{enumerable:!0,get:function(){return We}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"Gt",{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,"Ht",{enumerable:!0,get:function(){return 6e4}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,"It",{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,"J",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"Jt",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"Kt",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"Lt",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,"Mt",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return 1e3}}),Object.defineProperty(exports,"Nt",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"Ot",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,"Pt",{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,"Q",{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,"Qt",{enumerable:!0,get:function(){return`ui-observability.tab`}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"Rt",{enumerable:!0,get:function(){return`Safari/`}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,"St",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return Ne}}),Object.defineProperty(exports,"Tt",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,"Ut",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,"Vt",{enumerable:!0,get:function(){return`ui-observability.session`}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"Wt",{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,"X",{enumerable:!0,get:function(){return 55296}}),Object.defineProperty(exports,"Xt",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"Y",{enumerable:!0,get:function(){return 56319}}),Object.defineProperty(exports,"Yt",{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,"Z",{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,"Zt",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,"_t",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"an",{enumerable:!0,get:function(){return Me}}),Object.defineProperty(exports,"at",{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,"bt",{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"cn",{enumerable:!0,get:function(){return`AppleWebKit`}}),Object.defineProperty(exports,"ct",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"dt",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"en",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"et",{enumerable:!0,get:function(){return Ge}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"ft",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,"gt",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,"ht",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"in",{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,"it",{enumerable:!0,get:function(){return`[ui-observability]`}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,"jt",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"kt",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"lt",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,"mt",{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"nn",{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,"nt",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"on",{enumerable:!0,get:function(){return je}}),Object.defineProperty(exports,"ot",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"pt",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"qt",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"rn",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,"rt",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"sn",{enumerable:!0,get:function(){return 2048}}),Object.defineProperty(exports,"st",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"tn",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"tt",{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"ut",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"vt",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,"wt",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return Je}}),Object.defineProperty(exports,"xt",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"yt",{enumerable:!0,get:function(){return Xe}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return Ye}}),Object.defineProperty(exports,"zt",{enumerable:!0,get:function(){return N}});
|
|
2
|
-
//# sourceMappingURL=constants-DkrpC_xK.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-DkrpC_xK.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// All limits, thresholds, timing windows, storage keys, patterns, and\n// defaults used by the library.\n\nimport type { ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\nimport type { StorageLimits } from \"./models/storage\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/** Throttle window per diagnostic code, in milliseconds. Limits how often an error loop can spam the handler. */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Log level to OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names records carry on the wire, following\n// OpenTelemetry conventions. `uiobs.` marks this library's own fields.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number within its context, from zero. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key, set by network capture. Don't reuse `ATTR_PAGE_URL`; it would overwrite the request's target.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record whose attributes were dropped for exceeding the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.2.0\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. Retryable. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large; batch must be split. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. CORS-safelisted, avoids a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a parked batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch parked by exit flush. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store evicted on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/**\n * Native IndexedDB version. It starts at 11 because Dexie, which this replaced,\n * opened the same database at ten times its own declared version. Anything below\n * 11 makes open() fail with VersionError for an existing installation and every\n * batch already stored there is stranded.\n */\nexport const INDEXEDDB_SCHEMA_VERSION = 11;\n\n/** IndexedDB object store holding batches. Named by Dexie before it was removed. */\nexport const INDEXEDDB_STORE_NAME = \"batches\";\n\n/** Index on the batch store that orders reads by creation time. */\nexport const INDEXEDDB_CREATED_AT_INDEX = \"createdAt\";\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. A tripwire, not validation.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * How long to wait for `fin.me.getOptions()` before giving up on a seeded journey,\n * in milliseconds.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/**\n * W3C trace context header name\n * @see {@link TRACEPARENT_VERSION}\n */\nexport const TRACEPARENT_HEADER = \"traceparent\";\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants, used to turn a sampling key into a stable 0-1\n// fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. Mismatched versions are dropped. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** CSS styling applied to console prefix labels. */\nexport const CONSOLE_PREFIX_STYLE = \"color:#888\";\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\"redact\", \"onDiagnostic\", \"headers\", \"serializer\"] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\"sampling\", \"bus\", \"capture\"] as const;\n\n/**\n * Default runtime config, before a consumer's `configure()` call.\n * Excludes `serializer`; `resolveConfig` supplies its default to avoid a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n compression: \"gzip\",\n credentials: \"include\",\n storage: \"auto\",\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n bus: { mode: \"auto\", trustedOrigins: [], openFinRole: \"auto\" },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n },\n console: null,\n};\n\n/** Console mirroring level used when a consumer passes `console: true`. */\nexport const CONSOLE_DEFAULT_LEVEL: LogLevel = \"DEBUG\";\n\n// ----------------------------------\n// Batching\n// ----------------------------------\n\n/** Max time a partial log batch waits before it is sent, in milliseconds. */\nexport const LOG_FLUSH_INTERVAL_MS = 2000;\n\n/** Max records per log batch before it is sent early. */\nexport const LOG_BATCH_SIZE = 100;\n\n/** Max time a partial metric batch waits before it is sent, in milliseconds. Metrics batch harder than logs: higher volume, nothing waits on them. */\nexport const METRIC_FLUSH_INTERVAL_MS = 10_000;\n\n/** Max records per metric batch before it is sent early. */\nexport const METRIC_BATCH_SIZE = 500;\n\n/** Max concurrent ingest requests, across both streams. */\nexport const MAX_CONCURRENT_REQUESTS = 2;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Max time one ingest request may take before it is aborted and retried, in milliseconds. */\nexport const REQUEST_TIMEOUT_MS = 15_000;\n\n/** Min payload size to compress, in bytes. */\nexport const COMPRESSION_THRESHOLD_BYTES = 1024;\n\n// ----------------------------------\n// Storage retention\n// ----------------------------------\n\n/** IndexedDB database name. */\nexport const STORAGE_DB_NAME = \"UiObservability\";\n\n/** Capacity and retention thresholds every storage adapter enforces. */\nexport const STORAGE_LIMITS: StorageLimits = {\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n};\n\n// ----------------------------------\n// Retry backoff\n// ----------------------------------\n\n/** First backoff step, in milliseconds. Each attempt doubles it. */\nexport const RETRY_BASE_DELAY_MS = 2000;\n\n/** Backoff ceiling, in milliseconds. */\nexport const RETRY_MAX_DELAY_MS = 60_000;\n\n/** How often to check for stored work when nothing has failed recently, in milliseconds. */\nexport const RETRY_IDLE_DELAY_MS = 30_000;\n\n// ----------------------------------\n// Journey lifetime\n// ----------------------------------\n\n/** Max time a journey stays open before it is treated as abandoned, in milliseconds. */\nexport const JOURNEY_MAX_AGE_MS = 30 * 60 * 1000;\n\n/** Whether closing the owning context ends the journey for everyone. */\nexport const JOURNEY_END_ON_OWNER_CLOSE = false;\n\n/** Query parameter checked at boot for a seeded journey token. */\nexport const JOURNEY_URL_PARAM = \"__uiobs_journey\";\n\n// ----------------------------------\n// Bus handshake\n// ----------------------------------\n\n/** BroadcastChannel name for the control plane. */\nexport const BUS_CHANNEL_NAME = \"ui_observability_control\";\n\n/** Max time a forwarder waits for an owner to answer before it promotes itself, in milliseconds. */\nexport const BUS_HANDSHAKE_TIMEOUT_MS = 1500;\n\n/** Handshake attempts allowed before a cross-origin forwarder promotes itself to sender. */\nexport const BUS_MAX_HANDSHAKE_ATTEMPTS = 3;\n\n/** Max records a context buffers before its bus role is determined. */\nexport const BUS_MAX_BOOT_BUFFER_RECORDS = 500;\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Breadcrumbs kept as context for the next error. */\nexport const MAX_BREADCRUMBS = 50;\n\n/** Window within which identical errors are counted but not re-sent, in milliseconds. */\nexport const ERROR_DEDUPE_MS = 5000;\n\n// ----------------------------------\n// Per-record size caps\n// ----------------------------------\n\n/** Size caps applied to every record, enforced after sanitize and after redact. */\nexport const RECORD_LIMITS = {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxRecordBytes: 32_768,\n};\n"],"mappings":"AAcA,IAoCa,GAAqB,WAGrB,EAA6B,SAG7B,EAAwB,yBAGxB,EAAuB,gBAGvB,EAAoB,aAqDpB,EAA4C,CACvD,MAAO,EACP,MAAO,EACP,KAAM,EACN,KAAM,GACN,MAAO,GACP,MAAO,EACT,EAMa,EAAwC,EAUxC,EAAgB,WAGhB,EAAe,UAGf,EAAqB,gBAGrB,EAAgB,WAMhB,EAAgB,WAGhB,EAAkB,aAGlB,EAAoB,eAGpB,EAAyB,oBAGzB,EAAuB,wBAMvB,EAA0B,2BAM1B,EAAwB,yBAGxB,EAAwB,eAGxB,EAA2B,kBAG3B,EAAkC,yBAMlC,EAA8B,qBAM9B,EAAiC,wBAMjC,EAAkC,yBAGlC,EAAyB,gBAGzB,EAAsB,aAGtB,EAAkB,SAGlB,EAAsB,aAGtB,EAA8B,qBAG9B,EAAwB,eAGxB,EAAwB,eAMxB,EAAqB,0BAMrB,EAAwB,QAMxB,EAAyB,QAOzB,EAAuB,OAMvB,EAAoB,mBAGpB,EAAsB,uBAGtB,EAAkB,SAMlB,EAAg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