@utk09/ui-observability 0.7.0 → 0.8.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 (122) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/README.md +122 -0
  3. package/dist/bus/bus.d.ts +30 -0
  4. package/dist/bus-CUXRY0JR.cjs +2 -0
  5. package/dist/bus-CUXRY0JR.cjs.map +1 -0
  6. package/dist/{bus-DfAbg_pg.js → bus-DPDrlUBY.js} +96 -50
  7. package/dist/bus-DPDrlUBY.js.map +1 -0
  8. package/dist/capture/console.d.ts +37 -0
  9. package/dist/capture/errors.d.ts +2 -4
  10. package/dist/capture/long-frames.d.ts +31 -0
  11. package/dist/capture/storm.d.ts +17 -0
  12. package/dist/capture/types.d.ts +2 -0
  13. package/dist/console-CNljJict.js +81 -0
  14. package/dist/console-CNljJict.js.map +1 -0
  15. package/dist/console-PKzc-FmR.cjs +2 -0
  16. package/dist/console-PKzc-FmR.cjs.map +1 -0
  17. package/dist/constants-B28fDv2F.cjs +2 -0
  18. package/dist/constants-B28fDv2F.cjs.map +1 -0
  19. package/dist/constants-Bu49bm39.js +93 -0
  20. package/dist/constants-Bu49bm39.js.map +1 -0
  21. package/dist/constants.d.ts +32 -2
  22. package/dist/core/breadcrumbs.d.ts +1 -1
  23. package/dist/core/pipeline.d.ts +2 -2
  24. package/dist/core/record.d.ts +3 -0
  25. package/dist/core/remote-rules.d.ts +17 -0
  26. package/dist/core/remote-sampling.d.ts +65 -0
  27. package/dist/core/runtime.d.ts +10 -4
  28. package/dist/core/sampling.d.ts +5 -2
  29. package/dist/core/sender.d.ts +3 -0
  30. package/dist/errors-C78ZTjet.cjs +3 -0
  31. package/dist/errors-C78ZTjet.cjs.map +1 -0
  32. package/dist/{errors-4MQyjZVj.js → errors-Dnc-X4Ec.js} +19 -20
  33. package/dist/errors-Dnc-X4Ec.js.map +1 -0
  34. package/dist/global-scope-BN-Io_yv.cjs +2 -0
  35. package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
  36. package/dist/global-scope-dp2jADRl.js +19 -0
  37. package/dist/global-scope-dp2jADRl.js.map +1 -0
  38. package/dist/index.cjs +1 -1
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.js +287 -242
  42. package/dist/index.js.map +1 -1
  43. package/dist/indexeddb-storage-D0p3iMD0.cjs +2 -0
  44. package/dist/{indexeddb-storage-CcEJlq2l.cjs.map → indexeddb-storage-D0p3iMD0.cjs.map} +1 -1
  45. package/dist/{indexeddb-storage-0LtUALBg.js → indexeddb-storage-uD4oaRMc.js} +10 -10
  46. package/dist/{indexeddb-storage-0LtUALBg.js.map → indexeddb-storage-uD4oaRMc.js.map} +1 -1
  47. package/dist/{interactions-BMNPQ3WH.cjs → interactions-CsE2y_fQ.cjs} +2 -2
  48. package/dist/{interactions-BMNPQ3WH.cjs.map → interactions-CsE2y_fQ.cjs.map} +1 -1
  49. package/dist/{interactions-BaCmoGLB.js → interactions-igKTAJvj.js} +2 -2
  50. package/dist/{interactions-BaCmoGLB.js.map → interactions-igKTAJvj.js.map} +1 -1
  51. package/dist/library-request-Br_T09Bn.cjs +2 -0
  52. package/dist/library-request-Br_T09Bn.cjs.map +1 -0
  53. package/dist/library-request-Dt0fXhcn.js +14 -0
  54. package/dist/library-request-Dt0fXhcn.js.map +1 -0
  55. package/dist/long-frames-6pnjWSSR.js +65 -0
  56. package/dist/long-frames-6pnjWSSR.js.map +1 -0
  57. package/dist/long-frames-DahhqM6u.cjs +2 -0
  58. package/dist/long-frames-DahhqM6u.cjs.map +1 -0
  59. package/dist/models/bus.d.ts +16 -0
  60. package/dist/models/config.d.ts +90 -0
  61. package/dist/network-CZ0aFUsy.cjs +2 -0
  62. package/dist/network-CZ0aFUsy.cjs.map +1 -0
  63. package/dist/{network-jQ2t8rU4.js → network-aSNbwpue.js} +16 -15
  64. package/dist/network-aSNbwpue.js.map +1 -0
  65. package/dist/{platform-YuByH8A5.js → platform-BwbMRwHm.js} +7 -7
  66. package/dist/{platform-YuByH8A5.js.map → platform-BwbMRwHm.js.map} +1 -1
  67. package/dist/{platform-ByQllE_W.cjs → platform-D_XkVIF6.cjs} +2 -2
  68. package/dist/{platform-ByQllE_W.cjs.map → platform-D_XkVIF6.cjs.map} +1 -1
  69. package/dist/remote-rules-5UA23alm.js +86 -0
  70. package/dist/remote-rules-5UA23alm.js.map +1 -0
  71. package/dist/remote-rules-rJJZKVG8.cjs +2 -0
  72. package/dist/remote-rules-rJJZKVG8.cjs.map +1 -0
  73. package/dist/sampling-E4x92Nn2.cjs +2 -0
  74. package/dist/sampling-E4x92Nn2.cjs.map +1 -0
  75. package/dist/sampling-J1eahbfT.js +160 -0
  76. package/dist/sampling-J1eahbfT.js.map +1 -0
  77. package/dist/sanitize-BMhh8ghJ.cjs +2 -0
  78. package/dist/sanitize-BMhh8ghJ.cjs.map +1 -0
  79. package/dist/sanitize-UJ-4Lb0n.js +114 -0
  80. package/dist/sanitize-UJ-4Lb0n.js.map +1 -0
  81. package/dist/sender-B6ufz26f.cjs +3 -0
  82. package/dist/sender-B6ufz26f.cjs.map +1 -0
  83. package/dist/{sender-BIob8eZz.js → sender-G6v4Uqi4.js} +304 -219
  84. package/dist/sender-G6v4Uqi4.js.map +1 -0
  85. package/dist/storm-BtzgLOCX.cjs +2 -0
  86. package/dist/storm-BtzgLOCX.cjs.map +1 -0
  87. package/dist/storm-DJkEZP_8.js +10 -0
  88. package/dist/storm-DJkEZP_8.js.map +1 -0
  89. package/dist/transport/custom-transport.d.ts +20 -0
  90. package/dist/transport/errors.d.ts +2 -1
  91. package/dist/transport/exit-flush.d.ts +15 -0
  92. package/dist/transport/http-transport.d.ts +2 -24
  93. package/dist/transport/memory-transport.d.ts +30 -0
  94. package/dist/transport/retry-engine.d.ts +2 -2
  95. package/dist/transport/serializers/select.d.ts +12 -1
  96. package/dist/transport/status-transport.d.ts +72 -0
  97. package/dist/utils/deadline.d.ts +7 -0
  98. package/dist/utils/global-scope.d.ts +20 -0
  99. package/dist/utils/library-console.d.ts +11 -0
  100. package/dist/utils/library-request.d.ts +12 -0
  101. package/package.json +1 -1
  102. package/dist/bus-DeZzr2bx.cjs +0 -2
  103. package/dist/bus-DeZzr2bx.cjs.map +0 -1
  104. package/dist/bus-DfAbg_pg.js.map +0 -1
  105. package/dist/constants-C8nZQBmQ.js +0 -86
  106. package/dist/constants-C8nZQBmQ.js.map +0 -1
  107. package/dist/constants-IBL_jd5R.cjs +0 -2
  108. package/dist/constants-IBL_jd5R.cjs.map +0 -1
  109. package/dist/errors-4MQyjZVj.js.map +0 -1
  110. package/dist/errors-CUdShXe7.cjs +0 -3
  111. package/dist/errors-CUdShXe7.cjs.map +0 -1
  112. package/dist/indexeddb-storage-CcEJlq2l.cjs +0 -2
  113. package/dist/network-DBNvxCE3.cjs +0 -2
  114. package/dist/network-DBNvxCE3.cjs.map +0 -1
  115. package/dist/network-jQ2t8rU4.js.map +0 -1
  116. package/dist/sampling-CbYySsZ1.js +0 -251
  117. package/dist/sampling-CbYySsZ1.js.map +0 -1
  118. package/dist/sampling-Cs50xsZl.cjs +0 -2
  119. package/dist/sampling-Cs50xsZl.cjs.map +0 -1
  120. package/dist/sender-BIob8eZz.js.map +0 -1
  121. package/dist/sender-iOjzcueM.cjs +0 -3
  122. package/dist/sender-iOjzcueM.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-B28fDv2F.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.$).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.$).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.et,t).objectStore(e.et)}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.et,{keyPath:`id`}).createIndex(e.$,e.$)},i.onsuccess=()=>{let e=i.result;a?e.close():(e.onversionchange=()=>{e.close(),this.connection=null},n(e))},i.onerror=()=>{r(t(i))},i.onblocked=()=>{a=!0,r(Error(`Another connection blocks 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.nn;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. The library removes the oldest batches.`);let t=await this.diagnostics.guardAsync(`storage.degraded`,`The library could not remove old batches after a full disk.`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));t&&this.reportGap({...t,reason:`quota`}),await this.diagnostics.guardAsync(`storage.degraded`,`The library could not write the batch after it removed old batches.`,async()=>(await this.db.put(e),!0))!==!0&&this.reportGap({batches:1,records:e.records.length,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`The library could not store a batch.`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not read the stored batches.`,()=>this.db.takeOldest(e))??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not delete a batch.`,()=>this.db.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not update the attempt count.`,()=>this.db.bumpAttempts(e,t))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not prune the stored batches.`,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`,`The library could not count the stored batches.`,()=>this.db.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not clear the stored batches.`,()=>this.db.clear())}async close(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not close the database.`,()=>this.db.close())}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`The library 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-D0p3iMD0.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb-storage-CcEJlq2l.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","require_constants","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// 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 * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * 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. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * 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/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\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. It replaces a stored batch with 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. It does not remove 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 each batch with a createdAt value before the 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. A partial failure deletes none of\n * them.\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 * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that was delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then 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 the 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 /** This method deletes all stored batches. */\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. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\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 new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\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. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then 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 from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\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 already rejected. No reference to this connection remains.\n // 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 settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks 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// This module stores batches in IndexedDB. It indexes them by creation time.\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 * Returns the total record count of the 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/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code 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. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\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(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches 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 makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\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 \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\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 \"The library could not read the stored batches.\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\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(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n 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\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns the number 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(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and to the gap handler.\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 `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\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":"4CAqBA,SAASI,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CASA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxBC,EAAQF,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtBG,EAAOJ,EAAUC,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAaI,EAAb,KAAuB,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAA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AAC,EAEjD,CAAE,QAAS0B,EAAO,OAAQ,QAASZ,EAAaY,CAAM,CAAE,CACjE,CACF"}
1
+ {"version":3,"file":"indexeddb-storage-D0p3iMD0.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","require_constants","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// 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 * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * 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. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * 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/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\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. It replaces a stored batch with 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. It does not remove 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 each batch with a createdAt value before the 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. A partial failure deletes none of\n * them.\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 * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that was delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then 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 the 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 /** This method deletes all stored batches. */\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. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\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 new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\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. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then 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 from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\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 already rejected. No reference to this connection remains.\n // 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 settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks 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// This module stores batches in IndexedDB. It indexes them by creation time.\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 * Returns the total record count of the 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/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code 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. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\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(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches 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 makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\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 \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\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 \"The library could not read the stored batches.\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\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(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n 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\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns the number 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(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and to the gap handler.\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 `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\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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,WACrB,mBACA,gDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAMA,UAAkB,EAA2B,CACvCA,EAAO,UAAY,IAIvB,KAAK,YAAY,OACf,kBACA,uBAAuB,OAAOA,EAAO,OAAO,EAAE,mBAAmB,OAAOA,EAAO,OAAO,EAAE,YACxF,CAAE,GAAGA,CAAO,CACd,EACA,KAAK,QAAQA,CAAM,EACrB,CASA,MAAc,YAAY,EAAuD,CAC/E,IAAME,EAAS,MAAM,KAAK,GAAG,WAAWC,CAAO,EAG/C,OAFA,MAAM,KAAK,GAAG,WAAWD,EAAO,IAAK,GAAU1B,EAAM,EAAE,CAAC,EAEjD,CAAE,QAAS0B,EAAO,OAAQ,QAASZ,EAAaY,CAAM,CAAE,CACjE,CACF"}
@@ -1,4 +1,4 @@
1
- import { $ as e, Q as t, Xt as n } from "./constants-C8nZQBmQ.js";
1
+ import { $ as e, et as t, nn as n } from "./constants-Bu49bm39.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.");
@@ -21,12 +21,12 @@ var a = class {
21
21
  async put(e) {
22
22
  await i((await this.store("readwrite")).put(e));
23
23
  }
24
- async takeOldest(e) {
25
- return i((await this.store("readonly")).index(t).getAll(null, e));
24
+ async takeOldest(t) {
25
+ return i((await this.store("readonly")).index(e).getAll(null, t));
26
26
  }
27
- async takeBefore(e) {
28
- let n = await this.store("readonly"), r = IDBKeyRange.upperBound(e, !0);
29
- return i(n.index(t).getAll(r));
27
+ async takeBefore(t) {
28
+ let n = await this.store("readonly"), r = IDBKeyRange.upperBound(t, !0);
29
+ return i(n.index(e).getAll(r));
30
30
  }
31
31
  async delete(e) {
32
32
  await i((await this.store("readwrite")).delete(e));
@@ -55,8 +55,8 @@ var a = class {
55
55
  let e = this.connection;
56
56
  e !== null && (this.connection = null, (await e).close());
57
57
  }
58
- async store(t) {
59
- return (await this.open()).transaction(e, t).objectStore(e);
58
+ async store(e) {
59
+ return (await this.open()).transaction(t, e).objectStore(t);
60
60
  }
61
61
  open() {
62
62
  let n = this.connection;
@@ -65,7 +65,7 @@ var a = class {
65
65
  let a = indexedDB.open(this.name, 11), o = !1;
66
66
  a.onupgradeneeded = () => {
67
67
  let n = a.result;
68
- n.objectStoreNames.contains("batches") || n.createObjectStore(e, { keyPath: "id" }).createIndex(t, t);
68
+ n.objectStoreNames.contains("batches") || n.createObjectStore(t, { keyPath: "id" }).createIndex(e, e);
69
69
  }, a.onsuccess = () => {
70
70
  let e = a.result;
71
71
  o ? e.close() : (e.onversionchange = () => {
@@ -168,4 +168,4 @@ var s = class {
168
168
  //#endregion
169
169
  export { s as IndexedDbStorage };
170
170
 
171
- //# sourceMappingURL=indexeddb-storage-0LtUALBg.js.map
171
+ //# sourceMappingURL=indexeddb-storage-uD4oaRMc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb-storage-0LtUALBg.js","names":["INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","STORAGE_NAME_INDEXEDDB","failureOf","request","promisify","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","resolve","reject","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// 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 * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * 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. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * 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/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\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. It replaces a stored batch with 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. It does not remove 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 each batch with a createdAt value before the 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. A partial failure deletes none of\n * them.\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 * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that was delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then 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 the 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 /** This method deletes all stored batches. */\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. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\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 new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\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. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then 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 from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\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 already rejected. No reference to this connection remains.\n // 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 settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks 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// This module stores batches in IndexedDB. It indexes them by creation time.\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 * Returns the total record count of the 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/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code 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. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\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(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches 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 makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\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 \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\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 \"The library could not read the stored batches.\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\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(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n 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\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns the number 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(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and to the gap handler.\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 `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\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":";;AAqBA,SAASG,EAAU,GAA4B;CAC7C,OAAOC,EAAQ,SAAS,gBAAI,MAAM,+BAA+B;AACnE;AASA,SAASC,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQD,EAAQ,MAAW;EAC7B,GACA,EAAQ,gBAAgB;GACtB,EAAOD,EAAUC,CAAO,CAAC;EAC3B;CACF,CAAC;AACH;AAGA,IAAaE,IAAb,MAAuB;CAOQ;CAL7B,aAAkD;CAKlD,YAAY,GAA+B;EAAd,KAAA,OAAAC;CAAe;CAM5C,MAAM,IAAI,GAAgC;EAExC,MAAMF,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIG,CAAK,CAAC;CAClC;CAOA,MAAM,WAAW,GAAoC;EAEnD,OAAOH,GAAsB,MADT,KAAK,MAAM,UAAU,EAAA,CACN,MAAMJ,CAA0B,CAAC,CAAC,OAAO,MAAMQ,CAAK,CAAC;CAC1F;CAOA,MAAM,WAAW,GAAqC;EACpD,IAAMC,IAAQ,MAAM,KAAK,MAAM,UAAU,GACnCC,IAAQ,YAAY,WAAWC,GAAQ,EAAI;EACj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AK,GAAG,MAAM;GAClC,IAAIA,IAAQ,KAAK,OAAO,YAAY;IAClC,EAAO,SAAS;IAChB,IAAMM,IAAU,MAAM,KAAK,YAAYN,IAAQ,KAAK,OAAO,UAAU;IAErE,AADA,EAAO,WAAWM,EAAQ,SAC1B,EAAO,WAAWA,EAAQ;GAC5B;EACF,CACF,GAEA,KAAK,UAAUE,CAAM,GACdA;CACT;CAMA,MAAM,QAAyB;EAM7B,OAAO,MALa,KAAK,YAAY,WACnC,oBACA,yDACM,KAAK,GAAG,MAAM,CACtB,KACgB;CAClB;CAGA,MAAM,QAAuB;EAC3B,MAAM,KAAK,YAAY,WACrB,oBACA,yDACM,KAAK,GAAG,MAAM,CACtB;CACF;CAGA,MAAM,QAAuB;EAC3B,MAAM,KAAK,YAAY,WACrB,oBACA,mDACM,KAAK,GAAG,MAAM,CACtB;CACF;CAMA,UAAkB,GAA2B;EAC3C,AAAIA,EAAO,YAAY,MAIvB,KAAK,YAAY,OACf,mBACA,uBAAuB,OAAOA,EAAO,OAAO,EAAE,mBAAmB,OAAOA,EAAO,OAAO,EAAE,aACxF,EAAE,GAAGA,EAAO,CACd,GACA,KAAK,QAAQA,CAAM;CACrB;CASA,MAAc,YAAY,GAAuD;EAC/E,IAAME,IAAS,MAAM,KAAK,GAAG,WAAWC,CAAO;EAG/C,OAFA,MAAM,KAAK,GAAG,WAAWD,EAAO,KAAK,MAAU5B,EAAM,EAAE,CAAC,GAEjD;GAAE,SAAS4B,EAAO;GAAQ,SAASZ,EAAaY,CAAM;EAAE;CACjE;AACF"}
1
+ {"version":3,"file":"indexeddb-storage-uD4oaRMc.js","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","failureOf","request","promisify","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","resolve","reject","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// 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 * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * 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. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * 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/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\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. It replaces a stored batch with 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. It does not remove 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 each batch with a createdAt value before the 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. A partial failure deletes none of\n * them.\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 * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that was delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then 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 the 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 /** This method deletes all stored batches. */\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. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\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 new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\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. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then 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 from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\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 already rejected. No reference to this connection remains.\n // 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 settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks 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// This module stores batches in IndexedDB. It indexes them by creation time.\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 * Returns the total record count of the 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/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code 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. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\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(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches 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 makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\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 \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\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 \"The library could not read the stored batches.\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\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(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n 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\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns the number 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(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and to the gap handler.\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 `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\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":";;AAqBA,SAASG,EAAU,GAA4B;CAC7C,OAAOC,EAAQ,SAAS,gBAAI,MAAM,+BAA+B;AACnE;AASA,SAASC,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQD,EAAQ,MAAW;EAC7B,GACA,EAAQ,gBAAgB;GACtB,EAAOD,EAAUC,CAAO,CAAC;EAC3B;CACF,CAAC;AACH;AAGA,IAAaE,IAAb,MAAuB;C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AO;EAG/C,OAFA,MAAM,KAAK,GAAG,WAAWD,EAAO,KAAK,MAAU5B,EAAM,EAAE,CAAC,GAEjD;GAAE,SAAS4B,EAAO;GAAQ,SAASZ,EAAaY,CAAM;EAAE;CACjE;AACF"}
@@ -1,2 +1,2 @@
1
- const e=require("./platform-ByQllE_W.cjs");function t(e){if(e===null)return`unknown`;let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function n(){return history}var r=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(n().pushState=this.originalPushState),this.originalReplaceState&&(n().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let n=e.target,r=t(n instanceof Element?n:null),i=n instanceof HTMLElement?n.textContent.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:r,data:i===``?void 0:{text:i}})};onNavigate=()=>{let t=this.lastUrl,n=location.href;if(t===n)return;this.lastUrl=n;let r=this.ctx.config.capture.fullUrls,i=r?t:e.r(t),a=r?n:e.r(n);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${i} -> ${a}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":i})};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=n(),t=e.pushState,r=e.replaceState;this.originalPushState=t,this.originalReplaceState=r;let i=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(i)},e.replaceState=function(...e){r.apply(this,e),queueMicrotask(i)}}};exports.InteractionCapture=r;
2
- //# sourceMappingURL=interactions-BMNPQ3WH.cjs.map
1
+ const e=require("./platform-D_XkVIF6.cjs");function t(e){if(e===null)return`unknown`;let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function n(){return history}var r=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(n().pushState=this.originalPushState),this.originalReplaceState&&(n().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let n=e.target,r=t(n instanceof Element?n:null),i=n instanceof HTMLElement?n.textContent.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:r,data:i===``?void 0:{text:i}})};onNavigate=()=>{let t=this.lastUrl,n=location.href;if(t===n)return;this.lastUrl=n;let r=this.ctx.config.capture.fullUrls,i=r?t:e.r(t),a=r?n:e.r(n);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${i} -> ${a}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":i})};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=n(),t=e.pushState,r=e.replaceState;this.originalPushState=t,this.originalReplaceState=r;let i=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(i)},e.replaceState=function(...e){r.apply(this,e),queueMicrotask(i)}}};exports.InteractionCapture=r;
2
+ //# sourceMappingURL=interactions-CsE2y_fQ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"interactions-BMNPQ3WH.cjs","names":["stripUrlQuery","require_platform","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /** Removes interaction listeners and restores native history methods. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":"2CAcA,SAASE,EAAgB,EAAiC,CACxD,GAAIC,IAAY,KACd,MAAO,UAGT,IAAMC,EAAMD,EAAQ,QAAQ,YAAY,EAElCE,EAASF,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIE,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAIF,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAMG,EAAQH,EAAQ,aAAa,YAAY,EAC/C,GAAIG,IAAU,KACZ,MAAO,GAAGF,EAAI,eAAeE,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKpE,IAAMC,EAAiBJ,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,GAAK,GAMhE,OALII,IAAmB,GACdH,EAIF,GAAGA,EAAI,GADEG,EAAe,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAC/D,GACnB,CAiBA,SAASC,GAAiC,CACxC,OAAO,OACT,CAGA,IAAaC,EAAb,KAAmD,CAmBpB,IAjB7B,KAAgB,eAGhB,UAAoB,GAGpB,kBAAgE,KAGhE,qBAAsE,KAGtE,QAAkB,GAKlB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,SAAa,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AI,EACZ,SAAU,aACV,QAAS,GAAGE,EAAQ,MAAMC,GAC5B,CAAC,EAID,KAAK,IAAI,OAAO,SAAS,aAAc,CAAE,oBAAqBD,CAAQ,CAAC,CACzE,EAGA,gBAA+B,CAC7B,GAAI,OAAO,QAAY,KAAe,KAAK,kBACzC,OAMF,IAAMP,EAASH,EAAe,EACxBY,EAAoBT,EAAO,UAC3BU,EAAuBV,EAAO,aACpC,KAAK,kBAAoBS,EACzB,KAAK,qBAAuBC,EAC5B,IAAMC,EAAa,KAAK,WAExB,EAAO,UAAY,SAAyB,GAAGC,EAAqB,CAClEH,EAAkB,MAAM,KAAMG,CAAI,EAGlC,eAAeD,CAAU,CAC3B,EAEA,EAAO,aAAe,SAAyB,GAAGC,EAAqB,CACrEF,EAAqB,MAAM,KAAME,CAAI,EACrC,eAAeD,CAAU,CAC3B,CACF,CACF"}
1
+ {"version":3,"file":"interactions-CsE2y_fQ.cjs","names":["stripUrlQuery","require_platform","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /** Removes interaction listeners and restores native history methods. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":"2CAcA,SAASE,EAAgB,EAAiC,CACxD,GAAIC,IAAY,KACd,MAAO,UAGT,IAAMC,EAAMD,EAAQ,QAAQ,YAAY,EAElCE,EAASF,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIE,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAIF,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAMG,EAAQH,EAAQ,aAAa,YAAY,EAC/C,GAAIG,IAAU,KACZ,MAAO,GAAGF,EAAI,eAAeE,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKpE,IAAMC,EAAiBJ,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,GAAK,GAMhE,OALII,IAAmB,GACdH,EAIF,GAAGA,EAAI,GADEG,EAAe,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAC/D,GACnB,CAiBA,SAASC,GAAiC,CACxC,OAAO,OACT,CAGA,IAAaC,EAAb,KAAmD,CAmBpB,IAjB7B,KAAgB,eAGhB,UAAoB,GAGpB,kBAAgE,KAGhE,qBAAsE,KAGtE,QAAkB,GAKlB,YAAY,EAAsC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,QAAQ,OAAO,YAAY,EACpC,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,aACV,QAAS,GAAGE,EAAQ,MAAMC,GAC5B,CAAC,EAID,KAAK,IAAI,OAAO,SAAS,aAAc,CAAE,oBAAqBD,CAAQ,CAAC,CACzE,EAGA,gBAA+B,CAC7B,GAAI,OAAO,QAAY,KAAe,KAAK,kBACzC,OAMF,IAAMP,EAASH,EAAe,EACxBY,EAAoBT,EAAO,UAC3BU,EAAuBV,EAAO,aACpC,KAAK,kBAAoBS,EACzB,KAAK,qBAAuBC,EAC5B,IAAMC,EAAa,KAAK,WAExB,EAAO,UAAY,SAAyB,GAAGC,EAAqB,CAClEH,EAAkB,MAAM,KAAMG,CAAI,EAGlC,eAAeD,CAAU,CAC3B,EAEA,EAAO,aAAe,SAAyB,GAAGC,EAAqB,CACrEF,EAAqB,MAAM,KAAME,CAAI,EACrC,eAAeD,CAAU,CAC3B,CACF,CACF"}
@@ -1,4 +1,4 @@
1
- import { r as e } from "./platform-YuByH8A5.js";
1
+ import { r as e } from "./platform-BwbMRwHm.js";
2
2
  //#region src/capture/interactions.ts
3
3
  function t(e) {
4
4
  if (e === null) return "unknown";
@@ -64,4 +64,4 @@ var r = class {
64
64
  //#endregion
65
65
  export { r as InteractionCapture };
66
66
 
67
- //# sourceMappingURL=interactions-BaCmoGLB.js.map
67
+ //# sourceMappingURL=interactions-igKTAJvj.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"interactions-BaCmoGLB.js","names":["stripUrlQuery","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /** Removes interaction listeners and restores native history methods. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":";;AAcA,SAASC,EAAgB,GAAiC;CACxD,IAAIC,MAAY,MACd,OAAO;CAGT,IAAMC,IAAMD,EAAQ,QAAQ,YAAY,GAElCE,IAASF,EAAQ,aAAa,aAAa,KAAKA,EAAQ,aAAa,cAAc;CACzF,IAAIE,MAAW,MACb,OAAO,iBAAiBA,EAAO;CAEjC,IAAIF,EAAQ,OAAO,IACjB,OAAO,IAAIA,EAAQ;CAGrB,IAAMG,IAAQH,EAAQ,aAAa,YAAY;CAC/C,IAAIG,MAAU,MACZ,OAAO,GAAGF,EAAI,eAAeE,EAAM,MAAM,GAAA,EAAuB,EAAE;CAK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KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAASE;GACT,MAAMC,MAAS,KAAK,KAAA,IAAY,EAAE,QAAK;EACzC,CAAC;CACH;CAGA,mBAA0C;EACxC,IAAMC,IAAO,KAAK,SACZC,IAAK,SAAS;EACpB,IAAID,MAASC,GACX;EAEF,KAAK,UAAUA;EAIf,IAAMC,IAAO,KAAK,IAAI,OAAO,QAAQ,UAC/BC,IAAUD,IAAOF,IAAOd,EAAcc,CAAI,GAC1CI,IAAQF,IAAOD,IAAKf,EAAce,CAAE;EAW1C,AATA,KAAK,IAAI,QAAQ,OAAO,YAAY,GACpC,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,GAAGE,EAAQ,MAAMC;EAC5B,CAAC,GAID,KAAK,IAAI,OAAO,SAAS,cAAc,EAAE,qBAAqBD,EAAQ,CAAC;CACzE;CAGA,iBAA+B;EAC7B,IAAI,OAAO,UAAY,OAAe,KAAK,mBACzC;EAMF,IAAMP,IAASH,EAAe,GACxBY,IAAoBT,EAAO,WAC3BU,IAAuBV,EAAO;EAEpC,AADA,KAAK,oBAAoBS,GACzB,KAAK,uBAAuBC;EAC5B,IAAMC,IAAa,KAAK;EASxB,AAPA,EAAO,YAAY,SAAyB,GAAGC,GAAqB;GAIlE,AAHAH,EAAkB,MAAM,MAAMG,CAAI,GAGlC,eAAeD,CAAU;EAC3B,GAEA,EAAO,eAAe,SAAyB,GAAGC,GAAqB;GAErE,AADAF,EAAqB,MAAM,MAAME,CAAI,GACrC,eAAeD,CAAU;EAC3B;CACF;AACF"}
1
+ {"version":3,"file":"interactions-igKTAJvj.js","names":["stripUrlQuery","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /** Removes interaction listeners and restores native history methods. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":";;AAcA,SAASC,EAAgB,GAAiC;CACxD,IAAIC,MAAY,MACd,OAAO;CAGT,IAAMC,IAAMD,EAAQ,QAAQ,YAAY,GAElCE,IAASF,EAAQ,aAAa,aAAa,KAAKA,EAAQ,aAAa,cAAc;CACzF,IAAIE,MAAW,MACb,OAAO,iBAAiBA,EAAO;CAEjC,IAAIF,EAAQ,OAAO,IACjB,OAAO,IAAIA,EAAQ;CAGrB,IAAMG,IAAQH,EAAQ,aAAa,Y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MAAM,GAAA,EAAuB,IAAI;EAK7F,AADA,KAAK,IAAI,QAAQ,OAAO,aAAa,GACrC,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAASE;GACT,MAAMC,MAAS,KAAK,KAAA,IAAY,EAAE,QAAK;EACzC,CAAC;CACH;CAGA,mBAA0C;EACxC,IAAMC,IAAO,KAAK,SACZC,IAAK,SAAS;EACpB,IAAID,MAASC,GACX;EAEF,KAAK,UAAUA;EAIf,IAAMC,IAAO,KAAK,IAAI,OAAO,QAAQ,UAC/BC,IAAUD,IAAOF,IAAOd,EAAcc,CAAI,GAC1CI,IAAQF,IAAOD,IAAKf,EAAce,CAAE;EAW1C,AATA,KAAK,IAAI,QAAQ,OAAO,YAAY,GACpC,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,GAAGE,EAAQ,MAAMC;EAC5B,CAAC,GAID,KAAK,IAAI,OAAO,SAAS,cAAc,EAAE,qBAAqBD,EAAQ,CAAC;CACzE;CAGA,iBAA+B;EAC7B,IAAI,OAAO,UAAY,OAAe,KAAK,mBACzC;EAMF,IAAMP,IAASH,EAAe,GACxBY,IAAoBT,EAAO,WAC3BU,IAAuBV,EAAO;EAEpC,AADA,KAAK,oBAAoBS,GACzB,KAAK,uBAAuBC;EAC5B,IAAMC,IAAa,KAAK;EASxB,AAPA,EAAO,YAAY,SAAyB,GAAGC,GAAqB;GAIlE,AAHAH,EAAkB,MAAM,MAAMG,CAAI,GAGlC,eAAeD,CAAU;EAC3B,GAEA,EAAO,eAAe,SAAyB,GAAGC,GAAqB;GAErE,AADAF,EAAqB,MAAM,MAAME,CAAI,GACrC,eAAeD,CAAU;EAC3B;CACF;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-B28fDv2F.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.ct);function n(e){return t.run(e)}function r(){return t.open()}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
2
+ //# sourceMappingURL=library-request-Br_T09Bn.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"library-request-Br_T09Bn.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","require_constants","scope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests whether a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":"4CAUA,IAAMG,uCAAQH,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAQ7C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB"}
@@ -0,0 +1,14 @@
1
+ import { ct as e } from "./constants-Bu49bm39.js";
2
+ import { t } from "./global-scope-dp2jADRl.js";
3
+ //#region src/utils/library-request.ts
4
+ var n = t(e);
5
+ function r(e) {
6
+ return n.run(e);
7
+ }
8
+ function i() {
9
+ return n.open();
10
+ }
11
+ //#endregion
12
+ export { r as n, i as t };
13
+
14
+ //# sourceMappingURL=library-request-Dt0fXhcn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"library-request-Dt0fXhcn.js","names":["LIBRARY_REQUEST_KEY","scope","globalScope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests whether a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":";;;AAUA,IAAMC,IAAQC,EAAYF,CAAmB;AAQ7C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOF,EAAM,IAAIG,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOJ,EAAM,KAAK;AACpB"}
@@ -0,0 +1,65 @@
1
+ import { r as e } from "./platform-BwbMRwHm.js";
2
+ import { t } from "./storm-DJkEZP_8.js";
3
+ //#region src/capture/long-frames.ts
4
+ var n = ["long-animation-frame", "longtask"];
5
+ function r(e) {
6
+ let t;
7
+ for (let n of e ?? []) (!t || n.duration > t.duration) && (t = n);
8
+ return t;
9
+ }
10
+ var i = class {
11
+ ctx;
12
+ name = "long-frames";
13
+ observer;
14
+ window = {
15
+ start: 0,
16
+ count: 0
17
+ };
18
+ threshold = 100;
19
+ constructor(e) {
20
+ this.ctx = e;
21
+ }
22
+ install() {
23
+ if (this.observer) return;
24
+ let { once: e } = this.ctx, t = !e.longFrames;
25
+ e.longFrames = !0;
26
+ let r = typeof PerformanceObserver > "u" ? void 0 : PerformanceObserver.supportedEntryTypes, i = n.find((e) => r?.includes(e));
27
+ if (i === void 0) {
28
+ if (!t) return;
29
+ this.ctx.diagnostics.report("capture.install_failed", "The browser does not report long frames. The long frame capture is off.");
30
+ } else this.threshold = this.readThreshold(), this.observer = new PerformanceObserver((e) => {
31
+ for (let t of e.getEntries()) this.record(t);
32
+ }), this.observer.observe({
33
+ type: i,
34
+ buffered: t
35
+ });
36
+ }
37
+ uninstall() {
38
+ this.observer?.disconnect(), this.observer = void 0;
39
+ }
40
+ readThreshold() {
41
+ let e = this.ctx.config.capture.longFrameThresholdMs;
42
+ return typeof e == "number" && Number.isFinite(e) && e >= 0 ? e : (this.ctx.diagnostics.report("config.invalid", "capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100."), 100);
43
+ }
44
+ record(n) {
45
+ if (n.duration < this.threshold) return;
46
+ let { diagnostics: i } = this.ctx;
47
+ if (!t(this.window, 20, i, "long frames")) return;
48
+ let a = Math.round(n.duration), o = { "frame.type": n.entryType };
49
+ n.blockingDuration !== void 0 && (o["frame.blocking_ms"] = Math.round(n.blockingDuration));
50
+ let s = r(n.scripts), c = (t) => this.ctx.config.capture.fullUrls ? t : e(t);
51
+ if (s?.invoker) {
52
+ let { invoker: e } = s;
53
+ o["frame.script.invoker"] = e.includes("://") ? c(e) : e;
54
+ }
55
+ s?.sourceURL && (o["frame.script.source"] = c(s.sourceURL)), this.ctx.breadcrumbs.push({
56
+ t: Date.now(),
57
+ category: "frame",
58
+ message: `long frame ${String(a)} ms`
59
+ }), this.ctx.logger.logMetric("ui.long_frame.duration", a, "ms", "histogram", o);
60
+ }
61
+ };
62
+ //#endregion
63
+ export { i as LongFrameCapture };
64
+
65
+ //# sourceMappingURL=long-frames-6pnjWSSR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"long-frames-6pnjWSSR.js","names":["stripUrlQuery","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if fullUrls is set.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI,CAAC;EAEjE,IAAID,MAAS,KAAA,GAAW;GACtB,IAAI,CAACH,GACH;GAGF,KAAK,IAAI,YAAY,OACnB,0BACA,yEACF;EAEF,OAUA,AARA,KAAK,YAAY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U,MAAM,aAAaC,CAAK;CACxF;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./platform-D_XkVIF6.cjs"),t=require("./storm-BtzgLOCX.cjs");var n=[`long-animation-frame`,`longtask`];function r(e){let t;for(let n of e??[])(!t||n.duration>t.duration)&&(t=n);return t}var i=class{ctx;name=`long-frames`;observer;window={start:0,count:0};threshold=100;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.longFrames;e.longFrames=!0;let r=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes,i=n.find(e=>r?.includes(e));if(i===void 0){if(!t)return;this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long frames. The long frame capture is off.`)}else this.threshold=this.readThreshold(),this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:i,buffered:t})}uninstall(){this.observer?.disconnect(),this.observer=void 0}readThreshold(){let e=this.ctx.config.capture.longFrameThresholdMs;return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:(this.ctx.diagnostics.report(`config.invalid`,`capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100.`),100)}record(n){if(n.duration<this.threshold)return;let{diagnostics:i}=this.ctx;if(!t.t(this.window,20,i,`long frames`))return;let a=Math.round(n.duration),o={"frame.type":n.entryType};n.blockingDuration!==void 0&&(o[`frame.blocking_ms`]=Math.round(n.blockingDuration));let s=r(n.scripts),c=t=>this.ctx.config.capture.fullUrls?t:e.r(t);if(s?.invoker){let{invoker:e}=s;o[`frame.script.invoker`]=e.includes(`://`)?c(e):e}s?.sourceURL&&(o[`frame.script.source`]=c(s.sourceURL)),this.ctx.breadcrumbs.push({t:Date.now(),category:`frame`,message:`long frame ${String(a)} ms`}),this.ctx.logger.logMetric(`ui.long_frame.duration`,a,`ms`,`histogram`,o)}};exports.LongFrameCapture=i;
2
+ //# sourceMappingURL=long-frames-DahhqM6u.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"long-frames-DahhqM6u.cjs","names":["allowInWindow","stripUrlQuery","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if fullUrls is set.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAMC,KAAUC,GAAW,CAAC,GAC3B,CAACF,GAAWC,EAAO,SAAWD,EAAQ,YACxC,EAAUC,GAId,OAAOD,CACT,CAGA,IAAaG,EAAb,KAAiD,CAgBlB,IAd7B,KAAgB,cAGhB,SAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAG5D,UAAA,IAKA,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACd,GAAI,KAAK,SACP,OAKF,GAAM,CAAE,QAAS,KAAK,IAChBC,EAAQ,CAACC,EAAK,WACpB,EAAK,WAAa,GAGlB,IAAMC,EACJ,OAAO,oBAAwB,IAC3B,IAAA,GACA,oBAAoB,oBACpBC,EAAOV,EAAY,KAAM,GAASS,GAAW,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AAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
@@ -71,6 +71,22 @@ export type BusMessage =
71
71
  t: "tab";
72
72
  from: string;
73
73
  tabId: string;
74
+ }
75
+ /** Request of a forwarder for the remote sampling rules in force. */
76
+ | {
77
+ t: "sampling?";
78
+ from: string;
79
+ }
80
+ /**
81
+ * Remote sampling rules in the shape of the header, with the remaining TTL. The `to` field
82
+ * holds the address of the forwarder that asked. The receiver validates `rules` again.
83
+ * Null rules end the copy of the forwarder.
84
+ */
85
+ | {
86
+ t: "sampling";
87
+ from: string;
88
+ to: string;
89
+ rules: unknown;
74
90
  };
75
91
  /** Transport envelope wrapping bus messages with a protocol version tag. */
76
92
  export interface BusEnvelope {