@utk09/ui-observability 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +79 -1
- package/README.md +170 -41
- package/dist/bus/bus.d.ts +75 -11
- package/dist/bus/links.d.ts +6 -3
- package/dist/bus-CtJWf9QN.cjs +2 -0
- package/dist/bus-CtJWf9QN.cjs.map +1 -0
- package/dist/{bus-DfAbg_pg.js → bus-D8kH58tb.js} +176 -73
- package/dist/bus-D8kH58tb.js.map +1 -0
- package/dist/capture/console.d.ts +37 -0
- package/dist/capture/errors.d.ts +2 -4
- package/dist/capture/interactions.d.ts +7 -6
- package/dist/capture/long-frames.d.ts +31 -0
- package/dist/capture/network.d.ts +23 -9
- package/dist/capture/storm.d.ts +17 -0
- package/dist/capture/types.d.ts +5 -3
- package/dist/console-BpHfWstv.cjs +2 -0
- package/dist/console-BpHfWstv.cjs.map +1 -0
- package/dist/console-DjLbryED.js +82 -0
- package/dist/console-DjLbryED.js.map +1 -0
- package/dist/constants-Br3b89Wg.cjs +2 -0
- package/dist/constants-Br3b89Wg.cjs.map +1 -0
- package/dist/constants-DM94FjVX.js +96 -0
- package/dist/constants-DM94FjVX.js.map +1 -0
- package/dist/constants.d.ts +51 -10
- package/dist/core/breadcrumbs.d.ts +1 -1
- package/dist/core/diagnostics.d.ts +2 -2
- package/dist/core/journey.d.ts +16 -4
- package/dist/core/logger.d.ts +6 -2
- package/dist/core/pipeline.d.ts +20 -11
- package/dist/core/record.d.ts +14 -6
- package/dist/core/remote-rules.d.ts +17 -0
- package/dist/core/remote-sampling.d.ts +65 -0
- package/dist/core/runtime.d.ts +52 -18
- package/dist/core/sampling.d.ts +5 -2
- package/dist/core/sender.d.ts +18 -10
- package/dist/deadline-B5DINjD5.js +111 -0
- package/dist/deadline-B5DINjD5.js.map +1 -0
- package/dist/deadline-Cbg2cbUw.cjs +2 -0
- package/dist/deadline-Cbg2cbUw.cjs.map +1 -0
- package/dist/error-like-Ywo5uRHo.js +19 -0
- package/dist/error-like-Ywo5uRHo.js.map +1 -0
- package/dist/error-like-gGRx2s36.cjs +2 -0
- package/dist/error-like-gGRx2s36.cjs.map +1 -0
- package/dist/errors-CpGRhhIf.cjs +3 -0
- package/dist/errors-CpGRhhIf.cjs.map +1 -0
- package/dist/{errors-4MQyjZVj.js → errors-DH4QJS0u.js} +38 -20
- package/dist/errors-DH4QJS0u.js.map +1 -0
- package/dist/global-scope-BN-Io_yv.cjs +2 -0
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
- package/dist/global-scope-dp2jADRl.js +19 -0
- package/dist/global-scope-dp2jADRl.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +13 -5
- package/dist/index.js +633 -463
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-DNdf1fmL.cjs +2 -0
- package/dist/indexeddb-storage-DNdf1fmL.cjs.map +1 -0
- package/dist/{indexeddb-storage-0LtUALBg.js → indexeddb-storage-n1qkFBGA.js} +17 -17
- package/dist/indexeddb-storage-n1qkFBGA.js.map +1 -0
- package/dist/interactions-31eHGwEQ.cjs +2 -0
- package/dist/interactions-31eHGwEQ.cjs.map +1 -0
- package/dist/{interactions-BaCmoGLB.js → interactions-OU94MPXs.js} +22 -19
- package/dist/interactions-OU94MPXs.js.map +1 -0
- package/dist/journey-CE2EcwHW.cjs +2 -0
- package/dist/journey-CE2EcwHW.cjs.map +1 -0
- package/dist/journey-CeJ1QoT2.js +162 -0
- package/dist/journey-CeJ1QoT2.js.map +1 -0
- package/dist/library-request-C9uJFlbq.cjs +2 -0
- package/dist/library-request-C9uJFlbq.cjs.map +1 -0
- package/dist/library-request-DvhuplAB.js +14 -0
- package/dist/library-request-DvhuplAB.js.map +1 -0
- package/dist/long-frames-B8VdA_ny.cjs +2 -0
- package/dist/long-frames-B8VdA_ny.cjs.map +1 -0
- package/dist/long-frames-C_7OutLs.js +65 -0
- package/dist/long-frames-C_7OutLs.js.map +1 -0
- package/dist/models/batch.d.ts +1 -1
- package/dist/models/bus.d.ts +23 -4
- package/dist/models/config.d.ts +132 -11
- package/dist/models/log-record.d.ts +12 -6
- package/dist/network-BAV7ipyn.cjs +2 -0
- package/dist/network-BAV7ipyn.cjs.map +1 -0
- package/dist/network-D_lloS5t.js +174 -0
- package/dist/network-D_lloS5t.js.map +1 -0
- package/dist/patch-BX8KrPCT.cjs +2 -0
- package/dist/patch-BX8KrPCT.cjs.map +1 -0
- package/dist/patch-CCWfuEY7.js +9 -0
- package/dist/patch-CCWfuEY7.js.map +1 -0
- package/dist/{platform-ByQllE_W.cjs → platform-D4wu1eIF.cjs} +2 -2
- package/dist/platform-D4wu1eIF.cjs.map +1 -0
- package/dist/{platform-YuByH8A5.js → platform-IHBZGqUe.js} +9 -9
- package/dist/platform-IHBZGqUe.js.map +1 -0
- package/dist/remote-rules-Bt1XsdEQ.js +86 -0
- package/dist/remote-rules-Bt1XsdEQ.js.map +1 -0
- package/dist/remote-rules-kuDf5gbe.cjs +2 -0
- package/dist/remote-rules-kuDf5gbe.cjs.map +1 -0
- package/dist/sampling-BI15ds9D.cjs +2 -0
- package/dist/sampling-BI15ds9D.cjs.map +1 -0
- package/dist/sampling-o0VY1mqQ.js +63 -0
- package/dist/sampling-o0VY1mqQ.js.map +1 -0
- package/dist/sanitize-B9UheVKc.js +123 -0
- package/dist/sanitize-B9UheVKc.js.map +1 -0
- package/dist/sanitize-DSIP7amZ.cjs +2 -0
- package/dist/sanitize-DSIP7amZ.cjs.map +1 -0
- package/dist/{sender-BIob8eZz.js → sender-BnNj9bOX.js} +415 -272
- package/dist/sender-BnNj9bOX.js.map +1 -0
- package/dist/sender-D0OsyB1c.cjs +3 -0
- package/dist/sender-D0OsyB1c.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.ts +1 -1
- package/dist/storage/factory.d.ts +1 -1
- package/dist/storage/idb-driver.d.ts +1 -1
- package/dist/storage/local-storage.d.ts +3 -3
- package/dist/storage/memory-storage.d.ts +3 -3
- package/dist/storm-BTw0J6eE.js +10 -0
- package/dist/storm-BTw0J6eE.js.map +1 -0
- package/dist/storm-Y-yuBhvv.cjs +2 -0
- package/dist/storm-Y-yuBhvv.cjs.map +1 -0
- package/dist/transport/compression.d.ts +1 -1
- package/dist/transport/custom-transport.d.ts +20 -0
- package/dist/transport/errors.d.ts +2 -1
- package/dist/transport/exit-flush.d.ts +32 -13
- package/dist/transport/http-transport.d.ts +57 -25
- package/dist/transport/memory-transport.d.ts +30 -0
- package/dist/transport/retry-engine.d.ts +7 -7
- package/dist/transport/serializers/select.d.ts +12 -1
- package/dist/transport/status-transport.d.ts +74 -0
- package/dist/utils/console.d.ts +1 -1
- package/dist/utils/deadline.d.ts +7 -0
- package/dist/utils/error-like.d.ts +25 -0
- package/dist/utils/global-scope.d.ts +20 -0
- package/dist/utils/identity.d.ts +1 -1
- package/dist/utils/library-console.d.ts +11 -0
- package/dist/utils/library-request.d.ts +12 -0
- package/dist/utils/patch.d.ts +9 -0
- package/dist/utils/platform.d.ts +3 -3
- package/dist/utils/sequence.d.ts +0 -5
- package/dist/utils/timer.d.ts +1 -1
- package/dist/utils/tracing.d.ts +3 -3
- package/dist/utils/unref.d.ts +2 -2
- package/dist/{web-vitals-DHZ0yA_H.js → web-vitals-Bflr5jSA.js} +4 -2
- package/dist/web-vitals-Bflr5jSA.js.map +1 -0
- package/dist/web-vitals-DFuoTQbZ.cjs +2 -0
- package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -0
- package/package.json +2 -2
- package/dist/bus-DeZzr2bx.cjs +0 -2
- package/dist/bus-DeZzr2bx.cjs.map +0 -1
- package/dist/bus-DfAbg_pg.js.map +0 -1
- package/dist/constants-C8nZQBmQ.js +0 -86
- package/dist/constants-C8nZQBmQ.js.map +0 -1
- package/dist/constants-IBL_jd5R.cjs +0 -2
- package/dist/constants-IBL_jd5R.cjs.map +0 -1
- package/dist/errors-4MQyjZVj.js.map +0 -1
- package/dist/errors-CUdShXe7.cjs +0 -3
- package/dist/errors-CUdShXe7.cjs.map +0 -1
- package/dist/indexeddb-storage-0LtUALBg.js.map +0 -1
- package/dist/indexeddb-storage-CcEJlq2l.cjs +0 -2
- package/dist/indexeddb-storage-CcEJlq2l.cjs.map +0 -1
- package/dist/interactions-BMNPQ3WH.cjs +0 -2
- package/dist/interactions-BMNPQ3WH.cjs.map +0 -1
- package/dist/interactions-BaCmoGLB.js.map +0 -1
- package/dist/network-DBNvxCE3.cjs +0 -2
- package/dist/network-DBNvxCE3.cjs.map +0 -1
- package/dist/network-jQ2t8rU4.js +0 -111
- package/dist/network-jQ2t8rU4.js.map +0 -1
- package/dist/platform-ByQllE_W.cjs.map +0 -1
- package/dist/platform-YuByH8A5.js.map +0 -1
- package/dist/sampling-CbYySsZ1.js +0 -251
- package/dist/sampling-CbYySsZ1.js.map +0 -1
- package/dist/sampling-Cs50xsZl.cjs +0 -2
- package/dist/sampling-Cs50xsZl.cjs.map +0 -1
- package/dist/sender-BIob8eZz.js.map +0 -1
- package/dist/sender-iOjzcueM.cjs +0 -3
- package/dist/sender-iOjzcueM.cjs.map +0 -1
- package/dist/unref-16maCyKA.js +0 -8
- package/dist/unref-16maCyKA.js.map +0 -1
- package/dist/unref-CU9Nyz_9.cjs +0 -2
- package/dist/unref-CU9Nyz_9.cjs.map +0 -1
- package/dist/web-vitals-B2FYsEAU.cjs +0 -2
- package/dist/web-vitals-B2FYsEAU.cjs.map +0 -1
- package/dist/web-vitals-DHZ0yA_H.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-Br3b89Wg.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.tt).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.tt).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.nt,t).objectStore(e.nt)}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.nt,{keyPath:`id`}).createIndex(e.tt,e.tt)},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.an;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-DNdf1fmL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-DNdf1fmL.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 the library 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 // The library then loses the batch. No counter shows the loss.\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,C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A,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 {
|
|
1
|
+
import { an as e, nt as t, tt as n } from "./constants-DM94FjVX.js";
|
|
2
2
|
//#region src/storage/idb-driver.ts
|
|
3
3
|
function r(e) {
|
|
4
4
|
return e.error ?? /* @__PURE__ */ Error("The IndexedDB request failed.");
|
|
@@ -22,11 +22,11 @@ var a = class {
|
|
|
22
22
|
await i((await this.store("readwrite")).put(e));
|
|
23
23
|
}
|
|
24
24
|
async takeOldest(e) {
|
|
25
|
-
return i((await this.store("readonly")).index(
|
|
25
|
+
return i((await this.store("readonly")).index(n).getAll(null, e));
|
|
26
26
|
}
|
|
27
27
|
async takeBefore(e) {
|
|
28
|
-
let
|
|
29
|
-
return i(
|
|
28
|
+
let t = await this.store("readonly"), r = IDBKeyRange.upperBound(e, !0);
|
|
29
|
+
return i(t.index(n).getAll(r));
|
|
30
30
|
}
|
|
31
31
|
async delete(e) {
|
|
32
32
|
await i((await this.store("readwrite")).delete(e));
|
|
@@ -55,22 +55,22 @@ var a = class {
|
|
|
55
55
|
let e = this.connection;
|
|
56
56
|
e !== null && (this.connection = null, (await e).close());
|
|
57
57
|
}
|
|
58
|
-
async store(
|
|
59
|
-
return (await this.open()).transaction(
|
|
58
|
+
async store(e) {
|
|
59
|
+
return (await this.open()).transaction(t, e).objectStore(t);
|
|
60
60
|
}
|
|
61
61
|
open() {
|
|
62
|
-
let
|
|
63
|
-
if (
|
|
64
|
-
let i = new Promise((
|
|
62
|
+
let e = this.connection;
|
|
63
|
+
if (e !== null) return e;
|
|
64
|
+
let i = new Promise((e, i) => {
|
|
65
65
|
let a = indexedDB.open(this.name, 11), o = !1;
|
|
66
66
|
a.onupgradeneeded = () => {
|
|
67
|
-
let n = a.result;
|
|
68
|
-
n.objectStoreNames.contains("batches") || n.createObjectStore(e, { keyPath: "id" }).createIndex(t, t);
|
|
69
|
-
}, a.onsuccess = () => {
|
|
70
67
|
let e = a.result;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
68
|
+
e.objectStoreNames.contains("batches") || e.createObjectStore(t, { keyPath: "id" }).createIndex(n, n);
|
|
69
|
+
}, a.onsuccess = () => {
|
|
70
|
+
let t = a.result;
|
|
71
|
+
o ? t.close() : (t.onversionchange = () => {
|
|
72
|
+
t.close(), this.connection = null;
|
|
73
|
+
}, e(t));
|
|
74
74
|
}, a.onerror = () => {
|
|
75
75
|
i(r(a));
|
|
76
76
|
}, a.onblocked = () => {
|
|
@@ -91,7 +91,7 @@ var s = class {
|
|
|
91
91
|
limits;
|
|
92
92
|
diagnostics;
|
|
93
93
|
onGap;
|
|
94
|
-
name =
|
|
94
|
+
name = e;
|
|
95
95
|
db;
|
|
96
96
|
constructor(e, t, n, r) {
|
|
97
97
|
this.limits = t, this.diagnostics = n, this.onGap = r, this.db = new a(e);
|
|
@@ -168,4 +168,4 @@ var s = class {
|
|
|
168
168
|
//#endregion
|
|
169
169
|
export { s as IndexedDbStorage };
|
|
170
170
|
|
|
171
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
171
|
+
//# sourceMappingURL=indexeddb-storage-n1qkFBGA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-n1qkFBGA.js","names":["STORAGE_NAME_INDEXEDDB","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","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 the library 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 // The library then loses the batch. No counter shows the loss.\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,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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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./platform-D4wu1eIF.cjs"),t=require("./patch-BX8KrPCT.cjs");function n(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 r(){return history}var i=class{ctx;name=`interactions`;installed=!1;restores=[];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(){if(this.installed){this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate);for(let e of this.restores.splice(0))e()}}onClick=e=>{let t=e.target,r=n(t instanceof Element?t:null),i=t instanceof HTMLElement?t.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`)return;let e=r(),n=this.onNavigate,i=!0,a=t.t(e,`pushState`,e=>function(...t){e.apply(this,t),i&&queueMicrotask(n)}),o=t.t(e,`replaceState`,e=>function(...t){e.apply(this,t),i&&queueMicrotask(n)});this.restores.push(()=>{i=!1,a(),o()})}};exports.InteractionCapture=i;
|
|
2
|
+
//# sourceMappingURL=interactions-31eHGwEQ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions-31eHGwEQ.cjs","names":["stripUrlQuery","patch","require_platform","require_patch","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","selector","text","from","to","full","fromUrl","toUrl","onNavigate","active","restorePushState","args","original","restoreReplaceState"],"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 { patch } from \"../utils/patch\";\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 /** Restore functions of the history wrappers. */\n private readonly restores: (() => void)[] = [];\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 /**\n * Removes interaction listeners and restores each history method that still holds the\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\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 for (const restore of this.restores.splice(0)) {\n restore();\n }\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 /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */\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 you set fullUrls.\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\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. A read from the prototype skips a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.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 if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":"6EAeA,SAASI,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,CAgBpB,IAd7B,KAAgB,eAGhB,UAAoB,GAGpB,SAA4C,CAAC,EAG7C,QAAkB,GAKlB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,SAAa,MAG1C,KAAK,UAAY,GACjB,KAAK,QAAU,SAAS,KAEpB,KAAK,IAAI,OAAO,QAAQ,cAE1B,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAE1C,KAAK,IAAI,OAAO,QAAQ,aAC1B,KA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AK,WAEpBC,EAAS,GAEPC,EAAmBxB,EAAAA,EACvBa,EACA,YACC,GACC,SAAyB,GAAGY,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EAGrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEMK,EAAsB3B,EAAAA,EAC1Ba,EACA,eACC,GACC,SAAyB,GAAGY,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EACrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEA,KAAK,SAAS,SAAW,CACvB,EAAS,GACTE,EAAiB,EACjBG,EAAoB,CACtB,CAAC,CACH,CACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { r as e } from "./platform-
|
|
1
|
+
import { r as e } from "./platform-IHBZGqUe.js";
|
|
2
|
+
import { t } from "./patch-CCWfuEY7.js";
|
|
2
3
|
//#region src/capture/interactions.ts
|
|
3
|
-
function
|
|
4
|
+
function n(e) {
|
|
4
5
|
if (e === null) return "unknown";
|
|
5
6
|
let t = e.tagName.toLowerCase(), n = e.getAttribute("data-testid") ?? e.getAttribute("data-test-id");
|
|
6
7
|
if (n !== null) return `[data-testid="${n}"]`;
|
|
@@ -10,15 +11,14 @@ function t(e) {
|
|
|
10
11
|
let i = e.getAttribute("class")?.trim() ?? "";
|
|
11
12
|
return i === "" ? t : `${t}.${i.split(/\s+/).slice(0, 2).join(".")}`;
|
|
12
13
|
}
|
|
13
|
-
function
|
|
14
|
+
function r() {
|
|
14
15
|
return history;
|
|
15
16
|
}
|
|
16
|
-
var
|
|
17
|
+
var i = class {
|
|
17
18
|
ctx;
|
|
18
19
|
name = "interactions";
|
|
19
20
|
installed = !1;
|
|
20
|
-
|
|
21
|
-
originalReplaceState = null;
|
|
21
|
+
restores = [];
|
|
22
22
|
lastUrl = "";
|
|
23
23
|
constructor(e) {
|
|
24
24
|
this.ctx = e;
|
|
@@ -27,10 +27,13 @@ var r = class {
|
|
|
27
27
|
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)));
|
|
28
28
|
}
|
|
29
29
|
uninstall() {
|
|
30
|
-
|
|
30
|
+
if (this.installed) {
|
|
31
|
+
this.installed = !1, removeEventListener("click", this.onClick, !0), removeEventListener("popstate", this.onNavigate), removeEventListener("hashchange", this.onNavigate);
|
|
32
|
+
for (let e of this.restores.splice(0)) e();
|
|
33
|
+
}
|
|
31
34
|
}
|
|
32
35
|
onClick = (e) => {
|
|
33
|
-
let
|
|
36
|
+
let t = e.target, r = n(t instanceof Element ? t : null), i = t instanceof HTMLElement ? t.textContent.trim().slice(0, 50) : "";
|
|
34
37
|
this.ctx.tracing.rotate("interaction"), this.ctx.breadcrumbs.push({
|
|
35
38
|
t: Date.now(),
|
|
36
39
|
category: "click",
|
|
@@ -50,18 +53,18 @@ var r = class {
|
|
|
50
53
|
}), this.ctx.logger.logEvent("NAVIGATION", { "page.url.previous": i });
|
|
51
54
|
};
|
|
52
55
|
installHistory() {
|
|
53
|
-
if (typeof history > "u"
|
|
54
|
-
let e =
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
};
|
|
56
|
+
if (typeof history > "u") return;
|
|
57
|
+
let e = r(), n = this.onNavigate, i = !0, a = t(e, "pushState", (e) => function(...t) {
|
|
58
|
+
e.apply(this, t), i && queueMicrotask(n);
|
|
59
|
+
}), o = t(e, "replaceState", (e) => function(...t) {
|
|
60
|
+
e.apply(this, t), i && queueMicrotask(n);
|
|
61
|
+
});
|
|
62
|
+
this.restores.push(() => {
|
|
63
|
+
i = !1, a(), o();
|
|
64
|
+
});
|
|
62
65
|
}
|
|
63
66
|
};
|
|
64
67
|
//#endregion
|
|
65
|
-
export {
|
|
68
|
+
export { i as InteractionCapture };
|
|
66
69
|
|
|
67
|
-
//# sourceMappingURL=interactions-
|
|
70
|
+
//# sourceMappingURL=interactions-OU94MPXs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions-OU94MPXs.js","names":["stripUrlQuery","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","selector","text","from","to","full","fromUrl","toUrl","onNavigate","active","restorePushState","patch","args","original","restoreReplaceState"],"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 { patch } from \"../utils/patch\";\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 /** Restore functions of the history wrappers. */\n private readonly restores: (() => void)[] = [];\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 /**\n * Removes interaction listeners and restores each history method that still holds the\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\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 for (const restore of this.restores.splice(0)) {\n restore();\n }\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 /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */\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 you set fullUrls.\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\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. A read from the prototype skips a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.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 if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n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S,MAAM,MAAMD,CAAI,GACrBH,KACF,eAAeD,CAAU;EAE7B,CACJ;EAEA,KAAK,SAAS,WAAW;GAGvB,AAFA,IAAS,IACTE,EAAiB,GACjBI,EAAoB;EACtB,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-Br3b89Wg.cjs"),t=require("./deadline-Cbg2cbUw.cjs");var n={maxAgeMs:e.it,endOnOwnerClose:!1,urlParam:e.ot};function r(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function i(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function a(e){if(typeof e!=`object`||!e)return null;let t=r(e,`id`),n=r(e,`name`),a=i(e,`startedAt`);return t===void 0||n===void 0||a===void 0?null:{id:t,name:n,startedAt:a,parentId:r(e,`parentId`),ownerContextId:r(e,`ownerContextId`)??``}}function o(e){if(typeof e!=`object`||!e)return null;let t=r(e,`i`),n=r(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:i(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function s(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.v,`-`).replace(e.y,`_`).replace(e._,``)}var c=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,n,r,i,a=t.i){this.options=e,this.diagnostics=n,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`)){this.removeUrlToken();return}let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read the persisted journey.`,()=>this.stores.session().getItem(e.at));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,n={}){let r={id:n.id??t.s(this.diagnostics),name:e,startedAt:Date.now(),parentId:n.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(r),this.onLocalChange(r),r}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=s(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`The journey token is larger than the size limit. The library does not issue it.`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a seeded journey older than maxAgeMs.`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`The library adopted the journey "${r.name}".`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=a(this.diagnostics.guard(`storage.degraded`,`The library could not parse the persisted journey.`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a persisted journey older than maxAgeMs.`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`The library resumed the journey "${t.name}".`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`The library could not decode a seeded journey token.`,()=>{let n=t.replace(e.h,`+`).replace(e.g,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return o(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(n){if(this.journey=n,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`The library could not save the journey.`,()=>{n===null?this.stores.session().removeItem(e.at):this.stores.session().setItem(e.at,JSON.stringify(n))}),n===null)return;let r=Math.max(this.options.maxAgeMs-(Date.now()-n.startedAt),0),i=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`The journey "${n.name}" reached maxAgeMs. The library ended it.`,{journeyId:n.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},r);this.expiryTimer=i,t.r(i)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.at)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`The library could not read the journey token from the URL.`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}removeUrlToken(){this.diagnostics.guard(`platform.api_blocked`,`The library could not remove the journey token from the URL.`,()=>{let e=new URL(location.href);e.searchParams.delete(this.options.urlParam),history.replaceState(history.state,``,e.href)})}async readOpenFinToken(){let n=globalThis.fin?.me,r=n?.getOptions;if(r===void 0)return null;let i=(await this.diagnostics.guardAsync(`openfin.unavailable`,`The library could not read fin.me.getOptions().`,()=>t.n(r.call(n),e.xt)))?.customData?.[e.bt];return typeof i==`string`?i:null}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
|
|
2
|
+
//# sourceMappingURL=journey-CE2EcwHW.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journey-CE2EcwHW.cjs","names":["JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BROWSER_STORES","JOURNEY_STORAGE_KEY","newId","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","withDeadline","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","require_constants","require_deadline","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/** Structural interface for OpenFin window metadata. */\ninterface FinLike {\n /** Target OpenFin window or view. */\n me?: {\n /** Resolves initial window creation options including customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n };\n}\n\n/** Global environment extended with optional OpenFin APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: FinLike };\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from a bus message of another realm.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey. It replaces the active journey and tells connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(this.diagnostics),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar after the engine adopts it.\n * If not, a copy or a bookmark of the link starts the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state. A router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\n * @returns Promise that resolves to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = (globalThis as OpenFinGlobal).fin?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":"iFAsCA,IAAae,EAAkC,CAC7C,SAAUf,EAAAA,GACV,gBAAA,GACA,SAAUC,EAAAA,EACZ,EAkCA,SAASe,EAAW,EAAgB,EAAiC,CACnE,IAAMC,EAAiB,QAAQ,IAAIC,EAAQC,CAAG,EAC9C,OAAO,OAAOF,GAAU,UAAYA,IAAU,GAAKA,EAAQ,IAAA,E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,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,QAAQ,QAAQ,CAGjE,GAAS,IAClB,CAMA,gBAA+B,CAC7B,KAAK,YAAY,MACf,uBACA,mEACM,CACJ,IAAMgD,EAAM,IAAI,IAAI,SAAS,IAAI,EACjCA,EAAI,aAAa,OAAO,KAAK,QAAQ,QAAQ,EAE7C,QAAQ,aAAa,QAAQ,MAAO,GAAIA,EAAI,IAAI,CAClD,CACF,CACF,CAQA,MAAc,kBAA2C,CACvD,IAAMC,EAAM,WAA6B,KAAK,GACxCC,EAAaD,GAAI,WACvB,GAAIC,IAAe,IAAA,GACjB,OAAO,KAUT,IAAMb,GAAQ,MALQ,KAAK,YAAY,WACrC,sBACA,sDACMjC,EAAAA,EAAa8C,EAAW,KAAKD,CAAE,EAAG5C,EAAAA,EAA0B,CACpE,EAAA,EACuB,aAAaC,EAAAA,IACpC,OAAO,OAAO+B,GAAU,SAAWA,EAAQ,IAC7C,CACF"}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { _ as e, at as t, bt as n, g as r, h as i, it as a, ot as o, v as s, xt as c, y as l } from "./constants-DM94FjVX.js";
|
|
2
|
+
import { i as u, n as d, r as f, s as p } from "./deadline-B5DINjD5.js";
|
|
3
|
+
//#region src/core/journey.ts
|
|
4
|
+
var m = {
|
|
5
|
+
maxAgeMs: a,
|
|
6
|
+
endOnOwnerClose: !1,
|
|
7
|
+
urlParam: o
|
|
8
|
+
};
|
|
9
|
+
function h(e, t) {
|
|
10
|
+
let n = Reflect.get(e, t);
|
|
11
|
+
return typeof n == "string" && n !== "" ? n : void 0;
|
|
12
|
+
}
|
|
13
|
+
function g(e, t) {
|
|
14
|
+
let n = Reflect.get(e, t);
|
|
15
|
+
return typeof n == "number" && Number.isFinite(n) ? n : void 0;
|
|
16
|
+
}
|
|
17
|
+
function _(e) {
|
|
18
|
+
if (typeof e != "object" || !e) return null;
|
|
19
|
+
let t = h(e, "id"), n = h(e, "name"), r = g(e, "startedAt");
|
|
20
|
+
return t === void 0 || n === void 0 || r === void 0 ? null : {
|
|
21
|
+
id: t,
|
|
22
|
+
name: n,
|
|
23
|
+
startedAt: r,
|
|
24
|
+
parentId: h(e, "parentId"),
|
|
25
|
+
ownerContextId: h(e, "ownerContextId") ?? ""
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function v(e) {
|
|
29
|
+
if (typeof e != "object" || !e) return null;
|
|
30
|
+
let t = h(e, "i"), n = h(e, "n");
|
|
31
|
+
return t === void 0 || n === void 0 ? null : {
|
|
32
|
+
id: t,
|
|
33
|
+
name: n,
|
|
34
|
+
startedAt: g(e, "s") ?? Date.now(),
|
|
35
|
+
parentId: void 0,
|
|
36
|
+
ownerContextId: ""
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function y(t) {
|
|
40
|
+
let n = JSON.stringify({
|
|
41
|
+
i: t.id,
|
|
42
|
+
n: t.name.slice(0, 64),
|
|
43
|
+
s: t.startedAt
|
|
44
|
+
}), r = new TextEncoder().encode(n), i = "";
|
|
45
|
+
for (let e of r) i += String.fromCharCode(e);
|
|
46
|
+
return btoa(i).replace(s, "-").replace(l, "_").replace(e, "");
|
|
47
|
+
}
|
|
48
|
+
var b = class {
|
|
49
|
+
options;
|
|
50
|
+
diagnostics;
|
|
51
|
+
contextId;
|
|
52
|
+
onLocalChange;
|
|
53
|
+
stores;
|
|
54
|
+
journey = null;
|
|
55
|
+
expiryTimer = null;
|
|
56
|
+
constructor(e, t, n, r, i = u) {
|
|
57
|
+
this.options = e, this.diagnostics = t, this.contextId = n, this.onLocalChange = r, this.stores = i;
|
|
58
|
+
}
|
|
59
|
+
current() {
|
|
60
|
+
return this.journey;
|
|
61
|
+
}
|
|
62
|
+
async bootstrap() {
|
|
63
|
+
let e = this.readUrlToken();
|
|
64
|
+
if (e && this.adopt(e, "url")) {
|
|
65
|
+
this.removeUrlToken();
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
let n = this.diagnostics.guard("storage.unavailable", "The library could not read the persisted journey.", () => this.stores.session().getItem(t));
|
|
69
|
+
if (n && this.restore(n)) return;
|
|
70
|
+
let r = await this.readOpenFinToken();
|
|
71
|
+
r !== null && this.adopt(r, "openfin.customData");
|
|
72
|
+
}
|
|
73
|
+
start(e, t = {}) {
|
|
74
|
+
let n = {
|
|
75
|
+
id: t.id ?? p(this.diagnostics),
|
|
76
|
+
name: e,
|
|
77
|
+
startedAt: Date.now(),
|
|
78
|
+
parentId: t.parent ? this.journey?.id : void 0,
|
|
79
|
+
ownerContextId: this.contextId
|
|
80
|
+
};
|
|
81
|
+
return this.setJourney(n), this.onLocalChange(n), n;
|
|
82
|
+
}
|
|
83
|
+
end() {
|
|
84
|
+
this.journey !== null && (this.setJourney(null), this.onLocalChange(null));
|
|
85
|
+
}
|
|
86
|
+
applyRemote(e) {
|
|
87
|
+
let t = this.journey;
|
|
88
|
+
(e === null || t === null || e.id !== t.id) && this.setJourney(e);
|
|
89
|
+
}
|
|
90
|
+
getToken() {
|
|
91
|
+
let e = this.journey;
|
|
92
|
+
if (e === null) return;
|
|
93
|
+
let t = y(e);
|
|
94
|
+
if (t.length > 256) this.diagnostics.report("journey.token_too_large", "The journey token is larger than the size limit. The library does not issue it.", { length: t.length });
|
|
95
|
+
else return t;
|
|
96
|
+
}
|
|
97
|
+
adopt(e, t, n = !1) {
|
|
98
|
+
let r = this.decodeToken(e);
|
|
99
|
+
return r === null ? !1 : Date.now() - r.startedAt > this.options.maxAgeMs ? (this.diagnostics.report("journey.expired", "The library discarded a seeded journey older than maxAgeMs.", {
|
|
100
|
+
source: t,
|
|
101
|
+
name: r.name
|
|
102
|
+
}), !1) : (this.setJourney(r), this.diagnostics.report("journey.adopted", `The library adopted the journey "${r.name}".`, {
|
|
103
|
+
source: t,
|
|
104
|
+
journeyId: r.id
|
|
105
|
+
}), n && this.onLocalChange(r), !0);
|
|
106
|
+
}
|
|
107
|
+
ownerClosed(e) {
|
|
108
|
+
this.options.endOnOwnerClose && this.journey?.ownerContextId === e && this.end();
|
|
109
|
+
}
|
|
110
|
+
destroy() {
|
|
111
|
+
this.clearTimer();
|
|
112
|
+
}
|
|
113
|
+
restore(e) {
|
|
114
|
+
let t = _(this.diagnostics.guard("storage.degraded", "The library could not parse the persisted journey.", () => JSON.parse(e)));
|
|
115
|
+
return t === null ? !1 : Date.now() - t.startedAt > this.options.maxAgeMs ? (this.diagnostics.report("journey.expired", "The library discarded a persisted journey older than maxAgeMs.", { name: t.name }), this.clearStored(), !1) : (this.setJourney(t), this.diagnostics.report("journey.adopted", `The library resumed the journey "${t.name}".`, {
|
|
116
|
+
source: "sessionStorage",
|
|
117
|
+
journeyId: t.id
|
|
118
|
+
}), !0);
|
|
119
|
+
}
|
|
120
|
+
decodeToken(e) {
|
|
121
|
+
return this.diagnostics.guard("config.invalid", "The library could not decode a seeded journey token.", () => {
|
|
122
|
+
let t = e.replace(i, "+").replace(r, "/"), n = (4 - t.length % 4) % 4, a = "=".repeat(n), o = Uint8Array.from(atob(t + a), (e) => e.charCodeAt(0));
|
|
123
|
+
return v(JSON.parse(new TextDecoder().decode(o)));
|
|
124
|
+
}) ?? null;
|
|
125
|
+
}
|
|
126
|
+
setJourney(e) {
|
|
127
|
+
if (this.journey = e, this.clearTimer(), this.diagnostics.guard("storage.unavailable", "The library could not save the journey.", () => {
|
|
128
|
+
e === null ? this.stores.session().removeItem(t) : this.stores.session().setItem(t, JSON.stringify(e));
|
|
129
|
+
}), e === null) return;
|
|
130
|
+
let n = Math.max(this.options.maxAgeMs - (Date.now() - e.startedAt), 0), r = setTimeout(() => {
|
|
131
|
+
this.diagnostics.report("journey.expired", `The journey "${e.name}" reached maxAgeMs. The library ended it.`, { journeyId: e.id }), this.journey = null, this.expiryTimer = null, this.clearStored();
|
|
132
|
+
}, n);
|
|
133
|
+
this.expiryTimer = r, f(r);
|
|
134
|
+
}
|
|
135
|
+
clearStored() {
|
|
136
|
+
this.diagnostics.guard("storage.unavailable", "The library could not clear the persisted journey.", () => {
|
|
137
|
+
this.stores.session().removeItem(t);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
clearTimer() {
|
|
141
|
+
this.expiryTimer !== null && (clearTimeout(this.expiryTimer), this.expiryTimer = null);
|
|
142
|
+
}
|
|
143
|
+
readUrlToken() {
|
|
144
|
+
return this.diagnostics.guard("config.invalid", "The library could not read the journey token from the URL.", () => typeof location > "u" ? null : new URL(location.href).searchParams.get(this.options.urlParam)) ?? null;
|
|
145
|
+
}
|
|
146
|
+
removeUrlToken() {
|
|
147
|
+
this.diagnostics.guard("platform.api_blocked", "The library could not remove the journey token from the URL.", () => {
|
|
148
|
+
let e = new URL(location.href);
|
|
149
|
+
e.searchParams.delete(this.options.urlParam), history.replaceState(history.state, "", e.href);
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
async readOpenFinToken() {
|
|
153
|
+
let e = globalThis.fin?.me, t = e?.getOptions;
|
|
154
|
+
if (t === void 0) return null;
|
|
155
|
+
let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () => d(t.call(e), c)))?.customData?.[n];
|
|
156
|
+
return typeof r == "string" ? r : null;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
//#endregion
|
|
160
|
+
export { b as n, _ as r, m as t };
|
|
161
|
+
|
|
162
|
+
//# sourceMappingURL=journey-CeJ1QoT2.js.map
|