@utk09/ui-observability 0.1.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.
Files changed (62) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +217 -0
  3. package/dist/bus/bus.d.ts +134 -0
  4. package/dist/bus/links.d.ts +106 -0
  5. package/dist/capture/errors.d.ts +34 -0
  6. package/dist/capture/interactions.d.ts +29 -0
  7. package/dist/capture/network.d.ts +40 -0
  8. package/dist/capture/types.d.ts +78 -0
  9. package/dist/capture/web-vitals.d.ts +21 -0
  10. package/dist/constants-D8-4Ged5.cjs +2 -0
  11. package/dist/constants-D8-4Ged5.cjs.map +1 -0
  12. package/dist/constants-DbvMIryP.js +110 -0
  13. package/dist/constants-DbvMIryP.js.map +1 -0
  14. package/dist/constants.d.ts +339 -0
  15. package/dist/core/breadcrumbs.d.ts +48 -0
  16. package/dist/core/config.d.ts +16 -0
  17. package/dist/core/context.d.ts +35 -0
  18. package/dist/core/diagnostics.d.ts +76 -0
  19. package/dist/core/journey.d.ts +112 -0
  20. package/dist/core/logger.d.ts +117 -0
  21. package/dist/core/pipeline.d.ts +75 -0
  22. package/dist/core/record.d.ts +72 -0
  23. package/dist/core/runtime.d.ts +146 -0
  24. package/dist/core/sampling.d.ts +9 -0
  25. package/dist/index.cjs +4 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/index.d.ts +167 -0
  28. package/dist/index.js +2577 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/indexeddb-storage-DvsvCUlO.cjs +2 -0
  31. package/dist/indexeddb-storage-DvsvCUlO.cjs.map +1 -0
  32. package/dist/indexeddb-storage-DwpCDRnX.js +88 -0
  33. package/dist/indexeddb-storage-DwpCDRnX.js.map +1 -0
  34. package/dist/models/batch.d.ts +22 -0
  35. package/dist/models/bus.d.ts +97 -0
  36. package/dist/models/config.d.ts +528 -0
  37. package/dist/models/log-record.d.ts +54 -0
  38. package/dist/models/serializer.d.ts +23 -0
  39. package/dist/models/storage.d.ts +62 -0
  40. package/dist/storage/emergency-queue.d.ts +16 -0
  41. package/dist/storage/factory.d.ts +13 -0
  42. package/dist/storage/indexeddb-storage.d.ts +69 -0
  43. package/dist/storage/keys.d.ts +8 -0
  44. package/dist/storage/local-storage.d.ts +80 -0
  45. package/dist/storage/memory-storage.d.ts +52 -0
  46. package/dist/transport/compression.d.ts +7 -0
  47. package/dist/transport/errors.d.ts +29 -0
  48. package/dist/transport/exit-flush.d.ts +63 -0
  49. package/dist/transport/http-transport.d.ts +63 -0
  50. package/dist/transport/retry-engine.d.ts +69 -0
  51. package/dist/transport/serializers/ecs.d.ts +3 -0
  52. package/dist/transport/serializers/otlp.d.ts +3 -0
  53. package/dist/utils/console.d.ts +24 -0
  54. package/dist/utils/identity.d.ts +36 -0
  55. package/dist/utils/lock.d.ts +15 -0
  56. package/dist/utils/platform.d.ts +36 -0
  57. package/dist/utils/sanitize.d.ts +47 -0
  58. package/dist/utils/sequence.d.ts +15 -0
  59. package/dist/utils/timer.d.ts +19 -0
  60. package/dist/utils/tracing.d.ts +55 -0
  61. package/dist/utils/unref.d.ts +9 -0
  62. package/package.json +106 -0
@@ -0,0 +1,2 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));const c=require("./constants-D8-4Ged5.cjs");let l=require("dexie");l=s(l,1);function u(e){return e.reduce((e,t)=>e+t.records.length,0)}var d=class extends l.default{batches;constructor(e){super(e),this.version(1).stores({batches:`id, createdAt`})}},f=class{limits;diagnostics;onGap;name=c.Dt;db;constructor(e,t,n,r){this.limits=t,this.diagnostics=n,this.onGap=r,this.db=new d(e)}async save(e){try{await this.db.batches.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.batches.orderBy(`createdAt`).limit(e).toArray())??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`deleting a batch`,()=>this.db.batches.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`updating attempts`,()=>this.db.batches.update(e,{attempts: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.batches.where(`createdAt`).below(t).toArray();n.length>0&&(await this.db.batches.bulkDelete(n.map(e=>e.id)),e.batches+=n.length,e.records+=u(n));let r=await this.db.batches.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.batches.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`clearing`,()=>this.db.batches.clear())}close(){return this.diagnostics.guard(`storage.degraded`,`closing the database`,()=>{this.db.close()}),Promise.resolve()}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.batches.orderBy(`createdAt`).limit(e).toArray();return await this.db.batches.bulkDelete(t.map(e=>e.id)),{batches:t.length,records:u(t)}}};exports.IndexedDbStorage=f;
2
+ //# sourceMappingURL=indexeddb-storage-DvsvCUlO.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-storage-DvsvCUlO.cjs","names":[],"sources":["../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB and Dexie with time-ordered indexing.\n\nimport Dexie, { type Table } from \"dexie\";\nimport {\n INDEXEDDB_SCHEMA_VERSION,\n QUOTA_EVICTION_DIVISOR,\n QUOTA_EXCEEDED_ERROR,\n STORAGE_NAME_INDEXEDDB,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Dexie database instance schema definition for log batch storage. */\nclass ObservabilityDb extends Dexie {\n /** Table storing LogBatch entities keyed by id and indexed by createdAt. */\n batches!: Table<LogBatch, string>;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(name: string) {\n super(name);\n this.version(INDEXEDDB_SCHEMA_VERSION).stores({ batches: \"id, createdAt\" });\n }\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 /** Underlying Dexie database instance. */\n private readonly db: ObservabilityDb;\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 ObservabilityDb(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.batches.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.batches.orderBy(\"createdAt\").limit(limit).toArray(),\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.batches.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.batches.update(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.batches.where(\"createdAt\").below(cutoff).toArray();\n if (expired.length > 0) {\n await this.db.batches.bulkDelete(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.batches.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.batches.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\", () =>\n this.db.batches.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n close(): Promise<void> {\n this.diagnostics.guard(\"storage.degraded\", \"closing the database\", () => {\n this.db.close();\n });\n return Promise.resolve();\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.batches.orderBy(\"createdAt\").limit(howMany).toArray();\n await this.db.batches.bulkDelete(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length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C,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,QAAQ,QAAQ,WAAW,CAAC,CAAC,MAAM,CAAO,CAAC,CAAC,QAAQ,EAGjF,OAFA,MAAM,KAAK,GAAG,QAAQ,WAAW,EAAO,IAAK,GAAU,EAAM,EAAE,CAAC,EAEzD,CAAE,QAAS,EAAO,OAAQ,QAAS,EAAa,CAAM,CAAE,CACjE,CACF"}
@@ -0,0 +1,88 @@
1
+ import { Dt as e } from "./constants-DbvMIryP.js";
2
+ import t from "dexie";
3
+ //#region src/storage/indexeddb-storage.ts
4
+ function n(e) {
5
+ return e.reduce((e, t) => e + t.records.length, 0);
6
+ }
7
+ var r = class extends t {
8
+ batches;
9
+ constructor(e) {
10
+ super(e), this.version(1).stores({ batches: "id, createdAt" });
11
+ }
12
+ }, i = class {
13
+ limits;
14
+ diagnostics;
15
+ onGap;
16
+ name = e;
17
+ db;
18
+ constructor(e, t, n, i) {
19
+ this.limits = t, this.diagnostics = n, this.onGap = i, this.db = new r(e);
20
+ }
21
+ async save(e) {
22
+ try {
23
+ await this.db.batches.put(e), await this.prune();
24
+ } catch (t) {
25
+ if (t instanceof Error && t.name === "QuotaExceededError") {
26
+ this.diagnostics.report("storage.quota_exceeded", "IndexedDB is full, evicting the oldest");
27
+ let e = await this.diagnostics.guardAsync("storage.degraded", "evicting after a full disk", () => this.evictOldest(Math.ceil(this.limits.maxBatches / 4)));
28
+ e && this.reportGap({
29
+ ...e,
30
+ reason: "quota"
31
+ });
32
+ return;
33
+ }
34
+ this.diagnostics.report("storage.degraded", "could not persist a batch", { batchId: e.id }, t);
35
+ }
36
+ }
37
+ async take(e) {
38
+ return await this.diagnostics.guardAsync("storage.degraded", "reading stored batches", () => this.db.batches.orderBy("createdAt").limit(e).toArray()) ?? [];
39
+ }
40
+ async remove(e) {
41
+ await this.diagnostics.guardAsync("storage.degraded", "deleting a batch", () => this.db.batches.delete(e));
42
+ }
43
+ async bumpAttempts(e, t) {
44
+ await this.diagnostics.guardAsync("storage.degraded", "updating attempts", () => this.db.batches.update(e, { attempts: t }));
45
+ }
46
+ async prune() {
47
+ let e = {
48
+ batches: 0,
49
+ records: 0,
50
+ reason: "expired"
51
+ };
52
+ return await this.diagnostics.guardAsync("storage.degraded", "pruning", async () => {
53
+ let t = Date.now() - this.limits.maxAgeMs, r = await this.db.batches.where("createdAt").below(t).toArray();
54
+ r.length > 0 && (await this.db.batches.bulkDelete(r.map((e) => e.id)), e.batches += r.length, e.records += n(r));
55
+ let i = await this.db.batches.count();
56
+ if (i > this.limits.maxBatches) {
57
+ e.reason = "over_capacity";
58
+ let t = await this.evictOldest(i - this.limits.maxBatches);
59
+ e.batches += t.batches, e.records += t.records;
60
+ }
61
+ }), this.reportGap(e), e;
62
+ }
63
+ async count() {
64
+ return await this.diagnostics.guardAsync("storage.degraded", "counting", () => this.db.batches.count()) ?? 0;
65
+ }
66
+ async clear() {
67
+ await this.diagnostics.guardAsync("storage.degraded", "clearing", () => this.db.batches.clear());
68
+ }
69
+ close() {
70
+ return this.diagnostics.guard("storage.degraded", "closing the database", () => {
71
+ this.db.close();
72
+ }), Promise.resolve();
73
+ }
74
+ reportGap(e) {
75
+ e.batches !== 0 && (this.diagnostics.report("storage.evicted", `dropped ${String(e.batches)} stored batches (${String(e.records)} records)`, { ...e }), this.onGap?.(e));
76
+ }
77
+ async evictOldest(e) {
78
+ let t = await this.db.batches.orderBy("createdAt").limit(e).toArray();
79
+ return await this.db.batches.bulkDelete(t.map((e) => e.id)), {
80
+ batches: t.length,
81
+ records: n(t)
82
+ };
83
+ }
84
+ };
85
+ //#endregion
86
+ export { i as IndexedDbStorage };
87
+
88
+ //# sourceMappingURL=indexeddb-storage-DwpCDRnX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-storage-DwpCDRnX.js","names":[],"sources":["../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB and Dexie with time-ordered indexing.\n\nimport Dexie, { type Table } from \"dexie\";\nimport {\n INDEXEDDB_SCHEMA_VERSION,\n QUOTA_EVICTION_DIVISOR,\n QUOTA_EXCEEDED_ERROR,\n STORAGE_NAME_INDEXEDDB,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Dexie database instance schema definition for log batch storage. */\nclass ObservabilityDb extends Dexie {\n /** Table storing LogBatch entities keyed by id and indexed by createdAt. */\n batches!: Table<LogBatch, string>;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(name: string) {\n super(name);\n this.version(INDEXEDDB_SCHEMA_VERSION).stores({ batches: \"id, createdAt\" });\n }\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 /** Underlying Dexie database instance. */\n private readonly db: ObservabilityDb;\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 ObservabilityDb(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.batches.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.batches.orderBy(\"createdAt\").limit(limit).toArray(),\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.batches.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.batches.update(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.batches.where(\"createdAt\").below(cutoff).toArray();\n if (expired.length > 0) {\n await this.db.batches.bulkDelete(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.batches.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.batches.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\", () =>\n this.db.batches.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n close(): Promise<void> {\n this.diagnostics.guard(\"storage.degraded\", \"closing the database\", () => {\n this.db.close();\n });\n return Promise.resolve();\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.batches.orderBy(\"createdAt\").limit(howMany).toArray();\n await this.db.batches.bulkDelete(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":";;;AAoBA,SAAS,EAAa,GAA6B;CACjD,OAAO,EAAQ,QAAQ,GAAO,MAAU,IAAQ,EAAM,QAAQ,QAAQ,CAAC;AACzE;AAGA,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,EAAO,CACd,GACA,KAAK,QAAQ,CAAM;CACrB;CASA,MAAc,YAAY,GAAuD;EAC/E,IAAM,IAAS,MAAM,KAAK,GAAG,QAAQ,QAAQ,WAAW,CAAC,CAAC,MAAM,CAAO,CAAC,CAAC,QAAQ;EAGjF,OAFA,MAAM,KAAK,GAAG,QAAQ,WAAW,EAAO,KAAK,MAAU,EAAM,EAAE,CAAC,GAEzD;GAAE,SAAS,EAAO;GAAQ,SAAS,EAAa,CAAM;EAAE;CACjE;AACF"}
@@ -0,0 +1,22 @@
1
+ import type { LogRecord } from "./log-record";
2
+ /**
3
+ * A batch of records with a stable id used for server-side deduplication across retries.
4
+ * @see {@link splitBatch}
5
+ */
6
+ export interface LogBatch {
7
+ /** Deduplication key. Stable across retries and reloads. */
8
+ id: string;
9
+ /** Records to deliver, in log order. */
10
+ records: LogRecord[];
11
+ /** Batch creation time, in epoch milliseconds. */
12
+ createdAt: number;
13
+ /** Delivery attempts so far. */
14
+ attempts: number;
15
+ }
16
+ /**
17
+ * Splits a batch the server rejected as too large into two halves.
18
+ * Each half gets a fresh id; age and attempts carry over unchanged.
19
+ * @param batch The rejected batch.
20
+ * @returns Two batches, or `null` if a single record is already over the limit.
21
+ */
22
+ export declare function splitBatch(batch: LogBatch): [LogBatch, LogBatch] | null;
@@ -0,0 +1,97 @@
1
+ import { BUS_PROTOCOL } from "../constants";
2
+ import type { Journey } from "../core/journey";
3
+ import type { LogRecord } from "./log-record";
4
+ /** Delivery role indicating whether this context sends records directly or forwards upstream. */
5
+ export type BusRole = "sender" | "forwarder";
6
+ /**
7
+ * Transport channel classification used to route incoming and outgoing bus
8
+ * messages. If `receive` switches on the message alone and cannot tell the
9
+ * channels apart, a same-origin iframe looks like a duplicated tab.
10
+ */
11
+ export type LinkKind =
12
+ /** Synchronous call into a same-origin parent runtime. */
13
+ "direct"
14
+ /** postMessage to a parent window. */
15
+ | "parent"
16
+ /** postMessage to child frames. */
17
+ | "children"
18
+ /** BroadcastChannel across same-origin tabs and windows. */
19
+ | "broadcast"
20
+ /** OpenFin InterApplicationBus across desktop views and applications. */
21
+ | "openfin"
22
+ /** Dedicated worker communication to its owning document. */
23
+ | "owner"
24
+ /** Document-side communication to a dedicated worker. */
25
+ | "worker";
26
+ /** Origin and transport metadata for an incoming bus message. */
27
+ export interface MessageSource {
28
+ /** Inbound transport channel kind. */
29
+ link: LinkKind;
30
+ /** `event.origin` for `parent` and `children`; otherwise `"same-origin"` or `"openfin"`. */
31
+ origin: string;
32
+ }
33
+ /** Discriminated union of control and telemetry payload messages. */
34
+ export type BusMessage =
35
+ /** Handshake discovery announcement from a booting forwarder. */
36
+ {
37
+ t: "hello";
38
+ from: string;
39
+ tabId: string;
40
+ }
41
+ /**
42
+ * Handshake response acknowledging an upstream owner relationship. Addressed
43
+ * through `to`: a welcome published over InterApplicationBus reaches every
44
+ * subscriber, so an unaddressed one lets three waiting views each conclude
45
+ * it has found an owner of its own.
46
+ */
47
+ | {
48
+ t: "welcome";
49
+ from: string;
50
+ to: string;
51
+ tabId: string;
52
+ }
53
+ /** Telemetry log records forwarded to an upstream sender. */
54
+ | {
55
+ t: "records";
56
+ from: string;
57
+ records: LogRecord[];
58
+ }
59
+ /** Broadcast update announcing a new or ended journey state. */
60
+ | {
61
+ t: "journey";
62
+ from: string;
63
+ journey: Journey | null;
64
+ }
65
+ /** Query requesting active journey state from connected peers. */
66
+ | {
67
+ t: "journey?";
68
+ from: string;
69
+ }
70
+ /** Tab identifier claim broadcast to detect collisions across windows. */
71
+ | {
72
+ t: "tab";
73
+ from: string;
74
+ tabId: string;
75
+ };
76
+ /** Transport envelope wrapping bus messages with a protocol version tag. */
77
+ export interface BusEnvelope {
78
+ /** Protocol version identifier. */
79
+ p: typeof BUS_PROTOCOL;
80
+ /** Encapsulated bus payload. */
81
+ m: BusMessage;
82
+ }
83
+ /**
84
+ * Wraps a bus message in a versioned protocol envelope.
85
+ * @param message Message to encapsulate.
86
+ * @returns Envelope ready for transport.
87
+ */
88
+ export declare function envelope(message: BusMessage): BusEnvelope;
89
+ /**
90
+ * Validates protocol tags and unpacks raw payloads into bus messages. A
91
+ * document receives `message` events from every embedded thing on the page,
92
+ * including analytics tags, video players and extensions. Without the tag
93
+ * check a video player's message is parsed as a log record.
94
+ * @param data Raw payload received over a transport link.
95
+ * @returns Validated message, or null if payload is invalid or unrecognized.
96
+ */
97
+ export declare function unwrap(data: unknown): BusMessage | null;