-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathindex.ts
521 lines (457 loc) · 14.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import { getProcessEnv } from '../lib/get-process-env'
import { getCDN, setGlobalCDNUrl } from '../lib/parse-cdn'
import { fetch } from '../lib/fetch'
import { Analytics, NullAnalytics, InitOptions } from '../core/analytics'
import { Context } from '../core/context'
import { Plan } from '../core/events'
import { Plugin } from '../core/plugin'
import { MetricsOptions } from '../core/stats/remote-metrics'
import { mergedOptions } from '../lib/merged-options'
import { createDeferred } from '@segment/analytics-generic-utils'
import { envEnrichment } from '../plugins/env-enrichment'
import {
PluginFactory,
remoteLoader,
RemotePlugin,
} from '../plugins/remote-loader'
import type { RoutingRule } from '../plugins/routing-middleware'
import { segmentio, SegmentioSettings } from '../plugins/segmentio'
import {
AnalyticsBuffered,
PreInitMethodCallBuffer,
flushAnalyticsCallsInNewTask,
flushAddSourceMiddleware,
flushSetAnonymousID,
flushOn,
PreInitMethodCall,
flushRegister,
} from '../core/buffer'
import { ClassicIntegrationSource } from '../plugins/ajs-destination/types'
import { attachInspector } from '../core/inspector'
import { Stats } from '../core/stats'
import { setGlobalAnalyticsKey } from '../lib/global-analytics-helper'
export interface RemoteIntegrationSettings {
/* @deprecated - This does not indicate browser types anymore */
type?: string
versionSettings?: {
version?: string
override?: string
componentTypes?: ('browser' | 'android' | 'ios' | 'server')[]
}
/**
* We know if an integration is device mode if it has `bundlingStatus: 'bundled'` and the `browser` componentType in `versionSettings`.
* History: The term 'bundle' is left over from before action destinations, when a device mode destinations were 'bundled' in a custom bundle for every analytics.js source.
*/
bundlingStatus?: 'bundled' | 'unbundled'
/**
* Consent settings for the integration
*/
consentSettings?: {
/**
* Consent categories for the integration
* @example ["CAT001", "CAT002"]
*/
categories: string[]
}
// Segment.io specific
retryQueue?: boolean
// any extra unknown settings
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any
}
/**
* The remote settings object for a source, typically fetched from the Segment CDN.
* Warning: this is an *unstable* object.
*/
export interface CDNSettings {
integrations: {
[creationName: string]: RemoteIntegrationSettings
}
middlewareSettings?: {
routingRules: RoutingRule[]
}
enabledMiddleware?: Record<string, boolean>
metrics?: MetricsOptions
plan?: Plan
legacyVideoPluginsEnabled?: boolean
remotePlugins?: RemotePlugin[]
/**
* Top level consent settings
*/
consentSettings?: {
/**
* All unique consent categories for enabled destinations.
* There can be categories in this array that are important for consent that are not included in any integration (e.g. 2 cloud mode categories).
* @example ["Analytics", "Advertising", "CAT001"]
*/
allCategories: string[]
/**
* Whether or not there are any unmapped destinations for enabled destinations.
*/
hasUnmappedDestinations: boolean
}
/**
* Settings for edge function. Used for signals.
*/
edgeFunction?: // this is technically non-nullable according to ajs-renderer atm, but making it optional because it's strange API choice, and we might want to change it.
| {
/**
* The URL of the edge function (.js file).
* @example 'https://cdn.edgefn.segment.com/MY-WRITEKEY/foo.js',
*/
downloadURL: string
/**
* The version of the edge function
* @example 1
*/
version: number
}
| {}
/**
* Settings for auto instrumentation
*/
autoInstrumentationSettings?: {
sampleRate: number
}
}
export interface AnalyticsBrowserSettings {
writeKey: string
/**
* The settings for the Segment Source.
* If provided, `AnalyticsBrowser` will not fetch remote settings
* for the source.
*/
cdnSettings?: CDNSettings & Record<string, unknown>
/**
* If provided, will override the default Segment CDN (https://cdn.segment.com) for this application.
*/
cdnURL?: string
/**
* Plugins or npm-installed action destinations
*/
plugins?: (Plugin | PluginFactory)[]
/**
* npm-installed classic destinations
*/
classicIntegrations?: ClassicIntegrationSource[]
}
export function loadCDNSettings(
writeKey: string,
baseUrl: string
): Promise<CDNSettings> {
return fetch(`${baseUrl}/v1/projects/${writeKey}/settings`)
.then((res) => {
if (!res.ok) {
return res.text().then((errorResponseMessage) => {
throw new Error(errorResponseMessage)
})
}
return res.json()
})
.catch((err) => {
console.error(err.message)
throw err
})
}
function hasLegacyDestinations(settings: CDNSettings): boolean {
return (
getProcessEnv().NODE_ENV !== 'test' &&
// just one integration means segmentio
Object.keys(settings.integrations).length > 1
)
}
function hasTsubMiddleware(settings: CDNSettings): boolean {
return (
getProcessEnv().NODE_ENV !== 'test' &&
(settings.middlewareSettings?.routingRules?.length ?? 0) > 0
)
}
/**
* With AJS classic, we allow users to call setAnonymousId before the library initialization.
* This is important because some of the destinations will use the anonymousId during the initialization,
* and if we set anonId afterwards, that wouldn’t impact the destination.
*
* Also Ensures events can be registered before library initialization.
* This is important so users can register to 'initialize' and any events that may fire early during setup.
*/
function flushPreBuffer(
analytics: Analytics,
buffer: PreInitMethodCallBuffer
): void {
flushSetAnonymousID(analytics, buffer)
flushOn(analytics, buffer)
}
/**
* Finish flushing buffer and cleanup.
*/
async function flushFinalBuffer(
analytics: Analytics,
queryString: string,
buffer: PreInitMethodCallBuffer
): Promise<void> {
await flushQueryString(analytics, queryString)
flushAnalyticsCallsInNewTask(analytics, buffer)
}
const getQueryString = (): string => {
const hash = window.location.hash ?? ''
const search = window.location.search ?? ''
const term = search.length ? search : hash.replace(/(?=#).*(?=\?)/, '')
return term
}
const flushQueryString = async (
analytics: Analytics,
queryString: string
): Promise<void> => {
if (queryString.includes('ajs_')) {
await analytics.queryString(queryString).catch(console.error)
}
}
async function registerPlugins(
writeKey: string,
cdnSettings: CDNSettings,
analytics: Analytics,
options: InitOptions,
pluginLikes: (Plugin | PluginFactory)[] = [],
legacyIntegrationSources: ClassicIntegrationSource[],
preInitBuffer: PreInitMethodCallBuffer
): Promise<Context> {
flushPreBuffer(analytics, preInitBuffer)
const pluginsFromSettings = pluginLikes?.filter(
(pluginLike) => typeof pluginLike === 'object'
) as Plugin[]
const pluginSources = pluginLikes?.filter(
(pluginLike) =>
typeof pluginLike === 'function' &&
typeof pluginLike.pluginName === 'string'
) as PluginFactory[]
const tsubMiddleware = hasTsubMiddleware(cdnSettings)
? await import(
/* webpackChunkName: "tsub-middleware" */ '../plugins/routing-middleware'
).then((mod) => {
return mod.tsubMiddleware(cdnSettings.middlewareSettings!.routingRules)
})
: undefined
const legacyDestinations =
hasLegacyDestinations(cdnSettings) || legacyIntegrationSources.length > 0
? await import(
/* webpackChunkName: "ajs-destination" */ '../plugins/ajs-destination'
).then((mod) => {
return mod.ajsDestinations(
writeKey,
cdnSettings,
analytics.integrations,
options,
tsubMiddleware,
legacyIntegrationSources
)
})
: []
if (cdnSettings.legacyVideoPluginsEnabled) {
await import(
/* webpackChunkName: "legacyVideos" */ '../plugins/legacy-video-plugins'
).then((mod) => {
return mod.loadLegacyVideoPlugins(analytics)
})
}
const schemaFilter = options.plan?.track
? await import(
/* webpackChunkName: "schemaFilter" */ '../plugins/schema-filter'
).then((mod) => {
return mod.schemaFilter(options.plan?.track, cdnSettings)
})
: undefined
const mergedSettings = mergedOptions(cdnSettings, options)
const remotePlugins = await remoteLoader(
cdnSettings,
analytics.integrations,
mergedSettings,
options,
tsubMiddleware,
pluginSources
).catch(() => [])
const basePlugins = [envEnrichment, ...legacyDestinations, ...remotePlugins]
if (schemaFilter) {
basePlugins.push(schemaFilter)
}
const shouldIgnoreSegmentio =
(options.integrations?.All === false &&
!options.integrations['Segment.io']) ||
(options.integrations && options.integrations['Segment.io'] === false)
if (!shouldIgnoreSegmentio) {
basePlugins.push(
await segmentio(
analytics,
mergedSettings['Segment.io'] as SegmentioSettings,
cdnSettings.integrations
)
)
}
// order is important here, (for example, if there are multiple enrichment plugins, the last registered plugin will have access to the last context.)
const ctx = await analytics.register(
// register 'core' plugins and those via destinations
...basePlugins,
// register user-defined plugins passed into AnalyticsBrowser.load({ plugins: [plugin1, plugin2] }) -- relevant to npm-only
...pluginsFromSettings
)
// register user-defined plugins registered via analytics.register()
await flushRegister(analytics, preInitBuffer)
if (
Object.entries(cdnSettings.enabledMiddleware ?? {}).some(
([, enabled]) => enabled
)
) {
await import(
/* webpackChunkName: "remoteMiddleware" */ '../plugins/remote-middleware'
).then(async ({ remoteMiddlewares }) => {
const middleware = await remoteMiddlewares(
ctx,
cdnSettings,
options.obfuscate
)
const promises = middleware.map((mdw) =>
analytics.addSourceMiddleware(mdw)
)
return Promise.all(promises)
})
}
// register any user-defined plugins added via analytics.addSourceMiddleware()
await flushAddSourceMiddleware(analytics, preInitBuffer)
return ctx
}
async function loadAnalytics(
settings: AnalyticsBrowserSettings,
options: InitOptions = {},
preInitBuffer: PreInitMethodCallBuffer
): Promise<[Analytics, Context]> {
// return no-op analytics instance if disabled
if (options.disable === true) {
return [new NullAnalytics(), Context.system()]
}
if (options.globalAnalyticsKey)
setGlobalAnalyticsKey(options.globalAnalyticsKey)
// this is an ugly side-effect, but it's for the benefits of the plugins that get their cdn via getCDN()
if (settings.cdnURL) setGlobalCDNUrl(settings.cdnURL)
if (options.initialPageview) {
// capture the page context early, so it's always up-to-date
preInitBuffer.add(new PreInitMethodCall('page', []))
}
// reading the query string as early as possible in case the URL changes
const queryString = getQueryString()
const cdnURL = settings.cdnURL ?? getCDN()
let cdnSettings =
settings.cdnSettings ?? (await loadCDNSettings(settings.writeKey, cdnURL))
if (options.updateCDNSettings) {
cdnSettings = options.updateCDNSettings(cdnSettings)
}
// if options.disable is a function, we allow user to disable analytics based on CDN Settings
if (typeof options.disable === 'function') {
const disabled = await options.disable(cdnSettings)
if (disabled) {
return [new NullAnalytics(), Context.system()]
}
}
const retryQueue: boolean =
cdnSettings.integrations['Segment.io']?.retryQueue ?? true
options = {
retryQueue,
...options,
}
const analytics = new Analytics({ ...settings, cdnSettings, cdnURL }, options)
attachInspector(analytics)
const plugins = settings.plugins ?? []
const classicIntegrations = settings.classicIntegrations ?? []
const segmentLoadOptions = options.integrations?.['Segment.io'] as
| SegmentioSettings
| undefined
Stats.initRemoteMetrics({
...cdnSettings.metrics,
host: segmentLoadOptions?.apiHost ?? cdnSettings.metrics?.host,
protocol: segmentLoadOptions?.protocol,
})
const ctx = await registerPlugins(
settings.writeKey,
cdnSettings,
analytics,
options,
plugins,
classicIntegrations,
preInitBuffer
)
analytics.initialized = true
analytics.emit('initialize', settings, options)
await flushFinalBuffer(analytics, queryString, preInitBuffer)
return [analytics, ctx]
}
/**
* The public browser interface for Segment Analytics
*
* @example
* ```ts
* export const analytics = new AnalyticsBrowser()
* analytics.load({ writeKey: 'foo' })
* ```
* @link https://github.com/segmentio/analytics-next/#readme
*/
export class AnalyticsBrowser extends AnalyticsBuffered {
private _resolveLoadStart: (
settings: AnalyticsBrowserSettings,
options: InitOptions
) => void
constructor() {
const { promise: loadStart, resolve: resolveLoadStart } =
createDeferred<Parameters<AnalyticsBrowser['load']>>()
super((buffer) =>
loadStart.then(([settings, options]) =>
loadAnalytics(settings, options, buffer)
)
)
this._resolveLoadStart = (settings, options) =>
resolveLoadStart([settings, options])
}
/**
* Fully initialize an analytics instance, including:
*
* * Fetching settings from the segment CDN (by default).
* * Fetching all remote destinations configured by the user (if applicable).
* * Flushing buffered analytics events.
* * Loading all middleware.
*
* Note:️ This method should only be called *once* in your application.
*
* @example
* ```ts
* export const analytics = new AnalyticsBrowser()
* analytics.load({ writeKey: 'foo' })
* ```
*/
load(
settings: AnalyticsBrowserSettings,
options: InitOptions = {}
): AnalyticsBrowser {
this._resolveLoadStart(settings, options)
return this
}
/**
* Instantiates an object exposing Analytics methods.
*
* @example
* ```ts
* const ajs = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })
*
* ajs.track("foo")
* ...
* ```
*/
static load(
settings: AnalyticsBrowserSettings,
options: InitOptions = {}
): AnalyticsBrowser {
return new AnalyticsBrowser().load(settings, options)
}
static standalone(
writeKey: string,
options?: InitOptions
): Promise<Analytics> {
return AnalyticsBrowser.load({ writeKey }, options).then((res) => res[0])
}
}