posthog-node 5.71.0 → 5.73.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/dist/client.d.ts +53 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +94 -19
- package/dist/client.mjs +94 -19
- package/dist/emails/attachments.d.ts +23 -0
- package/dist/emails/attachments.d.ts.map +1 -0
- package/dist/emails/attachments.js +170 -0
- package/dist/emails/attachments.mjs +123 -0
- package/dist/emails/emails.d.ts +7 -2
- package/dist/emails/emails.d.ts.map +1 -1
- package/dist/emails/emails.js +193 -37
- package/dist/emails/emails.mjs +193 -37
- package/dist/emails/errors.d.ts +1 -1
- package/dist/emails/errors.d.ts.map +1 -1
- package/dist/emails/errors.js +6 -1
- package/dist/emails/errors.mjs +6 -1
- package/dist/emails/types.d.ts +23 -0
- package/dist/emails/types.d.ts.map +1 -1
- package/dist/exports.d.ts +1 -1
- package/dist/exports.d.ts.map +1 -1
- package/dist/feature-flag-evaluations.d.ts +14 -0
- package/dist/feature-flag-evaluations.d.ts.map +1 -1
- package/dist/feature-flag-evaluations.js +2 -1
- package/dist/feature-flag-evaluations.mjs +2 -1
- package/dist/flag-events.d.ts +112 -0
- package/dist/flag-events.d.ts.map +1 -0
- package/dist/flag-events.js +230 -0
- package/dist/flag-events.mjs +174 -0
- package/dist/flags-response.d.ts +83 -0
- package/dist/flags-response.d.ts.map +1 -0
- package/dist/flags-response.js +255 -0
- package/dist/flags-response.mjs +208 -0
- package/dist/types.d.ts +2 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +4 -3
- package/src/client.ts +238 -45
- package/src/emails/attachments.ts +209 -0
- package/src/emails/emails.ts +243 -35
- package/src/emails/errors.ts +7 -2
- package/src/emails/types.ts +24 -0
- package/src/exports.ts +1 -0
- package/src/feature-flag-evaluations.ts +17 -0
- package/src/flag-events.ts +280 -0
- package/src/flags-response.ts +340 -0
- package/src/types.ts +2 -1
- package/src/version.ts +1 -1
package/src/client.ts
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
PostHogEventProperties,
|
|
15
15
|
PostHogFetchOptions,
|
|
16
16
|
PostHogFetchResponse,
|
|
17
|
+
PostHogFeatureFlagsResponse,
|
|
17
18
|
PostHogFlagsAndPayloadsResponse,
|
|
18
19
|
PostHogFlagsResponse,
|
|
19
20
|
PostHogMetrics,
|
|
@@ -66,6 +67,20 @@ import {
|
|
|
66
67
|
FeatureFlagEvaluationsHost,
|
|
67
68
|
FlagCalledEventParams,
|
|
68
69
|
} from './feature-flag-evaluations'
|
|
70
|
+
import {
|
|
71
|
+
FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE,
|
|
72
|
+
isUnreadableFlagRecord,
|
|
73
|
+
ParsedFlagRecord,
|
|
74
|
+
parsedFlagRecordOf,
|
|
75
|
+
readFlagRecords,
|
|
76
|
+
} from './flags-response'
|
|
77
|
+
import {
|
|
78
|
+
applyFlagEventCapture,
|
|
79
|
+
buildConfigVersion2FlagEvents,
|
|
80
|
+
FlagEvent,
|
|
81
|
+
FlagEventCapture,
|
|
82
|
+
minimizeConfigVersion2FlagCalledProperties,
|
|
83
|
+
} from './flag-events'
|
|
69
84
|
import {
|
|
70
85
|
type FeatureFlagEvaluationContext,
|
|
71
86
|
FeatureFlagsPoller,
|
|
@@ -97,6 +112,18 @@ const WAITUNTIL_DEBOUNCE_MS = 50
|
|
|
97
112
|
const WAITUNTIL_MAX_WAIT_MS = 500
|
|
98
113
|
const DEFAULT_NODE_HOST = 'https://us.i.posthog.com'
|
|
99
114
|
|
|
115
|
+
// Internal options of one event's trip through the capture pipeline.
|
|
116
|
+
type PrepareEventOptions = {
|
|
117
|
+
includeContextProperties?: boolean
|
|
118
|
+
/** How a config version 2 flag event fixes its properties; see `flag-events.ts`. */
|
|
119
|
+
flagEvent?: FlagEventCapture
|
|
120
|
+
/**
|
|
121
|
+
* Called when capture fails: `before_send` throws, or the event cannot be prepared or queued.
|
|
122
|
+
* Not called when `before_send` discards the event.
|
|
123
|
+
*/
|
|
124
|
+
onCaptureFailed?: () => void
|
|
125
|
+
}
|
|
126
|
+
|
|
100
127
|
// Process-wide dedup for deprecation warnings — without this, calling a deprecated
|
|
101
128
|
// method in a loop would spam logs. Matches Python's `warnings.warn` default-dedup behavior.
|
|
102
129
|
const _emittedDeprecations = new Set<string>()
|
|
@@ -202,10 +229,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
202
229
|
// flag-definition loads) — both derive from the same per-team server config and converge.
|
|
203
230
|
private _minimalFlagCalledEvents: boolean = false
|
|
204
231
|
|
|
232
|
+
// Whether this client has logged that /flags sent records without typed values.
|
|
233
|
+
private _loggedFlagsResponseWithoutTypedValues = false
|
|
234
|
+
|
|
205
235
|
// Insertion-ordered LRU of the `$feature_flag_called` keys already reported per distinct id.
|
|
206
236
|
// Map iteration order is insertion order, so the first entry is always the least recently used.
|
|
207
237
|
private _distinctIdHasSentFlagCalls: Map<string, Set<string>>
|
|
208
238
|
|
|
239
|
+
// The `$experiment_exposure` keys already reported per distinct id, kept apart from the
|
|
240
|
+
// `$feature_flag_called` keys so that a reported call never suppresses its exposure. Same bound
|
|
241
|
+
// and eviction. Shutdown clears it.
|
|
242
|
+
private _experimentExposuresReported: Map<string, Set<string>> = new Map()
|
|
243
|
+
|
|
209
244
|
/**
|
|
210
245
|
* Snapshot of the `$feature_flag_called` dedupe state, keyed by distinct id.
|
|
211
246
|
* Adding or deleting keys on the returned object does not affect deduplication;
|
|
@@ -1055,6 +1090,32 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
1055
1090
|
return 'server'
|
|
1056
1091
|
}
|
|
1057
1092
|
|
|
1093
|
+
/**
|
|
1094
|
+
* posthog-node and posthog-edge request the v4 `/flags` response, which carries one typed
|
|
1095
|
+
* value per flag plus its reason and rule metadata. A server that does not serve v4 answers
|
|
1096
|
+
* with the older record, which is read as before. Other SDKs on the shared core keep `v=2`.
|
|
1097
|
+
*
|
|
1098
|
+
* The reader reads each flag record into its legacy rendering and keeps the parsed record,
|
|
1099
|
+
* then reads the rest of the response with the shared reader.
|
|
1100
|
+
*/
|
|
1101
|
+
protected override getFlagsResponseFormat(): {
|
|
1102
|
+
version: 4
|
|
1103
|
+
read: (body: unknown) => PostHogFeatureFlagsResponse
|
|
1104
|
+
} {
|
|
1105
|
+
const shared = super.getFlagsResponseFormat()
|
|
1106
|
+
return {
|
|
1107
|
+
version: 4,
|
|
1108
|
+
read: (response) => {
|
|
1109
|
+
const { body, withoutTypedValues } = readFlagRecords(response)
|
|
1110
|
+
if (withoutTypedValues && !this._loggedFlagsResponseWithoutTypedValues) {
|
|
1111
|
+
this._loggedFlagsResponseWithoutTypedValues = true
|
|
1112
|
+
this._logger.info(FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE)
|
|
1113
|
+
}
|
|
1114
|
+
return shared.read(body)
|
|
1115
|
+
},
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1058
1119
|
/**
|
|
1059
1120
|
* Returns the common properties attached to every captured event.
|
|
1060
1121
|
*
|
|
@@ -1161,12 +1222,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
1161
1222
|
type: string,
|
|
1162
1223
|
props: EventMessage,
|
|
1163
1224
|
immediate: boolean,
|
|
1164
|
-
prepareOptions?:
|
|
1225
|
+
prepareOptions?: PrepareEventOptions,
|
|
1165
1226
|
explicitRoute?: string
|
|
1166
1227
|
): Promise<void> {
|
|
1167
1228
|
return this.addPendingPromise(
|
|
1168
1229
|
this._prepareEventMessage(props, prepareOptions)
|
|
1169
1230
|
.then(({ distinctId, event, properties, options }) => {
|
|
1231
|
+
// The queue drops the event without an error when the client was disabled or opted out
|
|
1232
|
+
// while the event was prepared, so a flag event's dedupe key is released here.
|
|
1233
|
+
if (this.disabled || this.optedOut) {
|
|
1234
|
+
prepareOptions?.onCaptureFailed?.()
|
|
1235
|
+
}
|
|
1170
1236
|
const captureOptions: PostHogCaptureOptions = {
|
|
1171
1237
|
timestamp: options.timestamp,
|
|
1172
1238
|
disableGeoip: options.disableGeoip,
|
|
@@ -1185,8 +1251,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
1185
1251
|
: this.enqueue(type, message, captureOptions, explicitRoute)
|
|
1186
1252
|
})
|
|
1187
1253
|
.catch((err) => {
|
|
1254
|
+
// A `before_send` discard rejects with null; it is not a failure.
|
|
1188
1255
|
if (err) {
|
|
1189
1256
|
console.error(err)
|
|
1257
|
+
prepareOptions?.onCaptureFailed?.()
|
|
1190
1258
|
}
|
|
1191
1259
|
})
|
|
1192
1260
|
)
|
|
@@ -1772,6 +1840,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
1772
1840
|
let flagVersion: number | undefined = undefined
|
|
1773
1841
|
let flagReason: string | undefined = undefined
|
|
1774
1842
|
let flagHasExperiment: boolean | undefined = undefined
|
|
1843
|
+
// The parsed /flags record when it supplied the result. Only such a read can carry config
|
|
1844
|
+
// version 2 attribution and send $experiment_exposure.
|
|
1845
|
+
let flagRecord: ParsedFlagRecord | undefined = undefined
|
|
1775
1846
|
|
|
1776
1847
|
// Try local evaluation first
|
|
1777
1848
|
const localEvaluationEnabled = this.featureFlagsPoller !== undefined
|
|
@@ -1869,9 +1940,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
1869
1940
|
reason: flagReason,
|
|
1870
1941
|
reasonCode: flagDetail.reason?.code,
|
|
1871
1942
|
}
|
|
1943
|
+
flagRecord = parsedFlagRecordOf(flagDetail)
|
|
1872
1944
|
}
|
|
1873
1945
|
|
|
1874
|
-
if (
|
|
1946
|
+
if (flagDetail !== undefined && isUnreadableFlagRecord(flagDetail)) {
|
|
1947
|
+
// The record had a known field with the wrong JSON type, so the flag reads as disabled.
|
|
1948
|
+
// A single-flag read reports what a failed /flags request reports: an unknown error
|
|
1949
|
+
// and no request details.
|
|
1950
|
+
featureFlagError = FeatureFlagError.UNKNOWN_ERROR
|
|
1951
|
+
requestId = undefined
|
|
1952
|
+
evaluatedAt = undefined
|
|
1953
|
+
} else if (errors.length > 0) {
|
|
1875
1954
|
featureFlagError = errors.join(',')
|
|
1876
1955
|
}
|
|
1877
1956
|
}
|
|
@@ -1914,6 +1993,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
1914
1993
|
groups,
|
|
1915
1994
|
disableGeoip,
|
|
1916
1995
|
properties,
|
|
1996
|
+
record: flagRecord,
|
|
1917
1997
|
})
|
|
1918
1998
|
}
|
|
1919
1999
|
|
|
@@ -2475,10 +2555,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
2475
2555
|
*
|
|
2476
2556
|
* **Exposure events.** `isEnabled()` and `getFlag()` send a `$feature_flag_called` event the
|
|
2477
2557
|
* first time each flag value is read for a user. Experiments use these events as exposures.
|
|
2558
|
+
* When a remotely evaluated config version 2 flag assigns an experiment variant, the read also
|
|
2559
|
+
* sends `$experiment_exposure`, once per user, groups, flag, rule and variant.
|
|
2478
2560
|
* The client's `sendFeatureFlagEvent` option sets the default for these reads. Pass
|
|
2479
2561
|
* `{ sendFeatureFlagEvents: true }` or `{ sendFeatureFlagEvents: false }` to a read to override
|
|
2480
2562
|
* it, so one snapshot can serve both experiment flags and flags that should send no events.
|
|
2481
|
-
* `getFlagPayload()` never sends events.
|
|
2563
|
+
* The option governs both events. `getFlagPayload()` never sends events.
|
|
2482
2564
|
*
|
|
2483
2565
|
* **Trim the request.** Pass `flagKeys` to scope local evaluation, the underlying
|
|
2484
2566
|
* `/flags` request, and the returned snapshot to a subset of flags. Remote evaluation
|
|
@@ -2673,6 +2755,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
2673
2755
|
reason: detail.reason?.description ?? detail.reason?.code,
|
|
2674
2756
|
locallyEvaluated: false,
|
|
2675
2757
|
hasExperiment: detail.metadata?.has_experiment,
|
|
2758
|
+
parsed: parsedFlagRecordOf(detail),
|
|
2676
2759
|
}
|
|
2677
2760
|
}
|
|
2678
2761
|
}
|
|
@@ -2703,6 +2786,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
2703
2786
|
for (const [key, payload] of Object.entries(this._payloadOverrides)) {
|
|
2704
2787
|
const existing = records[key]
|
|
2705
2788
|
if (existing) {
|
|
2789
|
+
// A payload override keeps the parsed record, because the record still supplied the
|
|
2790
|
+
// flag's value. A value override, above, drops it.
|
|
2706
2791
|
records[key] = { ...existing, payload }
|
|
2707
2792
|
}
|
|
2708
2793
|
}
|
|
@@ -2755,50 +2840,142 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
2755
2840
|
}
|
|
2756
2841
|
|
|
2757
2842
|
/**
|
|
2758
|
-
*
|
|
2759
|
-
*
|
|
2760
|
-
*
|
|
2843
|
+
* Sends the flag events of a flag read: `$feature_flag_called` and, for a config version 2
|
|
2844
|
+
* experiment split, `$experiment_exposure`. Shared by the single-flag evaluation path and
|
|
2845
|
+
* `FeatureFlagEvaluations.isEnabled() / getFlag()` so both paths report and dedupe identically.
|
|
2846
|
+
*
|
|
2847
|
+
* `$feature_flag_called` is sent if the (distinctId, flag, response, groups) tuple hasn't already
|
|
2848
|
+
* been reported for this client. When `params.record` is a config version 2 record, both events
|
|
2849
|
+
* are built from it in one step (see `flag-events.ts`): the call gains the record's attribution
|
|
2850
|
+
* and its tuple gains the attribution too, and a complete experiment split also sends
|
|
2851
|
+
* `$experiment_exposure`, deduped in its own namespace. Config version 1 events are sent and
|
|
2852
|
+
* deduped as before.
|
|
2761
2853
|
*
|
|
2762
2854
|
* @internal
|
|
2763
2855
|
*/
|
|
2764
2856
|
protected _captureFlagCalledEventIfNeeded(params: FlagCalledEventParams): void {
|
|
2765
|
-
const { distinctId, key, response, groups, disableGeoip, properties } = params
|
|
2857
|
+
const { distinctId, key, response, groups, disableGeoip, properties, record } = params
|
|
2858
|
+
|
|
2859
|
+
const configVersion2Events = buildConfigVersion2FlagEvents({ key, response, groups, properties, record })
|
|
2860
|
+
if (configVersion2Events !== undefined) {
|
|
2861
|
+
// Each event is attempted on its own, so a failed capture of one does not stop the other.
|
|
2862
|
+
this._captureFlagEventOnce(this._distinctIdHasSentFlagCalls, distinctId, configVersion2Events.flagCalled, params)
|
|
2863
|
+
if (configVersion2Events.exposure !== undefined) {
|
|
2864
|
+
// Keyed by the distinct id as the event carries it, a string.
|
|
2865
|
+
this._captureFlagEventOnce(
|
|
2866
|
+
this._experimentExposuresReported,
|
|
2867
|
+
String(distinctId),
|
|
2868
|
+
configVersion2Events.exposure,
|
|
2869
|
+
params
|
|
2870
|
+
)
|
|
2871
|
+
}
|
|
2872
|
+
return
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2766
2875
|
const groupSuffix =
|
|
2767
2876
|
groups && Object.keys(groups).length > 0
|
|
2768
2877
|
? `_${JSON.stringify(Object.entries(groups).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))}`
|
|
2769
2878
|
: ''
|
|
2770
2879
|
const featureFlagReportedKey = `${key}_${response}${groupSuffix}`
|
|
2771
2880
|
|
|
2772
|
-
|
|
2881
|
+
if (this._reserveFlagEventKey(this._distinctIdHasSentFlagCalls, distinctId, featureFlagReportedKey) === undefined) {
|
|
2882
|
+
return
|
|
2883
|
+
}
|
|
2884
|
+
|
|
2885
|
+
this.capture({
|
|
2886
|
+
distinctId,
|
|
2887
|
+
event: '$feature_flag_called',
|
|
2888
|
+
properties,
|
|
2889
|
+
groups,
|
|
2890
|
+
disableGeoip,
|
|
2891
|
+
})
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2894
|
+
/**
|
|
2895
|
+
* Adds `key` to the keys reported for `distinctId` unless it is there already, and returns the
|
|
2896
|
+
* set that now holds it, or `undefined` when the event was already reported or is being
|
|
2897
|
+
* captured. Node runs one read at a time, so the check and the add are one step.
|
|
2898
|
+
*
|
|
2899
|
+
* The cache is an LRU of distinct ids: each call moves `distinctId` to the most recently used
|
|
2900
|
+
* end, and adding a key evicts only the least recently used distinct ids. Clearing the whole
|
|
2901
|
+
* cache under capacity pressure would re-send events for every active user at once. The current
|
|
2902
|
+
* id is always kept, even when maxCacheSize is below 1.
|
|
2903
|
+
*/
|
|
2904
|
+
private _reserveFlagEventKey(
|
|
2905
|
+
cache: Map<string, Set<string>>,
|
|
2906
|
+
distinctId: string,
|
|
2907
|
+
key: string
|
|
2908
|
+
): Set<string> | undefined {
|
|
2909
|
+
const reported = cache.get(distinctId) ?? new Set<string>()
|
|
2773
2910
|
|
|
2774
2911
|
// Re-insert so the distinct id moves to the most-recently-used end of the map.
|
|
2775
|
-
|
|
2776
|
-
|
|
2912
|
+
cache.delete(distinctId)
|
|
2913
|
+
cache.set(distinctId, reported)
|
|
2777
2914
|
|
|
2778
|
-
if (reported.has(
|
|
2779
|
-
return
|
|
2915
|
+
if (reported.has(key)) {
|
|
2916
|
+
return undefined
|
|
2780
2917
|
}
|
|
2781
2918
|
|
|
2782
|
-
reported.add(
|
|
2919
|
+
reported.add(key)
|
|
2783
2920
|
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
// is always kept, even when maxCacheSize is below 1.
|
|
2787
|
-
while (this._distinctIdHasSentFlagCalls.size > Math.max(this.maxCacheSize, 1)) {
|
|
2788
|
-
const lruDistinctId = this._distinctIdHasSentFlagCalls.keys().next().value
|
|
2921
|
+
while (cache.size > Math.max(this.maxCacheSize, 1)) {
|
|
2922
|
+
const lruDistinctId = cache.keys().next().value
|
|
2789
2923
|
if (lruDistinctId === undefined) {
|
|
2790
2924
|
break
|
|
2791
2925
|
}
|
|
2792
|
-
|
|
2926
|
+
cache.delete(lruDistinctId)
|
|
2793
2927
|
}
|
|
2928
|
+
return reported
|
|
2929
|
+
}
|
|
2794
2930
|
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2931
|
+
/**
|
|
2932
|
+
* Captures one config version 2 flag event, once per key in `cache`.
|
|
2933
|
+
*
|
|
2934
|
+
* The key is reserved before capture and stays reserved while capture runs, so a read during
|
|
2935
|
+
* capture does not send the event again. It is released when capture fails, so a later read
|
|
2936
|
+
* sends the event: the capture call throws, the client is disabled or opted out (also while the
|
|
2937
|
+
* event is prepared), `before_send` throws, or the event cannot be prepared or queued. An event that `before_send` discards keeps
|
|
2938
|
+
* its key: the application chose to drop it, and later reads would be dropped the same way.
|
|
2939
|
+
* A failure is logged and never reaches the read.
|
|
2940
|
+
*/
|
|
2941
|
+
private _captureFlagEventOnce(
|
|
2942
|
+
cache: Map<string, Set<string>>,
|
|
2943
|
+
distinctId: string,
|
|
2944
|
+
flagEvent: FlagEvent,
|
|
2945
|
+
params: FlagCalledEventParams
|
|
2946
|
+
): void {
|
|
2947
|
+
const reported = this._reserveFlagEventKey(cache, distinctId, flagEvent.dedupeKey)
|
|
2948
|
+
if (reported === undefined) {
|
|
2949
|
+
return
|
|
2950
|
+
}
|
|
2951
|
+
let released = false
|
|
2952
|
+
const release = (): void => {
|
|
2953
|
+
if (!released) {
|
|
2954
|
+
released = true
|
|
2955
|
+
reported.delete(flagEvent.dedupeKey)
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
try {
|
|
2959
|
+
if (this.disabled || this.optedOut) {
|
|
2960
|
+
release()
|
|
2961
|
+
return
|
|
2962
|
+
}
|
|
2963
|
+
void this._sendPreparedEvent(
|
|
2964
|
+
'capture',
|
|
2965
|
+
{
|
|
2966
|
+
distinctId: params.distinctId,
|
|
2967
|
+
event: flagEvent.event,
|
|
2968
|
+
properties: flagEvent.properties,
|
|
2969
|
+
groups: params.groups,
|
|
2970
|
+
disableGeoip: params.disableGeoip,
|
|
2971
|
+
},
|
|
2972
|
+
false,
|
|
2973
|
+
{ flagEvent: flagEvent.capture, onCaptureFailed: release }
|
|
2974
|
+
)
|
|
2975
|
+
} catch (error) {
|
|
2976
|
+
this._logger.error(`[FEATURE FLAGS] Failed to capture ${flagEvent.event}:`, error)
|
|
2977
|
+
release()
|
|
2978
|
+
}
|
|
2802
2979
|
}
|
|
2803
2980
|
|
|
2804
2981
|
/**
|
|
@@ -3220,6 +3397,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
3220
3397
|
await emailsSettled
|
|
3221
3398
|
await logsDrained
|
|
3222
3399
|
this._distinctIdHasSentFlagCalls.clear()
|
|
3400
|
+
this._experimentExposuresReported.clear()
|
|
3223
3401
|
resolve?.()
|
|
3224
3402
|
}
|
|
3225
3403
|
}
|
|
@@ -3531,8 +3709,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
3531
3709
|
* The configured service name, stamped on events as `service_name` so events
|
|
3532
3710
|
* from several services sharing one project can be told apart. Resolved with
|
|
3533
3711
|
* the same resolvers as the traces and metrics `service.name`, so the event
|
|
3534
|
-
* carries the name the telemetry does: traces first (
|
|
3535
|
-
*
|
|
3712
|
+
* carries the name the telemetry does: traces first (`resourceAttributes`,
|
|
3713
|
+
* then `serviceName`), then metrics the same way. Host resource attributes
|
|
3714
|
+
* are only `os.*`, so they never supply the name. Lowest precedence: a
|
|
3536
3715
|
* property set by the caller, the context or `register` wins.
|
|
3537
3716
|
*/
|
|
3538
3717
|
private _serviceNameProperties(): PostHogEventProperties {
|
|
@@ -3555,7 +3734,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
3555
3734
|
|
|
3556
3735
|
private async _prepareEventMessage(
|
|
3557
3736
|
props: EventMessage,
|
|
3558
|
-
options:
|
|
3737
|
+
options: PrepareEventOptions = {}
|
|
3559
3738
|
): Promise<{
|
|
3560
3739
|
distinctId: string
|
|
3561
3740
|
event: string
|
|
@@ -3601,26 +3780,37 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
3601
3780
|
mergedProperties.$session_id = contextData.sessionId
|
|
3602
3781
|
}
|
|
3603
3782
|
|
|
3783
|
+
// A config version 2 flag event fixes its attribution after super and context properties are
|
|
3784
|
+
// merged, so neither can change it or add a field the event never carries.
|
|
3785
|
+
const flagEvent = options.flagEvent
|
|
3786
|
+
const enrichedProperties = flagEvent ? applyFlagEventCapture(mergedProperties, flagEvent) : mergedProperties
|
|
3787
|
+
|
|
3604
3788
|
// Minimal $feature_flag_called events: rebuild from the strict allowlist before before_send
|
|
3605
3789
|
// runs, so a customer hook may deliberately re-add stripped properties. Everything the SDK
|
|
3606
3790
|
// itself adds after this point ($groups, $lib/$lib_version/$is_server, $geoip_disable) is
|
|
3607
|
-
// allowlisted — no SDK enrichment may reintroduce stripped properties.
|
|
3608
|
-
|
|
3609
|
-
|
|
3610
|
-
|
|
3791
|
+
// allowlisted — no SDK enrichment may reintroduce stripped properties. A config version 2
|
|
3792
|
+
// event also keeps its attribution.
|
|
3793
|
+
const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties)
|
|
3794
|
+
? flagEvent
|
|
3795
|
+
? minimizeConfigVersion2FlagCalledProperties(enrichedProperties)
|
|
3796
|
+
: minimizeFlagCalledEventProperties(enrichedProperties)
|
|
3797
|
+
: enrichedProperties
|
|
3611
3798
|
|
|
3612
3799
|
// Run before_send if configured
|
|
3613
|
-
const eventMessage = this._runBeforeSend(
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3800
|
+
const eventMessage = this._runBeforeSend(
|
|
3801
|
+
{
|
|
3802
|
+
distinctId: mergedDistinctId,
|
|
3803
|
+
event,
|
|
3804
|
+
properties: finalProperties,
|
|
3805
|
+
groups,
|
|
3806
|
+
flags,
|
|
3807
|
+
sendFeatureFlags,
|
|
3808
|
+
timestamp,
|
|
3809
|
+
disableGeoip,
|
|
3810
|
+
uuid,
|
|
3811
|
+
},
|
|
3812
|
+
options.onCaptureFailed
|
|
3813
|
+
)
|
|
3624
3814
|
|
|
3625
3815
|
if (!eventMessage) {
|
|
3626
3816
|
return Promise.reject(null)
|
|
@@ -3708,7 +3898,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
3708
3898
|
}
|
|
3709
3899
|
}
|
|
3710
3900
|
|
|
3711
|
-
|
|
3901
|
+
// `onError` is called when a hook throws. A hook that returns null discards the event, which
|
|
3902
|
+
// is not an error.
|
|
3903
|
+
private _runBeforeSend(eventMessage: EventMessage, onError?: () => void): EventMessage | null {
|
|
3712
3904
|
const beforeSend = this.options.before_send
|
|
3713
3905
|
if (!beforeSend) {
|
|
3714
3906
|
return eventMessage
|
|
@@ -3730,6 +3922,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
3730
3922
|
}
|
|
3731
3923
|
} catch (error) {
|
|
3732
3924
|
this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error)
|
|
3925
|
+
onError?.()
|
|
3733
3926
|
return null
|
|
3734
3927
|
}
|
|
3735
3928
|
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { EmailError } from './errors'
|
|
2
|
+
import type { EmailAttachment } from './types'
|
|
3
|
+
|
|
4
|
+
const MAX_ATTACHMENTS = 10
|
|
5
|
+
const MAX_MESSAGE_BYTES = 40_000_000
|
|
6
|
+
const MESSAGE_HEADERS_BYTES = 64 * 1024
|
|
7
|
+
const SUBJECT_BYTES_PER_ENCODED_WORD = 42
|
|
8
|
+
const ENCODED_WORD_BYTES = 75
|
|
9
|
+
const MESSAGE_LIMIT = '40 MB after Base64 encoding, about 29 MB of files'
|
|
10
|
+
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/
|
|
11
|
+
|
|
12
|
+
export interface AttachmentFile {
|
|
13
|
+
filename: string
|
|
14
|
+
bytes: Uint8Array<ArrayBuffer>
|
|
15
|
+
contentType?: string
|
|
16
|
+
contentId?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface HashedFile extends AttachmentFile {
|
|
20
|
+
sha256: string
|
|
21
|
+
field: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface CheckedAttachment {
|
|
25
|
+
filename: string
|
|
26
|
+
content: string | Uint8Array
|
|
27
|
+
size: number
|
|
28
|
+
contentType?: string
|
|
29
|
+
contentId?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function attachmentFiles(
|
|
33
|
+
attachments: unknown,
|
|
34
|
+
{ html, text, subject }: { html?: string; text?: string; subject: string }
|
|
35
|
+
): AttachmentFile[] {
|
|
36
|
+
if (!Array.isArray(attachments)) {
|
|
37
|
+
throw invalid('attachments must be a list of files.', 'attachments')
|
|
38
|
+
}
|
|
39
|
+
if (attachments.length > MAX_ATTACHMENTS) {
|
|
40
|
+
throw new EmailError({
|
|
41
|
+
code: 'too_many_attachments',
|
|
42
|
+
message: `An email carries at most ${MAX_ATTACHMENTS} files, so no email was sent.`,
|
|
43
|
+
field: 'attachments',
|
|
44
|
+
fix: `Attach at most ${MAX_ATTACHMENTS} files, and link to any others from the email body.`,
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
const checked = Array.from(attachments, checkedAttachment)
|
|
48
|
+
refuseMessageOverLimit(
|
|
49
|
+
checked.map(({ size }) => size),
|
|
50
|
+
[html ?? '', text || html || ''],
|
|
51
|
+
subject
|
|
52
|
+
)
|
|
53
|
+
return checked.map(({ content, size, ...file }) => ({
|
|
54
|
+
...file,
|
|
55
|
+
bytes: typeof content === 'string' ? bytesOfBase64(content) : new Uint8Array(content),
|
|
56
|
+
}))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Checks the email's size once a react element is rendered, since its html and the text derived
|
|
61
|
+
* from it were unknown when the files were checked.
|
|
62
|
+
*/
|
|
63
|
+
export function refuseRenderedMessageOverLimit(files: AttachmentFile[], content: Record<string, unknown>): void {
|
|
64
|
+
const html = typeof content.html === 'string' ? content.html : ''
|
|
65
|
+
const text = typeof content.text === 'string' ? content.text : ''
|
|
66
|
+
refuseMessageOverLimit(
|
|
67
|
+
files.map(({ bytes }) => bytes.byteLength),
|
|
68
|
+
[html, text || html],
|
|
69
|
+
typeof content.subject === 'string' ? content.subject : ''
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function hashedFiles(files: AttachmentFile[]): Promise<HashedFile[]> {
|
|
74
|
+
return Promise.all(
|
|
75
|
+
files.map(async (file, index) => ({
|
|
76
|
+
...file,
|
|
77
|
+
sha256: await sha256Hex(file.bytes),
|
|
78
|
+
field: `attachments__${index}`,
|
|
79
|
+
}))
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function attachmentReference({ sha256, filename, contentType, contentId }: HashedFile): Record<string, unknown> {
|
|
84
|
+
return {
|
|
85
|
+
sha256,
|
|
86
|
+
filename,
|
|
87
|
+
...(contentType !== undefined && { content_type: contentType }),
|
|
88
|
+
...(contentId !== undefined && { content_id: contentId }),
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function checkedAttachment(attachment: unknown, index: number): CheckedAttachment {
|
|
93
|
+
if (
|
|
94
|
+
typeof attachment !== 'object' ||
|
|
95
|
+
attachment === null ||
|
|
96
|
+
Array.isArray(attachment) ||
|
|
97
|
+
ArrayBuffer.isView(attachment)
|
|
98
|
+
) {
|
|
99
|
+
throw invalid(
|
|
100
|
+
"An attachment is an object with filename and content. Pass the file's bytes as its content.",
|
|
101
|
+
`attachments__${index}`
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
const { filename, content, contentType, contentId, path, ...unsupported } = attachment as Partial<
|
|
105
|
+
Record<keyof EmailAttachment, unknown>
|
|
106
|
+
>
|
|
107
|
+
if (path !== undefined) {
|
|
108
|
+
throw invalid(
|
|
109
|
+
"PostHog can't fetch an attachment from a path or URL. Read the file and pass its content instead.",
|
|
110
|
+
`attachments__${index}__path`
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
const unsupportedKey = Object.entries(unsupported).find(([, value]) => value !== undefined)?.[0]
|
|
114
|
+
if (unsupportedKey !== undefined) {
|
|
115
|
+
throw invalid(
|
|
116
|
+
`An attachment takes filename, content, contentType and contentId, not ${unsupportedKey}.`,
|
|
117
|
+
`attachments__${index}__${unsupportedKey}`
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
if (typeof filename !== 'string' || filename === '') {
|
|
121
|
+
throw invalid("An attachment needs a filename, such as 'invoice.pdf'.", `attachments__${index}__filename`)
|
|
122
|
+
}
|
|
123
|
+
if (typeof content !== 'string' && !(content instanceof Uint8Array)) {
|
|
124
|
+
throw invalid(
|
|
125
|
+
'An attachment needs content: a Buffer, a Uint8Array or a Base64 string.',
|
|
126
|
+
`attachments__${index}__content`
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
if (typeof content === 'string' && !isBase64(content)) {
|
|
130
|
+
throw invalid(
|
|
131
|
+
"An attachment's content string must be Base64. Pass text as a Buffer or a Uint8Array.",
|
|
132
|
+
`attachments__${index}__content`
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
if (contentType !== undefined && typeof contentType !== 'string') {
|
|
136
|
+
throw invalid(
|
|
137
|
+
"An attachment's contentType must be a string, such as 'application/pdf'.",
|
|
138
|
+
`attachments__${index}__contentType`
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
if (contentId !== undefined && typeof contentId !== 'string') {
|
|
142
|
+
throw invalid("An attachment's contentId must be a string.", `attachments__${index}__contentId`)
|
|
143
|
+
}
|
|
144
|
+
const size = typeof content === 'string' ? base64DecodedBytes(content) : content.byteLength
|
|
145
|
+
if (size === 0) {
|
|
146
|
+
throw invalid('An attachment needs at least one byte.', `attachments__${index}__content`)
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
filename,
|
|
150
|
+
content,
|
|
151
|
+
size,
|
|
152
|
+
...(contentType !== undefined && { contentType }),
|
|
153
|
+
...(contentId !== undefined && { contentId }),
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function isBase64(text: string): boolean {
|
|
158
|
+
return text.length % 4 === 0 && BASE64_PATTERN.test(text)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function base64DecodedBytes(text: string): number {
|
|
162
|
+
const padding = text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0
|
|
163
|
+
return (text.length / 4) * 3 - padding
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function bytesOfBase64(text: string): Uint8Array<ArrayBuffer> {
|
|
167
|
+
if (typeof Buffer !== 'undefined') {
|
|
168
|
+
return Buffer.from(text, 'base64')
|
|
169
|
+
}
|
|
170
|
+
const binary = atob(text)
|
|
171
|
+
const bytes = new Uint8Array(binary.length)
|
|
172
|
+
for (let index = 0; index < binary.length; index++) {
|
|
173
|
+
bytes[index] = binary.charCodeAt(index)
|
|
174
|
+
}
|
|
175
|
+
return bytes
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function refuseMessageOverLimit(fileSizes: number[], bodies: string[], subject: string): void {
|
|
179
|
+
if (fileSizes.length === 0) {
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
const encoder = new TextEncoder()
|
|
183
|
+
const sizes = [...fileSizes, ...bodies.map((body) => encoder.encode(body).byteLength)]
|
|
184
|
+
const headersBytes =
|
|
185
|
+
MESSAGE_HEADERS_BYTES +
|
|
186
|
+
Math.ceil(encoder.encode(subject).byteLength / SUBJECT_BYTES_PER_ENCODED_WORD) * ENCODED_WORD_BYTES
|
|
187
|
+
if (sizes.reduce((total, size) => total + base64LinesBytes(size), headersBytes) > MAX_MESSAGE_BYTES) {
|
|
188
|
+
throw new EmailError({
|
|
189
|
+
code: 'message_too_large',
|
|
190
|
+
message: `These files make the email larger than ${MESSAGE_LIMIT}, so no email was sent.`,
|
|
191
|
+
field: 'attachments',
|
|
192
|
+
why: "PostHog's email provider takes emails up to 40 MB, and Base64 encoding makes each file about a third larger.",
|
|
193
|
+
fix: 'Send fewer or smaller files, or link to large files from the email body.',
|
|
194
|
+
})
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function base64LinesBytes(size: number): number {
|
|
199
|
+
return Math.ceil((Math.ceil(size / 3) * 4 * 78) / 76)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function sha256Hex(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
|
|
203
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes))
|
|
204
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('')
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function invalid(message: string, field: string): EmailError {
|
|
208
|
+
return new EmailError({ code: 'invalid_attachment', message, field })
|
|
209
|
+
}
|