-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathindex.ts
More file actions
297 lines (266 loc) · 9.26 KB
/
index.ts
File metadata and controls
297 lines (266 loc) · 9.26 KB
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
import { Breaker, PostHogConfig, Properties } from '../types'
import { nativeForEach, nativeIndexOf } from './globals'
import { logger } from './logger'
import { isFormData, isNull, isNullish, isNumber, isString, hasOwnProperty, isArray } from '@posthog/core'
const breaker: Breaker = {}
export function eachArray<E = any>(
obj: E[] | null | undefined,
iterator: (value: E, key: number) => void | Breaker,
thisArg?: any
): void {
if (isArray(obj)) {
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, thisArg)
} else if ('length' in obj && obj.length === +obj.length) {
for (let i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
return
}
}
}
}
}
/**
* @param {*=} obj
* @param {function(...*)=} iterator
* @param {Object=} thisArg
*/
export function each(obj: any, iterator: (value: any, key: any) => void | Breaker, thisArg?: any): void {
if (isNullish(obj)) {
return
}
if (isArray(obj)) {
return eachArray(obj, iterator, thisArg)
}
if (isFormData(obj)) {
for (const pair of obj.entries()) {
if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {
return
}
}
return
}
for (const key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(thisArg, obj[key], key) === breaker) {
return
}
}
}
}
export const extend = function (obj: Record<string, any>, ...args: Record<string, any>[]): Record<string, any> {
eachArray(args, function (source) {
for (const prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop]
}
}
})
return obj
}
export const extendArray = function <T>(obj: T[], ...args: T[][]): T[] {
eachArray(args, function (source) {
eachArray(source, function (item) {
obj.push(item)
})
})
return obj
}
export const include = function (
obj: null | string | Array<any> | Record<string, any>,
target: any
): boolean | Breaker {
let found = false
if (isNull(obj)) {
return found
}
if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
return obj.indexOf(target) != -1
}
each(obj, function (value) {
if (found || (found = value === target)) {
return breaker
}
return
})
return found
}
/**
* Object.entries() polyfill
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
*/
export function entries<T = any>(obj: Record<string, T>): [string, T][] {
const ownProps = Object.keys(obj)
let i = ownProps.length
const resArray = new Array(i) // preallocate the Array
while (i--) {
resArray[i] = [ownProps[i], obj[ownProps[i]]]
}
return resArray
}
export const trySafe = function <T>(fn: () => T): T | undefined {
try {
return fn()
} catch {
return undefined
}
}
export class PostHogConfigError extends Error {}
export const safewrap = function <F extends (...args: any[]) => any = (...args: any[]) => any>(f: F): F {
return function (...args) {
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return f.apply(this, args)
} catch (e) {
if (e instanceof PostHogConfigError) {
throw e
}
logger.critical(
'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'
)
logger.critical(e)
}
} as F
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
export const safewrapClass = function (klass: Function, functions: string[]): void {
for (let i = 0; i < functions.length; i++) {
klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])
}
}
export const stripEmptyProperties = function (p: Properties): Properties {
const ret: Properties = {}
each(p, function (v, k) {
if ((isString(v) && v.length > 0) || isNumber(v)) {
ret[k] = v
}
})
return ret
}
/**
* Deep copies an object.
* It handles cycles by replacing all references to them with `undefined`
* Also supports customizing native values
*
* @param value
* @param customizer
* @returns {{}|undefined|*}
*/
function deepCircularCopy<T extends Record<string, any> = Record<string, any>>(
value: T,
customizer?: <K extends keyof T = keyof T>(value: T[K], key?: K) => T[K]
): T | undefined {
const COPY_IN_PROGRESS_SET = new Set()
function internalDeepCircularCopy(value: T, key?: string): T | undefined {
if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value
if (COPY_IN_PROGRESS_SET.has(value)) return undefined
COPY_IN_PROGRESS_SET.add(value)
let result: T
if (isArray(value)) {
result = [] as any as T
eachArray(value, (it) => {
result.push(internalDeepCircularCopy(it))
})
} else {
result = {} as T
each(value, (val, key) => {
if (!COPY_IN_PROGRESS_SET.has(val)) {
;(result as any)[key] = internalDeepCircularCopy(val, key)
}
})
}
return result
}
return internalDeepCircularCopy(value)
}
export function _copyAndTruncateStrings<T extends Record<string, any> = Record<string, any>>(
object: T,
maxStringLength: number | null
): T {
return deepCircularCopy(object, (value: any) => {
if (isString(value) && !isNull(maxStringLength)) {
return (value as string).slice(0, maxStringLength)
}
return value
}) as T
}
// NOTE: Update PostHogConfig docs if you change this list
// We will not try to catch all bullets here, but we should make an effort to catch the most common ones
// You should be highly against adding more to this list, because ultimately customers can configure
// their `cross_subdomain_cookie` setting to anything they want.
const EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app']
export function isCrossDomainCookie(documentLocation: Location | undefined) {
const hostname = documentLocation?.hostname
if (!isString(hostname)) {
return false
}
// split and slice isn't a great way to match arbitrary domains,
// but it's good enough for ensuring we only match herokuapp.com when it is the TLD
// for the hostname
const lastTwoParts = hostname.split('.').slice(-2).join('.')
for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {
if (lastTwoParts === excluded) {
return false
}
}
return true
}
export function find<T>(value: T[], predicate: (value: T) => boolean): T | undefined {
for (let i = 0; i < value.length; i++) {
if (predicate(value[i])) {
return value[i]
}
}
return undefined
}
// Use this instead of element.addEventListener to avoid eslint errors
// this properly implements the default options for passive event listeners
export function addEventListener(
element: Window | Document | Element | undefined,
event: string,
callback: EventListener,
options?: AddEventListenerOptions
): void {
const { capture = false, passive = true } = options ?? {}
// This is the only place where we are allowed to call this function
// because the whole idea is that we should be calling this instead of the built-in one
// eslint-disable-next-line posthog-js/no-add-event-listener
element?.addEventListener(event, callback, { capture, passive })
}
/**
* Helper to migrate deprecated config fields to new field names with appropriate warnings
* @param config - The config object to check
* @param newField - The new field name to use
* @param oldField - The deprecated field name to check for
* @param defaultValue - The default value if neither field is set
* @param loggerInstance - Optional logger instance for deprecation warnings
* @returns The value to use (new field takes precedence over old field)
*/
export function migrateConfigField<T>(
config: Record<string, any>,
newField: string,
oldField: string,
defaultValue: T,
loggerInstance?: { warn: (message: string) => void }
): T {
const hasNewField = newField in config && !isNullish(config[newField])
const hasOldField = oldField in config && !isNullish(config[oldField])
if (hasNewField) {
return config[newField]
}
if (hasOldField) {
if (loggerInstance) {
loggerInstance.warn(
`Config field '${oldField}' is deprecated. Please use '${newField}' instead. ` +
`The old field will be removed in a future major version.`
)
}
return config[oldField]
}
return defaultValue
}
const TOOLBAR_INTERNAL_INSTANCE_NAME = 'ph_toolbar_internal'
export function isToolbarInstance(config: Pick<PostHogConfig, 'name'>): boolean {
return config.name === TOOLBAR_INTERNAL_INSTANCE_NAME
}