@utk09/ui-observability 0.4.1 → 0.5.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 +47 -0
- package/README.md +69 -31
- package/dist/bus-D3OO0OcL.js +378 -0
- package/dist/bus-D3OO0OcL.js.map +1 -0
- package/dist/bus-OdRJVUzr.cjs +2 -0
- package/dist/bus-OdRJVUzr.cjs.map +1 -0
- package/dist/capture/web-vitals.d.ts +4 -1
- package/dist/{constants-DVbpJ1tv.js → constants-B6kdsCzF.js} +9 -8
- package/dist/constants-B6kdsCzF.js.map +1 -0
- package/dist/constants-DZH04585.cjs +2 -0
- package/dist/constants-DZH04585.cjs.map +1 -0
- package/dist/constants.d.ts +3 -1
- package/dist/core/journey.d.ts +5 -2
- package/dist/core/logger.d.ts +22 -3
- package/dist/core/runtime.d.ts +100 -18
- package/dist/core/sender.d.ts +58 -0
- package/dist/errors-DPju_xSI.cjs +3 -0
- package/dist/errors-DPju_xSI.cjs.map +1 -0
- package/dist/errors-Dme9tz-6.js +76 -0
- package/dist/errors-Dme9tz-6.js.map +1 -0
- package/dist/index.cjs +1 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +452 -2223
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-lGdoHGHy.cjs +2 -0
- package/dist/indexeddb-storage-lGdoHGHy.cjs.map +1 -0
- package/dist/{indexeddb-storage-B6uqejZb.js → indexeddb-storage-nxs_rxGx.js} +4 -8
- package/dist/indexeddb-storage-nxs_rxGx.js.map +1 -0
- package/dist/interactions-C1romMpE.js +67 -0
- package/dist/interactions-C1romMpE.js.map +1 -0
- package/dist/interactions-DP0-rIPJ.cjs +2 -0
- package/dist/interactions-DP0-rIPJ.cjs.map +1 -0
- package/dist/models/config.d.ts +29 -11
- package/dist/network-DDVIJSHd.cjs +2 -0
- package/dist/network-DDVIJSHd.cjs.map +1 -0
- package/dist/network-au-Tqt1n.js +111 -0
- package/dist/network-au-Tqt1n.js.map +1 -0
- package/dist/platform-DMYo3AX3.js +48 -0
- package/dist/platform-DMYo3AX3.js.map +1 -0
- package/dist/platform-g99Kn755.cjs +2 -0
- package/dist/platform-g99Kn755.cjs.map +1 -0
- package/dist/sampling-ByI5H44E.js +248 -0
- package/dist/sampling-ByI5H44E.js.map +1 -0
- package/dist/sampling-Dui-Fp3u.cjs +2 -0
- package/dist/sampling-Dui-Fp3u.cjs.map +1 -0
- package/dist/sender-R7lOpyNc.js +907 -0
- package/dist/sender-R7lOpyNc.js.map +1 -0
- package/dist/sender-vLcbQhiB.cjs +3 -0
- package/dist/sender-vLcbQhiB.cjs.map +1 -0
- package/dist/transport/http-transport.d.ts +2 -0
- package/dist/transport/serializers/select.d.ts +8 -0
- package/dist/unref-16maCyKA.js +8 -0
- package/dist/unref-16maCyKA.js.map +1 -0
- package/dist/unref-CU9Nyz_9.cjs +2 -0
- package/dist/unref-CU9Nyz_9.cjs.map +1 -0
- package/dist/utils/console.d.ts +11 -3
- package/dist/utils/identity.d.ts +47 -3
- package/dist/utils/tracing.d.ts +6 -5
- package/dist/web-vitals-DM2nvcMJ.cjs +2 -0
- package/dist/web-vitals-DM2nvcMJ.cjs.map +1 -0
- package/dist/web-vitals-DwWdLBq6.js +51 -0
- package/dist/web-vitals-DwWdLBq6.js.map +1 -0
- package/package.json +21 -11
- package/dist/constants-DVbpJ1tv.js.map +0 -1
- package/dist/constants-tQpoTzkY.cjs +0 -2
- package/dist/constants-tQpoTzkY.cjs.map +0 -1
- package/dist/indexeddb-storage-B6uqejZb.js.map +0 -1
- package/dist/indexeddb-storage-CgT1GLYj.cjs +0 -2
- package/dist/indexeddb-storage-CgT1GLYj.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-DZH04585.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 is blocking the IndexedDB upgrade`))}});return this.connection=r.catch(e=>{throw this.connection=null,e}),this.connection}};function i(e){return e.reduce((e,t)=>e+t.records.length,0)}var a=class{limits;diagnostics;onGap;name=e.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, evicting the oldest`);let t=await this.diagnostics.guardAsync(`storage.degraded`,`evicting after a full disk`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));t&&this.reportGap({...t,reason:`quota`}),await this.diagnostics.guardAsync(`storage.degraded`,`writing a batch after evicting`,async()=>(await this.db.put(e),!0))!==!0&&this.reportGap({batches:1,records:e.records.length,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`could not persist a batch`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`reading stored batches`,()=>this.db.takeOldest(e))??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`deleting a batch`,()=>this.db.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`updating attempts`,()=>this.db.bumpAttempts(e,t))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`pruning`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.takeBefore(t);n.length>0&&(await this.db.deleteMany(n.map(e=>e.id)),e.batches+=n.length,e.records+=i(n));let r=await this.db.count();if(r>this.limits.maxBatches){e.reason=`over_capacity`;let t=await this.evictOldest(r-this.limits.maxBatches);e.batches+=t.batches,e.records+=t.records}}),this.reportGap(e),e}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting`,()=>this.db.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`clearing`,()=>this.db.clear())}async close(){await this.diagnostics.guardAsync(`storage.degraded`,`closing the database`,()=>this.db.close())}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(e.batches)} stored batches (${String(e.records)} records)`,{...e}),this.onGap?.(e))}async evictOldest(e){let t=await this.db.takeOldest(e);return await this.db.deleteMany(t.map(e=>e.id)),{batches:t.length,records:i(t)}}};exports.IndexedDbStorage=a;
|
|
2
|
+
//# sourceMappingURL=indexeddb-storage-lGdoHGHy.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-lGdoHGHy.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// Raw IndexedDB mechanics for the batch store: opening, request promises, and the\n// createdAt-ordered reads. Everything above this file works in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Reads the failure off a request that has errored. A host whose request reports\n * no error gets a stand-in: rejecting with null makes the instanceof Error test\n * in save() false, and a full disk is then reported as an ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"the IndexedDB request failed\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with its error. The\n * request is read as IDBRequest<any>, so every caller names the type it expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** One IndexedDB database holding undelivered batches keyed by id. */\nexport class IdbDriver {\n /** Open in progress or completed, reused so one database is opened per driver. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any batch already stored under the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Reads every batch created strictly before a cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction, so a partial failure leaves none\n * of them deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Rewrites the attempt count of a stored batch. An id that is not stored is\n * left alone: a batch already delivered and deleted must not be resurrected.\n * One transaction for the get and the put. Across two transactions, a prune in\n * another window deletes the batch between them, and the put restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here, where the factory can select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** Closes the connection, if one was ever opened. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a fresh transaction. A transaction is only valid\n * until control returns to the event loop, so every call takes a new one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time and gives the same connection to each later call.\n * A failed open is not kept: the next call opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database written by an earlier release already carries the store.\n // Creating it again throws ConstraintError and the upgrade aborts.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler rejected already. No reference to this connection\n // remains, and an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not\n // settle until that window closes, and each storage call waits with it.\n abandoned = true;\n reject(new Error(\"another connection is blocking the IndexedDB upgrade\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB with time-ordered indexing.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** IndexedDB mechanics for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. Not guarded: the factory needs the rejection to select the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction exists to make room for this batch. Without a second\n // attempt save() resolves while the batch is gone and uncounted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"writing a batch after evicting\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () => this.db.clear());\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"closing the database\", () =>\n this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":"4CAmBA,SAASI,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,8BAA8B,CAClE,CAQA,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,KA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IAAK,GAAU1B,EAAM,EAAE,CAAC,EAEjD,CAAE,QAAS0B,EAAO,OAAQ,QAASZ,EAAaY,CAAM,CAAE,CACjE,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as e, Q as t,
|
|
1
|
+
import { $ as e, Q as t, Xt as n } from "./constants-B6kdsCzF.js";
|
|
2
2
|
//#region src/storage/idb-driver.ts
|
|
3
3
|
function r(e) {
|
|
4
4
|
return e.error ?? /* @__PURE__ */ Error("the IndexedDB request failed");
|
|
@@ -68,13 +68,9 @@ var a = class {
|
|
|
68
68
|
n.objectStoreNames.contains("batches") || n.createObjectStore(e, { keyPath: "id" }).createIndex(t, t);
|
|
69
69
|
}, a.onsuccess = () => {
|
|
70
70
|
let e = a.result;
|
|
71
|
-
|
|
72
|
-
e.close();
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
e.onversionchange = () => {
|
|
71
|
+
o ? e.close() : (e.onversionchange = () => {
|
|
76
72
|
e.close(), this.connection = null;
|
|
77
|
-
}, n(e);
|
|
73
|
+
}, n(e));
|
|
78
74
|
}, a.onerror = () => {
|
|
79
75
|
i(r(a));
|
|
80
76
|
}, a.onblocked = () => {
|
|
@@ -172,4 +168,4 @@ var s = class {
|
|
|
172
168
|
//#endregion
|
|
173
169
|
export { s as IndexedDbStorage };
|
|
174
170
|
|
|
175
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
171
|
+
//# sourceMappingURL=indexeddb-storage-nxs_rxGx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-nxs_rxGx.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// Raw IndexedDB mechanics for the batch store: opening, request promises, and the\n// createdAt-ordered reads. Everything above this file works in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Reads the failure off a request that has errored. A host whose request reports\n * no error gets a stand-in: rejecting with null makes the instanceof Error test\n * in save() false, and a full disk is then reported as an ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"the IndexedDB request failed\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with its error. The\n * request is read as IDBRequest<any>, so every caller names the type it expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** One IndexedDB database holding undelivered batches keyed by id. */\nexport class IdbDriver {\n /** Open in progress or completed, reused so one database is opened per driver. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any batch already stored under the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Reads every batch created strictly before a cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction, so a partial failure leaves none\n * of them deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Rewrites the attempt count of a stored batch. An id that is not stored is\n * left alone: a batch already delivered and deleted must not be resurrected.\n * One transaction for the get and the put. Across two transactions, a prune in\n * another window deletes the batch between them, and the put restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here, where the factory can select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** Closes the connection, if one was ever opened. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a fresh transaction. A transaction is only valid\n * until control returns to the event loop, so every call takes a new one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time and gives the same connection to each later call.\n * A failed open is not kept: the next call opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database written by an earlier release already carries the store.\n // Creating it again throws ConstraintError and the upgrade aborts.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler rejected already. No reference to this connection\n // remains, and an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not\n // settle until that window closes, and each storage call waits with it.\n abandoned = true;\n reject(new Error(\"another connection is blocking the IndexedDB upgrade\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Persistent storage adapter backed by IndexedDB with time-ordered indexing.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** Persistent StorageAdapter implementation backed by IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** IndexedDB mechanics for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. Not guarded: the factory needs the rejection to select the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Persists a batch to IndexedDB and triggers storage pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\"storage.quota_exceeded\", \"IndexedDB is full, evicting the oldest\");\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"evicting after a full disk\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction exists to make room for this batch. Without a second\n // attempt save() resolves while the batch is gone and uncounted.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"writing a batch after evicting\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"could not persist a batch\",\n { batchId: batch.id },\n error,\n );\n }\n }\n\n /**\n * Reads up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"reading stored batches\",\n () => this.db.takeOldest(limit),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes a batch from IndexedDB by ID.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"deleting a batch\", () =>\n this.db.delete(id),\n );\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"updating attempts\", () =>\n this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\"storage.degraded\", \"pruning\", async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n });\n\n this.reportGap(result);\n return result;\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\"storage.degraded\", \"counting\", () =>\n this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"clearing\", () => this.db.clear());\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\"storage.degraded\", \"closing the database\", () =>\n this.db.close(),\n );\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes a specified count of the oldest stored batches. Unguarded: both callers\n * guard it, and swallowing the failure here reports an eviction that did not\n * happen.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":";;AAmBA,SAASG,EAAU,GAA4B;CAC7C,OAAOC,EAAQ,SAAS,gBAAI,MAAM,8BAA8B;AAClE;AAQA,SAASC,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQD,EAAQ,MAAW;EAC7B,GACA,EAAQ,gBAAgB;GACtB,EAAOD,EAAUC,CAAO,CAAC;EAC3B;CACF,CAAC;AACH;AAGA,IAAaE,IAAb,MAAuB;CAOQ;CAL7B,aAAkD;CAKlD,YAAY,GAA+B;EAAd,KAAA,OAAAC;CAAe;CAM5C,MAAM,IAAI,GAAgC;EAExC,MAAMF,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIG,CAAK,CAAC;CAClC;CA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M;EAAE;CACjE;AACF"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { r as e } from "./platform-DMYo3AX3.js";
|
|
2
|
+
//#region src/capture/interactions.ts
|
|
3
|
+
function t(e) {
|
|
4
|
+
if (e === null) return "unknown";
|
|
5
|
+
let t = e.tagName.toLowerCase(), n = e.getAttribute("data-testid") ?? e.getAttribute("data-test-id");
|
|
6
|
+
if (n !== null) return `[data-testid="${n}"]`;
|
|
7
|
+
if (e.id !== "") return `#${e.id}`;
|
|
8
|
+
let r = e.getAttribute("aria-label");
|
|
9
|
+
if (r !== null) return `${t}[aria-label="${r.slice(0, 40)}"]`;
|
|
10
|
+
let i = e.getAttribute("class")?.trim() ?? "";
|
|
11
|
+
return i === "" ? t : `${t}.${i.split(/\s+/).slice(0, 2).join(".")}`;
|
|
12
|
+
}
|
|
13
|
+
function n() {
|
|
14
|
+
return history;
|
|
15
|
+
}
|
|
16
|
+
var r = class {
|
|
17
|
+
ctx;
|
|
18
|
+
name = "interactions";
|
|
19
|
+
installed = !1;
|
|
20
|
+
originalPushState = null;
|
|
21
|
+
originalReplaceState = null;
|
|
22
|
+
lastUrl = "";
|
|
23
|
+
constructor(e) {
|
|
24
|
+
this.ctx = e;
|
|
25
|
+
}
|
|
26
|
+
install() {
|
|
27
|
+
this.installed || typeof document > "u" || (this.installed = !0, this.lastUrl = location.href, this.ctx.config.capture.interactions && addEventListener("click", this.onClick, !0), this.ctx.config.capture.navigation && (this.installHistory(), addEventListener("popstate", this.onNavigate), addEventListener("hashchange", this.onNavigate)));
|
|
28
|
+
}
|
|
29
|
+
uninstall() {
|
|
30
|
+
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);
|
|
31
|
+
}
|
|
32
|
+
onClick = (e) => {
|
|
33
|
+
let n = e.target, r = t(n instanceof Element ? n : null), i = n instanceof HTMLElement ? n.textContent.trim().slice(0, 50) : "";
|
|
34
|
+
this.ctx.tracing.rotate("interaction"), this.ctx.breadcrumbs.push({
|
|
35
|
+
t: Date.now(),
|
|
36
|
+
category: "click",
|
|
37
|
+
message: r,
|
|
38
|
+
data: i === "" ? void 0 : { text: i }
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
onNavigate = () => {
|
|
42
|
+
let t = this.lastUrl, n = location.href;
|
|
43
|
+
if (t === n) return;
|
|
44
|
+
this.lastUrl = n;
|
|
45
|
+
let r = this.ctx.config.capture.fullUrls, i = r ? t : e(t), a = r ? n : e(n);
|
|
46
|
+
this.ctx.tracing.rotate("navigation"), this.ctx.breadcrumbs.push({
|
|
47
|
+
t: Date.now(),
|
|
48
|
+
category: "navigation",
|
|
49
|
+
message: `${i} -> ${a}`
|
|
50
|
+
}), this.ctx.logger.logEvent("NAVIGATION", { "page.url.previous": i });
|
|
51
|
+
};
|
|
52
|
+
installHistory() {
|
|
53
|
+
if (typeof history > "u" || this.originalPushState) return;
|
|
54
|
+
let e = n(), t = e.pushState, r = e.replaceState;
|
|
55
|
+
this.originalPushState = t, this.originalReplaceState = r;
|
|
56
|
+
let i = this.onNavigate;
|
|
57
|
+
e.pushState = function(...e) {
|
|
58
|
+
t.apply(this, e), queueMicrotask(i);
|
|
59
|
+
}, e.replaceState = function(...e) {
|
|
60
|
+
r.apply(this, e), queueMicrotask(i);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
//#endregion
|
|
65
|
+
export { r as InteractionCapture };
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=interactions-C1romMpE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions-C1romMpE.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 concise CSS selector for an element, prioritizing test IDs, IDs, aria-labels, and classes.\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 through getAttribute: an SVG element's `className` is an\n // SVGAnimatedString at runtime, and slicing it would throw.\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 this module replaces, typed as properties rather than\n * methods so the originals can be held unbound. Holding a bound copy instead\n * makes uninstall restore a different function than it replaced, and repeated\n * install cycles wrap a 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 * The History object, typed for holding 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 // Uses capture phase to observe clicks before event propagation is stopped.\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 // textContent, not innerText: layout defines innerText, so a read of it\n // causes style and layout work 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, so everything it causes shares one\n // trace id. Without the rotation a click and its five API calls cannot be\n // pulled back as one query.\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 // Compared on the whole URL above, recorded without it: a move that only\n // changes the query is still a navigation, but the query is not recorded.\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 // Only the previous URL is carried: the record builder stamps the current\n // one as `page.url`. Sending the new URL as `url.full` would make a\n // navigation look like an HTTP request to that address.\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 // Held unbound and called through apply. Reading History.prototype instead\n // skips whatever a router already installed on the instance, and leaves\n // uninstall writing a permanent own property where there was none.\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 // Queued: location.href is only updated once the call returns, so reading\n // it synchronously reports the previous URL as the new one.\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":";;AAaA,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,OA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@@
|
|
|
1
|
+
const e=require("./platform-g99Kn755.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-DP0-rIPJ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions-DP0-rIPJ.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 concise CSS selector for an element, prioritizing test IDs, IDs, aria-labels, and classes.\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 through getAttribute: an SVG element's `className` is an\n // SVGAnimatedString at runtime, and slicing it would throw.\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 this module replaces, typed as properties rather than\n * methods so the originals can be held unbound. Holding a bound copy instead\n * makes uninstall restore a different function than it replaced, and repeated\n * install cycles wrap a 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 * The History object, typed for holding 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 // Uses capture phase to observe clicks before event propagation is stopped.\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 // textContent, not innerText: layout defines innerText, so a read of it\n // causes style and layout work 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, so everything it causes shares one\n // trace id. Without the rotation a click and its five API calls cannot be\n // pulled back as one query.\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 // Compared on the whole URL above, recorded without it: a move that only\n // changes the query is still a navigation, but the query is not recorded.\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 // Only the previous URL is carried: the record builder stamps the current\n // one as `page.url`. Sending the new URL as `url.full` would make a\n // navigation look like an HTTP request to that address.\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 // Held unbound and called through apply. Reading History.prototype instead\n // skips whatever a router already installed on the instance, and leaves\n // uninstall writing a permanent own property where there was none.\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 // Queued: location.href is only updated once the call returns, so reading\n // it synchronously reports the previous URL as the new one.\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":"2CAaA,SAASE,EAAgB,EAAiC,CACxD,GAAIC,IAAY,KACd,MAAO,UAGT,IAAMC,EAAMD,EAAQ,QAAQ,YAAY,EAElCE,EAASF,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIE,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAIF,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAMG,EAAQH,EAAQ,aAAa,YAAY,EAC/C,GAAIG,IAAU,KACZ,MAAO,GAAGF,EAAI,eAAeE,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKpE,IAAMC,EAAiBJ,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,GAAK,GAMhE,OALII,IAAmB,GACdH,EAIF,GAAGA,EAAI,GADEG,EAAe,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAC/D,GACnB,CAiBA,SAASC,GAAiC,CACxC,OAAO,OACT,CAGA,IAAaC,EAAb,KAAmD,CAmBpB,IAjB7B,KAAgB,eAGhB,UAAoB,GAGpB,kBAAgE,KAGhE,qBAAsE,KAGtE,QAAkB,GAKlB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,SAAa,MAG1C,KAAK,UAAY,GACjB,KAAK,QAAU,SAAS,KAEpB,KAAK,IAAI,OAAO,QAAQ,cAE1B,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAE1C,KAAK,IAAI,OAAO,QAAQ,aAC1B,KAAK,eAAe,EACpB,iBAAiB,WAAY,KAAK,UAAU,EAC5C,iBAAiB,aAAc,KAAK,UAAU,GAElD,CAGA,WAAkB,CACX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AAO,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"}
|
package/dist/models/config.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { LogLevel, LogRecord } from "./log-record";
|
|
|
3
3
|
import type { LogSerializer } from "./serializer";
|
|
4
4
|
/** Backing store for undelivered records. "auto" picks the best one the host supports. */
|
|
5
5
|
export type StorageStrategy = "auto" | "indexeddb" | "localstorage" | "memory" | "none";
|
|
6
|
+
/** Selects where the library keeps session, tab and journey ids. "storage" uses browser storage. "memory" writes nothing. */
|
|
7
|
+
export type IdentityStrategy = "storage" | "memory";
|
|
6
8
|
/** What this context does with its records: `sender` delivers its own, `forwarder` hands them to another context, `auto` decides, `off` does neither. */
|
|
7
9
|
export type BusMode = "auto" | "sender" | "forwarder" | "off";
|
|
8
10
|
/** Structural type for the `web-vitals` package's metric shape, so this library has no hard dependency on the package. */
|
|
@@ -177,7 +179,7 @@ export interface CaptureOptions {
|
|
|
177
179
|
*/
|
|
178
180
|
navigation: boolean;
|
|
179
181
|
/**
|
|
180
|
-
* Report web vitals as metrics. Requires
|
|
182
|
+
* Report web vitals as metrics. Requires `webVitalsLoader`.
|
|
181
183
|
* @default false
|
|
182
184
|
*/
|
|
183
185
|
webVitals: boolean;
|
|
@@ -203,12 +205,18 @@ export interface CaptureOptions {
|
|
|
203
205
|
*/
|
|
204
206
|
webVitalsLoader?: () => Promise<WebVitalsModule>;
|
|
205
207
|
}
|
|
208
|
+
/** Serializer option after resolution. A name stays a name. The transport selects the implementation. */
|
|
209
|
+
export type SerializerChoice = "otlp" | "ecs" | LogSerializer;
|
|
206
210
|
/** Console mirroring. `false` is off, `true` mirrors from DEBUG, a level mirrors from that level up. */
|
|
207
211
|
export type ConsoleOption = boolean | LogLevel;
|
|
208
|
-
/** Options passed to `configure()`.
|
|
212
|
+
/** Options passed to `configure()`. */
|
|
209
213
|
export interface ObservabilityConfig {
|
|
210
|
-
/**
|
|
211
|
-
|
|
214
|
+
/**
|
|
215
|
+
* Ingest endpoint URL. Set `null` for console-only mode.
|
|
216
|
+
* In console-only mode, the library sends nothing. It writes records to the console if `console` is set.
|
|
217
|
+
* If the key is missing or `""`, the library reports `config.invalid`.
|
|
218
|
+
*/
|
|
219
|
+
endpoint?: string | null;
|
|
212
220
|
/**
|
|
213
221
|
* Reported as `service.name`.
|
|
214
222
|
* @default ""
|
|
@@ -243,7 +251,7 @@ export interface ObservabilityConfig {
|
|
|
243
251
|
* Wire format: a name, or a custom implementation.
|
|
244
252
|
* @default "otlp"
|
|
245
253
|
*/
|
|
246
|
-
serializer?:
|
|
254
|
+
serializer?: SerializerChoice;
|
|
247
255
|
/**
|
|
248
256
|
* Passed to `fetch`. Set "include" for an ingest endpoint that authenticates with cookies.
|
|
249
257
|
* @default "omit"
|
|
@@ -256,6 +264,14 @@ export interface ObservabilityConfig {
|
|
|
256
264
|
* @default "auto"
|
|
257
265
|
*/
|
|
258
266
|
storage?: StorageStrategy;
|
|
267
|
+
/**
|
|
268
|
+
* Selects where the library keeps session, tab and journey ids.
|
|
269
|
+
* Set "memory" to write no key to localStorage or sessionStorage.
|
|
270
|
+
* With "memory", each page load starts a new session.
|
|
271
|
+
* You cannot change this value after startup.
|
|
272
|
+
* @default "storage"
|
|
273
|
+
*/
|
|
274
|
+
identity?: IdentityStrategy;
|
|
259
275
|
/**
|
|
260
276
|
* Sampling policy.
|
|
261
277
|
* @see {@link SamplingOptions}
|
|
@@ -277,8 +293,8 @@ export interface ObservabilityConfig {
|
|
|
277
293
|
*/
|
|
278
294
|
console?: ConsoleOption;
|
|
279
295
|
/**
|
|
280
|
-
*
|
|
281
|
-
*
|
|
296
|
+
* Loads the `@opentelemetry/api` module. Example: `() => import("@opentelemetry/api")`.
|
|
297
|
+
* If you do not set it, OTel is off.
|
|
282
298
|
* @see {@link OtelLoader}
|
|
283
299
|
*/
|
|
284
300
|
otelLoader?: OtelLoader;
|
|
@@ -296,8 +312,8 @@ export interface ObservabilityConfig {
|
|
|
296
312
|
}
|
|
297
313
|
/** Fully resolved config, held by the runtime. */
|
|
298
314
|
export interface ResolvedConfig {
|
|
299
|
-
/** Ingest endpoint URL. */
|
|
300
|
-
endpoint: string;
|
|
315
|
+
/** Ingest endpoint URL, or null in console-only mode. */
|
|
316
|
+
endpoint: string | null;
|
|
301
317
|
/** Reported as `service.name`. */
|
|
302
318
|
serviceName: string;
|
|
303
319
|
/** Reported as `service.version`. */
|
|
@@ -314,6 +330,8 @@ export interface ResolvedConfig {
|
|
|
314
330
|
credentials: RequestCredentials;
|
|
315
331
|
/** Backing store for undelivered records. */
|
|
316
332
|
storage: StorageStrategy;
|
|
333
|
+
/** Store for session, tab and journey ids. */
|
|
334
|
+
identity: IdentityStrategy;
|
|
317
335
|
/**
|
|
318
336
|
* Sampling policy.
|
|
319
337
|
* @see {@link SamplingOptions}
|
|
@@ -331,8 +349,8 @@ export interface ResolvedConfig {
|
|
|
331
349
|
capture: CaptureOptions;
|
|
332
350
|
/** Min level mirrored to the console, or null when mirroring is off. */
|
|
333
351
|
console: LogLevel | null;
|
|
334
|
-
/** Wire format
|
|
335
|
-
serializer:
|
|
352
|
+
/** Wire format name, or a custom implementation. */
|
|
353
|
+
serializer: SerializerChoice;
|
|
336
354
|
/** Extra request headers, or a function returning them. */
|
|
337
355
|
headers?: ObservabilityConfig["headers"];
|
|
338
356
|
/** Supplies the `@opentelemetry/api` module in place of importing it. */
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./platform-g99Kn755.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`,`could not attach traceparent, sending 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`,`recording ${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-DDVIJSHd.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-DDVIJSHd.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 consumed by auto-capture modules. Naming the runtime class\n * here instead would 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, so instance state cannot\n * hold this. web-vitals has no unsubscribe, and a second subscription reports\n * each metric two times.\n */\nexport interface CaptureOnce {\n /** True once the web-vitals reporters are subscribed. */\n webVitals: boolean;\n /** True once navigation timing has been reported. */\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. Patching an\n * already patched function chains the wrapper and doubles every record, so a\n * second call 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 URL should be excluded from telemetry.\n */\n private ignored(url: string): boolean {\n // The endpoint is always in ignoreUrls, added by resolveConfig. Without it\n // one failed POST logs, which POSTs, which logs, forever.\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 // Allowlist only. An unexpected traceparent on a third-party request\n // forces a CORS preflight they will not answer, and their API stops\n // working inside the consumer's application.\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 // Never spread a non-empty init alongside a Request input: that\n // re-runs the Request constructor over `input` and consumes its\n // body, which throws TypeError on an already-read body.\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 exactly what the caller passed. Losing our header is always\n // better than breaking their request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"could not attach traceparent, sending 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, scrubbed before it is recorded.\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 // Scrubbed here, not at the call sites: ignoreUrls and propagateTraceHeaderTo\n // match on the whole URL, so only what is recorded loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // A throw here runs inside the caller's own fetch. Breaking their request\n // to record that their request broke is the one unacceptable outcome.\n this.ctx.diagnostics.guard(\"capture.record_failed\", `recording ${method} ${url}`, () => {\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 // DEBUG, so a successful request is dropped by the default minLevel of\n // INFO and only failures cost bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\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,EACjD,KAAK,cAAgB,WAAW,MAEhC,IAAM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S,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,CAAC,CACH,CACF"}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { r as e } from "./platform-DMYo3AX3.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", "could not attach traceparent, sending 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", `recording ${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-au-Tqt1n.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-au-Tqt1n.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 consumed by auto-capture modules. Naming the runtime class\n * here instead would 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, so instance state cannot\n * hold this. web-vitals has no unsubscribe, and a second subscription reports\n * each metric two times.\n */\nexport interface CaptureOnce {\n /** True once the web-vitals reporters are subscribed. */\n webVitals: boolean;\n /** True once navigation timing has been reported. */\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. Patching an\n * already patched function chains the wrapper and doubles every record, so a\n * second call 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 URL should be excluded from telemetry.\n */\n private ignored(url: string): boolean {\n // The endpoint is always in ignoreUrls, added by resolveConfig. Without it\n // one failed POST logs, which POSTs, which logs, forever.\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 // Allowlist only. An unexpected traceparent on a third-party request\n // forces a CORS preflight they will not answer, and their API stops\n // working inside the consumer's application.\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 // Never spread a non-empty init alongside a Request input: that\n // re-runs the Request constructor over `input` and consumes its\n // body, which throws TypeError on an already-read body.\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 exactly what the caller passed. Losing our header is always\n // better than breaking their request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"could not attach traceparent, sending 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, scrubbed before it is recorded.\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 // Scrubbed here, not at the call sites: ignoreUrls and propagateTraceHeaderTo\n // match on the whole URL, so only what is recorded loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // A throw here runs inside the caller's own fetch. Breaking their request\n // to record that their request broke is the one unacceptable outcome.\n this.ctx.diagnostics.guard(\"capture.record_failed\", `recording ${method} ${url}`, () => {\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 // DEBUG, so a successful request is dropped by the default minLevel of\n // INFO and only failures cost bandwidth.\n this.ctx.logger.debug(`${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