@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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"indexeddb-storage-0LtUALBg.js","names":["INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","STORAGE_NAME_INDEXEDDB","failureOf","request","promisify","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","resolve","reject","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch. It replaces a stored batch with the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads the oldest batches by createdAt. It does not remove them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Reads each batch with a createdAt value before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. A partial failure deletes none of\n * them.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that was delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** This method deletes all stored batches. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected. No reference to this connection remains.\n // An open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// This module stores batches in IndexedDB. It indexes them by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Returns the total record count of the batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n },\n );\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and to the gap handler.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":";;AAqBA,SAASG,EAAU,GAA4B;CAC7C,OAAOC,EAAQ,SAAS,gBAAI,MAAM,+BAA+B;AACnE;AASA,SAASC,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQD,EAAQ,MAAW;EAC7B,GACA,EAAQ,gBAAgB;GACtB,EAAOD,EAAUC,CAAO,CAAC;EAC3B;CACF,CAAC;AACH;AAGA,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MAAM,KAAK,GAAG,WAAWC,CAAO;EAG/C,OAFA,MAAM,KAAK,GAAG,WAAWD,EAAO,KAAK,MAAU5B,EAAM,EAAE,CAAC,GAEjD;GAAE,SAAS4B,EAAO;GAAQ,SAASZ,EAAaY,CAAM;EAAE;CACjE;AACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-IBL_jd5R.cjs");function t(e){return e.error??Error(`The IndexedDB request failed.`)}function n(e){return new Promise((n,r)=>{e.onsuccess=()=>{n(e.result)},e.onerror=()=>{r(t(e))}})}var r=class{name;connection=null;constructor(e){this.name=e}async put(e){await n((await this.store(`readwrite`)).put(e))}async takeOldest(t){return n((await this.store(`readonly`)).index(e.Q).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.Q).getAll(i))}async delete(e){await n((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>n(t.delete(e))))}async bumpAttempts(e,t){let r=await this.store(`readwrite`),i=await n(r.get(e));i!==void 0&&await n(r.put({...i,attempts:t}))}async count(){return n((await this.store(`readonly`)).count())}async clear(){await n((await this.store(`readwrite`)).clear())}async ready(){await this.open()}async close(){let e=this.connection;e!==null&&(this.connection=null,(await e).close())}async store(t){return(await this.open()).transaction(e.$,t).objectStore(e.$)}open(){let n=this.connection;if(n!==null)return n;let r=new Promise((n,r)=>{let i=indexedDB.open(this.name,11),a=!1;i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.$,{keyPath:`id`}).createIndex(e.Q,e.Q)},i.onsuccess=()=>{let e=i.result;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.Xt;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-CcEJlq2l.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"indexeddb-storage-CcEJlq2l.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","require_constants","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch. It replaces a stored batch with the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads the oldest batches by createdAt. It does not remove them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Reads each batch with a createdAt value before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. A partial failure deletes none of\n * them.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that was delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** This method deletes all stored batches. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected. No reference to this connection remains.\n // An open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// This module stores batches in IndexedDB. It indexes them by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Returns the total record count of the batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n },\n );\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and to the gap handler.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":"4CAqBA,SAASI,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CASA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxBC,EAAQF,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtBG,EAAOJ,EAAUC,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAaI,EAAb,KAAuB,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAAA,KAAAC,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAMJ,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIK,CAAK,CAAC,CAClC,CAOA,MAAM,WAAW,EAAoC,CAEnD,OAAOL,GAAsB,MADT,KAAK,MAAM,UAAU,EAAA,CACN,MAAMN,EAAAA,CAA0B,CAAC,CAAC,OAAO,KAAMY,CAAK,CAAC,CAC1F,CAOA,MAAM,WAAW,EAAqC,CACpD,IAAMC,EAAQ,MAAM,KAAK,MAAM,UAAU,EACnCC,EAAQ,YAAY,WAAWC,EAAQ,EAAI,EACjD,OAAOT,EAAsBO,EAAM,MAAMb,EAAAA,CAA0B,CAAC,CAAC,OAAOc,CAAK,CAAC,CACpF,CAMA,MAAM,OAAO,EAA2B,CAEtC,MAAMR,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,OAAOU,CAAE,CAAC,CAClC,CAOA,MAAM,WAAW,EAA8B,CAC7C,IAAMH,EAAQ,MAA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M7B,OAAO,MALa,KAAK,YAAY,WACnC,mBACA,sDACM,KAAK,GAAG,MAAM,CACtB,GACgB,CAClB,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,sDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,gDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAMA,UAAkB,EAA2B,CACvCA,EAAO,UAAY,IAIvB,KAAK,YAAY,OACf,kBACA,uBAAuB,OAAOA,EAAO,OAAO,EAAE,mBAAmB,OAAOA,EAAO,OAAO,EAAE,YACxF,CAAE,GAAGA,CAAO,CACd,EACA,KAAK,QAAQA,CAAM,EACrB,CASA,MAAc,YAAY,EAAuD,CAC/E,IAAME,EAAS,MAAM,KAAK,GAAG,WAAWC,CAAO,EAG/C,OAFA,MAAM,KAAK,GAAG,WAAWD,EAAO,IAAK,GAAU1B,EAAM,EAAE,CAAC,EAEjD,CAAE,QAAS0B,EAAO,OAAQ,QAASZ,EAAaY,CAAM,CAAE,CACjE,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./platform-ByQllE_W.cjs");function t(e){if(e===null)return`unknown`;let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function n(){return history}var r=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(n().pushState=this.originalPushState),this.originalReplaceState&&(n().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let n=e.target,r=t(n instanceof Element?n:null),i=n instanceof HTMLElement?n.textContent.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:r,data:i===``?void 0:{text:i}})};onNavigate=()=>{let t=this.lastUrl,n=location.href;if(t===n)return;this.lastUrl=n;let r=this.ctx.config.capture.fullUrls,i=r?t:e.r(t),a=r?n:e.r(n);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${i} -> ${a}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":i})};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=n(),t=e.pushState,r=e.replaceState;this.originalPushState=t,this.originalReplaceState=r;let i=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(i)},e.replaceState=function(...e){r.apply(this,e),queueMicrotask(i)}}};exports.InteractionCapture=r;
|
|
2
|
-
//# sourceMappingURL=interactions-BMNPQ3WH.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interactions-BMNPQ3WH.cjs","names":["stripUrlQuery","require_platform","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /** Removes interaction listeners and restores native history methods. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":"2CAcA,SAASE,EAAgB,EAAiC,CACxD,GAAIC,IAAY,KACd,MAAO,UAGT,IAAMC,EAAMD,EAAQ,QAAQ,YAAY,EAElCE,EAASF,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIE,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAIF,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAMG,EAAQH,EAAQ,aAAa,YAAY,EAC/C,GAAIG,IAAU,KACZ,MAAO,GAAGF,EAAI,eAAeE,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKp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AK,IAAI,EACZ,SAAU,QACV,QAASE,EACT,KAAMC,IAAS,GAAK,IAAA,GAAY,CAAE,MAAK,CACzC,CAAC,CACH,EAGA,eAA0C,CACxC,IAAMC,EAAO,KAAK,QACZC,EAAK,SAAS,KACpB,GAAID,IAASC,EACX,OAEF,KAAK,QAAUA,EAIf,IAAMC,EAAO,KAAK,IAAI,OAAO,QAAQ,SAC/BC,EAAUD,EAAOF,EAAOf,EAAAA,EAAce,CAAI,EAC1CI,EAAQF,EAAOD,EAAKhB,EAAAA,EAAcgB,CAAE,EAE1C,KAAK,IAAI,QAAQ,OAAO,YAAY,EACpC,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,aACV,QAAS,GAAGE,EAAQ,MAAMC,GAC5B,CAAC,EAID,KAAK,IAAI,OAAO,SAAS,aAAc,CAAE,oBAAqBD,CAAQ,CAAC,CACzE,EAGA,gBAA+B,CAC7B,GAAI,OAAO,QAAY,KAAe,KAAK,kBACzC,OAMF,IAAMP,EAASH,EAAe,EACxBY,EAAoBT,EAAO,UAC3BU,EAAuBV,EAAO,aACpC,KAAK,kBAAoBS,EACzB,KAAK,qBAAuBC,EAC5B,IAAMC,EAAa,KAAK,WAExB,EAAO,UAAY,SAAyB,GAAGC,EAAqB,CAClEH,EAAkB,MAAM,KAAMG,CAAI,EAGlC,eAAeD,CAAU,CAC3B,EAEA,EAAO,aAAe,SAAyB,GAAGC,EAAqB,CACrEF,EAAqB,MAAM,KAAME,CAAI,EACrC,eAAeD,CAAU,CAC3B,CACF,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interactions-BaCmoGLB.js","names":["stripUrlQuery","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /** Removes interaction listeners and restores native history methods. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":";;AAcA,SAASC,EAAgB,GAAiC;CACxD,IAAIC,MAAY,MACd,OAAO;CAGT,IAAMC,IAAMD,EAAQ,QAAQ,YAAY,GAElCE,IAASF,EAAQ,aAAa,aAAa,KAAKA,EAAQ,aAAa,cAAc;CACzF,IAAIE,MAAW,MACb,OAAO,iBAAiBA,EAAO;CAEjC,IAAIF,EAAQ,OAAO,IACjB,OAAO,IAAIA,EAAQ;CAGrB,IAAMG,IAAQH,EAAQ,aAAa,YA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AAM,GAAA,EAAuB,IAAI;EAK7F,AADA,KAAK,IAAI,QAAQ,OAAO,aAAa,GACrC,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAASE;GACT,MAAMC,MAAS,KAAK,KAAA,IAAY,EAAE,QAAK;EACzC,CAAC;CACH;CAGA,mBAA0C;EACxC,IAAMC,IAAO,KAAK,SACZC,IAAK,SAAS;EACpB,IAAID,MAASC,GACX;EAEF,KAAK,UAAUA;EAIf,IAAMC,IAAO,KAAK,IAAI,OAAO,QAAQ,UAC/BC,IAAUD,IAAOF,IAAOd,EAAcc,CAAI,GAC1CI,IAAQF,IAAOD,IAAKf,EAAce,CAAE;EAW1C,AATA,KAAK,IAAI,QAAQ,OAAO,YAAY,GACpC,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,GAAGE,EAAQ,MAAMC;EAC5B,CAAC,GAID,KAAK,IAAI,OAAO,SAAS,cAAc,EAAE,qBAAqBD,EAAQ,CAAC;CACzE;CAGA,iBAA+B;EAC7B,IAAI,OAAO,UAAY,OAAe,KAAK,mBACzC;EAMF,IAAMP,IAASH,EAAe,GACxBY,IAAoBT,EAAO,WAC3BU,IAAuBV,EAAO;EAEpC,AADA,KAAK,oBAAoBS,GACzB,KAAK,uBAAuBC;EAC5B,IAAMC,IAAa,KAAK;EASxB,AAPA,EAAO,YAAY,SAAyB,GAAGC,GAAqB;GAIlE,AAHAH,EAAkB,MAAM,MAAMG,CAAI,GAGlC,eAAeD,CAAU;EAC3B,GAEA,EAAO,eAAe,SAAyB,GAAGC,GAAqB;GAErE,AADAF,EAAqB,MAAM,MAAME,CAAI,GACrC,eAAeD,CAAU;EAC3B;CACF;AACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./platform-ByQllE_W.cjs");function t(e,t){return t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function n(){return XMLHttpRequest.prototype}var r=class{ctx;name=`network`;originalFetch=null;originalOpen=null;originalSend=null;constructor(e){this.ctx=e}install(){this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr()}uninstall(){this.originalFetch&&=(globalThis.fetch=this.originalFetch,null),this.originalOpen&&=(n().open=this.originalOpen,null),this.originalSend&&=(n().send=this.originalSend,null)}ignored(e){return t(e,this.ctx.config.capture.ignoreUrls)}installFetch(){if(typeof globalThis.fetch!=`function`||this.originalFetch)return;let e=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let n=this.ctx,r=e=>this.ignored(e),i=(e,t,n,r,i)=>{this.record(e,t,n,r,i)};globalThis.fetch=async function(a,o){let s=typeof a==`string`?a:a instanceof URL?a.href:a.url,c=(o?.method??(a instanceof Request?a.method:`GET`)).toUpperCase();if(r(s))return e(a,o);let l=a,u=o;if(t(s,n.config.capture.propagateTraceHeaderTo))try{let e=Object.entries(n.tracing.headers());if(a instanceof Request){let t=new Headers(a.headers);for(let[n,r]of e)t.set(n,r);l=new Request(a,{headers:t})}else{let t=new Headers(o?.headers);for(let[n,r]of e)t.set(n,r);u={...o,headers:t}}}catch(e){l=a,u=o,n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:s},e)}let d=performance.now();try{let t=await e(l,u);return i(c,s,t.status,performance.now()-d,void 0),t}catch(e){throw i(c,s,0,performance.now()-d,e),e}}}installXhr(){if(typeof XMLHttpRequest>`u`||this.originalOpen)return;let e=e=>this.ignored(e),t=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},r=n(),i=r.open,a=r.send;this.originalOpen=i,this.originalSend=a,r.open=function(e,t,...n){this.__uiobs={method:e.toUpperCase(),url:String(t),startedAt:0},i.apply(this,[e,t,...n])},r.send=function(...n){let r=this.__uiobs;r&&!e(r.url)&&(r.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{t(r.method,r.url,this.status,performance.now()-r.startedAt)})),a.apply(this,n)}}record(t,n,r,i,a){let o=this.ctx.config.capture.fullUrls?n:e.r(n);this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${t} ${o}.`,()=>{let e=Math.round(i);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${t} ${o} ${r===0?`failed`:String(r)}`,data:{durationMs:e}});let n={"http.request.method":t,"url.full":o,"http.response.status_code":r,"http.duration_ms":e};r===0?this.ctx.logger.error(`${t} ${o} failed`,a,n):r>=400?this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`,n):this.ctx.logger.debug(`${t} ${o}`,n)})}};exports.NetworkCapture=r;
|
|
2
|
-
//# sourceMappingURL=network-DBNvxCE3.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"network-DBNvxCE3.cjs","names":["stripUrlQuery","require_platform","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A body that was read\n // before causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless fullUrls is set.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n"],"mappings":"2CA8GA,SAAgBE,EAAW,EAAa,EAAwC,CAC9E,OAAOC,EAAS,KAAM,GACpB,OAAOC,GAAY,SAAWC,EAAI,SAASD,CAAO,EAAIA,EAAQ,KAAKC,CAAG,CACxE,CACF,CC5FA,SAASC,GAAyB,CAChC,OAAO,eAAe,SACxB,CAGA,IAAaC,EAAb,KAA+C,CAgBhB,IAd7B,KAAgB,UAGhB,cAAwC,KAGxC,aAAkD,KAGlD,aAAkD,KAKlD,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,IAAI,OAAO,QAAQ,OAC1B,KAAK,aAAa,EAEhB,KAAK,IAAI,OAAO,QAAQ,KAC1B,KAAK,WAAW,CAEpB,CAGA,WAAkB,CAChB,AAEE,KAAK,iBADL,WAAW,MAAQ,KAAK,cACH,MAEvB,AAEE,KAAK,gBADL,EAAW,CAAC,CAAC,KAAO,KAAK,aACL,MAEtB,AAEE,KAAK,gBADL,EAAW,CAAC,CAAC,KAAO,KAAK,aACL,KAExB,CAOA,QAAgB,EAAsB,CAGpC,OAAON,EAAWG,EAAK,KAAK,IAAI,OAAO,QAAQ,UAAU,CAC3D,CAGA,cAA6B,CAC3B,GAAI,OAAO,WAAW,OAAU,YAAc,KAAK,cACjD,OAGF,IAAMI,EAAW,WAAW,MAAM,KAAK,UAAU,EAC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xB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,GAAGF,EAAO,GAAGP,EAAI,GAAGQ,IAAW,EAAI,SAAW,OAAOA,CAAM,IACpE,KAAM,CAAE,WAAYoB,CAAQ,CAC9B,CAAC,EAED,IAAMC,EAAa,CACjB,sBAAuBtB,EACvB,WAAYP,EACZ,4BAA6BQ,EAC7B,mBAAoBoB,CACtB,EAEIpB,IAAW,EACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGP,EAAI,SAAUU,EAAOmB,CAAU,EAGhErB,GAAU,IACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGP,EAAI,YAAY,OAAOQ,CAAM,IAAKqB,CAAU,EAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGP,IAAO6B,CAAU,CACtD,CACF,CACF,CACF"}
|
package/dist/network-jQ2t8rU4.js
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
import { r as e } from "./platform-YuByH8A5.js";
|
|
2
|
-
//#region src/capture/types.ts
|
|
3
|
-
function t(e, t) {
|
|
4
|
-
return t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
|
|
5
|
-
}
|
|
6
|
-
//#endregion
|
|
7
|
-
//#region src/capture/network.ts
|
|
8
|
-
function n() {
|
|
9
|
-
return XMLHttpRequest.prototype;
|
|
10
|
-
}
|
|
11
|
-
var r = class {
|
|
12
|
-
ctx;
|
|
13
|
-
name = "network";
|
|
14
|
-
originalFetch = null;
|
|
15
|
-
originalOpen = null;
|
|
16
|
-
originalSend = null;
|
|
17
|
-
constructor(e) {
|
|
18
|
-
this.ctx = e;
|
|
19
|
-
}
|
|
20
|
-
install() {
|
|
21
|
-
this.ctx.config.capture.fetch && this.installFetch(), this.ctx.config.capture.xhr && this.installXhr();
|
|
22
|
-
}
|
|
23
|
-
uninstall() {
|
|
24
|
-
this.originalFetch &&= (globalThis.fetch = this.originalFetch, null), this.originalOpen &&= (n().open = this.originalOpen, null), this.originalSend &&= (n().send = this.originalSend, null);
|
|
25
|
-
}
|
|
26
|
-
ignored(e) {
|
|
27
|
-
return t(e, this.ctx.config.capture.ignoreUrls);
|
|
28
|
-
}
|
|
29
|
-
installFetch() {
|
|
30
|
-
if (typeof globalThis.fetch != "function" || this.originalFetch) return;
|
|
31
|
-
let e = globalThis.fetch.bind(globalThis);
|
|
32
|
-
this.originalFetch = globalThis.fetch;
|
|
33
|
-
let n = this.ctx, r = (e) => this.ignored(e), i = (e, t, n, r, i) => {
|
|
34
|
-
this.record(e, t, n, r, i);
|
|
35
|
-
};
|
|
36
|
-
globalThis.fetch = async function(a, o) {
|
|
37
|
-
let s = typeof a == "string" ? a : a instanceof URL ? a.href : a.url, c = (o?.method ?? (a instanceof Request ? a.method : "GET")).toUpperCase();
|
|
38
|
-
if (r(s)) return e(a, o);
|
|
39
|
-
let l = a, u = o;
|
|
40
|
-
if (t(s, n.config.capture.propagateTraceHeaderTo)) try {
|
|
41
|
-
let e = Object.entries(n.tracing.headers());
|
|
42
|
-
if (a instanceof Request) {
|
|
43
|
-
let t = new Headers(a.headers);
|
|
44
|
-
for (let [n, r] of e) t.set(n, r);
|
|
45
|
-
l = new Request(a, { headers: t });
|
|
46
|
-
} else {
|
|
47
|
-
let t = new Headers(o?.headers);
|
|
48
|
-
for (let [n, r] of e) t.set(n, r);
|
|
49
|
-
u = {
|
|
50
|
-
...o,
|
|
51
|
-
headers: t
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
} catch (e) {
|
|
55
|
-
l = a, u = o, n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: s }, e);
|
|
56
|
-
}
|
|
57
|
-
let d = performance.now();
|
|
58
|
-
try {
|
|
59
|
-
let t = await e(l, u);
|
|
60
|
-
return i(c, s, t.status, performance.now() - d, void 0), t;
|
|
61
|
-
} catch (e) {
|
|
62
|
-
throw i(c, s, 0, performance.now() - d, e), e;
|
|
63
|
-
}
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
installXhr() {
|
|
67
|
-
if (typeof XMLHttpRequest > "u" || this.originalOpen) return;
|
|
68
|
-
let e = (e) => this.ignored(e), t = (e, t, n, r) => {
|
|
69
|
-
this.record(e, t, n, r, void 0);
|
|
70
|
-
}, r = n(), i = r.open, a = r.send;
|
|
71
|
-
this.originalOpen = i, this.originalSend = a, r.open = function(e, t, ...n) {
|
|
72
|
-
this.__uiobs = {
|
|
73
|
-
method: e.toUpperCase(),
|
|
74
|
-
url: String(t),
|
|
75
|
-
startedAt: 0
|
|
76
|
-
}, i.apply(this, [
|
|
77
|
-
e,
|
|
78
|
-
t,
|
|
79
|
-
...n
|
|
80
|
-
]);
|
|
81
|
-
}, r.send = function(...n) {
|
|
82
|
-
let r = this.__uiobs;
|
|
83
|
-
r && !e(r.url) && (r.startedAt = performance.now(), this.addEventListener("loadend", () => {
|
|
84
|
-
t(r.method, r.url, this.status, performance.now() - r.startedAt);
|
|
85
|
-
})), a.apply(this, n);
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
record(t, n, r, i, a) {
|
|
89
|
-
let o = this.ctx.config.capture.fullUrls ? n : e(n);
|
|
90
|
-
this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${t} ${o}.`, () => {
|
|
91
|
-
let e = Math.round(i);
|
|
92
|
-
this.ctx.breadcrumbs.push({
|
|
93
|
-
t: Date.now(),
|
|
94
|
-
category: "http",
|
|
95
|
-
message: `${t} ${o} ${r === 0 ? "failed" : String(r)}`,
|
|
96
|
-
data: { durationMs: e }
|
|
97
|
-
});
|
|
98
|
-
let n = {
|
|
99
|
-
"http.request.method": t,
|
|
100
|
-
"url.full": o,
|
|
101
|
-
"http.response.status_code": r,
|
|
102
|
-
"http.duration_ms": e
|
|
103
|
-
};
|
|
104
|
-
r === 0 ? this.ctx.logger.error(`${t} ${o} failed`, a, n) : r >= 400 ? this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`, n) : this.ctx.logger.debug(`${t} ${o}`, n);
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
};
|
|
108
|
-
//#endregion
|
|
109
|
-
export { r as NetworkCapture };
|
|
110
|
-
|
|
111
|
-
//# sourceMappingURL=network-jQ2t8rU4.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"network-jQ2t8rU4.js","names":["stripUrlQuery","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A body that was read\n // before causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless fullUrls is set.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n"],"mappings":";;AA8GA,SAAgBC,EAAW,GAAa,GAAwC;CAC9E,OAAOC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWC,EAAI,SAASD,CAAO,IAAIA,EAAQ,KAAKC,CAAG,CACxE;AACF;;;AC5FA,SAASC,IAAyB;CAChC,OAAO,eAAe;AACxB;AAGA,IAAaC,IAAb,MAA+C;CAgBhB;CAd7B,OAAgB;CAGhB,gBAAwC;CAGxC,eAAkD;CAGlD,eAAkD;CAKlD,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EAId,AAHI,KAAK,IAAI,OAAO,QAAQ,SAC1B,KAAK,aAAa,GAEhB,KAAK,IAAI,OAAO,QAAQ,OAC1B,KAAK,WAAW;CAEpB;CAGA,YAAkB;EAShB,AARA,AAEE,KAAK,mBADL,WAAW,QAAQ,KAAK,eACH,OAEvB,AAEE,KAAK,kBADL,EAAW,CAAC,CAAC,OAAO,KAAK,cACL,OAEtB,AAEE,KAAK,kBADL,EAAW,CAAC,CAAC,OAAO,KAAK,cACL;CAExB;CAOA,QAAgB,GAAsB;EAGpC,OAAON,EAAWG,GAAK,KAAK,IAAI,OAAO,QAAQ,UAAU;CAC3D;CAGA,eAA6B;EAC3B,IAAI,OAAO,WAAW,SAAU,cAAc,KAAK,eACjD;EAGF,IAAMI,IAAW,WAAW,MAAM,KAAK,UAAU;EACjD,KAAK,gBAAgB,WAAW;EAEhC,IAAMD,IAAM,KAAK,KACXE,KAAW,MAAyB,KAAK,QAAQL,CAAG,GACpDM,KACJ,GACA,GACA,GACA,GACA,MACS;GACT,KAAK,OAAOC,GAAQP,GAAKQ,GAAQC,GAAYC,CAAK;EACpD;EAEA,WAAW,QAAQ,eAAiC,GAAO,GAAM;GAC/D,IAAMV,IAAM,O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oBAAoBoB;GACtB;GAEA,AAAIpB,MAAW,IACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGP,EAAI,UAAUU,GAAOmB,CAAU,IAGhErB,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGP,EAAI,YAAY,OAAOQ,CAAM,KAAKqB,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGP,KAAO6B,CAAU;EACtD,CACF;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"platform-ByQllE_W.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Evaluates whether globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Evaluates whether a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Determines whether the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"4CAiDA,IAAIM,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,EAAQC,EAAEC,GAIhB,OAHIF,IAAU,IAAA,IAGPC,aAAcD,CACvB,CAYA,SAAgBG,EAAe,EAA4C,CACzE,GAAIL,EACF,OAAOA,EAET,IAAMG,EAAI,WAEJG,EAAMH,EAAE,WAAqC,WAAa,GAC5DI,EAAyB,UACzBC,EACAC,EACAC,EAAW,GAETC,EAASR,EAAE,KAA6B,GAkC9C,OAhCIF,EAAcE,EAAG,0BAA0B,GAC7C,EAAW,iBACX,EAAW,IACFF,EAAcE,EAAG,yBAAyB,GACnD,EAAW,gBACX,EAAW,IACFF,EAAcE,EAAG,mBAAmB,GAC7C,EAAW,aACX,EAAW,IACFQ,IAAU,IAAA,GAOVR,EAAE,YAAc,IAAA,IAAaA,EAAE,QAAU,IAAA,GAClD,EAAW,QACFA,EAAE,UAAY,IAAA,IAAaS,EAAUN,CAAE,EAChD,EAAW,iBACF,OAAO,SAAa,KAAe,OAAO,QAAY,MAC/D,EAAW,SAXX,EAAWZ,EAAAA,GAAmB,KAAKY,CAAE,EAAI,UAAY,cACrDO,EAAY,MAAM,sBAAuB,kDAAqD,CAC5F,IAAMC,EAAWH,EAAM,SACvB,EAAcG,GAAU,KACxB,EAAcA,GAAU,IAC1B,CAAC,GASH,EAAS,CACP,WACA,cACA,cACA,UAAWR,EACX,WACA,mBAAoBS,EAAWF,CAAW,CAC5C,EACOb,CACT,CAOA,SAASY,EAAU,EAAqB,CAMtC,OALIjB,EAAAA,EAA2B,KAAKW,CAAE,EAC7B,IAGPV,EAAAA,GAAsB,KAAKU,CAAE,GAAMT,EAAAA,GAAqB,KAAKS,CAAE,GAAKR,EAAAA,GAAkB,KAAKQ,CAAE,IACjFA,EAAG,SAAA,aAAwB,GAAK,CAACA,EAAG,SAAA,SAAwB,CAC5E,CAOA,SAAgBS,EAAW,EAAmC,CAC5D,GAAI,OAAO,OAAW,IACpB,MAAO,GAET,GAAI,CACF,OAAO,OAAO,OAAS,OAAO,GAChC,MAAQ,CAGN,OADAF,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAOA,SAAgBG,EAAW,EAAkC,CAC3D,GAAI,CACF,OAAO,OAAO,SAAa,IAAc,SAAS,KAAO,EAC3D,MAAQ,CAGN,OADAH,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAQA,SAAgBI,EAAc,EAAqB,CACjD,IAAMC,EAAMC,EAAI,OAAO,MAAM,EAE7B,OAAOD,IAAQ,GAAKC,EAAMA,EAAI,MAAM,EAAGD,CAAG,CAC5C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"platform-YuByH8A5.js","names":["MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","IOS_DEVICE_UA_PATTERN","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Evaluates whether globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Evaluates whether a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Determines whether the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;AAiDA,IAAIK,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAYA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC,IAAW,IAETC,IAASR,EAAE,KAA6B;CAkC9C,OAhCIF,EAAcE,GAAG,0BAA0B,KAC7C,IAAW,kBACX,IAAW,MACFF,EAAcE,GAAG,yBAAyB,KACnD,IAAW,iBACX,IAAW,MACFF,EAAcE,GAAG,mBAAmB,KAC7C,IAAW,cACX,IAAW,MACFQ,MAAU,KAAA,IAOVR,EAAE,cAAc,KAAA,KAAaA,EAAE,UAAU,KAAA,IAClD,IAAW,UACFA,EAAE,YAAY,KAAA,KAAaS,EAAUN,CAAE,IAChD,IAAW,mBACF,OAAO,WAAa,OAAe,OAAO,UAAY,QAC/D,IAAW,WAXX,IAAWR,EAAmB,KAAKQ,CAAE,IAAI,YAAY,eACrDO,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