@amplitude/analytics-core 2.56.0-video-analytics-2.0 → 2.56.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/lib/cjs/analytics-connector.d.ts.map +1 -1
- package/lib/cjs/analytics-connector.js +2 -3
- package/lib/cjs/analytics-connector.js.map +1 -1
- package/lib/cjs/config.d.ts +0 -1
- package/lib/cjs/config.d.ts.map +1 -1
- package/lib/cjs/config.js +2 -2
- package/lib/cjs/config.js.map +1 -1
- package/lib/cjs/index.d.ts +1 -0
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js +5 -3
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/observers/video.d.ts +2 -4
- package/lib/cjs/observers/video.d.ts.map +1 -1
- package/lib/cjs/observers/video.js +2 -30
- package/lib/cjs/observers/video.js.map +1 -1
- package/lib/cjs/plugins/destination.d.ts +1 -21
- package/lib/cjs/plugins/destination.d.ts.map +1 -1
- package/lib/cjs/plugins/destination.js +25 -178
- package/lib/cjs/plugins/destination.js.map +1 -1
- package/lib/cjs/remote-config/remote-config.d.ts +2 -1
- package/lib/cjs/remote-config/remote-config.d.ts.map +1 -1
- package/lib/cjs/remote-config/remote-config.js +4 -2
- package/lib/cjs/remote-config/remote-config.js.map +1 -1
- package/lib/cjs/types/config/core-config.d.ts +0 -5
- package/lib/cjs/types/config/core-config.d.ts.map +1 -1
- package/lib/cjs/types/config/core-config.js.map +1 -1
- package/lib/cjs/types/event/base-event.d.ts +0 -1
- package/lib/cjs/types/event/base-event.d.ts.map +1 -1
- package/lib/cjs/types/event/base-event.js.map +1 -1
- package/lib/cjs/types/event/event.d.ts +1 -4
- package/lib/cjs/types/event/event.d.ts.map +1 -1
- package/lib/cjs/types/event/event.js.map +1 -1
- package/lib/cjs/types/payload.d.ts +0 -5
- package/lib/cjs/types/payload.d.ts.map +1 -1
- package/lib/cjs/types/payload.js.map +1 -1
- package/lib/cjs/utils/instance-name.d.ts +2 -0
- package/lib/cjs/utils/instance-name.d.ts.map +1 -0
- package/lib/cjs/utils/instance-name.js +9 -0
- package/lib/cjs/utils/instance-name.js.map +1 -0
- package/lib/cjs/video-analytics/track-video.d.ts +1 -1
- package/lib/cjs/video-analytics/track-video.js.map +1 -1
- package/lib/esm/analytics-connector.d.ts.map +1 -1
- package/lib/esm/analytics-connector.js +2 -3
- package/lib/esm/analytics-connector.js.map +1 -1
- package/lib/esm/config.d.ts +0 -1
- package/lib/esm/config.d.ts.map +1 -1
- package/lib/esm/config.js +2 -2
- package/lib/esm/config.js.map +1 -1
- package/lib/esm/index.d.ts +1 -0
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js +1 -0
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/observers/video.d.ts +2 -4
- package/lib/esm/observers/video.d.ts.map +1 -1
- package/lib/esm/observers/video.js +2 -30
- package/lib/esm/observers/video.js.map +1 -1
- package/lib/esm/plugins/destination.d.ts +1 -21
- package/lib/esm/plugins/destination.d.ts.map +1 -1
- package/lib/esm/plugins/destination.js +26 -179
- package/lib/esm/plugins/destination.js.map +1 -1
- package/lib/esm/remote-config/remote-config.d.ts +2 -1
- package/lib/esm/remote-config/remote-config.d.ts.map +1 -1
- package/lib/esm/remote-config/remote-config.js +4 -2
- package/lib/esm/remote-config/remote-config.js.map +1 -1
- package/lib/esm/types/config/core-config.d.ts +0 -5
- package/lib/esm/types/config/core-config.d.ts.map +1 -1
- package/lib/esm/types/config/core-config.js.map +1 -1
- package/lib/esm/types/event/base-event.d.ts +0 -1
- package/lib/esm/types/event/base-event.d.ts.map +1 -1
- package/lib/esm/types/event/base-event.js.map +1 -1
- package/lib/esm/types/event/event.d.ts +1 -4
- package/lib/esm/types/event/event.d.ts.map +1 -1
- package/lib/esm/types/event/event.js.map +1 -1
- package/lib/esm/types/payload.d.ts +0 -5
- package/lib/esm/types/payload.d.ts.map +1 -1
- package/lib/esm/types/payload.js.map +1 -1
- package/lib/esm/utils/instance-name.d.ts +2 -0
- package/lib/esm/utils/instance-name.d.ts.map +1 -0
- package/lib/esm/utils/instance-name.js +5 -0
- package/lib/esm/utils/instance-name.js.map +1 -0
- package/lib/esm/video-analytics/track-video.d.ts +1 -1
- package/lib/esm/video-analytics/track-video.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"destination.js","sourceRoot":"","sources":["../../../src/plugins/destination.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAQzC,OAAO,EACL,eAAe,EACf,4BAA4B,EAC5B,uBAAuB,EACvB,eAAe,EACf,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,EACpB,6BAA6B,EAC7B,uBAAuB,EACvB,cAAc,GACf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAIrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAa/C,IAAM,6BAA6B,GAAG,IAAI,GAAG,CAAC;IAC5C,oBAAoB;IACpB,uBAAuB;IACvB,0BAA0B;IAC1B,6BAA6B;CAC9B,CAAC,CAAC;AAEH,IAAM,kCAAkC,GAAG,UAAC,SAAiB,EAAE,4BAAoC;IAApC,6CAAA,EAAA,oCAAoC;IACjG,IAAI,6BAA6B,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;QAChD,OAAO,IAAI,CAAC;KACb;IAED,OAAO,4BAA4B,CAAC;AACtC,CAAC,CAAC;AAEF,SAAS,eAAe,CA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AAC;QAEF,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAC,OAAO;;YACzB,IAAI,CAAA,MAAA,OAAO,CAAC,KAAK,CAAC,KAAK,0CAAE,WAAW,KAAI,qBAAqB,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE;gBAC1F,OAAO,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC;aACxC;QACH,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;IACH,kBAAC;AAAD,CAAC,AAhgBD,IAggBC","sourcesContent":["import { DestinationPlugin } from '../types/plugin';\nimport { DelayedEvent, Event } from '../types/event/event';\nimport { Delay } from '../types/event/base-event';\nimport { Result } from '../types/result';\nimport { Status } from '../types/status';\nimport {\n Response,\n InvalidResponse,\n PayloadTooLargeResponse,\n RateLimitResponse,\n SuccessResponse,\n} from '../types/response';\nimport {\n INVALID_API_KEY,\n MAX_RETRIES_EXCEEDED_MESSAGE,\n MISSING_API_KEY_MESSAGE,\n SUCCESS_MESSAGE,\n UNEXPECTED_ERROR_MESSAGE,\n} from '../types/messages';\nimport {\n AMPLITUDE_BATCH_SERVER_URL,\n AMPLITUDE_SERVER_URL,\n EU_AMPLITUDE_BATCH_SERVER_URL,\n EU_AMPLITUDE_SERVER_URL,\n STORAGE_PREFIX,\n} from '../types/constants';\nimport { chunk } from '../utils/chunk';\nimport { buildResult } from '../utils/result-builder';\nimport { createServerConfig, RequestMetadata } from '../config';\nimport { UUID } from '../utils/uuid';\nimport { IConfig } from '../types/config/core-config';\nimport { EventCallback } from '../types/event-callback';\nimport { IDiagnosticsClient } from '../diagnostics/diagnostics-client';\nimport { isSuccessStatusCode } from '../utils/status-code';\nimport { getStacktrace } from '../utils/debug';\nimport { DelayedPayload, Payload } from '../types/payload';\n\nexport interface Context {\n event: Event;\n attempts: number;\n callback: EventCallback;\n timeout: number;\n delay?: Delay;\n}\n\ntype DelayedEventsById = Record<string, Context[]>;\n\nconst DEFAULT_AMPLITUDE_SERVER_URLS = new Set([\n AMPLITUDE_SERVER_URL,\n EU_AMPLITUDE_SERVER_URL,\n AMPLITUDE_BATCH_SERVER_URL,\n EU_AMPLITUDE_BATCH_SERVER_URL,\n]);\n\nconst shouldCompressUploadBodyForRequest = (serverUrl: string, enableRequestBodyCompression = false) => {\n if (DEFAULT_AMPLITUDE_SERVER_URLS.has(serverUrl)) {\n return true;\n }\n\n return enableRequestBodyCompression;\n};\n\nfunction getErrorMessage(error: unknown) {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nfunction isDelayedEvent(event: Event) {\n return event.delay !== undefined && event.delay !== null;\n}\n\nexport function getResponseBodyString(res: Response) {\n let responseBodyString = '';\n try {\n if ('body' in res) {\n responseBodyString = JSON.stringify(res.body, null, 2);\n }\n } catch {\n // to avoid crash, but don't care about the error, add comment to avoid empty block lint error\n }\n return responseBodyString;\n}\n\nexport class Destination implements DestinationPlugin {\n name = 'amplitude';\n type = 'destination' as const;\n\n retryTimeout = 1000;\n throttleTimeout = 30000;\n storageKey = '';\n // this.config is defined in setup() which will always be called first\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // Indicator of whether events that are scheduled (but not flushed yet).\n // When flush:\n // 1. assign `scheduleId` to `flushId`\n // 2. set `scheduleId` to null\n scheduleId: ReturnType<typeof setTimeout> | null = null;\n // Timeout in milliseconds of current schedule\n scheduledTimeout = 0;\n // Indicator of whether current flush resolves.\n // When flush resolves, set `flushId` to null\n flushId: ReturnType<typeof setTimeout> | null = null;\n queue: Context[] = [];\n diagnosticsClient: IDiagnosticsClient | undefined;\n inFlightDelayedEvents: Record<string, boolean> = {};\n\n constructor(context?: { diagnosticsClient: IDiagnosticsClient }) {\n this.diagnosticsClient = context?.diagnosticsClient;\n }\n\n async setup(config: IConfig): Promise<undefined> {\n this.config = config;\n\n this.storageKey = `${STORAGE_PREFIX}_${this.config.apiKey.substring(0, 10)}`;\n const unsent = await this.config.storageProvider?.get(this.storageKey);\n if (unsent && unsent.length > 0) {\n void Promise.all(unsent.map((event: Event) => this.execute(event))).catch();\n }\n\n return Promise.resolve(undefined);\n }\n\n execute(event: Event): Promise<Result> {\n // Assign insert_id for dropping invalid event later\n if (!event.insert_id) {\n event.insert_id = UUID();\n }\n\n return new Promise((resolve) => {\n const context = {\n event,\n attempts: 0,\n callback: (result: Result) => resolve(result),\n timeout: 0,\n };\n if (isDelayedEvent(event)) {\n this.removeStaleDelayedEvents(event as DelayedEvent);\n }\n this.queue.push(context);\n this.schedule(this.config.flushIntervalMillis);\n this.saveEvents();\n });\n }\n\n /**\n * If a stale delayed event is sitting in the queue, and it is not in flight,\n * remove it and resolve as \"stale\" with status code 0.\n *\n * If a matching delayed event is already in flight, clone `delay` onto the\n * incoming event and set skipRemoval so the in-flight send does not drop the\n * replacement. Earlier replacements waiting on the same send are discarded\n * as stale so only the latest copy remains.\n * @param incomingEvent { Event } the new event to check old events against\n * @returns void\n */\n private removeStaleDelayedEvents(incomingEvent: DelayedEvent) {\n try {\n /* istanbul ignore next */\n this.queue = this.queue.filter((context) => {\n const targetEvent = context.event;\n\n if (!isDelayedEvent(targetEvent)) {\n return true;\n }\n\n // target event matches the incoming event if it has the same insert_id and delay id\n // as the incoming event (the incoming event takes precedence)\n const isMatchingEvent =\n targetEvent.delay!.id === incomingEvent.delay.id && targetEvent.insert_id === incomingEvent.insert_id;\n\n // do not filter out non matching events\n if (!isMatchingEvent) {\n return true;\n }\n\n // are there delayed events for this delay id currently in flight?\n const areDelayedEventsInFlight = this.inFlightDelayedEvents[incomingEvent.delay.id];\n\n // if they are, then protect the target event from being removed from the queue\n // after the in-flight send completes by setting skipRemoval on the incoming event\n if (areDelayedEventsInFlight) {\n incomingEvent.delay = { ...incomingEvent.delay, skipRemoval: true };\n }\n\n // if events are not in flight, or if the target event is marked to skipRemoval,\n // then the incoming event supersedes the target event, and target event should be dropped\n if (!areDelayedEventsInFlight || targetEvent.delay?.skipRemoval) {\n context.callback(buildResult(targetEvent, 0, 'Stale event overwritten'));\n return false;\n }\n\n return true;\n });\n /* istanbul ignore next */\n } catch (e) {\n // swallow error\n }\n }\n\n removeEventsExceedFlushMaxRetries(list: Context[]) {\n return list.filter((context) => {\n context.attempts += 1;\n if (context.attempts < this.config.flushMaxRetries) {\n return true;\n }\n void this.fulfillRequest([context], 500, MAX_RETRIES_EXCEEDED_MESSAGE);\n return false;\n });\n }\n\n scheduleEvents(list: Context[]) {\n list.forEach((context) => {\n this.schedule(context.timeout === 0 ? this.config.flushIntervalMillis : context.timeout);\n });\n }\n\n // Schedule a flush in timeout when\n // 1. No schedule\n // 2. Timeout greater than existing timeout.\n // This makes sure that when throttled, no flush when throttle timeout expires.\n schedule(timeout: number) {\n if (this.config.offline) {\n return;\n }\n\n if (this.scheduleId === null || (this.scheduleId && timeout > this.scheduledTimeout)) {\n if (this.scheduleId) {\n clearTimeout(this.scheduleId);\n }\n this.scheduledTimeout = timeout;\n this.scheduleId = setTimeout(() => {\n this.queue = this.queue.map((context) => {\n context.timeout = 0;\n return context;\n });\n void this.flush(true);\n }, timeout);\n return;\n }\n }\n\n // Mark current schedule is flushed.\n resetSchedule() {\n this.scheduleId = null;\n this.scheduledTimeout = 0;\n }\n\n // Flush all events regardless of their timeout\n async flush(useRetry = false) {\n // Skip flush if offline\n if (this.config.offline) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush while offline.');\n return;\n }\n\n if (this.flushId) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush because previous flush has not resolved.');\n return;\n }\n\n this.flushId = this.scheduleId;\n this.resetSchedule();\n\n const list: Context[] = [];\n const delayed: DelayedEventsById = {};\n const later: Context[] = [];\n this.queue.forEach((context) => {\n if (context.timeout !== 0) {\n later.push(context);\n } else if (context.event.delay?.id) {\n const delay = context.event.delay;\n delayed[delay.id] = delayed[delay.id] || [];\n delayed[delay.id].push(context);\n } else {\n list.push(context);\n }\n });\n\n const batches = chunk(list, this.config.flushQueueSize);\n\n // Promise.all() doesn't guarantee resolve order.\n // Sequentially resolve to make sure backend receives events in order\n const regularEventBatch = batches.reduce(async (promise, batch) => {\n await promise;\n return await this.send(batch, useRetry);\n }, Promise.resolve());\n const eventPromises = [regularEventBatch];\n\n if (Object.keys(delayed).length > 0) {\n eventPromises.push(this.sendDelayedEvents(delayed, useRetry));\n }\n\n await Promise.all(eventPromises);\n\n // Mark current flush is done\n this.flushId = null;\n\n this.scheduleEvents(this.queue);\n }\n\n sendDelayedEvents(delayed: DelayedEventsById, useRetry: boolean) {\n const eventPromises = [];\n try {\n for (const [delayId, contexts] of Object.entries(delayed)) {\n this.inFlightDelayedEvents[delayId] = true;\n const delayedEventsSend = this.send(contexts, useRetry, true);\n eventPromises.push(delayedEventsSend);\n delayedEventsSend.finally(() => {\n delete this.inFlightDelayedEvents[delayId];\n });\n }\n } catch (e) {\n // swallow error\n }\n return eventPromises.reduce(async (promise, batch) => {\n await promise;\n return await batch;\n }, Promise.resolve());\n }\n\n translatePayloadToDelayedPayload(payload: Payload & Partial<DelayedPayload>, list: Context[]): void {\n const delayedEvents: Event[] = [];\n const instantEvents: Event[] = [];\n const delayedContexts: Context[] = [];\n const instantContexts: Context[] = [];\n\n list.forEach((context, index) => {\n if (context.event.delay!.timeout) {\n delayedEvents.push(payload.events[index]);\n delayedContexts.push(context);\n } else {\n instantEvents.push(payload.events[index]);\n instantContexts.push(context);\n }\n });\n\n list.splice(0, list.length, ...delayedContexts, ...instantContexts);\n\n /* istanbul ignore next */\n payload.timeout = delayedContexts[0]?.event.delay!.timeout ?? 0;\n payload.id = list[0].event.delay!.id;\n payload.events = delayedEvents;\n payload.instant_events = instantEvents;\n }\n\n async send(list: Context[], useRetry = true, delay?: boolean) {\n if (!this.config.apiKey) {\n return this.fulfillRequest(list, 400, MISSING_API_KEY_MESSAGE);\n }\n\n const payload: Payload = {\n api_key: this.config.apiKey,\n events: list.map((context) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { extra, delay, ...eventWithoutExtra } = context.event;\n return eventWithoutExtra;\n }),\n options: {\n min_id_length: this.config.minIdLength,\n },\n client_upload_time: new Date().toISOString(),\n request_metadata: delay ? undefined : this.config.requestMetadata,\n };\n if (!delay) {\n this.config.requestMetadata = new RequestMetadata();\n }\n\n try {\n let { serverUrl } = createServerConfig(this.config.serverUrl, this.config.serverZone, this.config.useBatch);\n let shouldCompressUploadBody = shouldCompressUploadBodyForRequest(\n serverUrl,\n this.config.enableRequestBodyCompression,\n );\n if (delay) {\n serverUrl = this.config.delayedEventsServerUrl || `${serverUrl}/delayed`;\n this.translatePayloadToDelayedPayload(payload, list);\n shouldCompressUploadBody = false; // delayed events doesn't support compression\n }\n const res = await this.config.transportProvider.send(serverUrl, payload, shouldCompressUploadBody);\n if (res === null) {\n this.fulfillRequest(list, 0, UNEXPECTED_ERROR_MESSAGE);\n return;\n }\n if (!useRetry) {\n if ('body' in res) {\n this.fulfillRequest(list, res.statusCode, `${res.status}: ${getResponseBodyString(res)}`);\n } else {\n this.fulfillRequest(list, res.statusCode, res.status);\n }\n return;\n }\n this.handleResponse(res, list);\n } catch (e) {\n const errorMessage = getErrorMessage(e);\n this.config.loggerProvider.error(errorMessage);\n\n this.diagnosticsClient?.recordEvent('analytics.events.unsuccessful.from.catch.error', {\n events: list.map((context) => context.event.event_type),\n message: errorMessage,\n stack_trace: getStacktrace(),\n });\n\n this.handleResponse({ status: Status.Failed, statusCode: 0 }, list);\n }\n }\n\n handleResponse(res: Response, list: Context[]) {\n if (!isSuccessStatusCode(res.statusCode)) {\n this.diagnosticsClient?.recordEvent('analytics.events.unsuccessful', {\n events: list.map((context) => context.event.event_type),\n code: res.statusCode,\n status: res.status,\n body: getResponseBodyString(res),\n stack_trace: getStacktrace(),\n });\n }\n\n const { status } = res;\n\n switch (status) {\n case Status.Success: {\n this.handleSuccessResponse(res, list);\n break;\n }\n case Status.Invalid: {\n this.handleInvalidResponse(res, list);\n break;\n }\n case Status.PayloadTooLarge: {\n this.handlePayloadTooLargeResponse(res, list);\n break;\n }\n case Status.RateLimit: {\n this.handleRateLimitResponse(res, list);\n break;\n }\n default: {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(`{code: 0, error: \"Status '${status}' provided for ${list.length} events\"}`);\n this.handleOtherResponse(list);\n break;\n }\n }\n }\n\n handleSuccessResponse(res: SuccessResponse, list: Context[]) {\n this.fulfillRequest(list, res.statusCode, SUCCESS_MESSAGE);\n }\n\n handleInvalidResponse(res: InvalidResponse, list: Context[]) {\n if (res.body.missingField || res.body.error.startsWith(INVALID_API_KEY)) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n const dropIndex = [\n ...Object.values(res.body.eventsWithInvalidFields),\n ...Object.values(res.body.eventsWithMissingFields),\n ...Object.values(res.body.eventsWithInvalidIdLengths),\n ...res.body.silencedEvents,\n ].flat();\n const dropIndexSet = new Set(dropIndex);\n\n const retry = list.filter((context, index) => {\n if (dropIndexSet.has(index)) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handlePayloadTooLargeResponse(res: PayloadTooLargeResponse, list: Context[]) {\n if (list.length === 1) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n\n this.config.flushQueueSize /= 2;\n\n const tryable = this.removeEventsExceedFlushMaxRetries(list);\n this.scheduleEvents(tryable);\n }\n\n handleRateLimitResponse(res: RateLimitResponse, list: Context[]) {\n const dropUserIds = Object.keys(res.body.exceededDailyQuotaUsers);\n const dropDeviceIds = Object.keys(res.body.exceededDailyQuotaDevices);\n const throttledIndex = res.body.throttledEvents;\n const dropUserIdsSet = new Set(dropUserIds);\n const dropDeviceIdsSet = new Set(dropDeviceIds);\n const throttledIndexSet = new Set(throttledIndex);\n\n const retry = list.filter((context, index) => {\n if (\n (context.event.user_id && dropUserIdsSet.has(context.event.user_id)) ||\n (context.event.device_id && dropDeviceIdsSet.has(context.event.device_id))\n ) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n if (throttledIndexSet.has(index)) {\n context.timeout = this.throttleTimeout;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handleOtherResponse(list: Context[]) {\n const later = list.map((context) => {\n context.timeout = context.attempts * this.retryTimeout;\n return context;\n });\n\n const tryable = this.removeEventsExceedFlushMaxRetries(later);\n this.scheduleEvents(tryable);\n }\n\n fulfillRequest(list: Context[], code: number, message: string) {\n // Record diagnostics for dropped events (non-success status codes)\n if (!isSuccessStatusCode(code)) {\n this.diagnosticsClient?.increment('analytics.events.dropped', list.length);\n this.diagnosticsClient?.recordEvent('analytics.events.dropped', {\n events: list.map((context) => context.event.event_type),\n code: code,\n message: message,\n stack_trace: getStacktrace(),\n });\n } else {\n this.diagnosticsClient?.increment('analytics.events.sent', list.length);\n }\n this.removeEvents(list);\n list.forEach((context) => context.callback(buildResult(context.event, code, message)));\n }\n\n /**\n * This is called on\n * 1) new events are added to queue; or\n * 2) response comes back for a request\n *\n * Update the event storage based on the queue\n */\n saveEvents() {\n if (!this.config.storageProvider) {\n return;\n }\n\n const updatedEvents = this.queue.map((context) => context.event);\n void this.config.storageProvider.set(this.storageKey, updatedEvents);\n }\n\n /**\n * This is called on response comes back for a request\n */\n removeEvents(eventsToRemove: Context[]) {\n const insertIdsBeingRemoved = new Set(eventsToRemove.map((context) => context.event.insert_id));\n\n this.queue = this.queue.filter(\n (queuedContext) =>\n !eventsToRemove.some(\n (context) =>\n context.event.insert_id === queuedContext.event.insert_id && !queuedContext.event.delay?.skipRemoval,\n ),\n );\n\n this.queue.forEach((context) => {\n if (context.event.delay?.skipRemoval && insertIdsBeingRemoved.has(context.event.insert_id)) {\n delete context.event.delay.skipRemoval;\n }\n });\n\n this.saveEvents();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"destination.js","sourceRoot":"","sources":["../../../src/plugins/destination.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAQzC,OAAO,EACL,eAAe,EACf,4BAA4B,EAC5B,uBAAuB,EACvB,eAAe,EACf,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,EACpB,6BAA6B,EAC7B,uBAAuB,EACvB,cAAc,GACf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAIrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAS/C,IAAM,6BAA6B,GAAG,IAAI,GAAG,CAAC;IAC5C,oBAAoB;IACpB,uBAAuB;IACvB,0BAA0B;IAC1B,6BAA6B;CAC9B,CAAC,CAAC;AAEH,IAAM,kCAAkC,GAAG,UAAC,SAAiB,EAAE,4BAAoC;IAApC,6CAAA,EAAA,oCAAoC;IACjG,IAAI,6BAA6B,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;QAChD,OAAO,IAAI,CAAC;KACb;IAED,OAAO,4BAA4B,CAAC;AACtC,CAAC,CAAC;AAEF,SAAS,eAAe,CAAC,KAAc;IACrC,IAAI,KAAK,YAAY,KAAK;QAAE,O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ACH,kCAAY,GAAZ,UAAa,cAAyB;QACpC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAC5B,UAAC,aAAa,IAAK,OAAA,CAAC,cAAc,CAAC,IAAI,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,KAAK,CAAC,SAAS,KAAK,aAAa,CAAC,KAAK,CAAC,SAAS,EAAzD,CAAyD,CAAC,EAA5F,CAA4F,CAChH,CAAC;QAEF,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;IACH,kBAAC;AAAD,CAAC,AAnXD,IAmXC","sourcesContent":["import { DestinationPlugin } from '../types/plugin';\nimport { Event } from '../types/event/event';\nimport { Result } from '../types/result';\nimport { Status } from '../types/status';\nimport {\n Response,\n InvalidResponse,\n PayloadTooLargeResponse,\n RateLimitResponse,\n SuccessResponse,\n} from '../types/response';\nimport {\n INVALID_API_KEY,\n MAX_RETRIES_EXCEEDED_MESSAGE,\n MISSING_API_KEY_MESSAGE,\n SUCCESS_MESSAGE,\n UNEXPECTED_ERROR_MESSAGE,\n} from '../types/messages';\nimport {\n AMPLITUDE_BATCH_SERVER_URL,\n AMPLITUDE_SERVER_URL,\n EU_AMPLITUDE_BATCH_SERVER_URL,\n EU_AMPLITUDE_SERVER_URL,\n STORAGE_PREFIX,\n} from '../types/constants';\nimport { chunk } from '../utils/chunk';\nimport { buildResult } from '../utils/result-builder';\nimport { createServerConfig, RequestMetadata } from '../config';\nimport { UUID } from '../utils/uuid';\nimport { IConfig } from '../types/config/core-config';\nimport { EventCallback } from '../types/event-callback';\nimport { IDiagnosticsClient } from '../diagnostics/diagnostics-client';\nimport { isSuccessStatusCode } from '../utils/status-code';\nimport { getStacktrace } from '../utils/debug';\n\nexport interface Context {\n event: Event;\n attempts: number;\n callback: EventCallback;\n timeout: number;\n}\n\nconst DEFAULT_AMPLITUDE_SERVER_URLS = new Set([\n AMPLITUDE_SERVER_URL,\n EU_AMPLITUDE_SERVER_URL,\n AMPLITUDE_BATCH_SERVER_URL,\n EU_AMPLITUDE_BATCH_SERVER_URL,\n]);\n\nconst shouldCompressUploadBodyForRequest = (serverUrl: string, enableRequestBodyCompression = false) => {\n if (DEFAULT_AMPLITUDE_SERVER_URLS.has(serverUrl)) {\n return true;\n }\n\n return enableRequestBodyCompression;\n};\n\nfunction getErrorMessage(error: unknown) {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nexport function getResponseBodyString(res: Response) {\n let responseBodyString = '';\n try {\n if ('body' in res) {\n responseBodyString = JSON.stringify(res.body, null, 2);\n }\n } catch {\n // to avoid crash, but don't care about the error, add comment to avoid empty block lint error\n }\n return responseBodyString;\n}\n\nexport class Destination implements DestinationPlugin {\n name = 'amplitude';\n type = 'destination' as const;\n\n retryTimeout = 1000;\n throttleTimeout = 30000;\n storageKey = '';\n // this.config is defined in setup() which will always be called first\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // Indicator of whether events that are scheduled (but not flushed yet).\n // When flush:\n // 1. assign `scheduleId` to `flushId`\n // 2. set `scheduleId` to null\n scheduleId: ReturnType<typeof setTimeout> | null = null;\n // Timeout in milliseconds of current schedule\n scheduledTimeout = 0;\n // Indicator of whether current flush resolves.\n // When flush resolves, set `flushId` to null\n flushId: ReturnType<typeof setTimeout> | null = null;\n queue: Context[] = [];\n diagnosticsClient: IDiagnosticsClient | undefined;\n\n constructor(context?: { diagnosticsClient: IDiagnosticsClient }) {\n this.diagnosticsClient = context?.diagnosticsClient;\n }\n\n async setup(config: IConfig): Promise<undefined> {\n this.config = config;\n\n this.storageKey = `${STORAGE_PREFIX}_${this.config.apiKey.substring(0, 10)}`;\n const unsent = await this.config.storageProvider?.get(this.storageKey);\n if (unsent && unsent.length > 0) {\n void Promise.all(unsent.map((event: Event) => this.execute(event))).catch();\n }\n\n return Promise.resolve(undefined);\n }\n\n execute(event: Event): Promise<Result> {\n // Assign insert_id for dropping invalid event later\n if (!event.insert_id) {\n event.insert_id = UUID();\n }\n\n return new Promise((resolve) => {\n const context = {\n event,\n attempts: 0,\n callback: (result: Result) => resolve(result),\n timeout: 0,\n };\n this.queue.push(context);\n this.schedule(this.config.flushIntervalMillis);\n this.saveEvents();\n });\n }\n\n removeEventsExceedFlushMaxRetries(list: Context[]) {\n return list.filter((context) => {\n context.attempts += 1;\n if (context.attempts < this.config.flushMaxRetries) {\n return true;\n }\n void this.fulfillRequest([context], 500, MAX_RETRIES_EXCEEDED_MESSAGE);\n return false;\n });\n }\n\n scheduleEvents(list: Context[]) {\n list.forEach((context) => {\n this.schedule(context.timeout === 0 ? this.config.flushIntervalMillis : context.timeout);\n });\n }\n\n // Schedule a flush in timeout when\n // 1. No schedule\n // 2. Timeout greater than existing timeout.\n // This makes sure that when throttled, no flush when throttle timeout expires.\n schedule(timeout: number) {\n if (this.config.offline) {\n return;\n }\n\n if (this.scheduleId === null || (this.scheduleId && timeout > this.scheduledTimeout)) {\n if (this.scheduleId) {\n clearTimeout(this.scheduleId);\n }\n this.scheduledTimeout = timeout;\n this.scheduleId = setTimeout(() => {\n this.queue = this.queue.map((context) => {\n context.timeout = 0;\n return context;\n });\n void this.flush(true);\n }, timeout);\n return;\n }\n }\n\n // Mark current schedule is flushed.\n resetSchedule() {\n this.scheduleId = null;\n this.scheduledTimeout = 0;\n }\n\n // Flush all events regardless of their timeout\n async flush(useRetry = false) {\n // Skip flush if offline\n if (this.config.offline) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush while offline.');\n return;\n }\n\n if (this.flushId) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush because previous flush has not resolved.');\n return;\n }\n\n this.flushId = this.scheduleId;\n this.resetSchedule();\n\n const list: Context[] = [];\n const later: Context[] = [];\n this.queue.forEach((context) => (context.timeout === 0 ? list.push(context) : later.push(context)));\n\n const batches = chunk(list, this.config.flushQueueSize);\n\n // Promise.all() doesn't guarantee resolve order.\n // Sequentially resolve to make sure backend receives events in order\n await batches.reduce(async (promise, batch) => {\n await promise;\n return await this.send(batch, useRetry);\n }, Promise.resolve());\n\n // Mark current flush is done\n this.flushId = null;\n\n this.scheduleEvents(this.queue);\n }\n\n async send(list: Context[], useRetry = true) {\n if (!this.config.apiKey) {\n return this.fulfillRequest(list, 400, MISSING_API_KEY_MESSAGE);\n }\n\n const payload = {\n api_key: this.config.apiKey,\n events: list.map((context) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { extra, ...eventWithoutExtra } = context.event;\n return eventWithoutExtra;\n }),\n options: {\n min_id_length: this.config.minIdLength,\n },\n client_upload_time: new Date().toISOString(),\n request_metadata: this.config.requestMetadata,\n };\n this.config.requestMetadata = new RequestMetadata();\n\n try {\n const { serverUrl } = createServerConfig(this.config.serverUrl, this.config.serverZone, this.config.useBatch);\n const shouldCompressUploadBody = shouldCompressUploadBodyForRequest(\n serverUrl,\n this.config.enableRequestBodyCompression,\n );\n const res = await this.config.transportProvider.send(serverUrl, payload, shouldCompressUploadBody);\n if (res === null) {\n this.fulfillRequest(list, 0, UNEXPECTED_ERROR_MESSAGE);\n return;\n }\n if (!useRetry) {\n if ('body' in res) {\n this.fulfillRequest(list, res.statusCode, `${res.status}: ${getResponseBodyString(res)}`);\n } else {\n this.fulfillRequest(list, res.statusCode, res.status);\n }\n return;\n }\n this.handleResponse(res, list);\n } catch (e) {\n const errorMessage = getErrorMessage(e);\n this.config.loggerProvider.error(errorMessage);\n\n this.diagnosticsClient?.recordEvent('analytics.events.unsuccessful.from.catch.error', {\n events: list.map((context) => context.event.event_type),\n message: errorMessage,\n stack_trace: getStacktrace(),\n });\n\n this.handleResponse({ status: Status.Failed, statusCode: 0 }, list);\n }\n }\n\n handleResponse(res: Response, list: Context[]) {\n if (!isSuccessStatusCode(res.statusCode)) {\n this.diagnosticsClient?.recordEvent('analytics.events.unsuccessful', {\n events: list.map((context) => context.event.event_type),\n code: res.statusCode,\n status: res.status,\n body: getResponseBodyString(res),\n stack_trace: getStacktrace(),\n });\n }\n\n const { status } = res;\n\n switch (status) {\n case Status.Success: {\n this.handleSuccessResponse(res, list);\n break;\n }\n case Status.Invalid: {\n this.handleInvalidResponse(res, list);\n break;\n }\n case Status.PayloadTooLarge: {\n this.handlePayloadTooLargeResponse(res, list);\n break;\n }\n case Status.RateLimit: {\n this.handleRateLimitResponse(res, list);\n break;\n }\n default: {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(`{code: 0, error: \"Status '${status}' provided for ${list.length} events\"}`);\n this.handleOtherResponse(list);\n break;\n }\n }\n }\n\n handleSuccessResponse(res: SuccessResponse, list: Context[]) {\n this.fulfillRequest(list, res.statusCode, SUCCESS_MESSAGE);\n }\n\n handleInvalidResponse(res: InvalidResponse, list: Context[]) {\n if (res.body.missingField || res.body.error.startsWith(INVALID_API_KEY)) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n const dropIndex = [\n ...Object.values(res.body.eventsWithInvalidFields),\n ...Object.values(res.body.eventsWithMissingFields),\n ...Object.values(res.body.eventsWithInvalidIdLengths),\n ...res.body.silencedEvents,\n ].flat();\n const dropIndexSet = new Set(dropIndex);\n\n const retry = list.filter((context, index) => {\n if (dropIndexSet.has(index)) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handlePayloadTooLargeResponse(res: PayloadTooLargeResponse, list: Context[]) {\n if (list.length === 1) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n\n this.config.flushQueueSize /= 2;\n\n const tryable = this.removeEventsExceedFlushMaxRetries(list);\n this.scheduleEvents(tryable);\n }\n\n handleRateLimitResponse(res: RateLimitResponse, list: Context[]) {\n const dropUserIds = Object.keys(res.body.exceededDailyQuotaUsers);\n const dropDeviceIds = Object.keys(res.body.exceededDailyQuotaDevices);\n const throttledIndex = res.body.throttledEvents;\n const dropUserIdsSet = new Set(dropUserIds);\n const dropDeviceIdsSet = new Set(dropDeviceIds);\n const throttledIndexSet = new Set(throttledIndex);\n\n const retry = list.filter((context, index) => {\n if (\n (context.event.user_id && dropUserIdsSet.has(context.event.user_id)) ||\n (context.event.device_id && dropDeviceIdsSet.has(context.event.device_id))\n ) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n if (throttledIndexSet.has(index)) {\n context.timeout = this.throttleTimeout;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handleOtherResponse(list: Context[]) {\n const later = list.map((context) => {\n context.timeout = context.attempts * this.retryTimeout;\n return context;\n });\n\n const tryable = this.removeEventsExceedFlushMaxRetries(later);\n this.scheduleEvents(tryable);\n }\n\n fulfillRequest(list: Context[], code: number, message: string) {\n // Record diagnostics for dropped events (non-success status codes)\n if (!isSuccessStatusCode(code)) {\n this.diagnosticsClient?.increment('analytics.events.dropped', list.length);\n this.diagnosticsClient?.recordEvent('analytics.events.dropped', {\n events: list.map((context) => context.event.event_type),\n code: code,\n message: message,\n stack_trace: getStacktrace(),\n });\n } else {\n this.diagnosticsClient?.increment('analytics.events.sent', list.length);\n }\n this.removeEvents(list);\n list.forEach((context) => context.callback(buildResult(context.event, code, message)));\n }\n\n /**\n * This is called on\n * 1) new events are added to queue; or\n * 2) response comes back for a request\n *\n * Update the event storage based on the queue\n */\n saveEvents() {\n if (!this.config.storageProvider) {\n return;\n }\n\n const updatedEvents = this.queue.map((context) => context.event);\n void this.config.storageProvider.set(this.storageKey, updatedEvents);\n }\n\n /**\n * This is called on response comes back for a request\n */\n removeEvents(eventsToRemove: Context[]) {\n this.queue = this.queue.filter(\n (queuedContext) => !eventsToRemove.some((context) => context.event.insert_id === queuedContext.event.insert_id),\n );\n\n this.saveEvents();\n }\n}\n"]}
|
|
@@ -111,7 +111,8 @@ export declare class RemoteConfigClient implements IRemoteConfigClient {
|
|
|
111
111
|
fetchPromise: Promise<RemoteConfigInfo> | null;
|
|
112
112
|
isLastFetchInvalidApiKey: boolean;
|
|
113
113
|
readonly customFetch?: RemoteConfigCustomFetch;
|
|
114
|
-
|
|
114
|
+
readonly configGroup: string;
|
|
115
|
+
constructor(apiKey: string, logger: ILogger, serverZone?: ServerZoneType, serverUrl?: string, customFetch?: RemoteConfigCustomFetch, configGroup?: string);
|
|
115
116
|
subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string;
|
|
116
117
|
unsubscribe(id: string): boolean;
|
|
117
118
|
updateConfigs(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-config.d.ts","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIpC;;;;;;;;;GASG;AACH,MAAM,MAAM,YAAY,GAAG,KAAK,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvD;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAC;AAExC;;;;;GAKG;AACH,MAAM,WAAW,wBAAwB;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,KAAK,CAAC;IACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,8FAA8F;IAC9F,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,EAAE,wBAAwB,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;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 5 * 60 * 1000; // 5 minutes
|
|
47
47
|
var RemoteConfigClient = /** @class */ (function () {
|
|
48
|
-
function RemoteConfigClient(apiKey, logger, serverZone, serverUrl, customFetch) {
|
|
48
|
+
function RemoteConfigClient(apiKey, logger, serverZone, serverUrl, customFetch, configGroup) {
|
|
49
49
|
if (serverZone === void 0) { serverZone = 'US'; }
|
|
50
|
+
if (configGroup === void 0) { configGroup = RemoteConfigClient.CONFIG_GROUP; }
|
|
50
51
|
// Registered callbackInfos by subscribe().
|
|
51
52
|
this.callbackInfos = [];
|
|
52
53
|
// Track the last successful fetch time for throttling (timestamp in milliseconds).
|
|
@@ -60,6 +61,7 @@ var RemoteConfigClient = /** @class */ (function () {
|
|
|
60
61
|
this.logger = logger;
|
|
61
62
|
this.storage = new RemoteConfigLocalStorage(apiKey, logger);
|
|
62
63
|
this.customFetch = customFetch;
|
|
64
|
+
this.configGroup = configGroup;
|
|
63
65
|
}
|
|
64
66
|
RemoteConfigClient.prototype.subscribe = function (key, deliveryMode, callback) {
|
|
65
67
|
var id = UUID();
|
|
@@ -401,7 +403,7 @@ var RemoteConfigClient = /** @class */ (function () {
|
|
|
401
403
|
// URL encode the API key to handle special characters
|
|
402
404
|
var encodedApiKey = encodeURIComponent(this.apiKey);
|
|
403
405
|
var urlParams = new URLSearchParams();
|
|
404
|
-
urlParams.append('config_group',
|
|
406
|
+
urlParams.append('config_group', this.configGroup);
|
|
405
407
|
return "".concat(this.serverUrl, "/").concat(encodedApiKey, "?").concat(urlParams.toString());
|
|
406
408
|
};
|
|
407
409
|
RemoteConfigClient.CONFIG_GROUP = 'browser';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAyCrC;;;;;GAKG;AACH,SAA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E9E,OAAO,GAAG,CAAC;;;6BAAE,CAAA,OAAO,GAAG,OAAO,CAAA;sDAA9B,OAAO;;;;;;;;;wBAAyB,OAAO,EAAE,CAAA;;4BA4ElD,sBAAO,sBAAsB,EAAC;;;;KAC/B;IAED;;OAEG;IACH,2CAAc,GAAd,UAAe,SAAiB;QAC9B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IAC/C,CAAC;IAED,yCAAY,GAAZ;QACE,sDAAsD;QACtD,IAAM,aAAa,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEtD,IAAM,SAAS,GAAG,IAAI,eAAe,EAAE,CAAC;QACxC,SAAS,CAAC,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC,YAAY,CAAC,CAAC;QAElE,OAAO,UAAG,IAAI,CAAC,SAAS,cAAI,aAAa,cAAI,SAAS,CAAC,QAAQ,EAAE,CAAE,CAAC;IACtE,CAAC;IAvUe,+BAAY,GAAG,SAAS,CAAC;IAwU3C,yBAAC;CAAA,AAzUD,IAyUC;SAzUY,kBAAkB","sourcesContent":["import { ServerZoneType } from '../types/server-zone';\nimport { ILogger } from '../logger';\nimport { RemoteConfigLocalStorage } from './remote-config-localstorage';\nimport { UUID } from '../utils/uuid';\n\n/**\n * Modes for receiving remote config updates:\n * - `'all'` – Optimized for both speed and freshness. Returns the fastest response first\n * (cache or remote), then always waits for and returns the remote response to ensure\n * the most up-to-date config. Callback may be called once (if remote wins) or twice\n * (cache first, then remote).\n * - `{ timeout: number }` – Prefers remote data but with a fallback strategy. Waits for\n * a remote response until the specified timeout (in milliseconds), then falls back to\n * cached data if available. Callback is called exactly once.\n */\nexport type DeliveryMode = 'all' | { timeout: number };\n\n/**\n * Sources of returned remote config:\n * - `cache` - Fetched from local storage.\n * - `remote` - Fetched from remote.\n */\nexport type Source = 'cache' | 'remote';\n\n/**\n * The fully-formed remote-config request handed to a custom transport. Consumers that need to\n * own the network call (e.g. to attach auth headers and route through a proxy) supply a\n * {@link RemoteConfigCustomFetch} via the client constructor; the client builds this request\n * (resolved URL, headers, abort signal) and the callback executes it.\n */\nexport interface RemoteConfigFetchRequest {\n url: string;\n method: 'GET';\n headers: Record<string, string>;\n /** Abort signal the client uses to enforce the fetch timeout; honor it in your fetch call. */\n signal?: AbortSignal;\n}\n\n/**\n * Custom transport for the remote-config fetch. Must return a `Response`. Retry/backoff stays\n * in the client around this callback, so it is invoked once per attempt.\n */\nexport type RemoteConfigCustomFetch = (request: RemoteConfigFetchRequest) => Promise<Response>;\n\n/**\n * Settles with `promise`, but rejects with an AbortError when `signal` fires. The request-timeout\n * signal is handed to customFetch, but a transport that ignores it would block the await (and the\n * retry loop) indefinitely; racing the abort guarantees the client-side timeout always applies.\n * The transport's own promise keeps running — we can't cancel it — we just stop awaiting it.\n */\nfunction abortableFetch(promise: Promise<Response>, signal: AbortSignal): Promise<Response> {\n return new Promise<Response>((resolve, reject) => {\n const onAbort = () => {\n // Match how a native aborted fetch rejects (name 'AbortError') so fetch()'s catch logs it\n // as a timeout; either way the loop retries since the abort doesn't clear shouldRetry.\n const err = new Error('Remote config custom fetch aborted by timeout');\n err.name = 'AbortError';\n reject(err);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (err) => {\n signal.removeEventListener('abort', onAbort);\n reject(err);\n },\n );\n });\n}\n\nexport const US_SERVER_URL = 'https://sr-client-cfg.amplitude.com/config';\nexport const EU_SERVER_URL = 'https://sr-client-cfg.eu.amplitude.com/config';\nexport const DEFAULT_MAX_RETRIES = 3;\nconst CODE_STATUS = {\n INVALID_API_KEY: 401,\n FORBIDDEN: 403,\n RATE_LIMIT: 429,\n} as const;\n\n/**\n * The default timeout for fetch in milliseconds.\n * Linear backoff policy: timeout / retry times is the interval between fetch retry.\n */\nconst DEFAULT_TIMEOUT = 1000;\n\n/**\n * The minimum time between fetches in milliseconds.\n * This prevents too many requests from being sent in a short period of time.\n */\nconst DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes\n\nexport interface RemoteConfig {\n [key: string]: any;\n}\n\nexport interface RemoteConfigInfo {\n remoteConfig: RemoteConfig | null;\n // Timestamp of when the remote config was fetched.\n lastFetch: Date;\n}\n\nexport interface RemoteConfigStorage {\n /**\n * Fetch remote config from storage asynchronously.\n */\n fetchConfig(): Promise<RemoteConfigInfo>;\n\n /**\n * Set remote config to storage asynchronously.\n */\n setConfig(config: RemoteConfigInfo): Promise<boolean>;\n}\n\n/**\n * Information about each callback registered by `RemoteConfigClient.subscribe()`,\n * managed internally by `RemoteConfigClient`.\n */\nexport interface CallbackInfo {\n id: string;\n key?: string;\n deliveryMode: DeliveryMode;\n callback: RemoteConfigCallback;\n lastCallback?: Date;\n}\n\n/**\n * Callback used in `RemoteConfigClient.subscribe()`.\n * This function is called when the remote config is fetched.\n */\ntype RemoteConfigCallback = (remoteConfig: RemoteConfig | null, source: Source, lastFetch: Date) => void;\n\nexport interface IRemoteConfigClient {\n /**\n * Subscribe for updates to remote config.\n * Callback is guaranteed to be called at least once,\n * Whether we are able to fetch a config or not.\n *\n * @param key - a string containing a series of period delimited keys to filter the returned config.\n * Ie, {a: {b: {c: ...}}} would return {b: {c: ...}} for \"a\" or {c: ...} for \"a.b\".\n * Set to `undefined` to subscribe all keys.\n * @param deliveryMode - how the initial callback is sent.\n * @param callback - a block that will be called when remote config is fetched.\n * @return id - identification of the subscribe and can be used to unsubscribe from updates.\n */\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string;\n\n /**\n * Unsubscribe a callback from receiving future updates.\n *\n * @param id - identification of the callback that you want to unsubscribe.\n * It's the return value of subscribe().\n * @return boolean - whether the callback is removed.\n */\n unsubscribe(id: string): boolean;\n\n /**\n * Request the remote config client to fetch from remote, update cache, and callback.\n */\n updateConfigs(): void;\n}\n\nexport class RemoteConfigClient implements IRemoteConfigClient {\n static readonly CONFIG_GROUP = 'browser';\n\n readonly apiKey: string;\n readonly serverUrl: string;\n readonly logger: ILogger;\n readonly storage: RemoteConfigStorage;\n // Registered callbackInfos by subscribe().\n callbackInfos: CallbackInfo[] = [];\n // Track the last successful fetch time for throttling (timestamp in milliseconds).\n lastSuccessfulFetch: number | null = null;\n // Store the in-flight fetch promise for deduplication.\n fetchPromise: Promise<RemoteConfigInfo> | null = null;\n // Used to skip periodic updateConfigs calls when API key is invalid.\n isLastFetchInvalidApiKey = false;\n // Optional custom transport. When provided, it replaces the internal fetch for the config GET\n // (e.g. to attach auth and route through a proxy). Retry stays in the client around it.\n readonly customFetch?: RemoteConfigCustomFetch;\n\n constructor(\n apiKey: string,\n logger: ILogger,\n serverZone: ServerZoneType = 'US',\n serverUrl?: string,\n customFetch?: RemoteConfigCustomFetch,\n ) {\n this.apiKey = apiKey;\n this.serverUrl = serverUrl || (serverZone === 'US' ? US_SERVER_URL : EU_SERVER_URL);\n this.logger = logger;\n this.storage = new RemoteConfigLocalStorage(apiKey, logger);\n this.customFetch = customFetch;\n }\n\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string {\n const id = UUID();\n const callbackInfo = {\n id: id,\n key: key,\n deliveryMode: deliveryMode,\n callback: callback,\n };\n this.callbackInfos.push(callbackInfo);\n\n if (deliveryMode === 'all') {\n void this.subscribeAll(callbackInfo);\n } else {\n void this.subscribeWaitForRemote(callbackInfo, deliveryMode.timeout);\n }\n\n return id;\n }\n\n unsubscribe(id: string): boolean {\n const index = this.callbackInfos.findIndex((callbackInfo) => callbackInfo.id === id);\n if (index === -1) {\n this.logger.debug(`Remote config client unsubscribe failed because callback with id ${id} doesn't exist.`);\n return false;\n }\n\n this.callbackInfos.splice(index, 1);\n this.logger.debug(`Remote config client unsubscribe succeeded removing callback with id ${id}.`);\n return true;\n }\n\n async updateConfigs() {\n // Check if we need to throttle based on last successful fetch time\n if (this.lastSuccessfulFetch) {\n const timeSinceLastFetch = Date.now() - this.lastSuccessfulFetch;\n if (timeSinceLastFetch < DEFAULT_MIN_TIME_BETWEEN_FETCHES) {\n this.logger.debug('Remote config client skipping updateConfigs: Too recent');\n return;\n }\n }\n\n const result = await this.getOrCreateFetchPromise();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\n }\n\n /**\n * Get the in-flight fetch promise or create a new one.\n * This ensures multiple subscribe calls share the same network request.\n */\n getOrCreateFetchPromise(): Promise<RemoteConfigInfo> {\n if (this.fetchPromise) {\n return this.fetchPromise;\n }\n\n if (this.isLastFetchInvalidApiKey) {\n this.logger.debug('Remote config client skipping fetch: Invalid API key');\n this.fetchPromise = Promise.resolve({\n remoteConfig: null,\n lastFetch: new Date(),\n }).finally(() => {\n this.fetchPromise = null;\n });\n return this.fetchPromise;\n }\n\n this.fetchPromise = this.fetch()\n .then((result) => {\n // Update last successful fetch time if we got a valid config\n if (result.remoteConfig !== null) {\n this.lastSuccessfulFetch = Date.now();\n }\n return result;\n })\n .finally(() => {\n // Clear the promise after it settles (success or failure)\n this.fetchPromise = null;\n });\n\n return this.fetchPromise;\n }\n\n /**\n * Send remote first. If it's already complete, we can skip the cached response.\n * - if remote is fetched first, no cache fetch.\n * - if cache is fetched first, still fetching remote.\n */\n async subscribeAll(callbackInfo: CallbackInfo) {\n const remotePromise = this.getOrCreateFetchPromise().then((result) => {\n this.logger.debug(`Remote config client subscription all mode fetched from remote: ${JSON.stringify(result)}`);\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n });\n\n const cachePromise = this.storage.fetchConfig().then((result) => {\n return result;\n });\n\n // Wait for the first result to resolve\n const result = await Promise.race([remotePromise, cachePromise]);\n\n // If cache is fetched first, wait for remote.\n if (result !== undefined) {\n this.logger.debug(`Remote config client subscription all mode fetched from cache: ${JSON.stringify(result)}`);\n // Skip sending callback if cache is empty (first time user).\n if (result.remoteConfig !== null) {\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client skips sending callback because cache is empty (first time user).');\n }\n }\n await remotePromise;\n }\n\n /**\n * Waits for a remote response until the given timeout, then return a cached copy, if available.\n */\n async subscribeWaitForRemote(callbackInfo: CallbackInfo, timeout: number) {\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject('Timeout exceeded');\n }, timeout);\n });\n\n try {\n const result: RemoteConfigInfo = (await Promise.race([\n this.getOrCreateFetchPromise(),\n timeoutPromise,\n ])) as RemoteConfigInfo;\n\n this.logger.debug('Remote config client subscription wait for remote mode returns from remote.');\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n } catch (error) {\n this.logger.debug(\n 'Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache.',\n );\n const result = await this.storage.fetchConfig();\n if (result.remoteConfig !== null) {\n this.logger.debug('Remote config client subscription wait for remote mode returns a cached copy.');\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client subscription wait for remote mode failed to fetch cache.');\n this.sendCallback(callbackInfo, result, 'remote');\n }\n }\n }\n\n /**\n * Call the callback with filtered remote config based on key.\n * @param remoteConfigInfo - the whole remote config object without filtering by key.\n */\n sendCallback(callbackInfo: CallbackInfo, remoteConfigInfo: RemoteConfigInfo, source: Source) {\n callbackInfo.lastCallback = new Date();\n\n let filteredConfig: RemoteConfig | null;\n if (callbackInfo.key) {\n // Filter remote config by key.\n // For example, if remote config is {a: {b: {c: 1}}},\n // if key = 'a', filter result is {b: {c: 1}};\n // if key = 'a.b', filter result is {c: 1}\n filteredConfig = callbackInfo.key.split('.').reduce((config, key) => {\n if (config === null) {\n return config;\n }\n\n return key in config ? (config[key] as RemoteConfig) : null;\n }, remoteConfigInfo.remoteConfig);\n } else {\n filteredConfig = remoteConfigInfo.remoteConfig;\n }\n\n callbackInfo.callback(filteredConfig, source, remoteConfigInfo.lastFetch);\n }\n\n /**\n * Fetch remote config from remote.\n * @param retries - the number of retries. default is 3.\n * @param timeout - the timeout in milliseconds. Default is 1000.\n * This timeout serves two purposes:\n * 1. It determines how long to wait for each remote config fetch request before aborting it.\n * If the fetch does not complete within the specified timeout, the request is cancelled using AbortController,\n * and the attempt is considered failed (and may be retried if retries remain).\n * 2. It is also used to calculate the interval between retries. The total timeout is divided by the number of retries,\n * so each retry waits for (timeout / retries) milliseconds before the next attempt (linear backoff).\n * Retry behavior by status code:\n * - 401: invalid API key (stop retries and disable future updateConfigs calls).\n * - 429: retry up to max retries.\n * - other 4xx: no retry.\n * - 5xx and network failures: retry up to max retries.\n * @returns the remote config info. null if failed to fetch or the response is not valid JSON.\n */\n async fetch(retries: number = DEFAULT_MAX_RETRIES, timeout: number = DEFAULT_TIMEOUT): Promise<RemoteConfigInfo> {\n const interval = timeout / retries;\n const failedRemoteConfigInfo: RemoteConfigInfo = {\n remoteConfig: null,\n lastFetch: new Date(),\n };\n\n for (let attempt = 0; attempt < retries; attempt++) {\n let shouldRetry = true;\n // Create AbortController for request timeout\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => abortController.abort(), timeout);\n\n try {\n const url = this.getUrlParams();\n const headers: Record<string, string> = { Accept: '*/*' };\n // When a custom transport is configured, hand it the fully-formed request and let it own\n // the network call; otherwise use the built-in fetch. Retry/response handling is identical.\n // The built-in fetch cancels directly on the signal; the custom transport can't be\n // cancelled, so race it against the abort (abortableFetch) to enforce the timeout even if\n // the transport ignores the signal — otherwise a hung transport would block every retry.\n const res = this.customFetch\n ? await abortableFetch(\n this.customFetch({ url, method: 'GET', headers, signal: abortController.signal }),\n abortController.signal,\n )\n : await fetch(url, {\n method: 'GET',\n headers,\n signal: abortController.signal,\n });\n\n // Treat a 2xx status as success even when `res.ok` is absent. A custom transport may return\n // a Response-like object that sets `status`/`text()`/`json()` but not `ok` (e.g. an axios\n // adapter); falling back to the status range keeps the config path consistent with the\n // event-upload path while still honoring native fetch's `ok`.\n const isSuccess = res.ok || (res.status >= 200 && res.status < 300);\n // Handle unsuccessful fetch\n if (!isSuccess) {\n const body = await res.text();\n this.logger.debug(`Remote config client fetch with retry time ${retries} failed with ${res.status}: ${body}`);\n\n if (res.status === CODE_STATUS.INVALID_API_KEY || res.status === CODE_STATUS.FORBIDDEN) {\n this.logger.error(\n `Remote config client fetch failed with ${res.status}. Invalid API key; future fetches will be skipped.`,\n );\n this.isLastFetchInvalidApiKey = true;\n shouldRetry = false;\n } else if (res.status >= 400 && res.status < 500 && res.status !== CODE_STATUS.RATE_LIMIT) {\n shouldRetry = false;\n }\n } else {\n // Handle successful fetch\n const remoteConfig: RemoteConfig = (await res.json()) as RemoteConfig;\n return {\n remoteConfig: remoteConfig,\n lastFetch: new Date(),\n };\n }\n } catch (error) {\n // Handle rejects when the request fails, for example, a network error or timeout\n if (error instanceof Error && error.name === 'AbortError') {\n this.logger.debug(`Remote config client fetch with retry time ${retries} timed out after ${timeout}ms`);\n } else {\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\n }\n } finally {\n // Clear the timeout since request completed or failed\n clearTimeout(timeoutId);\n }\n\n if (!shouldRetry) {\n break;\n }\n\n // Linear backoff:\n // wait for the specified interval before the next attempt\n // except after the last attempt.\n if (attempt < retries - 1) {\n await new Promise((resolve) => setTimeout(resolve, this.getJitterDelay(interval)));\n }\n }\n\n return failedRemoteConfigInfo;\n }\n\n /**\n * Return jitter in the bound of [0,baseDelay) and then floor round.\n */\n getJitterDelay(baseDelay: number): number {\n return Math.floor(Math.random() * baseDelay);\n }\n\n getUrlParams(): string {\n // URL encode the API key to handle special characters\n const encodedApiKey = encodeURIComponent(this.apiKey);\n\n const urlParams = new URLSearchParams();\n urlParams.append('config_group', RemoteConfigClient.CONFIG_GROUP);\n\n return `${this.serverUrl}/${encodedApiKey}?${urlParams.toString()}`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":";AAEA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GAAG,OAAO,GAAG,CAAC,CAAA,EAArB,yBAAqB;wCACvB,qBAAM,IAAI,OAAO,CAAC,UAAC,OAAO,IAAK,OAAA,UAAU,CAAC,OAAO,EAAE,KAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,EAAlD,CAAkD,CAAC,EAAA;;wCAAlF,SAAkF,CAAC;;;;;;;wBAxE9E,OAAO,GAAG,CAAC;;;6BAAE,CAAA,OAAO,GAAG,OAAO,CAAA;sDAA9B,OAAO;;;;;;;;;wBAAyB,OAAO,EAAE,CAAA;;4BA4ElD,sBAAO,sBAAsB,EAAC;;;;KAC/B;IAED;;OAEG;IACH,2CAAc,GAAd,UAAe,SAAiB;QAC9B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IAC/C,CAAC;IAED,yCAAY,GAAZ;QACE,sDAAsD;QACtD,IAAM,aAAa,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEtD,IAAM,SAAS,GAAG,IAAI,eAAe,EAAE,CAAC;QACxC,SAAS,CAAC,MAAM,CAAC,cAAc,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QAEnD,OAAO,UAAG,IAAI,CAAC,SAAS,cAAI,aAAa,cAAI,SAAS,CAAC,QAAQ,EAAE,CAAE,CAAC;IACtE,CAAC;IA1Ue,+BAAY,GAAG,SAAS,CAAC;IA2U3C,yBAAC;CAAA,AA5UD,IA4UC;SA5UY,kBAAkB","sourcesContent":["import { ServerZoneType } from '../types/server-zone';\nimport { ILogger } from '../logger';\nimport { RemoteConfigLocalStorage } from './remote-config-localstorage';\nimport { UUID } from '../utils/uuid';\n\n/**\n * Modes for receiving remote config updates:\n * - `'all'` – Optimized for both speed and freshness. Returns the fastest response first\n * (cache or remote), then always waits for and returns the remote response to ensure\n * the most up-to-date config. Callback may be called once (if remote wins) or twice\n * (cache first, then remote).\n * - `{ timeout: number }` – Prefers remote data but with a fallback strategy. Waits for\n * a remote response until the specified timeout (in milliseconds), then falls back to\n * cached data if available. Callback is called exactly once.\n */\nexport type DeliveryMode = 'all' | { timeout: number };\n\n/**\n * Sources of returned remote config:\n * - `cache` - Fetched from local storage.\n * - `remote` - Fetched from remote.\n */\nexport type Source = 'cache' | 'remote';\n\n/**\n * The fully-formed remote-config request handed to a custom transport. Consumers that need to\n * own the network call (e.g. to attach auth headers and route through a proxy) supply a\n * {@link RemoteConfigCustomFetch} via the client constructor; the client builds this request\n * (resolved URL, headers, abort signal) and the callback executes it.\n */\nexport interface RemoteConfigFetchRequest {\n url: string;\n method: 'GET';\n headers: Record<string, string>;\n /** Abort signal the client uses to enforce the fetch timeout; honor it in your fetch call. */\n signal?: AbortSignal;\n}\n\n/**\n * Custom transport for the remote-config fetch. Must return a `Response`. Retry/backoff stays\n * in the client around this callback, so it is invoked once per attempt.\n */\nexport type RemoteConfigCustomFetch = (request: RemoteConfigFetchRequest) => Promise<Response>;\n\n/**\n * Settles with `promise`, but rejects with an AbortError when `signal` fires. The request-timeout\n * signal is handed to customFetch, but a transport that ignores it would block the await (and the\n * retry loop) indefinitely; racing the abort guarantees the client-side timeout always applies.\n * The transport's own promise keeps running — we can't cancel it — we just stop awaiting it.\n */\nfunction abortableFetch(promise: Promise<Response>, signal: AbortSignal): Promise<Response> {\n return new Promise<Response>((resolve, reject) => {\n const onAbort = () => {\n // Match how a native aborted fetch rejects (name 'AbortError') so fetch()'s catch logs it\n // as a timeout; either way the loop retries since the abort doesn't clear shouldRetry.\n const err = new Error('Remote config custom fetch aborted by timeout');\n err.name = 'AbortError';\n reject(err);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (err) => {\n signal.removeEventListener('abort', onAbort);\n reject(err);\n },\n );\n });\n}\n\nexport const US_SERVER_URL = 'https://sr-client-cfg.amplitude.com/config';\nexport const EU_SERVER_URL = 'https://sr-client-cfg.eu.amplitude.com/config';\nexport const DEFAULT_MAX_RETRIES = 3;\nconst CODE_STATUS = {\n INVALID_API_KEY: 401,\n FORBIDDEN: 403,\n RATE_LIMIT: 429,\n} as const;\n\n/**\n * The default timeout for fetch in milliseconds.\n * Linear backoff policy: timeout / retry times is the interval between fetch retry.\n */\nconst DEFAULT_TIMEOUT = 1000;\n\n/**\n * The minimum time between fetches in milliseconds.\n * This prevents too many requests from being sent in a short period of time.\n */\nconst DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes\n\nexport interface RemoteConfig {\n [key: string]: any;\n}\n\nexport interface RemoteConfigInfo {\n remoteConfig: RemoteConfig | null;\n // Timestamp of when the remote config was fetched.\n lastFetch: Date;\n}\n\nexport interface RemoteConfigStorage {\n /**\n * Fetch remote config from storage asynchronously.\n */\n fetchConfig(): Promise<RemoteConfigInfo>;\n\n /**\n * Set remote config to storage asynchronously.\n */\n setConfig(config: RemoteConfigInfo): Promise<boolean>;\n}\n\n/**\n * Information about each callback registered by `RemoteConfigClient.subscribe()`,\n * managed internally by `RemoteConfigClient`.\n */\nexport interface CallbackInfo {\n id: string;\n key?: string;\n deliveryMode: DeliveryMode;\n callback: RemoteConfigCallback;\n lastCallback?: Date;\n}\n\n/**\n * Callback used in `RemoteConfigClient.subscribe()`.\n * This function is called when the remote config is fetched.\n */\ntype RemoteConfigCallback = (remoteConfig: RemoteConfig | null, source: Source, lastFetch: Date) => void;\n\nexport interface IRemoteConfigClient {\n /**\n * Subscribe for updates to remote config.\n * Callback is guaranteed to be called at least once,\n * Whether we are able to fetch a config or not.\n *\n * @param key - a string containing a series of period delimited keys to filter the returned config.\n * Ie, {a: {b: {c: ...}}} would return {b: {c: ...}} for \"a\" or {c: ...} for \"a.b\".\n * Set to `undefined` to subscribe all keys.\n * @param deliveryMode - how the initial callback is sent.\n * @param callback - a block that will be called when remote config is fetched.\n * @return id - identification of the subscribe and can be used to unsubscribe from updates.\n */\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string;\n\n /**\n * Unsubscribe a callback from receiving future updates.\n *\n * @param id - identification of the callback that you want to unsubscribe.\n * It's the return value of subscribe().\n * @return boolean - whether the callback is removed.\n */\n unsubscribe(id: string): boolean;\n\n /**\n * Request the remote config client to fetch from remote, update cache, and callback.\n */\n updateConfigs(): void;\n}\n\nexport class RemoteConfigClient implements IRemoteConfigClient {\n static readonly CONFIG_GROUP = 'browser';\n\n readonly apiKey: string;\n readonly serverUrl: string;\n readonly logger: ILogger;\n readonly storage: RemoteConfigStorage;\n // Registered callbackInfos by subscribe().\n callbackInfos: CallbackInfo[] = [];\n // Track the last successful fetch time for throttling (timestamp in milliseconds).\n lastSuccessfulFetch: number | null = null;\n // Store the in-flight fetch promise for deduplication.\n fetchPromise: Promise<RemoteConfigInfo> | null = null;\n // Used to skip periodic updateConfigs calls when API key is invalid.\n isLastFetchInvalidApiKey = false;\n // Optional custom transport. When provided, it replaces the internal fetch for the config GET\n // (e.g. to attach auth and route through a proxy). Retry stays in the client around it.\n readonly customFetch?: RemoteConfigCustomFetch;\n readonly configGroup: string;\n\n constructor(\n apiKey: string,\n logger: ILogger,\n serverZone: ServerZoneType = 'US',\n serverUrl?: string,\n customFetch?: RemoteConfigCustomFetch,\n configGroup: string = RemoteConfigClient.CONFIG_GROUP,\n ) {\n this.apiKey = apiKey;\n this.serverUrl = serverUrl || (serverZone === 'US' ? US_SERVER_URL : EU_SERVER_URL);\n this.logger = logger;\n this.storage = new RemoteConfigLocalStorage(apiKey, logger);\n this.customFetch = customFetch;\n this.configGroup = configGroup;\n }\n\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string {\n const id = UUID();\n const callbackInfo = {\n id: id,\n key: key,\n deliveryMode: deliveryMode,\n callback: callback,\n };\n this.callbackInfos.push(callbackInfo);\n\n if (deliveryMode === 'all') {\n void this.subscribeAll(callbackInfo);\n } else {\n void this.subscribeWaitForRemote(callbackInfo, deliveryMode.timeout);\n }\n\n return id;\n }\n\n unsubscribe(id: string): boolean {\n const index = this.callbackInfos.findIndex((callbackInfo) => callbackInfo.id === id);\n if (index === -1) {\n this.logger.debug(`Remote config client unsubscribe failed because callback with id ${id} doesn't exist.`);\n return false;\n }\n\n this.callbackInfos.splice(index, 1);\n this.logger.debug(`Remote config client unsubscribe succeeded removing callback with id ${id}.`);\n return true;\n }\n\n async updateConfigs() {\n // Check if we need to throttle based on last successful fetch time\n if (this.lastSuccessfulFetch) {\n const timeSinceLastFetch = Date.now() - this.lastSuccessfulFetch;\n if (timeSinceLastFetch < DEFAULT_MIN_TIME_BETWEEN_FETCHES) {\n this.logger.debug('Remote config client skipping updateConfigs: Too recent');\n return;\n }\n }\n\n const result = await this.getOrCreateFetchPromise();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\n }\n\n /**\n * Get the in-flight fetch promise or create a new one.\n * This ensures multiple subscribe calls share the same network request.\n */\n getOrCreateFetchPromise(): Promise<RemoteConfigInfo> {\n if (this.fetchPromise) {\n return this.fetchPromise;\n }\n\n if (this.isLastFetchInvalidApiKey) {\n this.logger.debug('Remote config client skipping fetch: Invalid API key');\n this.fetchPromise = Promise.resolve({\n remoteConfig: null,\n lastFetch: new Date(),\n }).finally(() => {\n this.fetchPromise = null;\n });\n return this.fetchPromise;\n }\n\n this.fetchPromise = this.fetch()\n .then((result) => {\n // Update last successful fetch time if we got a valid config\n if (result.remoteConfig !== null) {\n this.lastSuccessfulFetch = Date.now();\n }\n return result;\n })\n .finally(() => {\n // Clear the promise after it settles (success or failure)\n this.fetchPromise = null;\n });\n\n return this.fetchPromise;\n }\n\n /**\n * Send remote first. If it's already complete, we can skip the cached response.\n * - if remote is fetched first, no cache fetch.\n * - if cache is fetched first, still fetching remote.\n */\n async subscribeAll(callbackInfo: CallbackInfo) {\n const remotePromise = this.getOrCreateFetchPromise().then((result) => {\n this.logger.debug(`Remote config client subscription all mode fetched from remote: ${JSON.stringify(result)}`);\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n });\n\n const cachePromise = this.storage.fetchConfig().then((result) => {\n return result;\n });\n\n // Wait for the first result to resolve\n const result = await Promise.race([remotePromise, cachePromise]);\n\n // If cache is fetched first, wait for remote.\n if (result !== undefined) {\n this.logger.debug(`Remote config client subscription all mode fetched from cache: ${JSON.stringify(result)}`);\n // Skip sending callback if cache is empty (first time user).\n if (result.remoteConfig !== null) {\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client skips sending callback because cache is empty (first time user).');\n }\n }\n await remotePromise;\n }\n\n /**\n * Waits for a remote response until the given timeout, then return a cached copy, if available.\n */\n async subscribeWaitForRemote(callbackInfo: CallbackInfo, timeout: number) {\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject('Timeout exceeded');\n }, timeout);\n });\n\n try {\n const result: RemoteConfigInfo = (await Promise.race([\n this.getOrCreateFetchPromise(),\n timeoutPromise,\n ])) as RemoteConfigInfo;\n\n this.logger.debug('Remote config client subscription wait for remote mode returns from remote.');\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n } catch (error) {\n this.logger.debug(\n 'Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache.',\n );\n const result = await this.storage.fetchConfig();\n if (result.remoteConfig !== null) {\n this.logger.debug('Remote config client subscription wait for remote mode returns a cached copy.');\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client subscription wait for remote mode failed to fetch cache.');\n this.sendCallback(callbackInfo, result, 'remote');\n }\n }\n }\n\n /**\n * Call the callback with filtered remote config based on key.\n * @param remoteConfigInfo - the whole remote config object without filtering by key.\n */\n sendCallback(callbackInfo: CallbackInfo, remoteConfigInfo: RemoteConfigInfo, source: Source) {\n callbackInfo.lastCallback = new Date();\n\n let filteredConfig: RemoteConfig | null;\n if (callbackInfo.key) {\n // Filter remote config by key.\n // For example, if remote config is {a: {b: {c: 1}}},\n // if key = 'a', filter result is {b: {c: 1}};\n // if key = 'a.b', filter result is {c: 1}\n filteredConfig = callbackInfo.key.split('.').reduce((config, key) => {\n if (config === null) {\n return config;\n }\n\n return key in config ? (config[key] as RemoteConfig) : null;\n }, remoteConfigInfo.remoteConfig);\n } else {\n filteredConfig = remoteConfigInfo.remoteConfig;\n }\n\n callbackInfo.callback(filteredConfig, source, remoteConfigInfo.lastFetch);\n }\n\n /**\n * Fetch remote config from remote.\n * @param retries - the number of retries. default is 3.\n * @param timeout - the timeout in milliseconds. Default is 1000.\n * This timeout serves two purposes:\n * 1. It determines how long to wait for each remote config fetch request before aborting it.\n * If the fetch does not complete within the specified timeout, the request is cancelled using AbortController,\n * and the attempt is considered failed (and may be retried if retries remain).\n * 2. It is also used to calculate the interval between retries. The total timeout is divided by the number of retries,\n * so each retry waits for (timeout / retries) milliseconds before the next attempt (linear backoff).\n * Retry behavior by status code:\n * - 401: invalid API key (stop retries and disable future updateConfigs calls).\n * - 429: retry up to max retries.\n * - other 4xx: no retry.\n * - 5xx and network failures: retry up to max retries.\n * @returns the remote config info. null if failed to fetch or the response is not valid JSON.\n */\n async fetch(retries: number = DEFAULT_MAX_RETRIES, timeout: number = DEFAULT_TIMEOUT): Promise<RemoteConfigInfo> {\n const interval = timeout / retries;\n const failedRemoteConfigInfo: RemoteConfigInfo = {\n remoteConfig: null,\n lastFetch: new Date(),\n };\n\n for (let attempt = 0; attempt < retries; attempt++) {\n let shouldRetry = true;\n // Create AbortController for request timeout\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => abortController.abort(), timeout);\n\n try {\n const url = this.getUrlParams();\n const headers: Record<string, string> = { Accept: '*/*' };\n // When a custom transport is configured, hand it the fully-formed request and let it own\n // the network call; otherwise use the built-in fetch. Retry/response handling is identical.\n // The built-in fetch cancels directly on the signal; the custom transport can't be\n // cancelled, so race it against the abort (abortableFetch) to enforce the timeout even if\n // the transport ignores the signal — otherwise a hung transport would block every retry.\n const res = this.customFetch\n ? await abortableFetch(\n this.customFetch({ url, method: 'GET', headers, signal: abortController.signal }),\n abortController.signal,\n )\n : await fetch(url, {\n method: 'GET',\n headers,\n signal: abortController.signal,\n });\n\n // Treat a 2xx status as success even when `res.ok` is absent. A custom transport may return\n // a Response-like object that sets `status`/`text()`/`json()` but not `ok` (e.g. an axios\n // adapter); falling back to the status range keeps the config path consistent with the\n // event-upload path while still honoring native fetch's `ok`.\n const isSuccess = res.ok || (res.status >= 200 && res.status < 300);\n // Handle unsuccessful fetch\n if (!isSuccess) {\n const body = await res.text();\n this.logger.debug(`Remote config client fetch with retry time ${retries} failed with ${res.status}: ${body}`);\n\n if (res.status === CODE_STATUS.INVALID_API_KEY || res.status === CODE_STATUS.FORBIDDEN) {\n this.logger.error(\n `Remote config client fetch failed with ${res.status}. Invalid API key; future fetches will be skipped.`,\n );\n this.isLastFetchInvalidApiKey = true;\n shouldRetry = false;\n } else if (res.status >= 400 && res.status < 500 && res.status !== CODE_STATUS.RATE_LIMIT) {\n shouldRetry = false;\n }\n } else {\n // Handle successful fetch\n const remoteConfig: RemoteConfig = (await res.json()) as RemoteConfig;\n return {\n remoteConfig: remoteConfig,\n lastFetch: new Date(),\n };\n }\n } catch (error) {\n // Handle rejects when the request fails, for example, a network error or timeout\n if (error instanceof Error && error.name === 'AbortError') {\n this.logger.debug(`Remote config client fetch with retry time ${retries} timed out after ${timeout}ms`);\n } else {\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\n }\n } finally {\n // Clear the timeout since request completed or failed\n clearTimeout(timeoutId);\n }\n\n if (!shouldRetry) {\n break;\n }\n\n // Linear backoff:\n // wait for the specified interval before the next attempt\n // except after the last attempt.\n if (attempt < retries - 1) {\n await new Promise((resolve) => setTimeout(resolve, this.getJitterDelay(interval)));\n }\n }\n\n return failedRemoteConfigInfo;\n }\n\n /**\n * Return jitter in the bound of [0,baseDelay) and then floor round.\n */\n getJitterDelay(baseDelay: number): number {\n return Math.floor(Math.random() * baseDelay);\n }\n\n getUrlParams(): string {\n // URL encode the API key to handle special characters\n const encodedApiKey = encodeURIComponent(this.apiKey);\n\n const urlParams = new URLSearchParams();\n urlParams.append('config_group', this.configGroup);\n\n return `${this.serverUrl}/${encodedApiKey}?${urlParams.toString()}`;\n }\n}\n"]}
|
|
@@ -75,11 +75,6 @@ export interface IConfig {
|
|
|
75
75
|
* The URL where events are upload to.
|
|
76
76
|
*/
|
|
77
77
|
serverUrl?: string;
|
|
78
|
-
/**
|
|
79
|
-
* The URL where delayed events are uploaded to.
|
|
80
|
-
* @experimental this is experimental and subject to change.
|
|
81
|
-
*/
|
|
82
|
-
delayedEventsServerUrl?: string;
|
|
83
78
|
/**
|
|
84
79
|
* The Amplitude server zone.
|
|
85
80
|
* Set this to EU for Amplitude projects created in EU data center.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core-config.d.ts","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,MAAM,WAAW,OAAO;IACtB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;OAEG;IACH,mBAAmB,EAAE,MAAM,CAAC;IAC5B;;OAEG;IACH,eAAe,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,QAAQ,EAAE,QAAQ,CAAC;IACnB;;OAEG;IACH,cAAc,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,eAAe,CAAC;IAC3C;;;OAGG;IACH,MAAM,EAAE,OAAO,CAAC;IAChB;;;OAGG;IACH,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ;;;OAGG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC;;;;;;;;OAQG;IACH,4BAA4B,CAAC,EAAE,OAAO,CAAC;IACvC;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,
|
|
1
|
+
{"version":3,"file":"core-config.d.ts","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,MAAM,WAAW,OAAO;IACtB;;OAEG;IACH,MAAM,EAAE,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;IAChC,4BAA4B,CAAC,EAAE,MAAM,CAAC;IACtC,oCAAoC,CAAC,EAAE,MAAM,CAAC;IAC9C,iCAAiC,CAAC,EAAE,MAAM,CAAC;CAC5C;AAED,MAAM,MAAM,YAAY,GAAG,MAAM,iBAAiB,CAAC;AAEnD,MAAM,WAAW,aAAc,SAAQ,OAAO,CAAC,OAAO,CAAC;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,iBAAiB,EAAE,SAAS,CAAC;CAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core-config.js","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"","sourcesContent":["import { LogLevel } from '../loglevel';\nimport { ILogger } from '../../logger';\nimport { OfflineDisabled } from '../offline';\nimport { Plan } from '../event/plan';\nimport { IngestionMetadata } from '../event/ingestion-metadata';\nimport { ServerZoneType } from '../server-zone';\nimport { Transport } from '../transport';\nimport { Storage } from '../storage';\nimport { Event } from '../event/event';\nimport { IIdentify } from '../../identify';\n\nexport interface IConfig {\n /**\n * Your Amplitude Project API key.\n */\n apiKey: string;\n /**\n * The interval of uploading events to Amplitude in milliseconds.\n */\n flushIntervalMillis: number;\n /**\n * The maximum number of retries for failed upload attempts. This is only applicable to retryable errors.\n */\n flushMaxRetries: number;\n /**\n * The maximum number of events that are batched in a single upload attempt.\n */\n flushQueueSize: number;\n /**\n * The instance name. For tracking events to multiple Amplitude projects in your application.\n */\n instanceName?: string;\n /**\n * Level of logs to be printed in the developer console.\n * Valid values are `LogLevel.None`, `LogLevel.Error`, `LogLevel.Warn`, `LogLevel.Verbose`, `LogLevel.Debug`\n */\n logLevel: LogLevel;\n /**\n * A custom Logger class to emit log messages to desired destination.\n */\n loggerProvider: ILogger;\n /**\n * The minimum length for the value of userId and deviceId properties.\n */\n minIdLength?: number;\n /**\n * Whether the SDK is connected to network.\n */\n offline?: boolean | typeof OfflineDisabled;\n /**\n * The flag to opt this device out of Amplitude tracking.\n * If this flag is set, no additional information will be stored for the user.\n */\n optOut: boolean;\n /**\n * Tracking plan properties.\n * Amplitude internal use.\n */\n plan?: Plan;\n /**\n * Ingestion metadata.\n * Amplitude internal use.\n */\n ingestionMetadata?: IngestionMetadata;\n /**\n * Compress network request body payloads with gzip.\n *\n * For custom `serverUrl` values, this option controls whether compression is attempted.\n * For default Amplitude endpoints, compression remains enabled.\n * Compression is best-effort and only applies when the platform supports it,\n * the payload meets the minimum size threshold, and the transport can set request headers.\n * @defaultValue `false`\n */\n enableRequestBodyCompression?: boolean;\n /**\n * The URL where events are upload to.\n */\n serverUrl?: string;\n /**\n * The
|
|
1
|
+
{"version":3,"file":"core-config.js","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"","sourcesContent":["import { LogLevel } from '../loglevel';\nimport { ILogger } from '../../logger';\nimport { OfflineDisabled } from '../offline';\nimport { Plan } from '../event/plan';\nimport { IngestionMetadata } from '../event/ingestion-metadata';\nimport { ServerZoneType } from '../server-zone';\nimport { Transport } from '../transport';\nimport { Storage } from '../storage';\nimport { Event } from '../event/event';\nimport { IIdentify } from '../../identify';\n\nexport interface IConfig {\n /**\n * Your Amplitude Project API key.\n */\n apiKey: string;\n /**\n * The interval of uploading events to Amplitude in milliseconds.\n */\n flushIntervalMillis: number;\n /**\n * The maximum number of retries for failed upload attempts. This is only applicable to retryable errors.\n */\n flushMaxRetries: number;\n /**\n * The maximum number of events that are batched in a single upload attempt.\n */\n flushQueueSize: number;\n /**\n * The instance name. For tracking events to multiple Amplitude projects in your application.\n */\n instanceName?: string;\n /**\n * Level of logs to be printed in the developer console.\n * Valid values are `LogLevel.None`, `LogLevel.Error`, `LogLevel.Warn`, `LogLevel.Verbose`, `LogLevel.Debug`\n */\n logLevel: LogLevel;\n /**\n * A custom Logger class to emit log messages to desired destination.\n */\n loggerProvider: ILogger;\n /**\n * The minimum length for the value of userId and deviceId properties.\n */\n minIdLength?: number;\n /**\n * Whether the SDK is connected to network.\n */\n offline?: boolean | typeof OfflineDisabled;\n /**\n * The flag to opt this device out of Amplitude tracking.\n * If this flag is set, no additional information will be stored for the user.\n */\n optOut: boolean;\n /**\n * Tracking plan properties.\n * Amplitude internal use.\n */\n plan?: Plan;\n /**\n * Ingestion metadata.\n * Amplitude internal use.\n */\n ingestionMetadata?: IngestionMetadata;\n /**\n * Compress network request body payloads with gzip.\n *\n * For custom `serverUrl` values, this option controls whether compression is attempted.\n * For default Amplitude endpoints, compression remains enabled.\n * Compression is best-effort and only applies when the platform supports it,\n * the payload meets the minimum size threshold, and the transport can set request headers.\n * @defaultValue `false`\n */\n enableRequestBodyCompression?: boolean;\n /**\n * The URL where events are upload to.\n */\n serverUrl?: string;\n /**\n * The Amplitude server zone.\n * Set this to EU for Amplitude projects created in EU data center.\n */\n serverZone?: ServerZoneType;\n /**\n * The storage provider to persist unsent events.\n */\n storageProvider?: Storage<Event[]>;\n /**\n * A customer Transport Class for sending data to a server.\n */\n transportProvider: Transport;\n /**\n * The flag of whether to upload events to Batch API instead of the default HTTP V2 API.\n */\n useBatch: boolean;\n /**\n * Metrics of the SDK.\n */\n requestMetadata?: IRequestMetadata;\n /**\n * Invokes identify on this Identify object prior to initializing the SDK.\n */\n identify?: IIdentify;\n}\n\nexport interface IRequestMetadata {\n sdk: {\n metrics: {\n histogram: IHistogramOptions;\n };\n };\n\n recordHistogram<T extends HistogramKey>(key: T, value: IHistogramOptions[T]): void;\n}\n\nexport interface IHistogramOptions {\n remote_config_fetch_time_IDB?: number;\n remote_config_fetch_time_API_success?: number;\n remote_config_fetch_time_API_fail?: number;\n}\n\nexport type HistogramKey = keyof IHistogramOptions;\n\nexport interface ConfigOptions extends Partial<IConfig> {\n apiKey: string;\n transportProvider: Transport;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-event.d.ts","sourceRoot":"","sources":["../../../../src/types/event/base-event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;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AAA;KAAE,GAAG,SAAS,CAAC;IAC5C,KAAK,CAAC,EAAE,KAAK,CAAC;CACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-event.js","sourceRoot":"","sources":["../../../../src/types/event/base-event.ts"],"names":[],"mappings":"","sourcesContent":["import { Plan } from './plan';\nimport { IngestionMetadataEventProperty } from './ingestion-metadata';\n\nexport interface Delay {\n id: string;\n timeout?: number;\n
|
|
1
|
+
{"version":3,"file":"base-event.js","sourceRoot":"","sources":["../../../../src/types/event/base-event.ts"],"names":[],"mappings":"","sourcesContent":["import { Plan } from './plan';\nimport { IngestionMetadataEventProperty } from './ingestion-metadata';\n\nexport interface Delay {\n id: string;\n timeout?: number;\n}\n\nexport interface BaseEvent extends EventOptions {\n event_type: string;\n event_properties?: { [key: string]: any } | undefined;\n user_properties?: { [key: string]: any } | undefined;\n group_properties?: { [key: string]: any } | undefined;\n}\n\nexport interface EventOptions {\n user_id?: string;\n device_id?: string;\n time?: number;\n location_lat?: number;\n location_lng?: number;\n app_version?: string;\n version_name?: string;\n library?: string;\n platform?: string;\n os_name?: string;\n os_version?: string;\n device_brand?: string;\n device_manufacturer?: string;\n device_model?: string;\n carrier?: string;\n country?: string;\n region?: string;\n city?: string;\n dma?: string;\n idfa?: string;\n idfv?: string;\n adid?: string;\n android_id?: string;\n language?: string;\n ip?: string;\n price?: number;\n quantity?: number;\n revenue?: number;\n receipt?: string;\n receiptSig?: string;\n productId?: string;\n revenueType?: string;\n currency?: string;\n event_id?: number;\n session_id?: number;\n insert_id?: string;\n plan?: Plan;\n ingestion_metadata?: IngestionMetadataEventProperty;\n partner_id?: string;\n user_agent?: string;\n android_app_set_id?: string;\n extra?: { [key: string]: any };\n groups?: { [key: string]: any } | undefined;\n delay?: Delay;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BaseEvent
|
|
1
|
+
import { BaseEvent } from './base-event';
|
|
2
2
|
import { RevenueEventProperties } from '../../revenue';
|
|
3
3
|
export declare enum IdentifyOperation {
|
|
4
4
|
SET = "$set",
|
|
@@ -96,9 +96,6 @@ export interface RevenueEvent extends BaseEvent {
|
|
|
96
96
|
[key: string]: any;
|
|
97
97
|
};
|
|
98
98
|
}
|
|
99
|
-
export interface DelayedEvent extends BaseEvent {
|
|
100
|
-
delay: Delay;
|
|
101
|
-
}
|
|
102
99
|
export type Event = TrackEvent | IdentifyEvent | GroupIdentifyEvent | RevenueEvent;
|
|
103
100
|
export {};
|
|
104
101
|
//# sourceMappingURL=event.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../../../src/types/event/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,
|
|
1
|
+
{"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../../../src/types/event/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,oBAAY,iBAAiB;IAE3B,GAAG,SAAS;IACZ,QAAQ,aAAa;IAGrB,GAAG,SAAS;IACZ,MAAM,YAAY;IAClB,OAAO,aAAa;IACpB,MAAM,YAAY;IAGlB,SAAS,eAAe;IACxB,UAAU,gBAAgB;IAG1B,KAAK,WAAW;IAChB,SAAS,cAAc;CACxB;AAED,MAAM,MAAM,iBAAiB,GACzB,MAAM,GACN,MAAM,GACN,OAAO,GACP,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,GACtB;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAAA;CAAE,GACpC,KAAK,CAAC;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAAA;CAAE,CAAC,CAAC;AAEhD,UAAU,mBAAmB;IAC3B,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAAC;CAClC;AAED,MAAM,WAAW,sBAAsB;IAErC,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,SAAS;IACnD,UAAU,EAAE,gBAAgB,CAAC,cAAc,CAAC;IAC5C,gBAAgB,EAAE,cAAc,CAAC;CAClC;AAED,MAAM,WAAW,YAAa,SAAQ,SAAS;IAC7C,UAAU,EAAE,gBAAgB,CAAC,OAAO,CAAC;IACrC,gBAAgB,EACZ,sBAAsB,GACtB;QACE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;KACpB,CAAC;CACP;AAED,MAAM,MAAM,KAAK,GAAG,UAAU,GAAG,aAAa,GAAG,kBAAkB,GAAG,YAAY,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../src/types/event/event.ts"],"names":[],"mappings":"AAGA,MAAM,CAAN,IAAY,iBAkBX;AAlBD,WAAY,iBAAiB;IAC3B,gCAAgC;IAChC,iCAAY,CAAA;IACZ,0CAAqB,CAAA;IAErB,8CAA8C;IAC9C,iCAAY,CAAA;IACZ,uCAAkB,CAAA;IAClB,yCAAoB,CAAA;IACpB,uCAAkB,CAAA;IAElB,8DAA8D;IAC9D,6CAAwB,CAAA;IACxB,+CAA0B,CAAA;IAE1B,+CAA+C;IAC/C,qCAAgB,CAAA;IAChB,4CAAuB,CAAA;AACzB,CAAC,EAlBW,iBAAiB,KAAjB,iBAAiB,QAkB5B;AAwED;;;GAGG;AACH,MAAM,CAAN,IAAY,gBAIX;AAJD,WAAY,gBAAgB;IAC1B,0CAAsB,CAAA;IACtB,qDAAiC,CAAA;IACjC,8CAA0B,CAAA;AAC5B,CAAC,EAJW,gBAAgB,KAAhB,gBAAgB,QAI3B","sourcesContent":["import { BaseEvent
|
|
1
|
+
{"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../src/types/event/event.ts"],"names":[],"mappings":"AAGA,MAAM,CAAN,IAAY,iBAkBX;AAlBD,WAAY,iBAAiB;IAC3B,gCAAgC;IAChC,iCAAY,CAAA;IACZ,0CAAqB,CAAA;IAErB,8CAA8C;IAC9C,iCAAY,CAAA;IACZ,uCAAkB,CAAA;IAClB,yCAAoB,CAAA;IACpB,uCAAkB,CAAA;IAElB,8DAA8D;IAC9D,6CAAwB,CAAA;IACxB,+CAA0B,CAAA;IAE1B,+CAA+C;IAC/C,qCAAgB,CAAA;IAChB,4CAAuB,CAAA;AACzB,CAAC,EAlBW,iBAAiB,KAAjB,iBAAiB,QAkB5B;AAwED;;;GAGG;AACH,MAAM,CAAN,IAAY,gBAIX;AAJD,WAAY,gBAAgB;IAC1B,0CAAsB,CAAA;IACtB,qDAAiC,CAAA;IACjC,8CAA0B,CAAA;AAC5B,CAAC,EAJW,gBAAgB,KAAhB,gBAAgB,QAI3B","sourcesContent":["import { BaseEvent } from './base-event';\nimport { RevenueEventProperties } from '../../revenue';\n\nexport enum IdentifyOperation {\n // Base Operations to set values\n SET = '$set',\n SET_ONCE = '$setOnce',\n\n // Operations around modifying existing values\n ADD = '$add',\n APPEND = '$append',\n PREPEND = '$prepend',\n REMOVE = '$remove',\n\n // Operations around appending values *if* they aren't present\n PREINSERT = '$preInsert',\n POSTINSERT = '$postInsert',\n\n // Operations around removing properties/values\n UNSET = '$unset',\n CLEAR_ALL = '$clearAll',\n}\n\nexport type ValidPropertyType =\n | number\n | string\n | boolean\n | Array<string | number>\n | { [key: string]: ValidPropertyType }\n | Array<{ [key: string]: ValidPropertyType }>;\n\ninterface BaseOperationConfig {\n [key: string]: ValidPropertyType;\n}\n\nexport interface IdentifyUserProperties {\n // Add operations can only take numbers\n [IdentifyOperation.ADD]?: { [key: string]: number };\n\n // This reads the keys of the passed object, but the values are not used\n [IdentifyOperation.UNSET]?: BaseOperationConfig;\n // This option does not read the key as it unsets all user properties\n [IdentifyOperation.CLEAR_ALL]?: any;\n\n // These operations can take numbers, strings, or arrays of both.\n [IdentifyOperation.SET]?: BaseOperationConfig;\n [IdentifyOperation.SET_ONCE]?: BaseOperationConfig;\n [IdentifyOperation.APPEND]?: BaseOperationConfig;\n [IdentifyOperation.PREPEND]?: BaseOperationConfig;\n [IdentifyOperation.POSTINSERT]?: BaseOperationConfig;\n [IdentifyOperation.PREINSERT]?: BaseOperationConfig;\n [IdentifyOperation.REMOVE]?: BaseOperationConfig;\n}\n\n/**\n * Represents the structure of user properties that can be sent with an Identify or GroupIdentify event.\n *\n * This type supports both:\n *\n * 1. Reserved Amplitude identify operations via `IdentifyUserProperties`:\n * These operations enable structured updates to user properties.\n *\n * Example:\n * ```ts\n * {\n * $set: { plan: 'premium', login_count: 1 },\n * $add: { login_count: 1 },\n * $unset: { plan: '-' },\n * $clearAll: '-'\n * }\n * ```\n *\n * 2. Custom user-defined properties (excluding reserved operation keys):\n * Useful for assigning static properties without using Identify operations.\n *\n * Example:\n * ```ts\n * {\n * custom_flag: true,\n * experiment_group: 'B',\n * favorite_color: 'blue'\n * }\n * ```\n *\n * This union ensures compatibility with Amplitude's identify semantics\n * while allowing flexibility to define arbitrary non-reserved properties.\n */\nexport type UserProperties =\n | IdentifyUserProperties\n | {\n [key in Exclude<string, IdentifyOperation>]: any;\n };\n\n/**\n * Strings that have special meaning when used as an event's type\n * and have different specifications.\n */\nexport enum SpecialEventType {\n IDENTIFY = '$identify',\n GROUP_IDENTIFY = '$groupidentify',\n REVENUE = 'revenue_amount',\n}\n\nexport interface TrackEvent extends BaseEvent {\n event_type: Exclude<string, SpecialEventType>;\n}\n\nexport interface IdentifyEvent extends BaseEvent {\n event_type: SpecialEventType.IDENTIFY;\n user_properties: UserProperties;\n}\n\nexport interface GroupIdentifyEvent extends BaseEvent {\n event_type: SpecialEventType.GROUP_IDENTIFY;\n group_properties: UserProperties;\n}\n\nexport interface RevenueEvent extends BaseEvent {\n event_type: SpecialEventType.REVENUE;\n event_properties:\n | RevenueEventProperties\n | {\n [key: string]: any;\n };\n}\n\nexport type Event = TrackEvent | IdentifyEvent | GroupIdentifyEvent | RevenueEvent;\n"]}
|
|
@@ -10,9 +10,4 @@ export interface Payload {
|
|
|
10
10
|
client_upload_time?: string;
|
|
11
11
|
request_metadata?: RequestMetadata;
|
|
12
12
|
}
|
|
13
|
-
export interface DelayedPayload extends Payload {
|
|
14
|
-
id: string;
|
|
15
|
-
timeout: number;
|
|
16
|
-
instant_events?: readonly Event[];
|
|
17
|
-
}
|
|
18
13
|
//# sourceMappingURL=payload.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload.d.ts","sourceRoot":"","sources":["../../../src/types/payload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAE5C,MAAM,WAAW,cAAc;IAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,OAAO;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,SAAS,KAAK,EAAE,CAAC;IACzB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gBAAgB,CAAC,EAAE,eAAe,CAAC;CACpC
|
|
1
|
+
{"version":3,"file":"payload.d.ts","sourceRoot":"","sources":["../../../src/types/payload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAE5C,MAAM,WAAW,cAAc;IAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,OAAO;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,SAAS,KAAK,EAAE,CAAC;IACzB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gBAAgB,CAAC,EAAE,eAAe,CAAC;CACpC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload.js","sourceRoot":"","sources":["../../../src/types/payload.ts"],"names":[],"mappings":"","sourcesContent":["import { Event } from './event/event';\nimport { RequestMetadata } from '../config';\n\nexport interface PayloadOptions {\n min_id_length?: number;\n}\n\nexport interface Payload {\n api_key: string;\n events: readonly Event[];\n options?: PayloadOptions;\n client_upload_time?: string;\n request_metadata?: RequestMetadata;\n}\n
|
|
1
|
+
{"version":3,"file":"payload.js","sourceRoot":"","sources":["../../../src/types/payload.ts"],"names":[],"mappings":"","sourcesContent":["import { Event } from './event/event';\nimport { RequestMetadata } from '../config';\n\nexport interface PayloadOptions {\n min_id_length?: number;\n}\n\nexport interface Payload {\n api_key: string;\n events: readonly Event[];\n options?: PayloadOptions;\n client_upload_time?: string;\n request_metadata?: RequestMetadata;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instance-name.d.ts","sourceRoot":"","sources":["../../../src/utils/instance-name.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,qBAAqB,kBAAmB,MAAM,KAAG,MAE7D,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instance-name.js","sourceRoot":"","sources":["../../../src/utils/instance-name.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,MAAM,CAAC,IAAM,qBAAqB,GAAG,UAAC,YAAqB;IACzD,OAAO,YAAY,KAAK,SAAS,IAAI,YAAY,KAAK,EAAE,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,YAAY,CAAC;AAClG,CAAC,CAAC","sourcesContent":["import { DEFAULT_INSTANCE_NAME } from '../types/constants';\n\nexport const normalizeInstanceName = (instanceName?: string): string => {\n return instanceName === undefined || instanceName === '' ? DEFAULT_INSTANCE_NAME : instanceName;\n};\n"]}
|
|
@@ -6,6 +6,6 @@ import { VideoHandler, EmbeddedVideoPlayer, MuxElement, Vendor } from './types';
|
|
|
6
6
|
* @param handlers - The video handlers to call when on video lifecycle events.
|
|
7
7
|
* @returns A function to untrack the video.
|
|
8
8
|
*/
|
|
9
|
-
export declare function trackHtmlVideo(videoEl:
|
|
9
|
+
export declare function trackHtmlVideo(videoEl: HTMLVideoElement | MuxElement, handlers: VideoHandler, vendor?: Vendor): () => void;
|
|
10
10
|
export declare function trackEmbeddedVideo(player: EmbeddedVideoPlayer, handlers: VideoHandler, vendor?: Vendor | null): () => void;
|
|
11
11
|
//# sourceMappingURL=track-video.d.ts.map
|