@utk09/ui-observability 0.4.0 → 0.4.1

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,4 +1,4 @@
1
- import { $ as e, Jt as t, Q as n } from "./constants-CrU3IUyy.js";
1
+ import { $ as e, Q as t, Yt as n } from "./constants-DVbpJ1tv.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(n).getAll(null, e));
25
+ return i((await this.store("readonly")).index(t).getAll(null, e));
26
26
  }
27
27
  async takeBefore(e) {
28
- let t = await this.store("readonly"), r = IDBKeyRange.upperBound(e, !0);
29
- return i(t.index(n).getAll(r));
28
+ let n = await this.store("readonly"), r = IDBKeyRange.upperBound(e, !0);
29
+ return i(n.index(t).getAll(r));
30
30
  }
31
31
  async delete(e) {
32
32
  await i((await this.store("readwrite")).delete(e));
@@ -36,9 +36,9 @@ var a = class {
36
36
  await Promise.all(e.map((e) => i(t.delete(e))));
37
37
  }
38
38
  async bumpAttempts(e, t) {
39
- let n = await i((await this.store("readonly")).get(e));
40
- n !== void 0 && await i((await this.store("readwrite")).put({
41
- ...n,
39
+ let n = await this.store("readwrite"), r = await i(n.get(e));
40
+ r !== void 0 && await i(n.put({
41
+ ...r,
42
42
  attempts: t
43
43
  }));
44
44
  }
@@ -48,6 +48,9 @@ var a = class {
48
48
  async clear() {
49
49
  await i((await this.store("readwrite")).clear());
50
50
  }
51
+ async ready() {
52
+ await this.open();
53
+ }
51
54
  async close() {
52
55
  let e = this.connection;
53
56
  e !== null && (this.connection = null, (await e).close());
@@ -56,20 +59,31 @@ var a = class {
56
59
  return (await this.open()).transaction(e, t).objectStore(e);
57
60
  }
58
61
  open() {
59
- let t = this.connection;
60
- if (t !== null) return t;
61
- let i = new Promise((t, i) => {
62
- let a = indexedDB.open(this.name, 11);
62
+ let n = this.connection;
63
+ if (n !== null) return n;
64
+ let i = new Promise((n, i) => {
65
+ let a = indexedDB.open(this.name, 11), o = !1;
63
66
  a.onupgradeneeded = () => {
64
- let t = a.result;
65
- t.objectStoreNames.contains("batches") || t.createObjectStore(e, { keyPath: "id" }).createIndex(n, n);
67
+ let n = a.result;
68
+ n.objectStoreNames.contains("batches") || n.createObjectStore(e, { keyPath: "id" }).createIndex(t, t);
66
69
  }, a.onsuccess = () => {
67
- t(a.result);
70
+ let e = a.result;
71
+ if (o) {
72
+ e.close();
73
+ return;
74
+ }
75
+ e.onversionchange = () => {
76
+ e.close(), this.connection = null;
77
+ }, n(e);
68
78
  }, a.onerror = () => {
69
79
  i(r(a));
80
+ }, a.onblocked = () => {
81
+ o = !0, i(/* @__PURE__ */ Error("another connection is blocking the IndexedDB upgrade"));
70
82
  };
71
83
  });
72
- return this.connection = i, i;
84
+ return this.connection = i.catch((e) => {
85
+ throw this.connection = null, e;
86
+ }), this.connection;
73
87
  }
74
88
  };
75
89
  //#endregion
@@ -81,11 +95,14 @@ var s = class {
81
95
  limits;
82
96
  diagnostics;
83
97
  onGap;
84
- name = t;
98
+ name = n;
85
99
  db;
86
100
  constructor(e, t, n, r) {
87
101
  this.limits = t, this.diagnostics = n, this.onGap = r, this.db = new a(e);
88
102
  }
103
+ async open() {
104
+ await this.db.ready();
105
+ }
89
106
  async save(e) {
90
107
  try {
91
108
  await this.db.put(e), await this.prune();
@@ -155,4 +172,4 @@ var s = class {
155
172
  //#endregion
156
173
  export { s as IndexedDbStorage };
157
174
 
158
- //# sourceMappingURL=indexeddb-storage-CSaDuHGk.js.map
175
+ //# sourceMappingURL=indexeddb-storage-B6uqejZb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-storage-B6uqejZb.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 * One transaction for the get and the put. Across two transactions, a prune in\n * another window deletes the batch between them, and the put restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.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 /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here, where the factory can select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\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 one time and gives the same connection to each later call.\n * A failed open is not kept: the next call opens again.\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 let abandoned = false;\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 const db = request.result;\n\n if (abandoned) {\n // The blocked handler rejected already. No reference to this connection\n // remains, and an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not\n // settle until that window closes, and each storage call waits with it.\n abandoned = true;\n reject(new Error(\"another connection is blocking the IndexedDB upgrade\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\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 * Opens the database. Not guarded: the factory needs the rejection to select the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\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,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,UAA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,GACzD,EAAO,WAAW,EAAQ,QAC1B,EAAO,WAAW,EAAa,CAAO;GAGxC,IAAM,IAAQ,MAAM,KAAK,GAAG,MAAM;GAClC,IAAI,IAAQ,KAAK,OAAO,YAAY;IAClC,EAAO,SAAS;IAChB,IAAM,IAAU,MAAM,KAAK,YAAY,IAAQ,KAAK,OAAO,UAAU;IAErE,AADA,EAAO,WAAW,EAAQ,SAC1B,EAAO,WAAW,EAAQ;GAC5B;EACF,CAAC,GAED,KAAK,UAAU,CAAM,GACd;CACT;CAMA,MAAM,QAAyB;EAI7B,OAAO,MAHa,KAAK,YAAY,WAAW,oBAAoB,kBAClE,KAAK,GAAG,MAAM,CAChB,KACgB;CAClB;CAGA,MAAM,QAAuB;EAC3B,MAAM,KAAK,YAAY,WAAW,oBAAoB,kBAAkB,KAAK,GAAG,MAAM,CAAC;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"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-tQpoTzkY.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.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 this.store(`readwrite`),i=await n(r.get(e));i!==void 0&&await n(r.put({...i,attempts:t}))}async count(){return n((await this.store(`readonly`)).count())}async clear(){await n((await this.store(`readwrite`)).clear())}async ready(){await this.open()}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),a=!1;i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.$,{keyPath:`id`}).createIndex(e.Q,e.Q)},i.onsuccess=()=>{let e=i.result;if(a){e.close();return}e.onversionchange=()=>{e.close(),this.connection=null},n(e)},i.onerror=()=>{r(t(i))},i.onblocked=()=>{a=!0,r(Error(`another connection is blocking the IndexedDB upgrade`))}});return this.connection=r.catch(e=>{throw this.connection=null,e}),this.connection}};function i(e){return e.reduce((e,t)=>e+t.records.length,0)}var a=class{limits;diagnostics;onGap;name=e.Yt;db;constructor(e,t,n,i){this.limits=t,this.diagnostics=n,this.onGap=i,this.db=new r(e)}async open(){await this.db.ready()}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-CgT1GLYj.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-storage-CgT1GLYj.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 * One transaction for the get and the put. Across two transactions, a prune in\n * another window deletes the batch between them, and the put restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.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 /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here, where the factory can select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\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 one time and gives the same connection to each later call.\n * A failed open is not kept: the next call opens again.\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 let abandoned = false;\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 const db = request.result;\n\n if (abandoned) {\n // The blocked handler rejected already. No reference to this connection\n // remains, and an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not\n // settle until that window closes, and each storage call waits with it.\n abandoned = true;\n reject(new Error(\"another connection is blocking the IndexedDB upgrade\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\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 * Opens the database. Not guarded: the factory needs the rejection to select the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\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":"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,I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AAO,WAAY,CAClC,EAAO,OAAS,gBAChB,IAAM,EAAU,MAAM,KAAK,YAAY,EAAQ,KAAK,OAAO,UAAU,EACrE,EAAO,SAAW,EAAQ,QAC1B,EAAO,SAAW,EAAQ,OAC5B,CACF,CAAC,EAED,KAAK,UAAU,CAAM,EACd,CACT,CAMA,MAAM,OAAyB,CAI7B,OAAO,MAHa,KAAK,YAAY,WAAW,mBAAoB,eAClE,KAAK,GAAG,MAAM,CAChB,GACgB,CAClB,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,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"}
@@ -39,6 +39,8 @@ export declare class IdbDriver {
39
39
  /**
40
40
  * Rewrites the attempt count of a stored batch. An id that is not stored is
41
41
  * left alone: a batch already delivered and deleted must not be resurrected.
42
+ * One transaction for the get and the put. Across two transactions, a prune in
43
+ * another window deletes the batch between them, and the put restores it.
42
44
  * @param id Batch identifier.
43
45
  * @param attempts New absolute attempt count.
44
46
  */
@@ -50,6 +52,11 @@ export declare class IdbDriver {
50
52
  count(): Promise<number>;
51
53
  /** Deletes every stored batch. */
52
54
  clear(): Promise<void>;
55
+ /**
56
+ * Opens the connection. A host that defines indexedDB but rejects open() fails
57
+ * here, where the factory can select a different adapter.
58
+ */
59
+ ready(): Promise<void>;
53
60
  /** Closes the connection, if one was ever opened. */
54
61
  close(): Promise<void>;
55
62
  /**
@@ -60,7 +67,8 @@ export declare class IdbDriver {
60
67
  */
61
68
  private store;
62
69
  /**
63
- * Opens the database once and hands the same connection to every later call.
70
+ * Opens the database one time and gives the same connection to each later call.
71
+ * A failed open is not kept: the next call opens again.
64
72
  * @returns The open database.
65
73
  */
66
74
  private open;
@@ -17,6 +17,11 @@ export declare class IndexedDbStorage implements StorageAdapter {
17
17
  * @param onGap Optional callback for dropped record reporting.
18
18
  */
19
19
  constructor(dbName: string, limits: StorageLimits, diagnostics: Diagnostics, onGap?: GapReporter | undefined);
20
+ /**
21
+ * Opens the database. Not guarded: the factory needs the rejection to select the
22
+ * next adapter.
23
+ */
24
+ open(): Promise<void>;
20
25
  /**
21
26
  * Persists a batch to IndexedDB and triggers storage pruning.
22
27
  * @param batch Batch to store.
@@ -11,6 +11,8 @@ export interface ExitFlushDeps {
11
11
  diagnostics: Diagnostics;
12
12
  /** Callback draining all pending buffered and unconfirmed batches into a single LogBatch. */
13
13
  drainForExit: () => LogBatch | null;
14
+ /** Callback draining the buffered records only. An in-flight batch stays where it is. */
15
+ drainPending: () => LogBatch | null;
14
16
  }
15
17
  /** Flushes pending telemetry on document unload using sendBeacon, keepalive fetch, or emergency storage. */
16
18
  export declare class ExitFlush {
@@ -40,6 +42,14 @@ export declare class ExitFlush {
40
42
  * @param reason Trigger reason code.
41
43
  */
42
44
  flush(reason: ExitReason): void;
45
+ /**
46
+ * Selects the drain for the reason. `hidden` occurs at each tab switch, and the
47
+ * document continues to run. Taken here, an in-flight batch goes out a second
48
+ * time under a new id, which the server cannot deduplicate.
49
+ * @param reason Trigger reason code.
50
+ * @returns Combined LogBatch, or null if no records are pending.
51
+ */
52
+ private drain;
43
53
  /**
44
54
  * Resolves and parses the destination endpoint URL.
45
55
  * @returns URL instance or null if missing or invalid.
@@ -49,7 +59,7 @@ export declare class ExitFlush {
49
59
  * Attempts transmission via navigator.sendBeacon with text/plain payload.
50
60
  * @param url Target endpoint URL with query parameters.
51
61
  * @param body Serialized payload string.
52
- * @returns True if the beacon was accepted by the browser.
62
+ * @returns The answer of the browser.
53
63
  */
54
64
  private beacon;
55
65
  /**
@@ -1,4 +1,5 @@
1
1
  import type { Diagnostics } from "../core/diagnostics";
2
+ import { type LogBatch } from "../models/batch";
2
3
  import type { ResolvedConfig } from "../models/config";
3
4
  import type { StorageAdapter } from "../models/storage";
4
5
  import type { HttpTransport } from "./http-transport";
@@ -31,6 +32,14 @@ export declare class RetryEngine {
31
32
  start(): void;
32
33
  /** Triggers an accelerated retry schedule when a new batch is stored offline. */
33
34
  nudge(): void;
35
+ /**
36
+ * Persists a batch that failed outside the drain loop, under the same rules the
37
+ * drain applies. Storing it whole would spend another request on a payload the
38
+ * server already refused.
39
+ * @param batch Rejected batch, with its attempt already counted.
40
+ * @param error Failure thrown by the transport.
41
+ */
42
+ storeFailed(batch: LogBatch, error: unknown): Promise<void>;
34
43
  /** Halts retry execution, removes listeners, and clears pending timers. */
35
44
  stop(): void;
36
45
  /**
@@ -38,6 +47,13 @@ export declare class RetryEngine {
38
47
  * @param delayMs Delay duration in milliseconds.
39
48
  */
40
49
  private schedule;
50
+ /**
51
+ * Bounds a storage call. A call that does not settle keeps `draining` set, and
52
+ * this window then runs no more drains.
53
+ * @param work Storage promise to bound.
54
+ * @returns The value of the promise, or a rejection after the deadline.
55
+ */
56
+ private bounded;
41
57
  /** Clears the pending timer handle if active. */
42
58
  private clearTimer;
43
59
  /**
@@ -61,9 +77,18 @@ export declare class RetryEngine {
61
77
  */
62
78
  private deliver;
63
79
  /**
64
- * Splits an oversized batch into two smaller stored batches after a 413 rejection.
80
+ * Replaces a stored batch with what survives its failure: the split halves, or
81
+ * nothing when the server refuses the records for good.
82
+ * @param batch Rejected log batch, already held in storage.
83
+ * @param error Failure thrown by the transport.
84
+ */
85
+ private replaceStored;
86
+ /**
87
+ * Decides what a failed batch leaves behind. A 413 splits in two, a permanent
88
+ * refusal keeps nothing, and every other failure keeps the batch whole.
65
89
  * @param batch Rejected log batch.
66
- * @param serverMaxBytes Optional byte limit reported by the server.
90
+ * @param error Failure thrown by the transport.
91
+ * @returns Batches to persist, empty when the records are dropped.
67
92
  */
68
- private splitStored;
93
+ private toStorable;
69
94
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Rejects when a promise does not settle within a deadline.
3
+ * @param work Promise to bound.
4
+ * @param ms Deadline in milliseconds.
5
+ * @returns The value of the promise, or a rejection after the deadline.
6
+ */
7
+ export declare function withDeadline<T>(work: Promise<T>, ms: number): Promise<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@utk09/ui-observability",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "UI observability and logging for browser, OpenFin and webview applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -1,2 +0,0 @@
1
- var ee=/OpenFin/i,te=/\bwv\b/,e=/\b(iPhone|iPad|iPod)\b/,t=/\bMacintosh\b/,n=/\bMobile\b/,r={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17,FATAL:21},i=r,a=`log.type`,o=`log.seq`,s=`app.namespace`,c=`page.url`,l=`url.full`,u=`journey.id`,d=`journey.name`,f=`journey.parent_id`,p=`uiobs.sanitize_failed`,m=`uiobs.attributes_dropped`,h=`uiobs.attributes_bytes`,g=`service.name`,_=`service.version`,v=`deployment.environment`,y=`telemetry.sdk.name`,b=`telemetry.sdk.version`,x=`telemetry.sdk.language`,S=`host.platform`,C=`session.id`,w=`tab.id`,T=`context.id`,E=`browser.user_agent`,D=`openfin.uuid`,O=`openfin.name`,k=`@utk09/ui-observability`,A=`0.4.0`,j=`webjs`,M=`otlp`,N={WARN:`warning`},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`,ne=`batches`,$=`createdAt`,re=`indexeddb`,ie=`localstorage`,ae=`memory`,oe=`none`,se=`ui-observability.drain`,ce=`ui-observability.emergency`,le=`ui-observability.journey`,ue=2e3,de=`uiObsJourney`,fe=/\+/g,pe=/\//g,me=/=+$/,he=/-/g,ge=/_/g,_e=3e5,ve=`traceparent`,ye=2166136261,be=16777619,xe=4294967295,Se=`metric`,Ce=`ui-observability/1`,we=`ui-observability.runtime`,Te=1e4,Ee=`color:#888`,De=1e3,Oe=6e4,ke=`uiobs.capture`,Ae=`uiobs.storage`,je=`count`,Me=`unknown-service`,Ne=[`redact`,`onDiagnostic`,`headers`,`serializer`,`otelLoader`],Pe=[`sampling`,`bus`,`capture`],Fe={sampling:[],bus:[],capture:[`webVitalsLoader`]},Ie={endpoint:``,serviceName:``,serviceVersion:``,environment:``,enabled:!0,minLevel:`INFO`,compression:`gzip`,credentials:`omit`,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,fullUrls:!1,ignoreUrls:[],propagateTraceHeaderTo:[]},console:null},Le=`DEBUG`,Re=2e3,ze=1e4,Be=15e3,Ve=1024,He=`UiObservability`,Ue={maxBatches:500,maxAgeMs:864e5,maxAttempts:5},We=2e3,Ge=6e4,Ke=3e4,qe=18e5,Je=`__uiobs_journey`,Ye=`ui_observability_control`,Xe=1500,Ze=5e3,Qe={maxBodyChars:4096,maxAttributeChars:8192,maxAttributeCount:128,maxStackChars:8192,maxDepth:6,maxArrayLength:100,maxNodes:1e4,maxRecordBytes:32768};Object.defineProperty(exports,"$",{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,"$t",{enumerable:!0,get:function(){return`ui-observability.tab`}}),Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"At",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return Ze}}),Object.defineProperty(exports,"Bt",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,"Ct",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,"Dt",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,"Et",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,"Ft",{enumerable:!0,get:function(){return We}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"Gt",{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,"Ht",{enumerable:!0,get:function(){return`ui-observability.session`}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"It",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(exports,"J",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"Jt",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"Kt",{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,"Lt",{enumerable:!0,get:function(){return Ge}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return je}}),Object.defineProperty(exports,"Mt",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return 1e3}}),Object.defineProperty(exports,"Nt",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"Ot",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,"Pt",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"Q",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"Qt",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"Rt",{enumerable:!0,get:function(){return we}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,"St",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,"Tt",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,"Ut",{enumerable:!0,get:function(){return 6e4}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,"Vt",{enumerable:!0,get:function(){return 18e5}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,"Wt",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"X",{enumerable:!0,get:function(){return 56319}}),Object.defineProperty(exports,"Xt",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"Y",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"Yt",{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,"Z",{enumerable:!0,get:function(){return 55296}}),Object.defineProperty(exports,"Zt",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,"_t",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"an",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,"at",{enumerable:!0,get:function(){return`[ui-observability]`}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return Ye}}),Object.defineProperty(exports,"bt",{enumerable:!0,get:function(){return Qe}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"cn",{enumerable:!0,get:function(){return Me}}),Object.defineProperty(exports,"ct",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"dt",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"en",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"et",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"ft",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,"gt",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"ht",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"in",{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,"it",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,"jt",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"kt",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"ln",{enumerable:!0,get:function(){return 2048}}),Object.defineProperty(exports,"lt",{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,"mt",{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"nn",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"nt",{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"on",{enumerable:!0,get:function(){return Ne}}),Object.defineProperty(exports,"ot",{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,"pt",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"qt",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"rn",{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,"rt",{enumerable:!0,get:function(){return Je}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"sn",{enumerable:!0,get:function(){return Fe}}),Object.defineProperty(exports,"st",{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,"tn",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"tt",{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"un",{enumerable:!0,get:function(){return`AppleWebKit`}}),Object.defineProperty(exports,"ut",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"vt",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,"wt",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return Xe}}),Object.defineProperty(exports,"xt",{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"yt",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"zt",{enumerable:!0,get:function(){return`Safari/`}});
2
- //# sourceMappingURL=constants-BpFlszME.cjs.map
@@ -1 +0,0 @@
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,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,WAAW,GAAQ,EAAI;EACjD,OAAO,EAAsB,EAAM,MAAM,CAA0B,CAAC,CAAC,OAA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;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,2 +0,0 @@
1
- const e=require("./constants-BpFlszME.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.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
@@ -1 +0,0 @@
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"],"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,MAAM,KAAK,MAAM,UAAU,EACnC,EAAQ,YAAY,WAAW,EAAQ,EAAI,EACjD,OAAO,EAAsB,EAAM,MAAM,EAAA,CAA0B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