@utk09/ui-observability 0.2.0 → 0.3.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.
@@ -1,2 +1,2 @@
1
- const e=require("./constants-DkrpC_xK.cjs");function t(e){return e.error??Error(`the IndexedDB request failed`)}function n(e){return new 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.Z).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.Z).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.Q,t).objectStore(e.Q)}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.Q,{keyPath:`id`}).createIndex(e.Z,e.Z)},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.qt;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 e=await this.diagnostics.guardAsync(`storage.degraded`,`evicting after a full disk`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));e&&this.reportGap({...e,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`could not persist a batch`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`reading stored batches`,()=>this.db.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-CH9NocOC.cjs.map
1
+ const e=require("./constants-BmO0GRWM.cjs");function t(e){return e.error??Error(`the IndexedDB request failed`)}function n(e){return new 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.Z).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.Z).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.Q,t).objectStore(e.Q)}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.Q,{keyPath:`id`}).createIndex(e.Z,e.Z)},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.qt;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 e=await this.diagnostics.guardAsync(`storage.degraded`,`evicting after a full disk`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));e&&this.reportGap({...e,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`could not persist a batch`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`reading stored batches`,()=>this.db.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-DeEh8Ag-.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb-storage-CH9NocOC.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 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":"4CAmBA,SAAS,EAAU,EAA4B,CAC7C,OAAO,EAAQ,OAAa,MAAM,8BAA8B,CAClE,CAQA,SAAS,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxB,EAAQ,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtB,EAAO,EAAU,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAa,EAAb,KAAuB,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAAA,KAAA,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAM,GAAU,MADI,KAAK,MAAM,WAAW,EAAA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AAK,YAAY,WAAW,mBAAoB,eAAkB,KAAK,GAAG,MAAM,CAAC,CACzF,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WAAW,mBAAoB,2BACpD,KAAK,GAAG,MAAM,CAChB,CACF,CAMA,UAAkB,EAA2B,CACvC,EAAO,UAAY,IAIvB,KAAK,YAAY,OACf,kBACA,WAAW,OAAO,EAAO,OAAO,EAAE,mBAAmB,OAAO,EAAO,OAAO,EAAE,WAC5E,CAAE,GAAG,CAAO,CACd,EACA,KAAK,QAAQ,CAAM,EACrB,CASA,MAAc,YAAY,EAAuD,CAC/E,IAAM,EAAS,MAAM,KAAK,GAAG,WAAW,CAAO,EAG/C,OAFA,MAAM,KAAK,GAAG,WAAW,EAAO,IAAK,GAAU,EAAM,EAAE,CAAC,EAEjD,CAAE,QAAS,EAAO,OAAQ,QAAS,EAAa,CAAM,CAAE,CACjE,CACF"}
1
+ {"version":3,"file":"indexeddb-storage-DeEh8Ag-.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 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":"4CAmBA,SAAS,EAAU,EAA4B,CAC7C,OAAO,EAAQ,OAAa,MAAM,8BAA8B,CAClE,CAQA,SAAS,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxB,EAAQ,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtB,EAAO,EAAU,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAa,EAAb,KAAuB,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAAA,KAAA,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAM,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAI,CAAK,CAAC,CAClC,CAOA,MAAM,WAAW,EAAoC,CAEnD,OAAO,GAAsB,MADT,KAAK,MAAM,UAAU,EAAA,CACN,MAAM,EAAA,CAA0B,CAAC,CAAC,OAAO,KAAM,CAAK,CAAC,CAC1F,CAOA,MAAM,WAAW,EAAqC,CACpD,IAAM,EAAQ,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f,kBACA,WAAW,OAAO,EAAO,OAAO,EAAE,mBAAmB,OAAO,EAAO,OAAO,EAAE,WAC5E,CAAE,GAAG,CAAO,CACd,EACA,KAAK,QAAQ,CAAM,EACrB,CASA,MAAc,YAAY,EAAuD,CAC/E,IAAM,EAAS,MAAM,KAAK,GAAG,WAAW,CAAO,EAG/C,OAFA,MAAM,KAAK,GAAG,WAAW,EAAO,IAAK,GAAU,EAAM,EAAE,CAAC,EAEjD,CAAE,QAAS,EAAO,OAAQ,QAAS,EAAa,CAAM,CAAE,CACjE,CACF"}
@@ -1,4 +1,4 @@
1
- import { Q as e, Z as t, qt as n } from "./constants-NJNXpfPi.js";
1
+ import { Q as e, Z as t, qt as n } from "./constants-CQr0wwbQ.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");
@@ -151,4 +151,4 @@ var s = class {
151
151
  //#endregion
152
152
  export { s as IndexedDbStorage };
153
153
 
154
- //# sourceMappingURL=indexeddb-storage-DAoHV_oL.js.map
154
+ //# sourceMappingURL=indexeddb-storage-bibcl7ZS.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb-storage-DAoHV_oL.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 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,gBAAI,MAAM,8BAA8B;AAClE;AAQA,SAAS,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQ,EAAQ,MAAW;EAC7B,GACA,EAAQ,gBAAgB;GACtB,EAAO,EAAU,CAAO,CAAC;EAC3B;CACF,CAAC;AACH;AAGA,IAAa,IAAb,MAAuB;CAOQ;CAL7B,aAAkD;CAKlD,YAAY,GAA+B;EAAd,KAAA,OAAA;CAAe;CAM5C,MAAM,IAAI,GAAgC;EAExC,MAAM,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAI,CAAK,CAAC;CAClC;CAOA,MAAM,WAAW,G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AAC;CACzF;CAGA,MAAM,QAAuB;EAC3B,MAAM,KAAK,YAAY,WAAW,oBAAoB,8BACpD,KAAK,GAAG,MAAM,CAChB;CACF;CAMA,UAAkB,GAA2B;EACvC,EAAO,YAAY,MAIvB,KAAK,YAAY,OACf,mBACA,WAAW,OAAO,EAAO,OAAO,EAAE,mBAAmB,OAAO,EAAO,OAAO,EAAE,YAC5E,EAAE,GAAG,EAAO,CACd,GACA,KAAK,QAAQ,CAAM;CACrB;CASA,MAAc,YAAY,GAAuD;EAC/E,IAAM,IAAS,MAAM,KAAK,GAAG,WAAW,CAAO;EAG/C,OAFA,MAAM,KAAK,GAAG,WAAW,EAAO,KAAK,MAAU,EAAM,EAAE,CAAC,GAEjD;GAAE,SAAS,EAAO;GAAQ,SAAS,EAAa,CAAM;EAAE;CACjE;AACF"}
1
+ {"version":3,"file":"indexeddb-storage-bibcl7ZS.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 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,gBAAI,MAAM,8BAA8B;AAClE;AAQA,SAAS,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQ,EAAQ,MAAW;EAC7B,GACA,EAAQ,gBAAgB;GACtB,EAAO,EAAU,CAAO,CAAC;EAC3B;CACF,CAAC;AACH;AAGA,IAAa,IAAb,MAAuB;CAOQ;CAL7B,aAAkD;CAKlD,YAAY,GAA+B;EAAd,KAAA,OAAA;CAAe;CAM5C,MAAM,IAAI,GAAgC;EAExC,MAAM,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAI,CAAK,CAAC;CAClC;CAOA,MAAM,WAAW,GAAoC;EAEnD,OAAO,GAAsB,MADT,KAAK,MAAM,UAAU,EAAA,CACN,MAAM,CAA0B,CAAC,CAAC,OAAO,MAAM,CAAK,CAAC;CAC1F;CAOA,MAAM,WAAW,GAAqC;EACpD,IAAM,IAAQ,MAAM,KAAK,MAAM,UAAU,GACnC,IAAQ,YAAY,W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BAAmB,OAAO,EAAO,OAAO,EAAE,YAC5E,EAAE,GAAG,EAAO,CACd,GACA,KAAK,QAAQ,CAAM;CACrB;CASA,MAAc,YAAY,GAAuD;EAC/E,IAAM,IAAS,MAAM,KAAK,GAAG,WAAW,CAAO;EAG/C,OAFA,MAAM,KAAK,GAAG,WAAW,EAAO,KAAK,MAAU,EAAM,EAAE,CAAC,GAEjD;GAAE,SAAS,EAAO;GAAQ,SAAS,EAAa,CAAM;EAAE;CACjE;AACF"}
@@ -47,6 +47,59 @@ export interface WebVitalsModule {
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 "include"
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.
@@ -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
- drainPending: () => LogBatch | null;
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 {
@@ -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;
@@ -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.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "UI observability and logging for browser, OpenFin and webview applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -75,19 +75,21 @@
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",
@@ -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