@amplitude/analytics-core 2.27.0 → 2.27.1

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.
@@ -31,7 +31,7 @@ var DiagnosticsClient = /** @class */ (function () {
31
31
  // Diagnostics is enabled by default with sample rate of 0 (no sampling)
32
32
  this.config = tslib_1.__assign({ enabled: true, sampleRate: 0 }, options);
33
33
  this.startTimestamp = Date.now();
34
- this.shouldTrack = (0, sampling_1.isTimestampInSample)(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
34
+ this.shouldTrack = (0, sampling_1.isTimestampInSampleTemp)(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
35
35
  if (diagnostics_storage_1.DiagnosticsStorage.isSupported()) {
36
36
  this.storage = new diagnostics_storage_1.DiagnosticsStorage(apiKey, logger);
37
37
  }
@@ -321,7 +321,7 @@ var DiagnosticsClient = /** @class */ (function () {
321
321
  DiagnosticsClient.prototype._setSampleRate = function (sampleRate) {
322
322
  this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);
323
323
  this.config.sampleRate = sampleRate;
324
- this.shouldTrack = (0, sampling_1.isTimestampInSample)(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
324
+ this.shouldTrack = (0, sampling_1.isTimestampInSampleTemp)(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
325
325
  this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);
326
326
  };
327
327
  return DiagnosticsClient;
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";;;;AACA,6DAAgF;AAEhF,gDAAiD;AACjD,8CAAwD;AAE3C,QAAA,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACpC,QAAA,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC/C,QAAA,yBAAyB,GAAG,6DAA6D,CAAC;AAC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BAC3C,oDAAoD;4BACpD,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;4BACnB,sBAAO;yBACR;6BAAM;4BACL,+BAA+B;4BAC/B,IAAI,CAAC,cAAc,CAAC,yBAAiB,GAAG,kBAAkB,CAAC,CAAC;yBAC7D;;;;;KACF;IAED;;OAEG;IACK,0CAAc,GAAtB,UAAuB,KAAa;QAApC,iBAUC;QATC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;YAC3B,KAAI,CAAC,MAAM,EAAE;iBACV,KAAK,CAAC,UAAC,KAAK;gBACX,KAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YACjE,CAAC,CAAC;iBACD,OAAO,CAAC;gBACP,KAAI,CAAC,UAAU,GAAG,IAAI,CAAC;YACzB,CAAC,CAAC,CAAC;QACP,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,0CAAc,GAAd,UAAe,UAAkB;QAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2CAA2C,EAAE,UAAU,CAAC,CAAC;QAC3E,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC;QACpC,IAAI,CAAC,WAAW,GAAG,IAAA,8BAAmB,EAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAC3G,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IACH,wBAAC;AAAD,CAAC,AA5UD,IA4UC;AA5UY,8CAAiB","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\nimport { isTimestampInSample } from '../utils/sampling';\n\nexport const SAVE_INTERVAL_MS = 1000; // 1 second\nexport const FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nexport const DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';\nexport const DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';\n\n// In-memory storage limits\nexport const MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately\nexport const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;\n\n// === Core Data Types ===\n\n/**\n * Key-value pairs for environment/context information\n */\ntype DiagnosticsTags = Record<string, string>;\n\n/**\n * Numeric counters that can be incremented\n */\ntype DiagnosticsCounters = Record<string, number>;\n\n/**\n * Properties for diagnostic events\n */\ntype EventProperties = Record<string, any>;\n\n/**\n * Individual diagnostic event\n */\ninterface DiagnosticsEvent {\n readonly event_name: string;\n readonly time: number;\n readonly event_properties: EventProperties;\n}\n\n/**\n * Computed histogram statistics for final payload\n */\ninterface HistogramResult {\n readonly count: number;\n readonly min: number;\n readonly max: number;\n readonly avg: number;\n}\n\n/**\n * Internal histogram statistics with sum for efficient incremental updates\n */\nexport interface HistogramStats {\n count: number;\n min: number;\n max: number;\n sum: number; // Used for avg calculation\n}\n\n/**\n * Collection of histogram results keyed by histogram name\n */\ntype DiagnosticsHistograms = Record<string, HistogramResult>;\n\n/**\n * Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)\n */\ntype DiagnosticsHistogramStats = Record<string, HistogramStats>;\n\n// === Payload Types ===\n\n/**\n * Complete diagnostics payload sent to backend\n */\ninterface FlushPayload {\n readonly tags: DiagnosticsTags;\n readonly histogram: DiagnosticsHistograms;\n readonly counters: DiagnosticsCounters;\n readonly events: readonly DiagnosticsEvent[];\n}\n\n/**\n * Amplitude Diagnostics Client\n *\n * A client for collecting and managing diagnostics data including tags, counters,\n * histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.\n *\n * Key Features:\n * - IndexedDB storage\n * - Time-based persistent storage flush interval (5 minutes since last flush)\n * - 1 second time-based memory storage flush to persistent storage\n * - Histogram statistics calculation (min, max, avg)\n */\nexport interface IDiagnosticsClient {\n /**\n * Set or update a tag\n *\n * @example\n * ```typescript\n * // Set environment tags\n * diagnostics.setTag('library', 'amplitude-typescript/2.0.0');\n * diagnostics.setTag('user_agent', navigator.userAgent);\n * ```\n */\n setTag(name: string, value: string): void;\n\n /**\n * Increment a counter. If doesn't exist, create a counter and set value to 1\n *\n * @example\n * ```typescript\n * // Track counters\n * diagnostics.increment('analytics.fileNotFound');\n * diagnostics.increment('network.retry', 3);\n * ```\n */\n increment(name: string, size?: number): void;\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * // Record performance metrics\n * diagnostics.recordHistogram('sr.time', 5.2);\n * diagnostics.recordHistogram('network.latency', 150);\n * ```\n */\n recordHistogram(name: string, value: number): void;\n\n /**\n * Record an event\n *\n * @example\n * ```typescript\n * // Record diagnostic events\n * diagnostics.recordEvent('error', {\n * stack_trace: '...',\n * });\n * ```\n */\n recordEvent(name: string, properties: EventProperties): void;\n\n // Flush storage\n _flush(): void;\n\n /**\n * Sets the sample rate for diagnostics.\n *\n * @example\n * ```typescript\n * diagnostics.setSampleRate(0.5);\n * ```\n */\n _setSampleRate(sampleRate: number): void;\n}\n\nexport class DiagnosticsClient implements IDiagnosticsClient {\n storage?: IDiagnosticsStorage;\n logger: ILogger;\n serverUrl: string;\n apiKey: string;\n // Whether to track diagnostics data based on sample rate and enabled flag\n shouldTrack: boolean;\n config: {\n enabled: boolean;\n sampleRate: number;\n };\n /**\n * The timestamp when the diagnostics client was initialized.\n * Save in memory to keep lifecycle sample rate calculation consistency.\n */\n startTimestamp: number;\n\n // In-memory storages\n inMemoryTags: DiagnosticsTags = {};\n inMemoryCounters: DiagnosticsCounters = {};\n inMemoryHistograms: DiagnosticsHistogramStats = {};\n inMemoryEvents: DiagnosticsEvent[] = [];\n\n // Timer for 1-second persistence\n saveTimer: ReturnType<typeof setTimeout> | null = null;\n // Timer for flush interval\n flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n apiKey: string,\n logger: ILogger,\n serverZone: ServerZoneType = 'US',\n options?: {\n enabled?: boolean;\n sampleRate?: number;\n },\n ) {\n this.apiKey = apiKey;\n this.logger = logger;\n this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;\n\n this.logger.debug('DiagnosticsClient: Initializing with options', JSON.stringify(options, null, 2));\n // Diagnostics is enabled by default with sample rate of 0 (no sampling)\n this.config = { enabled: true, sampleRate: 0, ...options };\n this.startTimestamp = Date.now();\n this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n\n if (DiagnosticsStorage.isSupported()) {\n this.storage = new DiagnosticsStorage(apiKey, logger);\n } else {\n this.logger.debug('DiagnosticsClient: IndexedDB is not supported');\n }\n\n void this.initializeFlushInterval();\n }\n\n /**\n * Check if storage is available and tracking is enabled\n */\n isStorageAndTrackEnabled(): boolean {\n return Boolean(this.storage) && Boolean(this.shouldTrack);\n }\n\n setTag(name: string, value: string) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');\n return;\n }\n\n this.inMemoryTags[name] = value;\n this.startTimersIfNeeded();\n }\n\n increment(name: string, size = 1) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');\n return;\n }\n\n this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;\n this.startTimersIfNeeded();\n }\n\n recordHistogram(name: string, value: number) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');\n return;\n }\n\n const existing = this.inMemoryHistograms[name];\n if (existing) {\n // Update existing stats incrementally\n existing.count += 1;\n existing.min = Math.min(existing.min, value);\n existing.max = Math.max(existing.max, value);\n existing.sum += value;\n } else {\n // Create new stats\n this.inMemoryHistograms[name] = {\n count: 1,\n min: value,\n max: value,\n sum: value,\n };\n }\n this.startTimersIfNeeded();\n }\n\n recordEvent(name: string, properties: EventProperties) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');\n return;\n }\n\n this.inMemoryEvents.push({\n event_name: name,\n time: Date.now(),\n event_properties: properties,\n });\n this.startTimersIfNeeded();\n }\n\n startTimersIfNeeded() {\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveAllDataToStorage()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);\n })\n .finally(() => {\n this.saveTimer = null;\n });\n }, SAVE_INTERVAL_MS);\n }\n\n if (!this.flushTimer) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n async saveAllDataToStorage() {\n if (!this.storage) {\n return;\n }\n const tagsToSave = { ...this.inMemoryTags };\n const countersToSave = { ...this.inMemoryCounters };\n const histogramsToSave = { ...this.inMemoryHistograms };\n const eventsToSave = [...this.inMemoryEvents];\n\n this.inMemoryEvents = [];\n this.inMemoryTags = {};\n this.inMemoryCounters = {};\n this.inMemoryHistograms = {};\n\n await Promise.all([\n this.storage.setTags(tagsToSave),\n this.storage.incrementCounters(countersToSave),\n this.storage.setHistogramStats(histogramsToSave),\n this.storage.addEventRecords(eventsToSave),\n ]);\n }\n\n async _flush() {\n if (!this.storage) {\n return;\n }\n\n await this.saveAllDataToStorage();\n this.saveTimer = null;\n this.flushTimer = null;\n\n // Get all data from storage and clear it\n const {\n tags: tagRecords,\n counters: counterRecords,\n histogramStats: histogramStatsRecords,\n events: eventRecords,\n } = await this.storage.getAllAndClear();\n\n // Update the last flush timestamp\n void this.storage.setLastFlushTimestamp(Date.now());\n\n // Convert metrics to the expected format\n const tags: DiagnosticsTags = {};\n tagRecords.forEach((record) => {\n tags[record.key] = record.value;\n });\n\n const counters: DiagnosticsCounters = {};\n counterRecords.forEach((record) => {\n counters[record.key] = record.value;\n });\n\n const histogram: DiagnosticsHistograms = {};\n histogramStatsRecords.forEach((stats) => {\n histogram[stats.key] = {\n count: stats.count,\n min: stats.min,\n max: stats.max,\n avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.\n };\n });\n\n const events: DiagnosticsEvent[] = eventRecords.map((record) => ({\n event_name: record.event_name,\n time: record.time,\n event_properties: record.event_properties,\n }));\n\n // Early return if all data collections are empty\n if (Object.keys(counters).length === 0 && Object.keys(histogram).length === 0 && events.length === 0) {\n return;\n }\n\n // Create flush payload\n const payload: FlushPayload = {\n tags,\n histogram,\n counters,\n events,\n };\n\n // Send payload to diagnostics server\n void this.fetch(payload);\n }\n\n /**\n * Send diagnostics data to the server\n */\n async fetch(payload: FlushPayload) {\n try {\n if (!getGlobalScope()) {\n throw new Error('DiagnosticsClient: Fetch is not supported');\n }\n\n const response = await fetch(this.serverUrl, {\n method: 'POST',\n headers: {\n 'X-ApiKey': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');\n return;\n }\n\n this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');\n } catch (error) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error);\n }\n }\n\n /**\n * Initialize flush interval logic.\n * Check if 5 minutes has passed since last flush, if so flush immediately.\n * Otherwise set a timer to flush when the interval is reached.\n */\n async initializeFlushInterval() {\n if (!this.storage) {\n return;\n }\n const now = Date.now();\n const lastFlushTimestamp = (await this.storage.getLastFlushTimestamp()) || -1;\n\n // If last flush timestamp is -1, it means this is a new client\n // Save current timestamp as the initial \"last flush timestamp\"\n // and schedule the flush timer\n if (lastFlushTimestamp === -1) {\n void this.storage.setLastFlushTimestamp(now);\n this._setFlushTimer(FLUSH_INTERVAL_MS);\n return;\n }\n\n const timeSinceLastFlush = now - lastFlushTimestamp;\n if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) {\n // More than 5 minutes has passed, flush immediately\n void this._flush();\n return;\n } else {\n // Set timer for remaining time\n this._setFlushTimer(FLUSH_INTERVAL_MS - timeSinceLastFlush);\n }\n }\n\n /**\n * Helper method to set flush timer with consistent error handling\n */\n private _setFlushTimer(delay: number) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, delay);\n }\n\n _setSampleRate(sampleRate: number): void {\n this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);\n this.config.sampleRate = sampleRate;\n this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);\n }\n}\n"]}
1
+ {"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";;;;AACA,6DAAgF;AAEhF,gDAAiD;AACjD,8CAA4D;AAE/C,QAAA,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACpC,QAAA,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC/C,QAAA,yBAAyB,GAAG,6DAA6D,CAAC;AAC1F,QAAA,yBAAyB,GAAG,gEAAgE,CAAC;AAE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AAM,EAAE,CAAC;4BACnB,sBAAO;yBACR;6BAAM;4BACL,+BAA+B;4BAC/B,IAAI,CAAC,cAAc,CAAC,yBAAiB,GAAG,kBAAkB,CAAC,CAAC;yBAC7D;;;;;KACF;IAED;;OAEG;IACK,0CAAc,GAAtB,UAAuB,KAAa;QAApC,iBAUC;QATC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;YAC3B,KAAI,CAAC,MAAM,EAAE;iBACV,KAAK,CAAC,UAAC,KAAK;gBACX,KAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YACjE,CAAC,CAAC;iBACD,OAAO,CAAC;gBACP,KAAI,CAAC,UAAU,GAAG,IAAI,CAAC;YACzB,CAAC,CAAC,CAAC;QACP,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,0CAAc,GAAd,UAAe,UAAkB;QAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2CAA2C,EAAE,UAAU,CAAC,CAAC;QAC3E,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC;QACpC,IAAI,CAAC,WAAW,GAAG,IAAA,kCAAuB,EAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAC/G,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IACH,wBAAC;AAAD,CAAC,AA5UD,IA4UC;AA5UY,8CAAiB","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\nimport { isTimestampInSampleTemp } from '../utils/sampling';\n\nexport const SAVE_INTERVAL_MS = 1000; // 1 second\nexport const FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nexport const DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';\nexport const DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';\n\n// In-memory storage limits\nexport const MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately\nexport const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;\n\n// === Core Data Types ===\n\n/**\n * Key-value pairs for environment/context information\n */\ntype DiagnosticsTags = Record<string, string>;\n\n/**\n * Numeric counters that can be incremented\n */\ntype DiagnosticsCounters = Record<string, number>;\n\n/**\n * Properties for diagnostic events\n */\ntype EventProperties = Record<string, any>;\n\n/**\n * Individual diagnostic event\n */\ninterface DiagnosticsEvent {\n readonly event_name: string;\n readonly time: number;\n readonly event_properties: EventProperties;\n}\n\n/**\n * Computed histogram statistics for final payload\n */\ninterface HistogramResult {\n readonly count: number;\n readonly min: number;\n readonly max: number;\n readonly avg: number;\n}\n\n/**\n * Internal histogram statistics with sum for efficient incremental updates\n */\nexport interface HistogramStats {\n count: number;\n min: number;\n max: number;\n sum: number; // Used for avg calculation\n}\n\n/**\n * Collection of histogram results keyed by histogram name\n */\ntype DiagnosticsHistograms = Record<string, HistogramResult>;\n\n/**\n * Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)\n */\ntype DiagnosticsHistogramStats = Record<string, HistogramStats>;\n\n// === Payload Types ===\n\n/**\n * Complete diagnostics payload sent to backend\n */\ninterface FlushPayload {\n readonly tags: DiagnosticsTags;\n readonly histogram: DiagnosticsHistograms;\n readonly counters: DiagnosticsCounters;\n readonly events: readonly DiagnosticsEvent[];\n}\n\n/**\n * Amplitude Diagnostics Client\n *\n * A client for collecting and managing diagnostics data including tags, counters,\n * histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.\n *\n * Key Features:\n * - IndexedDB storage\n * - Time-based persistent storage flush interval (5 minutes since last flush)\n * - 1 second time-based memory storage flush to persistent storage\n * - Histogram statistics calculation (min, max, avg)\n */\nexport interface IDiagnosticsClient {\n /**\n * Set or update a tag\n *\n * @example\n * ```typescript\n * // Set environment tags\n * diagnostics.setTag('library', 'amplitude-typescript/2.0.0');\n * diagnostics.setTag('user_agent', navigator.userAgent);\n * ```\n */\n setTag(name: string, value: string): void;\n\n /**\n * Increment a counter. If doesn't exist, create a counter and set value to 1\n *\n * @example\n * ```typescript\n * // Track counters\n * diagnostics.increment('analytics.fileNotFound');\n * diagnostics.increment('network.retry', 3);\n * ```\n */\n increment(name: string, size?: number): void;\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * // Record performance metrics\n * diagnostics.recordHistogram('sr.time', 5.2);\n * diagnostics.recordHistogram('network.latency', 150);\n * ```\n */\n recordHistogram(name: string, value: number): void;\n\n /**\n * Record an event\n *\n * @example\n * ```typescript\n * // Record diagnostic events\n * diagnostics.recordEvent('error', {\n * stack_trace: '...',\n * });\n * ```\n */\n recordEvent(name: string, properties: EventProperties): void;\n\n // Flush storage\n _flush(): void;\n\n /**\n * Sets the sample rate for diagnostics.\n *\n * @example\n * ```typescript\n * diagnostics.setSampleRate(0.5);\n * ```\n */\n _setSampleRate(sampleRate: number): void;\n}\n\nexport class DiagnosticsClient implements IDiagnosticsClient {\n storage?: IDiagnosticsStorage;\n logger: ILogger;\n serverUrl: string;\n apiKey: string;\n // Whether to track diagnostics data based on sample rate and enabled flag\n shouldTrack: boolean;\n config: {\n enabled: boolean;\n sampleRate: number;\n };\n /**\n * The timestamp when the diagnostics client was initialized.\n * Save in memory to keep lifecycle sample rate calculation consistency.\n */\n startTimestamp: number;\n\n // In-memory storages\n inMemoryTags: DiagnosticsTags = {};\n inMemoryCounters: DiagnosticsCounters = {};\n inMemoryHistograms: DiagnosticsHistogramStats = {};\n inMemoryEvents: DiagnosticsEvent[] = [];\n\n // Timer for 1-second persistence\n saveTimer: ReturnType<typeof setTimeout> | null = null;\n // Timer for flush interval\n flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n apiKey: string,\n logger: ILogger,\n serverZone: ServerZoneType = 'US',\n options?: {\n enabled?: boolean;\n sampleRate?: number;\n },\n ) {\n this.apiKey = apiKey;\n this.logger = logger;\n this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;\n\n this.logger.debug('DiagnosticsClient: Initializing with options', JSON.stringify(options, null, 2));\n // Diagnostics is enabled by default with sample rate of 0 (no sampling)\n this.config = { enabled: true, sampleRate: 0, ...options };\n this.startTimestamp = Date.now();\n this.shouldTrack = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n\n if (DiagnosticsStorage.isSupported()) {\n this.storage = new DiagnosticsStorage(apiKey, logger);\n } else {\n this.logger.debug('DiagnosticsClient: IndexedDB is not supported');\n }\n\n void this.initializeFlushInterval();\n }\n\n /**\n * Check if storage is available and tracking is enabled\n */\n isStorageAndTrackEnabled(): boolean {\n return Boolean(this.storage) && Boolean(this.shouldTrack);\n }\n\n setTag(name: string, value: string) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');\n return;\n }\n\n this.inMemoryTags[name] = value;\n this.startTimersIfNeeded();\n }\n\n increment(name: string, size = 1) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');\n return;\n }\n\n this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;\n this.startTimersIfNeeded();\n }\n\n recordHistogram(name: string, value: number) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');\n return;\n }\n\n const existing = this.inMemoryHistograms[name];\n if (existing) {\n // Update existing stats incrementally\n existing.count += 1;\n existing.min = Math.min(existing.min, value);\n existing.max = Math.max(existing.max, value);\n existing.sum += value;\n } else {\n // Create new stats\n this.inMemoryHistograms[name] = {\n count: 1,\n min: value,\n max: value,\n sum: value,\n };\n }\n this.startTimersIfNeeded();\n }\n\n recordEvent(name: string, properties: EventProperties) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');\n return;\n }\n\n this.inMemoryEvents.push({\n event_name: name,\n time: Date.now(),\n event_properties: properties,\n });\n this.startTimersIfNeeded();\n }\n\n startTimersIfNeeded() {\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveAllDataToStorage()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);\n })\n .finally(() => {\n this.saveTimer = null;\n });\n }, SAVE_INTERVAL_MS);\n }\n\n if (!this.flushTimer) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n async saveAllDataToStorage() {\n if (!this.storage) {\n return;\n }\n const tagsToSave = { ...this.inMemoryTags };\n const countersToSave = { ...this.inMemoryCounters };\n const histogramsToSave = { ...this.inMemoryHistograms };\n const eventsToSave = [...this.inMemoryEvents];\n\n this.inMemoryEvents = [];\n this.inMemoryTags = {};\n this.inMemoryCounters = {};\n this.inMemoryHistograms = {};\n\n await Promise.all([\n this.storage.setTags(tagsToSave),\n this.storage.incrementCounters(countersToSave),\n this.storage.setHistogramStats(histogramsToSave),\n this.storage.addEventRecords(eventsToSave),\n ]);\n }\n\n async _flush() {\n if (!this.storage) {\n return;\n }\n\n await this.saveAllDataToStorage();\n this.saveTimer = null;\n this.flushTimer = null;\n\n // Get all data from storage and clear it\n const {\n tags: tagRecords,\n counters: counterRecords,\n histogramStats: histogramStatsRecords,\n events: eventRecords,\n } = await this.storage.getAllAndClear();\n\n // Update the last flush timestamp\n void this.storage.setLastFlushTimestamp(Date.now());\n\n // Convert metrics to the expected format\n const tags: DiagnosticsTags = {};\n tagRecords.forEach((record) => {\n tags[record.key] = record.value;\n });\n\n const counters: DiagnosticsCounters = {};\n counterRecords.forEach((record) => {\n counters[record.key] = record.value;\n });\n\n const histogram: DiagnosticsHistograms = {};\n histogramStatsRecords.forEach((stats) => {\n histogram[stats.key] = {\n count: stats.count,\n min: stats.min,\n max: stats.max,\n avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.\n };\n });\n\n const events: DiagnosticsEvent[] = eventRecords.map((record) => ({\n event_name: record.event_name,\n time: record.time,\n event_properties: record.event_properties,\n }));\n\n // Early return if all data collections are empty\n if (Object.keys(counters).length === 0 && Object.keys(histogram).length === 0 && events.length === 0) {\n return;\n }\n\n // Create flush payload\n const payload: FlushPayload = {\n tags,\n histogram,\n counters,\n events,\n };\n\n // Send payload to diagnostics server\n void this.fetch(payload);\n }\n\n /**\n * Send diagnostics data to the server\n */\n async fetch(payload: FlushPayload) {\n try {\n if (!getGlobalScope()) {\n throw new Error('DiagnosticsClient: Fetch is not supported');\n }\n\n const response = await fetch(this.serverUrl, {\n method: 'POST',\n headers: {\n 'X-ApiKey': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');\n return;\n }\n\n this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');\n } catch (error) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error);\n }\n }\n\n /**\n * Initialize flush interval logic.\n * Check if 5 minutes has passed since last flush, if so flush immediately.\n * Otherwise set a timer to flush when the interval is reached.\n */\n async initializeFlushInterval() {\n if (!this.storage) {\n return;\n }\n const now = Date.now();\n const lastFlushTimestamp = (await this.storage.getLastFlushTimestamp()) || -1;\n\n // If last flush timestamp is -1, it means this is a new client\n // Save current timestamp as the initial \"last flush timestamp\"\n // and schedule the flush timer\n if (lastFlushTimestamp === -1) {\n void this.storage.setLastFlushTimestamp(now);\n this._setFlushTimer(FLUSH_INTERVAL_MS);\n return;\n }\n\n const timeSinceLastFlush = now - lastFlushTimestamp;\n if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) {\n // More than 5 minutes has passed, flush immediately\n void this._flush();\n return;\n } else {\n // Set timer for remaining time\n this._setFlushTimer(FLUSH_INTERVAL_MS - timeSinceLastFlush);\n }\n }\n\n /**\n * Helper method to set flush timer with consistent error handling\n */\n private _setFlushTimer(delay: number) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, delay);\n }\n\n _setSampleRate(sampleRate: number): void {\n this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);\n this.config.sampleRate = sampleRate;\n this.shouldTrack = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
1
  export declare const generateHashCode: (str: string) => number;
2
2
  export declare const isTimestampInSample: (timestamp: string | number, sampleRate: number) => boolean;
3
+ export declare const isTimestampInSampleTemp: (timestamp: string | number, sampleRate: number) => boolean;
3
4
  //# sourceMappingURL=sampling.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sampling.d.ts","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,QAAkB,MAAM,WASpD,CAAC;AAEF,eAAO,MAAM,mBAAmB,cAAwB,MAAM,GAAG,MAAM,cAAc,MAAM,YAM1F,CAAC"}
1
+ {"version":3,"file":"sampling.d.ts","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,QAAkB,MAAM,WASpD,CAAC;AAEF,eAAO,MAAM,mBAAmB,cAAwB,MAAM,GAAG,MAAM,cAAc,MAAM,YAM1F,CAAC;AAIF,eAAO,MAAM,uBAAuB,cAAwB,MAAM,GAAG,MAAM,cAAc,MAAM,YAM9F,CAAC"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isTimestampInSample = exports.generateHashCode = void 0;
3
+ exports.isTimestampInSampleTemp = exports.isTimestampInSample = exports.generateHashCode = void 0;
4
4
  var generateHashCode = function (str) {
5
5
  var hash = 0;
6
6
  if (str.length === 0)
@@ -21,4 +21,14 @@ var isTimestampInSample = function (timestamp, sampleRate) {
21
21
  return mod / 1000000 < sampleRate;
22
22
  };
23
23
  exports.isTimestampInSample = isTimestampInSample;
24
+ // TODO(xinyi): replace the temp one in diagnostics client after the fix
25
+ // istanbul ignore next
26
+ var isTimestampInSampleTemp = function (timestamp, sampleRate) {
27
+ var hashNumber = (0, exports.generateHashCode)(timestamp.toString());
28
+ var absHash = Math.abs(hashNumber);
29
+ var absHashMultiply = absHash * 31;
30
+ var mod = absHashMultiply % 100000;
31
+ return mod / 100000 < sampleRate;
32
+ };
33
+ exports.isTimestampInSampleTemp = isTimestampInSampleTemp;
24
34
  //# sourceMappingURL=sampling.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":";;;AAAO,IAAM,gBAAgB,GAAG,UAAU,GAAW;IACnD,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAM,GAAG,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC;QAChC,IAAI,IAAI,CAAC,CAAC;KACX;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AATW,QAAA,gBAAgB,oBAS3B;AAEK,IAAM,mBAAmB,GAAG,UAAU,SAA0B,EAAE,UAAkB;IACzF,IAAM,UAAU,GAAG,IAAA,wBAAgB,EAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC1D,IAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACrC,IAAM,eAAe,GAAG,OAAO,GAAG,EAAE,CAAC;IACrC,IAAM,GAAG,GAAG,eAAe,GAAG,OAAO,CAAC;IACtC,OAAO,GAAG,GAAG,OAAO,GAAG,UAAU,CAAC;AACpC,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B","sourcesContent":["export const generateHashCode = function (str: string) {\n let hash = 0;\n if (str.length === 0) return hash;\n for (let i = 0; i < str.length; i++) {\n const chr = str.charCodeAt(i);\n hash = (hash << 5) - hash + chr;\n hash |= 0;\n }\n return hash;\n};\n\nexport const isTimestampInSample = function (timestamp: string | number, sampleRate: number) {\n const hashNumber = generateHashCode(timestamp.toString());\n const absHash = Math.abs(hashNumber);\n const absHashMultiply = absHash * 31;\n const mod = absHashMultiply % 1000000;\n return mod / 1000000 < sampleRate;\n};\n"]}
1
+ {"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":";;;AAAO,IAAM,gBAAgB,GAAG,UAAU,GAAW;IACnD,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAM,GAAG,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC;QAChC,IAAI,IAAI,CAAC,CAAC;KACX;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AATW,QAAA,gBAAgB,oBAS3B;AAEK,IAAM,mBAAmB,GAAG,UAAU,SAA0B,EAAE,UAAkB;IACzF,IAAM,UAAU,GAAG,IAAA,wBAAgB,EAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC1D,IAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACrC,IAAM,eAAe,GAAG,OAAO,GAAG,EAAE,CAAC;IACrC,IAAM,GAAG,GAAG,eAAe,GAAG,OAAO,CAAC;IACtC,OAAO,GAAG,GAAG,OAAO,GAAG,UAAU,CAAC;AACpC,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B;AAEF,wEAAwE;AACxE,uBAAuB;AAChB,IAAM,uBAAuB,GAAG,UAAU,SAA0B,EAAE,UAAkB;IAC7F,IAAM,UAAU,GAAG,IAAA,wBAAgB,EAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC1D,IAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACrC,IAAM,eAAe,GAAG,OAAO,GAAG,EAAE,CAAC;IACrC,IAAM,GAAG,GAAG,eAAe,GAAG,MAAM,CAAC;IACrC,OAAO,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AACnC,CAAC,CAAC;AANW,QAAA,uBAAuB,2BAMlC","sourcesContent":["export const generateHashCode = function (str: string) {\n let hash = 0;\n if (str.length === 0) return hash;\n for (let i = 0; i < str.length; i++) {\n const chr = str.charCodeAt(i);\n hash = (hash << 5) - hash + chr;\n hash |= 0;\n }\n return hash;\n};\n\nexport const isTimestampInSample = function (timestamp: string | number, sampleRate: number) {\n const hashNumber = generateHashCode(timestamp.toString());\n const absHash = Math.abs(hashNumber);\n const absHashMultiply = absHash * 31;\n const mod = absHashMultiply % 1000000;\n return mod / 1000000 < sampleRate;\n};\n\n// TODO(xinyi): replace the temp one in diagnostics client after the fix\n// istanbul ignore next\nexport const isTimestampInSampleTemp = function (timestamp: string | number, sampleRate: number) {\n const hashNumber = generateHashCode(timestamp.toString());\n const absHash = Math.abs(hashNumber);\n const absHashMultiply = absHash * 31;\n const mod = absHashMultiply % 100000;\n return mod / 100000 < sampleRate;\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  import { __assign, __awaiter, __generator, __read, __spreadArray } from "tslib";
2
2
  import { DiagnosticsStorage } from './diagnostics-storage';
3
3
  import { getGlobalScope } from '../global-scope';
4
- import { isTimestampInSample } from '../utils/sampling';
4
+ import { isTimestampInSampleTemp } from '../utils/sampling';
5
5
  export var SAVE_INTERVAL_MS = 1000; // 1 second
6
6
  export var FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
7
7
  export var DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';
@@ -28,7 +28,7 @@ var DiagnosticsClient = /** @class */ (function () {
28
28
  // Diagnostics is enabled by default with sample rate of 0 (no sampling)
29
29
  this.config = __assign({ enabled: true, sampleRate: 0 }, options);
30
30
  this.startTimestamp = Date.now();
31
- this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
31
+ this.shouldTrack = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
32
32
  if (DiagnosticsStorage.isSupported()) {
33
33
  this.storage = new DiagnosticsStorage(apiKey, logger);
34
34
  }
@@ -318,7 +318,7 @@ var DiagnosticsClient = /** @class */ (function () {
318
318
  DiagnosticsClient.prototype._setSampleRate = function (sampleRate) {
319
319
  this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);
320
320
  this.config.sampleRate = sampleRate;
321
- this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
321
+ this.shouldTrack = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
322
322
  this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);
323
323
  };
324
324
  return DiagnosticsClient;
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAuB,MAAM,uBAAuB,CAAC;AAEhF,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,CAAC,IAAM,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACjD,MAAM,CAAC,IAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC5D,MAAM,CAAC,IAAM,yBAAyB,GAAG,6DAA6D,CAAC;AACvG,MAAM,CAAC,IAAM,yBAAyB,GAAG,gEAAgE,CAAC;AAE1G,2BAA2B;AAC3B,MAAM,CAAC,IAAM,wBAAwB,GAAG,KAAK,CAAC,CAAC,4CAA4C;AAC3F,MAAM,CAAC,IAAM,+BAA+B,GAAG,EAAE,CAAC;AAkJlD;IA4BE,2BACE,MAAc,EACd,MAAe,EACf,UAAiC,EACjC,OAGC;QAJD,2BAAA,EAAA,iBAAiC;QAdnC,qBAAqB;QACrB,iBAAY,GAAoB,EAAE,CAAC;QACnC,qBAAgB,GAAwB,EAAE,CAAC;QAC3C,uBAAkB,GAA8B,EAAE,CAAC;QACnD,mBAAc,GAAuB,EAAE,CAAC;QAExC,iCAAiC;QACjC,cAAS,GAAyC,IA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AC;iBACD,OAAO,CAAC;gBACP,KAAI,CAAC,UAAU,GAAG,IAAI,CAAC;YACzB,CAAC,CAAC,CAAC;QACP,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,0CAAc,GAAd,UAAe,UAAkB;QAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2CAA2C,EAAE,UAAU,CAAC,CAAC;QAC3E,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC;QACpC,IAAI,CAAC,WAAW,GAAG,mBAAmB,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAC3G,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IACH,wBAAC;AAAD,CAAC,AA5UD,IA4UC","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\nimport { isTimestampInSample } from '../utils/sampling';\n\nexport const SAVE_INTERVAL_MS = 1000; // 1 second\nexport const FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nexport const DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';\nexport const DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';\n\n// In-memory storage limits\nexport const MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately\nexport const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;\n\n// === Core Data Types ===\n\n/**\n * Key-value pairs for environment/context information\n */\ntype DiagnosticsTags = Record<string, string>;\n\n/**\n * Numeric counters that can be incremented\n */\ntype DiagnosticsCounters = Record<string, number>;\n\n/**\n * Properties for diagnostic events\n */\ntype EventProperties = Record<string, any>;\n\n/**\n * Individual diagnostic event\n */\ninterface DiagnosticsEvent {\n readonly event_name: string;\n readonly time: number;\n readonly event_properties: EventProperties;\n}\n\n/**\n * Computed histogram statistics for final payload\n */\ninterface HistogramResult {\n readonly count: number;\n readonly min: number;\n readonly max: number;\n readonly avg: number;\n}\n\n/**\n * Internal histogram statistics with sum for efficient incremental updates\n */\nexport interface HistogramStats {\n count: number;\n min: number;\n max: number;\n sum: number; // Used for avg calculation\n}\n\n/**\n * Collection of histogram results keyed by histogram name\n */\ntype DiagnosticsHistograms = Record<string, HistogramResult>;\n\n/**\n * Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)\n */\ntype DiagnosticsHistogramStats = Record<string, HistogramStats>;\n\n// === Payload Types ===\n\n/**\n * Complete diagnostics payload sent to backend\n */\ninterface FlushPayload {\n readonly tags: DiagnosticsTags;\n readonly histogram: DiagnosticsHistograms;\n readonly counters: DiagnosticsCounters;\n readonly events: readonly DiagnosticsEvent[];\n}\n\n/**\n * Amplitude Diagnostics Client\n *\n * A client for collecting and managing diagnostics data including tags, counters,\n * histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.\n *\n * Key Features:\n * - IndexedDB storage\n * - Time-based persistent storage flush interval (5 minutes since last flush)\n * - 1 second time-based memory storage flush to persistent storage\n * - Histogram statistics calculation (min, max, avg)\n */\nexport interface IDiagnosticsClient {\n /**\n * Set or update a tag\n *\n * @example\n * ```typescript\n * // Set environment tags\n * diagnostics.setTag('library', 'amplitude-typescript/2.0.0');\n * diagnostics.setTag('user_agent', navigator.userAgent);\n * ```\n */\n setTag(name: string, value: string): void;\n\n /**\n * Increment a counter. If doesn't exist, create a counter and set value to 1\n *\n * @example\n * ```typescript\n * // Track counters\n * diagnostics.increment('analytics.fileNotFound');\n * diagnostics.increment('network.retry', 3);\n * ```\n */\n increment(name: string, size?: number): void;\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * // Record performance metrics\n * diagnostics.recordHistogram('sr.time', 5.2);\n * diagnostics.recordHistogram('network.latency', 150);\n * ```\n */\n recordHistogram(name: string, value: number): void;\n\n /**\n * Record an event\n *\n * @example\n * ```typescript\n * // Record diagnostic events\n * diagnostics.recordEvent('error', {\n * stack_trace: '...',\n * });\n * ```\n */\n recordEvent(name: string, properties: EventProperties): void;\n\n // Flush storage\n _flush(): void;\n\n /**\n * Sets the sample rate for diagnostics.\n *\n * @example\n * ```typescript\n * diagnostics.setSampleRate(0.5);\n * ```\n */\n _setSampleRate(sampleRate: number): void;\n}\n\nexport class DiagnosticsClient implements IDiagnosticsClient {\n storage?: IDiagnosticsStorage;\n logger: ILogger;\n serverUrl: string;\n apiKey: string;\n // Whether to track diagnostics data based on sample rate and enabled flag\n shouldTrack: boolean;\n config: {\n enabled: boolean;\n sampleRate: number;\n };\n /**\n * The timestamp when the diagnostics client was initialized.\n * Save in memory to keep lifecycle sample rate calculation consistency.\n */\n startTimestamp: number;\n\n // In-memory storages\n inMemoryTags: DiagnosticsTags = {};\n inMemoryCounters: DiagnosticsCounters = {};\n inMemoryHistograms: DiagnosticsHistogramStats = {};\n inMemoryEvents: DiagnosticsEvent[] = [];\n\n // Timer for 1-second persistence\n saveTimer: ReturnType<typeof setTimeout> | null = null;\n // Timer for flush interval\n flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n apiKey: string,\n logger: ILogger,\n serverZone: ServerZoneType = 'US',\n options?: {\n enabled?: boolean;\n sampleRate?: number;\n },\n ) {\n this.apiKey = apiKey;\n this.logger = logger;\n this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;\n\n this.logger.debug('DiagnosticsClient: Initializing with options', JSON.stringify(options, null, 2));\n // Diagnostics is enabled by default with sample rate of 0 (no sampling)\n this.config = { enabled: true, sampleRate: 0, ...options };\n this.startTimestamp = Date.now();\n this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n\n if (DiagnosticsStorage.isSupported()) {\n this.storage = new DiagnosticsStorage(apiKey, logger);\n } else {\n this.logger.debug('DiagnosticsClient: IndexedDB is not supported');\n }\n\n void this.initializeFlushInterval();\n }\n\n /**\n * Check if storage is available and tracking is enabled\n */\n isStorageAndTrackEnabled(): boolean {\n return Boolean(this.storage) && Boolean(this.shouldTrack);\n }\n\n setTag(name: string, value: string) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');\n return;\n }\n\n this.inMemoryTags[name] = value;\n this.startTimersIfNeeded();\n }\n\n increment(name: string, size = 1) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');\n return;\n }\n\n this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;\n this.startTimersIfNeeded();\n }\n\n recordHistogram(name: string, value: number) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');\n return;\n }\n\n const existing = this.inMemoryHistograms[name];\n if (existing) {\n // Update existing stats incrementally\n existing.count += 1;\n existing.min = Math.min(existing.min, value);\n existing.max = Math.max(existing.max, value);\n existing.sum += value;\n } else {\n // Create new stats\n this.inMemoryHistograms[name] = {\n count: 1,\n min: value,\n max: value,\n sum: value,\n };\n }\n this.startTimersIfNeeded();\n }\n\n recordEvent(name: string, properties: EventProperties) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');\n return;\n }\n\n this.inMemoryEvents.push({\n event_name: name,\n time: Date.now(),\n event_properties: properties,\n });\n this.startTimersIfNeeded();\n }\n\n startTimersIfNeeded() {\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveAllDataToStorage()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);\n })\n .finally(() => {\n this.saveTimer = null;\n });\n }, SAVE_INTERVAL_MS);\n }\n\n if (!this.flushTimer) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n async saveAllDataToStorage() {\n if (!this.storage) {\n return;\n }\n const tagsToSave = { ...this.inMemoryTags };\n const countersToSave = { ...this.inMemoryCounters };\n const histogramsToSave = { ...this.inMemoryHistograms };\n const eventsToSave = [...this.inMemoryEvents];\n\n this.inMemoryEvents = [];\n this.inMemoryTags = {};\n this.inMemoryCounters = {};\n this.inMemoryHistograms = {};\n\n await Promise.all([\n this.storage.setTags(tagsToSave),\n this.storage.incrementCounters(countersToSave),\n this.storage.setHistogramStats(histogramsToSave),\n this.storage.addEventRecords(eventsToSave),\n ]);\n }\n\n async _flush() {\n if (!this.storage) {\n return;\n }\n\n await this.saveAllDataToStorage();\n this.saveTimer = null;\n this.flushTimer = null;\n\n // Get all data from storage and clear it\n const {\n tags: tagRecords,\n counters: counterRecords,\n histogramStats: histogramStatsRecords,\n events: eventRecords,\n } = await this.storage.getAllAndClear();\n\n // Update the last flush timestamp\n void this.storage.setLastFlushTimestamp(Date.now());\n\n // Convert metrics to the expected format\n const tags: DiagnosticsTags = {};\n tagRecords.forEach((record) => {\n tags[record.key] = record.value;\n });\n\n const counters: DiagnosticsCounters = {};\n counterRecords.forEach((record) => {\n counters[record.key] = record.value;\n });\n\n const histogram: DiagnosticsHistograms = {};\n histogramStatsRecords.forEach((stats) => {\n histogram[stats.key] = {\n count: stats.count,\n min: stats.min,\n max: stats.max,\n avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.\n };\n });\n\n const events: DiagnosticsEvent[] = eventRecords.map((record) => ({\n event_name: record.event_name,\n time: record.time,\n event_properties: record.event_properties,\n }));\n\n // Early return if all data collections are empty\n if (Object.keys(counters).length === 0 && Object.keys(histogram).length === 0 && events.length === 0) {\n return;\n }\n\n // Create flush payload\n const payload: FlushPayload = {\n tags,\n histogram,\n counters,\n events,\n };\n\n // Send payload to diagnostics server\n void this.fetch(payload);\n }\n\n /**\n * Send diagnostics data to the server\n */\n async fetch(payload: FlushPayload) {\n try {\n if (!getGlobalScope()) {\n throw new Error('DiagnosticsClient: Fetch is not supported');\n }\n\n const response = await fetch(this.serverUrl, {\n method: 'POST',\n headers: {\n 'X-ApiKey': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');\n return;\n }\n\n this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');\n } catch (error) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error);\n }\n }\n\n /**\n * Initialize flush interval logic.\n * Check if 5 minutes has passed since last flush, if so flush immediately.\n * Otherwise set a timer to flush when the interval is reached.\n */\n async initializeFlushInterval() {\n if (!this.storage) {\n return;\n }\n const now = Date.now();\n const lastFlushTimestamp = (await this.storage.getLastFlushTimestamp()) || -1;\n\n // If last flush timestamp is -1, it means this is a new client\n // Save current timestamp as the initial \"last flush timestamp\"\n // and schedule the flush timer\n if (lastFlushTimestamp === -1) {\n void this.storage.setLastFlushTimestamp(now);\n this._setFlushTimer(FLUSH_INTERVAL_MS);\n return;\n }\n\n const timeSinceLastFlush = now - lastFlushTimestamp;\n if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) {\n // More than 5 minutes has passed, flush immediately\n void this._flush();\n return;\n } else {\n // Set timer for remaining time\n this._setFlushTimer(FLUSH_INTERVAL_MS - timeSinceLastFlush);\n }\n }\n\n /**\n * Helper method to set flush timer with consistent error handling\n */\n private _setFlushTimer(delay: number) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, delay);\n }\n\n _setSampleRate(sampleRate: number): void {\n this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);\n this.config.sampleRate = sampleRate;\n this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);\n }\n}\n"]}
1
+ {"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAuB,MAAM,uBAAuB,CAAC;AAEhF,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,MAAM,CAAC,IAAM,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACjD,MAAM,CAAC,IAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC5D,MAAM,CAAC,IAAM,yBAAyB,GAAG,6DAA6D,CAAC;AACvG,MAAM,CAAC,IAAM,yBAAyB,GAAG,gEAAgE,CAAC;AAE1G,2BAA2B;AAC3B,MAAM,CAAC,IAAM,wBAAwB,GAAG,KAAK,CAAC,CAAC,4CAA4C;AAC3F,MAAM,CAAC,IAAM,+BAA+B,GAAG,EAAE,CAAC;AAkJlD;IA4BE,2BACE,MAAc,EACd,MAAe,EACf,UAAiC,EACjC,OAGC;QAJD,2BAAA,EAAA,iBAAiC;QAdnC,qBAAqB;QACrB,iBAAY,GAAoB,EAAE,CAAC;QACnC,qBAAgB,GAAwB,EAAE,CAA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AAC,UAAC,KAAK;gBACX,KAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YACjE,CAAC,CAAC;iBACD,OAAO,CAAC;gBACP,KAAI,CAAC,UAAU,GAAG,IAAI,CAAC;YACzB,CAAC,CAAC,CAAC;QACP,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,0CAAc,GAAd,UAAe,UAAkB;QAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2CAA2C,EAAE,UAAU,CAAC,CAAC;QAC3E,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC;QACpC,IAAI,CAAC,WAAW,GAAG,uBAAuB,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAC/G,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IACH,wBAAC;AAAD,CAAC,AA5UD,IA4UC","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\nimport { isTimestampInSampleTemp } from '../utils/sampling';\n\nexport const SAVE_INTERVAL_MS = 1000; // 1 second\nexport const FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nexport const DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';\nexport const DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';\n\n// In-memory storage limits\nexport const MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately\nexport const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;\n\n// === Core Data Types ===\n\n/**\n * Key-value pairs for environment/context information\n */\ntype DiagnosticsTags = Record<string, string>;\n\n/**\n * Numeric counters that can be incremented\n */\ntype DiagnosticsCounters = Record<string, number>;\n\n/**\n * Properties for diagnostic events\n */\ntype EventProperties = Record<string, any>;\n\n/**\n * Individual diagnostic event\n */\ninterface DiagnosticsEvent {\n readonly event_name: string;\n readonly time: number;\n readonly event_properties: EventProperties;\n}\n\n/**\n * Computed histogram statistics for final payload\n */\ninterface HistogramResult {\n readonly count: number;\n readonly min: number;\n readonly max: number;\n readonly avg: number;\n}\n\n/**\n * Internal histogram statistics with sum for efficient incremental updates\n */\nexport interface HistogramStats {\n count: number;\n min: number;\n max: number;\n sum: number; // Used for avg calculation\n}\n\n/**\n * Collection of histogram results keyed by histogram name\n */\ntype DiagnosticsHistograms = Record<string, HistogramResult>;\n\n/**\n * Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)\n */\ntype DiagnosticsHistogramStats = Record<string, HistogramStats>;\n\n// === Payload Types ===\n\n/**\n * Complete diagnostics payload sent to backend\n */\ninterface FlushPayload {\n readonly tags: DiagnosticsTags;\n readonly histogram: DiagnosticsHistograms;\n readonly counters: DiagnosticsCounters;\n readonly events: readonly DiagnosticsEvent[];\n}\n\n/**\n * Amplitude Diagnostics Client\n *\n * A client for collecting and managing diagnostics data including tags, counters,\n * histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.\n *\n * Key Features:\n * - IndexedDB storage\n * - Time-based persistent storage flush interval (5 minutes since last flush)\n * - 1 second time-based memory storage flush to persistent storage\n * - Histogram statistics calculation (min, max, avg)\n */\nexport interface IDiagnosticsClient {\n /**\n * Set or update a tag\n *\n * @example\n * ```typescript\n * // Set environment tags\n * diagnostics.setTag('library', 'amplitude-typescript/2.0.0');\n * diagnostics.setTag('user_agent', navigator.userAgent);\n * ```\n */\n setTag(name: string, value: string): void;\n\n /**\n * Increment a counter. If doesn't exist, create a counter and set value to 1\n *\n * @example\n * ```typescript\n * // Track counters\n * diagnostics.increment('analytics.fileNotFound');\n * diagnostics.increment('network.retry', 3);\n * ```\n */\n increment(name: string, size?: number): void;\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * // Record performance metrics\n * diagnostics.recordHistogram('sr.time', 5.2);\n * diagnostics.recordHistogram('network.latency', 150);\n * ```\n */\n recordHistogram(name: string, value: number): void;\n\n /**\n * Record an event\n *\n * @example\n * ```typescript\n * // Record diagnostic events\n * diagnostics.recordEvent('error', {\n * stack_trace: '...',\n * });\n * ```\n */\n recordEvent(name: string, properties: EventProperties): void;\n\n // Flush storage\n _flush(): void;\n\n /**\n * Sets the sample rate for diagnostics.\n *\n * @example\n * ```typescript\n * diagnostics.setSampleRate(0.5);\n * ```\n */\n _setSampleRate(sampleRate: number): void;\n}\n\nexport class DiagnosticsClient implements IDiagnosticsClient {\n storage?: IDiagnosticsStorage;\n logger: ILogger;\n serverUrl: string;\n apiKey: string;\n // Whether to track diagnostics data based on sample rate and enabled flag\n shouldTrack: boolean;\n config: {\n enabled: boolean;\n sampleRate: number;\n };\n /**\n * The timestamp when the diagnostics client was initialized.\n * Save in memory to keep lifecycle sample rate calculation consistency.\n */\n startTimestamp: number;\n\n // In-memory storages\n inMemoryTags: DiagnosticsTags = {};\n inMemoryCounters: DiagnosticsCounters = {};\n inMemoryHistograms: DiagnosticsHistogramStats = {};\n inMemoryEvents: DiagnosticsEvent[] = [];\n\n // Timer for 1-second persistence\n saveTimer: ReturnType<typeof setTimeout> | null = null;\n // Timer for flush interval\n flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n apiKey: string,\n logger: ILogger,\n serverZone: ServerZoneType = 'US',\n options?: {\n enabled?: boolean;\n sampleRate?: number;\n },\n ) {\n this.apiKey = apiKey;\n this.logger = logger;\n this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;\n\n this.logger.debug('DiagnosticsClient: Initializing with options', JSON.stringify(options, null, 2));\n // Diagnostics is enabled by default with sample rate of 0 (no sampling)\n this.config = { enabled: true, sampleRate: 0, ...options };\n this.startTimestamp = Date.now();\n this.shouldTrack = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n\n if (DiagnosticsStorage.isSupported()) {\n this.storage = new DiagnosticsStorage(apiKey, logger);\n } else {\n this.logger.debug('DiagnosticsClient: IndexedDB is not supported');\n }\n\n void this.initializeFlushInterval();\n }\n\n /**\n * Check if storage is available and tracking is enabled\n */\n isStorageAndTrackEnabled(): boolean {\n return Boolean(this.storage) && Boolean(this.shouldTrack);\n }\n\n setTag(name: string, value: string) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');\n return;\n }\n\n this.inMemoryTags[name] = value;\n this.startTimersIfNeeded();\n }\n\n increment(name: string, size = 1) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');\n return;\n }\n\n this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;\n this.startTimersIfNeeded();\n }\n\n recordHistogram(name: string, value: number) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');\n return;\n }\n\n const existing = this.inMemoryHistograms[name];\n if (existing) {\n // Update existing stats incrementally\n existing.count += 1;\n existing.min = Math.min(existing.min, value);\n existing.max = Math.max(existing.max, value);\n existing.sum += value;\n } else {\n // Create new stats\n this.inMemoryHistograms[name] = {\n count: 1,\n min: value,\n max: value,\n sum: value,\n };\n }\n this.startTimersIfNeeded();\n }\n\n recordEvent(name: string, properties: EventProperties) {\n if (!this.isStorageAndTrackEnabled()) {\n return;\n }\n\n if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');\n return;\n }\n\n this.inMemoryEvents.push({\n event_name: name,\n time: Date.now(),\n event_properties: properties,\n });\n this.startTimersIfNeeded();\n }\n\n startTimersIfNeeded() {\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveAllDataToStorage()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);\n })\n .finally(() => {\n this.saveTimer = null;\n });\n }, SAVE_INTERVAL_MS);\n }\n\n if (!this.flushTimer) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n async saveAllDataToStorage() {\n if (!this.storage) {\n return;\n }\n const tagsToSave = { ...this.inMemoryTags };\n const countersToSave = { ...this.inMemoryCounters };\n const histogramsToSave = { ...this.inMemoryHistograms };\n const eventsToSave = [...this.inMemoryEvents];\n\n this.inMemoryEvents = [];\n this.inMemoryTags = {};\n this.inMemoryCounters = {};\n this.inMemoryHistograms = {};\n\n await Promise.all([\n this.storage.setTags(tagsToSave),\n this.storage.incrementCounters(countersToSave),\n this.storage.setHistogramStats(histogramsToSave),\n this.storage.addEventRecords(eventsToSave),\n ]);\n }\n\n async _flush() {\n if (!this.storage) {\n return;\n }\n\n await this.saveAllDataToStorage();\n this.saveTimer = null;\n this.flushTimer = null;\n\n // Get all data from storage and clear it\n const {\n tags: tagRecords,\n counters: counterRecords,\n histogramStats: histogramStatsRecords,\n events: eventRecords,\n } = await this.storage.getAllAndClear();\n\n // Update the last flush timestamp\n void this.storage.setLastFlushTimestamp(Date.now());\n\n // Convert metrics to the expected format\n const tags: DiagnosticsTags = {};\n tagRecords.forEach((record) => {\n tags[record.key] = record.value;\n });\n\n const counters: DiagnosticsCounters = {};\n counterRecords.forEach((record) => {\n counters[record.key] = record.value;\n });\n\n const histogram: DiagnosticsHistograms = {};\n histogramStatsRecords.forEach((stats) => {\n histogram[stats.key] = {\n count: stats.count,\n min: stats.min,\n max: stats.max,\n avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.\n };\n });\n\n const events: DiagnosticsEvent[] = eventRecords.map((record) => ({\n event_name: record.event_name,\n time: record.time,\n event_properties: record.event_properties,\n }));\n\n // Early return if all data collections are empty\n if (Object.keys(counters).length === 0 && Object.keys(histogram).length === 0 && events.length === 0) {\n return;\n }\n\n // Create flush payload\n const payload: FlushPayload = {\n tags,\n histogram,\n counters,\n events,\n };\n\n // Send payload to diagnostics server\n void this.fetch(payload);\n }\n\n /**\n * Send diagnostics data to the server\n */\n async fetch(payload: FlushPayload) {\n try {\n if (!getGlobalScope()) {\n throw new Error('DiagnosticsClient: Fetch is not supported');\n }\n\n const response = await fetch(this.serverUrl, {\n method: 'POST',\n headers: {\n 'X-ApiKey': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');\n return;\n }\n\n this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');\n } catch (error) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error);\n }\n }\n\n /**\n * Initialize flush interval logic.\n * Check if 5 minutes has passed since last flush, if so flush immediately.\n * Otherwise set a timer to flush when the interval is reached.\n */\n async initializeFlushInterval() {\n if (!this.storage) {\n return;\n }\n const now = Date.now();\n const lastFlushTimestamp = (await this.storage.getLastFlushTimestamp()) || -1;\n\n // If last flush timestamp is -1, it means this is a new client\n // Save current timestamp as the initial \"last flush timestamp\"\n // and schedule the flush timer\n if (lastFlushTimestamp === -1) {\n void this.storage.setLastFlushTimestamp(now);\n this._setFlushTimer(FLUSH_INTERVAL_MS);\n return;\n }\n\n const timeSinceLastFlush = now - lastFlushTimestamp;\n if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) {\n // More than 5 minutes has passed, flush immediately\n void this._flush();\n return;\n } else {\n // Set timer for remaining time\n this._setFlushTimer(FLUSH_INTERVAL_MS - timeSinceLastFlush);\n }\n }\n\n /**\n * Helper method to set flush timer with consistent error handling\n */\n private _setFlushTimer(delay: number) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, delay);\n }\n\n _setSampleRate(sampleRate: number): void {\n this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);\n this.config.sampleRate = sampleRate;\n this.shouldTrack = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
1
  export declare const generateHashCode: (str: string) => number;
2
2
  export declare const isTimestampInSample: (timestamp: string | number, sampleRate: number) => boolean;
3
+ export declare const isTimestampInSampleTemp: (timestamp: string | number, sampleRate: number) => boolean;
3
4
  //# sourceMappingURL=sampling.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sampling.d.ts","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,QAAkB,MAAM,WASpD,CAAC;AAEF,eAAO,MAAM,mBAAmB,cAAwB,MAAM,GAAG,MAAM,cAAc,MAAM,YAM1F,CAAC"}
1
+ {"version":3,"file":"sampling.d.ts","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,QAAkB,MAAM,WASpD,CAAC;AAEF,eAAO,MAAM,mBAAmB,cAAwB,MAAM,GAAG,MAAM,cAAc,MAAM,YAM1F,CAAC;AAIF,eAAO,MAAM,uBAAuB,cAAwB,MAAM,GAAG,MAAM,cAAc,MAAM,YAM9F,CAAC"}
@@ -16,4 +16,13 @@ export var isTimestampInSample = function (timestamp, sampleRate) {
16
16
  var mod = absHashMultiply % 1000000;
17
17
  return mod / 1000000 < sampleRate;
18
18
  };
19
+ // TODO(xinyi): replace the temp one in diagnostics client after the fix
20
+ // istanbul ignore next
21
+ export var isTimestampInSampleTemp = function (timestamp, sampleRate) {
22
+ var hashNumber = generateHashCode(timestamp.toString());
23
+ var absHash = Math.abs(hashNumber);
24
+ var absHashMultiply = absHash * 31;
25
+ var mod = absHashMultiply % 100000;
26
+ return mod / 100000 < sampleRate;
27
+ };
19
28
  //# sourceMappingURL=sampling.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,gBAAgB,GAAG,UAAU,GAAW;IACnD,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAM,GAAG,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC;QAChC,IAAI,IAAI,CAAC,CAAC;KACX;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAEF,MAAM,CAAC,IAAM,mBAAmB,GAAG,UAAU,SAA0B,EAAE,UAAkB;IACzF,IAAM,UAAU,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC1D,IAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACrC,IAAM,eAAe,GAAG,OAAO,GAAG,EAAE,CAAC;IACrC,IAAM,GAAG,GAAG,eAAe,GAAG,OAAO,CAAC;IACtC,OAAO,GAAG,GAAG,OAAO,GAAG,UAAU,CAAC;AACpC,CAAC,CAAC","sourcesContent":["export const generateHashCode = function (str: string) {\n let hash = 0;\n if (str.length === 0) return hash;\n for (let i = 0; i < str.length; i++) {\n const chr = str.charCodeAt(i);\n hash = (hash << 5) - hash + chr;\n hash |= 0;\n }\n return hash;\n};\n\nexport const isTimestampInSample = function (timestamp: string | number, sampleRate: number) {\n const hashNumber = generateHashCode(timestamp.toString());\n const absHash = Math.abs(hashNumber);\n const absHashMultiply = absHash * 31;\n const mod = absHashMultiply % 1000000;\n return mod / 1000000 < sampleRate;\n};\n"]}
1
+ {"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../../src/utils/sampling.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,gBAAgB,GAAG,UAAU,GAAW;IACnD,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAM,GAAG,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC;QAChC,IAAI,IAAI,CAAC,CAAC;KACX;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAEF,MAAM,CAAC,IAAM,mBAAmB,GAAG,UAAU,SAA0B,EAAE,UAAkB;IACzF,IAAM,UAAU,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC1D,IAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACrC,IAAM,eAAe,GAAG,OAAO,GAAG,EAAE,CAAC;IACrC,IAAM,GAAG,GAAG,eAAe,GAAG,OAAO,CAAC;IACtC,OAAO,GAAG,GAAG,OAAO,GAAG,UAAU,CAAC;AACpC,CAAC,CAAC;AAEF,wEAAwE;AACxE,uBAAuB;AACvB,MAAM,CAAC,IAAM,uBAAuB,GAAG,UAAU,SAA0B,EAAE,UAAkB;IAC7F,IAAM,UAAU,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC1D,IAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACrC,IAAM,eAAe,GAAG,OAAO,GAAG,EAAE,CAAC;IACrC,IAAM,GAAG,GAAG,eAAe,GAAG,MAAM,CAAC;IACrC,OAAO,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AACnC,CAAC,CAAC","sourcesContent":["export const generateHashCode = function (str: string) {\n let hash = 0;\n if (str.length === 0) return hash;\n for (let i = 0; i < str.length; i++) {\n const chr = str.charCodeAt(i);\n hash = (hash << 5) - hash + chr;\n hash |= 0;\n }\n return hash;\n};\n\nexport const isTimestampInSample = function (timestamp: string | number, sampleRate: number) {\n const hashNumber = generateHashCode(timestamp.toString());\n const absHash = Math.abs(hashNumber);\n const absHashMultiply = absHash * 31;\n const mod = absHashMultiply % 1000000;\n return mod / 1000000 < sampleRate;\n};\n\n// TODO(xinyi): replace the temp one in diagnostics client after the fix\n// istanbul ignore next\nexport const isTimestampInSampleTemp = function (timestamp: string | number, sampleRate: number) {\n const hashNumber = generateHashCode(timestamp.toString());\n const absHash = Math.abs(hashNumber);\n const absHashMultiply = absHash * 31;\n const mod = absHashMultiply % 100000;\n return mod / 100000 < sampleRate;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amplitude/analytics-core",
3
- "version": "2.27.0",
3
+ "version": "2.27.1",
4
4
  "description": "",
5
5
  "author": "Amplitude Inc",
6
6
  "homepage": "https://github.com/amplitude/Amplitude-TypeScript",
@@ -42,5 +42,5 @@
42
42
  "files": [
43
43
  "lib"
44
44
  ],
45
- "gitHead": "9ad8b4e5050a8c1e02617661ab41ff301c003da2"
45
+ "gitHead": "131c24c2f551a68b037157cca2f0b77857608f42"
46
46
  }