posthog-node 6.4.0 → 6.4.2

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.
Files changed (71) hide show
  1. package/dist/capture-lane/lane.d.ts +4 -4
  2. package/dist/capture-lane/lane.d.ts.map +1 -1
  3. package/dist/capture-lane/lane.js +8 -9
  4. package/dist/capture-lane/lane.mjs +1 -2
  5. package/dist/capture-lane/settings.d.ts +1 -1
  6. package/dist/capture-lane/settings.d.ts.map +1 -1
  7. package/dist/capture-lane/settings.js +3 -3
  8. package/dist/capture-lane/settings.mjs +1 -1
  9. package/dist/client.d.ts +3 -3
  10. package/dist/client.js +16 -20
  11. package/dist/client.mjs +2 -6
  12. package/dist/compression.node.d.ts +1 -1
  13. package/dist/entrypoints/index.node.d.ts +1 -1
  14. package/dist/entrypoints/index.node.d.ts.map +1 -1
  15. package/dist/exports.d.ts +3 -3
  16. package/dist/exports.d.ts.map +1 -1
  17. package/dist/exports.js +5 -5
  18. package/dist/exports.mjs +1 -1
  19. package/dist/extensions/nestjs.d.ts.map +1 -1
  20. package/dist/extensions/nestjs.js +1 -0
  21. package/dist/extensions/nestjs.mjs +1 -0
  22. package/dist/types.d.ts +3 -3
  23. package/dist/types.d.ts.map +1 -1
  24. package/dist/version.d.ts +1 -1
  25. package/dist/version.js +1 -1
  26. package/dist/version.mjs +1 -1
  27. package/package.json +4 -4
  28. package/src/capture-lane/lane.ts +4 -4
  29. package/src/capture-lane/settings.ts +1 -1
  30. package/src/client.ts +9 -9
  31. package/src/compression.node.ts +1 -1
  32. package/src/entrypoints/index.node.ts +1 -1
  33. package/src/exports.ts +3 -3
  34. package/src/extensions/nestjs.ts +12 -0
  35. package/src/types.ts +3 -3
  36. package/src/version.ts +1 -1
  37. package/dist/capture-v1/compression.d.ts +0 -18
  38. package/dist/capture-v1/compression.d.ts.map +0 -1
  39. package/dist/capture-v1/compression.js +0 -70
  40. package/dist/capture-v1/compression.mjs +0 -26
  41. package/dist/capture-v1/errors.d.ts +0 -48
  42. package/dist/capture-v1/errors.d.ts.map +0 -1
  43. package/dist/capture-v1/errors.js +0 -82
  44. package/dist/capture-v1/errors.mjs +0 -38
  45. package/dist/capture-v1/sender.d.ts +0 -110
  46. package/dist/capture-v1/sender.d.ts.map +0 -1
  47. package/dist/capture-v1/sender.js +0 -481
  48. package/dist/capture-v1/sender.mjs +0 -434
  49. package/dist/capture-v1/serialize.d.ts +0 -28
  50. package/dist/capture-v1/serialize.d.ts.map +0 -1
  51. package/dist/capture-v1/serialize.js +0 -82
  52. package/dist/capture-v1/serialize.mjs +0 -38
  53. package/dist/capture-v1/transform.d.ts +0 -19
  54. package/dist/capture-v1/transform.d.ts.map +0 -1
  55. package/dist/capture-v1/transform.js +0 -118
  56. package/dist/capture-v1/transform.mjs +0 -77
  57. package/dist/capture-v1/types.d.ts +0 -52
  58. package/dist/capture-v1/types.d.ts.map +0 -1
  59. package/dist/capture-v1/types.js +0 -44
  60. package/dist/capture-v1/types.mjs +0 -3
  61. package/dist/capture-v1/uuid.d.ts +0 -9
  62. package/dist/capture-v1/uuid.d.ts.map +0 -1
  63. package/dist/capture-v1/uuid.js +0 -75
  64. package/dist/capture-v1/uuid.mjs +0 -34
  65. package/src/capture-v1/compression.ts +0 -50
  66. package/src/capture-v1/errors.ts +0 -91
  67. package/src/capture-v1/sender.ts +0 -668
  68. package/src/capture-v1/serialize.ts +0 -77
  69. package/src/capture-v1/transform.ts +0 -134
  70. package/src/capture-v1/types.ts +0 -59
  71. package/src/capture-v1/uuid.ts +0 -53
@@ -1,77 +0,0 @@
1
- import { type PostHogEventProperties, safeJsonStringify } from '@posthog/core'
2
-
3
- import { buildV1Event } from './transform'
4
-
5
- const encoder = new TextEncoder()
6
-
7
- // `buildV1Event` puts `properties` last, so the event JSON is the rest of the event with this key and the properties appended.
8
- const PROPERTIES_KEY = ',"properties":'
9
- const PROPERTIES_KEY_BYTES = encoder.encode(PROPERTIES_KEY).length
10
-
11
- /** One wire event, serialized once and reused verbatim in every request body that carries it. */
12
- export interface SerializedV1Event {
13
- uuid: string
14
- json: string
15
- /** UTF-8 size of `json`. */
16
- bytes: number
17
- /** UTF-8 size of the serialized `properties` object alone, which is what the AI endpoint limits. */
18
- propertiesBytes: number
19
- }
20
-
21
- const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
22
- // JSON.stringify writes a lone surrogate as a `\udXXX` escape (a valid pair stays raw), which capture rejects for the whole
23
- // request. The lookbehind skips an escaped backslash followed by literal "udXXX" text.
24
- const LONE_SURROGATE_ESCAPE = /(?<!\\)((?:\\\\)*)\\u[dD][89a-fA-F][0-9a-fA-F]{2}/g
25
-
26
- /**
27
- * Why capture would reject this event, or undefined when it can be sent. A name must be a non-empty string, the
28
- * distinct id a string, and the name and ids well-formed Unicode: a broken id is never repaired, because two broken ids
29
- * could collapse into one.
30
- */
31
- export function wireProblem(message: PostHogEventProperties): string | undefined {
32
- const { event, distinct_id: distinctId, properties } = message
33
- if (typeof event !== 'string' || event === '') {
34
- return 'event name is missing, empty or not a string'
35
- }
36
- // Caller ids are already strings, so only a beforeSend hook can leave a non-string here.
37
- if (typeof distinctId !== 'string') {
38
- return 'distinct id is missing or not a string'
39
- }
40
- const props = (properties ?? {}) as Record<string, unknown>
41
- const ids = [event, distinctId, props.$session_id, props.$window_id]
42
- if (ids.some((value) => typeof value === 'string' && LONE_SURROGATE.test(value))) {
43
- return 'event name or id is not well-formed Unicode'
44
- }
45
- return undefined
46
- }
47
-
48
- export function serializeV1Event(message: PostHogEventProperties): SerializedV1Event {
49
- const { properties, ...rest } = buildV1Event(message)
50
- const restJson = safeJsonStringify(rest)
51
- const rawPropertiesJson = safeJsonStringify(properties)
52
- // Property strings are repaired to U+FFFD rather than dropping the event.
53
- const propertiesJson =
54
- rawPropertiesJson.includes('\\ud') || rawPropertiesJson.includes('\\uD')
55
- ? rawPropertiesJson.replace(LONE_SURROGATE_ESCAPE, '$1\\ufffd')
56
- : rawPropertiesJson
57
- const propertiesBytes = encoder.encode(propertiesJson).length
58
- return {
59
- uuid: rest.uuid,
60
- json: `${restJson.slice(0, -1)}${PROPERTIES_KEY}${propertiesJson}}`,
61
- // The closing brace moves from the end of `restJson` to the end of the event, so it is counted once.
62
- bytes: encoder.encode(restJson).length + PROPERTIES_KEY_BYTES + propertiesBytes,
63
- propertiesBytes,
64
- }
65
- }
66
-
67
- /**
68
- * The Capture V1 batch envelope, built from already-serialized events. Unlike v0 there is no
69
- * `api_key` (Bearer auth) and no `sent_at`. `historical_migration` is omitted when false.
70
- */
71
- export function buildV1Body(
72
- events: readonly { json: string }[],
73
- { createdAt, historicalMigration }: { createdAt: string; historicalMigration: boolean }
74
- ): string {
75
- const migration = historicalMigration ? ',"historical_migration":true' : ''
76
- return `{"created_at":${JSON.stringify(createdAt)}${migration},"batch":[${events.map((event) => event.json).join(',')}]}`
77
- }
@@ -1,134 +0,0 @@
1
- import { EVENT_OPTION_LEGACY_PROPERTIES, type JsonType, type PostHogEventProperties } from '@posthog/core'
2
-
3
- import type { V1Event } from './types'
4
-
5
- /** Property -> top-level string field; any value that is not a string is dropped. */
6
- const TOPLEVEL_SENTINELS: ReadonlyArray<{ property: string; field: 'session_id' | 'window_id' }> = [
7
- { property: '$session_id', field: 'session_id' },
8
- { property: '$window_id', field: 'window_id' },
9
- ]
10
-
11
- function isRecord(value: unknown): value is PostHogEventProperties {
12
- return typeof value === 'object' && value !== null && !Array.isArray(value)
13
- }
14
-
15
- function jsonTypeName(value: JsonType): string {
16
- return Array.isArray(value) ? 'array' : typeof value
17
- }
18
-
19
- /**
20
- * A copy of the caller's per-event options, or undefined when there are none. Any value that
21
- * is not an object is reported and ignored, so the event is still sent.
22
- */
23
- export function readEventOptions(value: unknown): Record<string, JsonType> | undefined {
24
- if (value === undefined || value === null) {
25
- return undefined
26
- }
27
- if (isRecord(value)) {
28
- return { ...value }
29
- }
30
- // console.error, not the client logger: the logger only prints in debug mode, and the event loses its options.
31
- console.error(
32
- `[PostHog] options must be an object, got ${jsonTypeName(value as JsonType)}; sending the event without its options`
33
- )
34
- return undefined
35
- }
36
-
37
- /**
38
- * Normalize an event timestamp to an RFC 3339 string. The queued message
39
- * carries either an ISO string (from `currentISOTime()`) or a `Date` (when the
40
- * caller passed one); numbers are treated as epoch milliseconds. Invalid values
41
- * fall back to "now" so a bad timestamp never rejects the whole batch.
42
- */
43
- function replaceUnparseableTimestamp(): string {
44
- // console.warn, not the client logger: the logger only prints in debug mode, and the event's time changes. Never logs the value.
45
- console.warn('[PostHog] replacing an unparseable event timestamp with the current time')
46
- return new Date().toISOString()
47
- }
48
-
49
- function toRfc3339(timestamp: unknown): string {
50
- if (typeof timestamp === 'string') {
51
- const asDate = new Date(timestamp)
52
- if (Number.isNaN(asDate.getTime())) {
53
- return replaceUnparseableTimestamp()
54
- }
55
-
56
- const normalized = asDate.toISOString()
57
- const fractionalSeconds = timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]
58
- return fractionalSeconds && fractionalSeconds.length > 3
59
- ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`)
60
- : normalized
61
- }
62
- if (timestamp instanceof Date) {
63
- return Number.isNaN(timestamp.getTime()) ? replaceUnparseableTimestamp() : timestamp.toISOString()
64
- }
65
- const asDate = timestamp == null ? new Date() : new Date(timestamp as string | number)
66
- return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString()
67
- }
68
-
69
- /**
70
- * Relocate a top-level `$set`/`$set_once` value into `properties`. v1 has no
71
- * top-level form; the server reads them from inside `properties`. An existing
72
- * `properties` value wins on collision.
73
- */
74
- function relocateInto(properties: PostHogEventProperties, key: string, value: JsonType | undefined): void {
75
- if (value !== undefined && !(key in properties)) {
76
- properties[key] = value
77
- }
78
- }
79
-
80
- /**
81
- * Transform one already-normalized queued message into a Capture V1 wire event.
82
- *
83
- * The input message is never mutated (events may be retried or handed to
84
- * callbacks): fresh `options` and `properties` maps are built. Option values are
85
- * sent unchanged; capture reads them. Each legacy option property is removed from
86
- * `properties` and fills its option when the caller left that option missing or
87
- * `null`. `$session_id`/`$window_id` move to the top-level `session_id`/`window_id`
88
- * fields; top-level `$set`/`$set_once` are relocated into `properties`.
89
- */
90
- export function buildV1Event(message: PostHogEventProperties): V1Event {
91
- const sourceProperties = isRecord(message.properties) ? message.properties : {}
92
- const properties: PostHogEventProperties = { ...sourceProperties }
93
-
94
- const options = readEventOptions(message.options) ?? {}
95
- for (const [optionKey, property] of Object.entries(EVENT_OPTION_LEGACY_PROPERTIES)) {
96
- if (!(property in properties)) {
97
- continue
98
- }
99
- const legacyValue = properties[property]
100
- delete properties[property]
101
- const option = options[optionKey]
102
- if ((option === undefined || option === null) && legacyValue !== undefined) {
103
- options[optionKey] = legacyValue
104
- }
105
- }
106
-
107
- const topLevel: { session_id?: string; window_id?: string } = {}
108
- for (const { property, field } of TOPLEVEL_SENTINELS) {
109
- if (!(property in properties)) {
110
- continue
111
- }
112
- const value = properties[property]
113
- delete properties[property]
114
- if (typeof value === 'string') {
115
- topLevel[field] = value
116
- } else if (value !== undefined && value !== null) {
117
- // console.warn, not the client logger: the logger only prints in debug mode, and the event loses this id.
118
- console.warn(`[PostHog] dropping ${property}: a ${jsonTypeName(value)} value is not a string`)
119
- }
120
- }
121
-
122
- relocateInto(properties, '$set', message.$set)
123
- relocateInto(properties, '$set_once', message.$set_once)
124
-
125
- return {
126
- event: String(message.event ?? ''),
127
- uuid: String(message.uuid ?? ''),
128
- distinct_id: String(message.distinct_id ?? ''),
129
- timestamp: toRfc3339(message.timestamp),
130
- ...topLevel,
131
- options,
132
- properties,
133
- }
134
- }
@@ -1,59 +0,0 @@
1
- import type { JsonType, PostHogEventProperties } from '@posthog/core'
2
-
3
- /** Capture lane for analytics events. */
4
- export const ANALYTICS_CAPTURE_ENDPOINT = '/i/v1/analytics/events'
5
-
6
- /** Capture lane for events sent through `captureAi`. */
7
- export const AI_CAPTURE_ENDPOINT = '/i/v1/ai/events'
8
-
9
- export type CaptureEndpoint = typeof ANALYTICS_CAPTURE_ENDPOINT | typeof AI_CAPTURE_ENDPOINT
10
-
11
- /**
12
- * The `options` object on a Capture V1 event: the caller's options plus any legacy
13
- * `$`-prefixed option properties lifted by the transform. Values are sent unchanged.
14
- * Always serialized as an object (`{}` when empty), never `null`.
15
- */
16
- export interface V1EventOptions {
17
- /** Whether to process this event in cookieless mode. */
18
- cookieless_mode?: boolean
19
- /** Whether to disable server-side timestamp skew correction for this event. */
20
- disable_skew_correction?: boolean
21
- /** Whether to create or update a person profile for this event. */
22
- process_person_profile?: boolean
23
- /** Additional capture options, sent to capture v1 unchanged. */
24
- [key: string]: JsonType | undefined
25
- }
26
-
27
- /**
28
- * A single event in a Capture V1 batch.
29
- * `session_id`/`window_id` are promoted from the `$session_id`/`$window_id`
30
- * sentinels; there is no top-level `api_key`.
31
- */
32
- export interface V1Event {
33
- event: string
34
- uuid: string
35
- distinct_id: string
36
- timestamp: string
37
- session_id?: string
38
- window_id?: string
39
- options: V1EventOptions
40
- properties: PostHogEventProperties
41
- }
42
-
43
- /**
44
- * Per-event result codes in a v1 2xx response body. Unknown strings are
45
- * tolerated as terminal success for forward compatibility.
46
- */
47
- export type V1ResultCode = 'ok' | 'warning' | 'drop' | 'retry'
48
-
49
- export interface V1EventResult {
50
- result: V1ResultCode | string
51
- details?: string | null
52
- /** How many later copies of this uuid in the request the server dropped as duplicates. */
53
- duplicates_dropped?: number
54
- }
55
-
56
- /** Shape of a v1 2xx response body: a per-uuid map of results. */
57
- export interface V1BatchResponse {
58
- results: Record<string, V1EventResult>
59
- }
@@ -1,53 +0,0 @@
1
- import { V7Generator } from '@posthog/core'
2
-
3
- const HYPHENATED = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
4
- const HEX_32 = /^[0-9a-f]{32}$/i
5
- const URN_PREFIX = 'urn:uuid:'
6
-
7
- /**
8
- * The lowercase, hyphenated form of an RFC 4122 uuid string, or undefined for anything else.
9
- * Accepts 32 hex digits, the hyphenated form, the hyphenated form in braces, and the
10
- * `urn:uuid:` form, in any case.
11
- */
12
- export function canonicalizeUuid(value: string): string | undefined {
13
- let hyphenated = value
14
- if (value.length === 38 && value.startsWith('{') && value.endsWith('}')) {
15
- hyphenated = value.slice(1, -1)
16
- } else if (value.length === 45 && value.slice(0, URN_PREFIX.length).toLowerCase() === URN_PREFIX) {
17
- hyphenated = value.slice(URN_PREFIX.length)
18
- } else if (HEX_32.test(value)) {
19
- hyphenated = `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`
20
- }
21
- return HYPHENATED.test(hyphenated) ? hyphenated.toLowerCase() : undefined
22
- }
23
-
24
- type CryptoLike = { getRandomValues(array: Uint32Array): Uint32Array }
25
-
26
- /** 32-bit words from the platform's cryptographic source, filled eight at a time to keep the per-uuid cost low. */
27
- class CryptoRandom {
28
- private readonly words = new Uint32Array(8)
29
- private cursor = this.words.length
30
-
31
- constructor(private readonly crypto: CryptoLike) {}
32
-
33
- nextUint32(): number {
34
- if (this.cursor >= this.words.length) {
35
- this.crypto.getRandomValues(this.words)
36
- this.cursor = 0
37
- }
38
- return this.words[this.cursor++]
39
- }
40
- }
41
-
42
- function cryptoRandom(): CryptoRandom | undefined {
43
- const crypto = (globalThis as { crypto?: Partial<CryptoLike> }).crypto
44
- return typeof crypto?.getRandomValues === 'function' ? new CryptoRandom(crypto as CryptoLike) : undefined
45
- }
46
-
47
- // Without a crypto source (none in supported Node and edge runtimes), the core generator's Math.random source is used.
48
- const generator = new V7Generator(cryptoRandom())
49
-
50
- /** A v7 uuid for an event or a personless distinct id, with random bits from `crypto.getRandomValues`. */
51
- export function eventUuidv7(): string {
52
- return generator.generate().toString()
53
- }