posthog-node 5.51.1 → 5.51.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.
@@ -1,19 +1,21 @@
1
1
  import { FeatureFlagCondition, FlagProperty, FlagPropertyValue, PostHogFeatureFlag, PropertyGroup } from '../../types'
2
2
  import type { FeatureFlagValue, JsonType, PostHogFetchOptions, PostHogFetchResponse } from '@posthog/core'
3
- import { raceWithTimeout, safeSetTimeout } from '@posthog/core'
4
- import { hashSHA1 } from './crypto'
3
+ import {
4
+ getFeatureFlagHash,
5
+ getFeatureFlagVariant,
6
+ getFeatureFlagVariantLookupTable,
7
+ InconclusiveMatchError,
8
+ matchFeatureFlagProperty,
9
+ parseFeatureFlagSemver,
10
+ raceWithTimeout,
11
+ relativeDateParseForFeatureFlagMatching,
12
+ resolveFeatureFlagPayload,
13
+ safeSetTimeout,
14
+ } from '@posthog/core'
5
15
  import { FlagDefinitionCacheProvider, FlagDefinitionCacheData } from './cache'
6
16
 
7
17
  const SIXTY_SECONDS = 60 * 1000
8
18
 
9
- // eslint-disable-next-line
10
- const LONG_SCALE = 0xfffffffffffffff
11
-
12
- // Operators that should still run their switch case when the property value is null/undefined.
13
- // `is_not` may legitimately compare against null; `is_set` only cares about key presence and
14
- // must not be short-circuited by the null guard in `matchProperty`.
15
- const NULL_VALUES_ALLOWED_OPERATORS = ['is_not', 'is_set']
16
-
17
19
  // Outcome of evaluating a single condition group. `out_of_rollout_bound` means the group's property
18
20
  // filters matched (or there were none) but the rollout percentage excluded the user — the only case
19
21
  // that triggers a flag's `early_exit` short-circuit.
@@ -38,13 +40,6 @@ function setCustomErrorPrototype(error: Error, constructor: new (message: string
38
40
  Object.setPrototypeOf(error, constructor.prototype)
39
41
  }
40
42
 
41
- class InconclusiveMatchError extends Error {
42
- constructor(message: string) {
43
- super(message)
44
- setCustomErrorPrototype(this, InconclusiveMatchError)
45
- }
46
- }
47
-
48
43
  class RequiresServerEvaluation extends Error {
49
44
  constructor(message: string) {
50
45
  super(message)
@@ -378,34 +373,7 @@ class FeatureFlagsPoller {
378
373
  }
379
374
 
380
375
  private getFeatureFlagPayload(key: string, flagValue: FeatureFlagValue): JsonType | null {
381
- let payload: JsonType | null = null
382
-
383
- if (flagValue !== false && flagValue !== null && flagValue !== undefined) {
384
- if (typeof flagValue == 'boolean') {
385
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null
386
- } else if (typeof flagValue == 'string') {
387
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null
388
- }
389
-
390
- if (payload !== null && payload !== undefined) {
391
- // If payload is already an object, return it directly
392
- if (typeof payload === 'object') {
393
- return payload
394
- }
395
- // If payload is a string, try to parse it as JSON
396
- if (typeof payload === 'string') {
397
- try {
398
- return JSON.parse(payload)
399
- } catch {
400
- // If parsing fails, return the string as is
401
- return payload
402
- }
403
- }
404
- // For other types, return as is
405
- return payload
406
- }
407
- }
408
- return null
376
+ return resolveFeatureFlagPayload(this.featureFlagsByKey?.[key]?.filters?.payloads, flagValue)
409
377
  }
410
378
 
411
379
  private async evaluateFlagDependency(
@@ -640,7 +608,10 @@ class FeatureFlagsPoller {
640
608
 
641
609
  // Property filters (if any) matched; only the rollout check remains. A failure here means the
642
610
  // user was targeted but excluded by rollout — the server-side engine's `OutOfRolloutBound`.
643
- if (rolloutPercentage != undefined && (await _hash(flag.key, bucketingValue)) > rolloutPercentage / 100.0) {
611
+ if (
612
+ rolloutPercentage != undefined &&
613
+ (await getFeatureFlagHash(flag.key, bucketingValue)) > rolloutPercentage / 100.0
614
+ ) {
644
615
  return 'out_of_rollout_bound'
645
616
  }
646
617
 
@@ -648,33 +619,11 @@ class FeatureFlagsPoller {
648
619
  }
649
620
 
650
621
  async getMatchingVariant(flag: PostHogFeatureFlag, bucketingValue: string): Promise<FeatureFlagValue | undefined> {
651
- const hashValue = await _hash(flag.key, bucketingValue, 'variant')
652
- const matchingVariant = this.variantLookupTable(flag).find((variant) => {
653
- return hashValue >= variant.valueMin && hashValue < variant.valueMax
654
- })
655
-
656
- if (matchingVariant) {
657
- return matchingVariant.key
658
- }
659
- return undefined
622
+ return getFeatureFlagVariant(flag.key, bucketingValue, flag.filters?.multivariate?.variants || [])
660
623
  }
661
624
 
662
625
  variantLookupTable(flag: PostHogFeatureFlag): { valueMin: number; valueMax: number; key: string }[] {
663
- const lookupTable: { valueMin: number; valueMax: number; key: string }[] = []
664
- let valueMin = 0
665
- let valueMax = 0
666
- const flagFilters = flag.filters || {}
667
- const multivariates: {
668
- key: string
669
- rollout_percentage: number
670
- }[] = flagFilters.multivariate?.variants || []
671
-
672
- multivariates.forEach((variant) => {
673
- valueMax = valueMin + variant.rollout_percentage / 100.0
674
- lookupTable.push({ valueMin, valueMax, key: variant.key })
675
- valueMin = valueMax
676
- })
677
- return lookupTable
626
+ return getFeatureFlagVariantLookupTable(flag.filters?.multivariate?.variants || [])
678
627
  }
679
628
 
680
629
  /**
@@ -1078,176 +1027,16 @@ class FeatureFlagsPoller {
1078
1027
  }
1079
1028
  }
1080
1029
 
1081
- // # This function takes a bucketing identifier and a feature flag key and returns a float between 0 and 1.
1082
- // # Given the same bucketing identifier and key, it'll always return the same float. These floats are
1083
- // # uniformly distributed between 0 and 1, so if we want to show this feature to 20% of traffic
1084
- // # we can do _hash(key, bucketing_identifier) < 0.2
1085
- async function _hash(key: string, bucketingValue: string, salt: string = ''): Promise<number> {
1086
- const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`)
1087
- return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE
1088
- }
1089
-
1090
1030
  function matchProperty(
1091
1031
  property: FeatureFlagCondition['properties'][number],
1092
1032
  propertyValues: Record<string, any>,
1093
1033
  warnFunction?: (msg: string) => void
1094
1034
  ): boolean {
1095
- const key = property.key
1096
- const value = property.value
1097
- const operator = property.operator || 'exact'
1098
-
1099
- if (!(key in propertyValues)) {
1100
- // When the property is genuinely absent we can answer `is_not_set` locally — no need to
1101
- // bail out as inconclusive and force the flag to return undefined.
1102
- if (operator === 'is_not_set') {
1103
- return true
1104
- }
1105
- throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`)
1106
- } else if (operator === 'is_not_set') {
1107
- return false
1108
- }
1109
-
1110
- const overrideValue = propertyValues[key]
1111
- if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
1112
- // if the value is null, just fail the feature flag comparison
1113
- // this isn't an InconclusiveMatchError because the property value was provided.
1114
- if (warnFunction) {
1115
- warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`)
1116
- }
1117
-
1118
- return false
1119
- }
1120
-
1121
- function computeExactMatch(value: any, overrideValue: any): boolean {
1122
- if (Array.isArray(value)) {
1123
- return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase())
1124
- }
1125
- return String(value).toLowerCase() === String(overrideValue).toLowerCase()
1126
- }
1127
-
1128
- function compare(lhs: any, rhs: any, operator: string): boolean {
1129
- if (operator === 'gt') {
1130
- return lhs > rhs
1131
- } else if (operator === 'gte') {
1132
- return lhs >= rhs
1133
- } else if (operator === 'lt') {
1134
- return lhs < rhs
1135
- } else if (operator === 'lte') {
1136
- return lhs <= rhs
1137
- } else {
1138
- throw new Error(`Invalid operator: ${operator}`)
1139
- }
1140
- }
1141
-
1142
- switch (operator) {
1143
- case 'exact':
1144
- return computeExactMatch(value, overrideValue)
1145
- case 'is_not':
1146
- return !computeExactMatch(value, overrideValue)
1147
- case 'is_set':
1148
- return key in propertyValues
1149
- case 'icontains':
1150
- return String(overrideValue).toLowerCase().includes(String(value).toLowerCase())
1151
- case 'not_icontains':
1152
- return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase())
1153
- case 'starts_with':
1154
- return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase())
1155
- case 'not_starts_with':
1156
- return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase())
1157
- case 'ends_with':
1158
- return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase())
1159
- case 'not_ends_with':
1160
- return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase())
1161
- case 'regex':
1162
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null
1163
- case 'not_regex':
1164
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null
1165
- case 'gt':
1166
- case 'gte':
1167
- case 'lt':
1168
- case 'lte': {
1169
- // Try a numeric comparison first; only fall back to lexicographic when one side genuinely
1170
- // isn't a number. `parseFloat` returns NaN for non-numeric strings, so `Number.isFinite`
1171
- // is the right guard — `NaN != null` would slip through and produce nonsense comparisons
1172
- // like `NaN > 5`. Likewise, when a person property arrives as the string `"10"` we want
1173
- // `"10" > "9"` to evaluate numerically (true), not lexicographically (false).
1174
- const parsedValue = typeof value === 'number' ? value : parseFloat(String(value))
1175
- let parsedOverride: number
1176
- if (typeof overrideValue === 'number') {
1177
- parsedOverride = overrideValue
1178
- } else if (overrideValue != null) {
1179
- parsedOverride = parseFloat(String(overrideValue))
1180
- } else {
1181
- parsedOverride = NaN
1182
- }
1183
- if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride)) {
1184
- return compare(parsedOverride, parsedValue, operator)
1185
- }
1186
- return compare(String(overrideValue), String(value), operator)
1187
- }
1188
- case 'is_date_after':
1189
- case 'is_date_before': {
1190
- // Boolean values should never be used with date operations
1191
- if (typeof value === 'boolean') {
1192
- throw new InconclusiveMatchError(`Date operations cannot be performed on boolean values`)
1193
- }
1194
-
1195
- let parsedDate = relativeDateParseForFeatureFlagMatching(String(value))
1196
- if (parsedDate == null) {
1197
- parsedDate = convertToDateTime(value)
1198
- }
1035
+ return matchFeatureFlagProperty(property, propertyValues, { warnFunction })
1036
+ }
1199
1037
 
1200
- if (parsedDate == null) {
1201
- throw new InconclusiveMatchError(`Invalid date: ${value}`)
1202
- }
1203
- const overrideDate = convertToDateTime(overrideValue)
1204
- if (['is_date_before'].includes(operator)) {
1205
- return overrideDate < parsedDate
1206
- }
1207
- return overrideDate > parsedDate
1208
- }
1209
- case 'semver_eq': {
1210
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)))
1211
- return cmp === 0
1212
- }
1213
- case 'semver_neq': {
1214
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)))
1215
- return cmp !== 0
1216
- }
1217
- case 'semver_gt': {
1218
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)))
1219
- return cmp > 0
1220
- }
1221
- case 'semver_gte': {
1222
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)))
1223
- return cmp >= 0
1224
- }
1225
- case 'semver_lt': {
1226
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)))
1227
- return cmp < 0
1228
- }
1229
- case 'semver_lte': {
1230
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)))
1231
- return cmp <= 0
1232
- }
1233
- case 'semver_tilde': {
1234
- const overrideParsed = parseSemver(String(overrideValue))
1235
- const { lower, upper } = computeTildeBounds(String(value))
1236
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0
1237
- }
1238
- case 'semver_caret': {
1239
- const overrideParsed = parseSemver(String(overrideValue))
1240
- const { lower, upper } = computeCaretBounds(String(value))
1241
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0
1242
- }
1243
- case 'semver_wildcard': {
1244
- const overrideParsed = parseSemver(String(overrideValue))
1245
- const { lower, upper } = computeWildcardBounds(String(value))
1246
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0
1247
- }
1248
- default:
1249
- throw new InconclusiveMatchError(`Unknown operator: ${operator}`)
1250
- }
1038
+ function parseSemver(value: string): [number, number, number] {
1039
+ return parseFeatureFlagSemver(value, 'strict')
1251
1040
  }
1252
1041
 
1253
1042
  function checkCohortExists(cohortId: string, cohortProperties: FeatureFlagsPoller['cohorts']): void {
@@ -1396,204 +1185,6 @@ async function matchPropertyGroup(
1396
1185
  }
1397
1186
  }
1398
1187
 
1399
- function isValidRegex(regex: string): boolean {
1400
- try {
1401
- new RegExp(regex)
1402
- return true
1403
- } catch (err) {
1404
- return false
1405
- }
1406
- }
1407
-
1408
- type SemverTuple = [number, number, number]
1409
-
1410
- /**
1411
- * Parse a single numeric identifier from a semver string.
1412
- * Per semver 2.0.0 §2, numeric identifiers MUST NOT include leading zeros.
1413
- */
1414
- function parseSemverNumericIdentifier(part: string, raw: string): number {
1415
- if (!/^\d+$/.test(part)) {
1416
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`)
1417
- }
1418
- if (part.length > 1 && part[0] === '0') {
1419
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`)
1420
- }
1421
- return parseInt(part, 10)
1422
- }
1423
-
1424
- /**
1425
- * Parse a version string into a [major, minor, patch] tuple.
1426
- * - Strips leading/trailing whitespace
1427
- * - Strips 'v' or 'V' prefix
1428
- * - Strips pre-release and build metadata (-alpha, +build)
1429
- * - Defaults missing components to 0
1430
- * - Ignores extra components beyond the third
1431
- * - Throws InconclusiveMatchError for invalid input
1432
- */
1433
- function parseSemver(value: string): SemverTuple {
1434
- const text = String(value).trim().replace(/^[vV]/, '')
1435
-
1436
- // Strip pre-release and build metadata
1437
- const baseVersion = text.split('-')[0].split('+')[0]
1438
-
1439
- if (!baseVersion || baseVersion.startsWith('.')) {
1440
- throw new InconclusiveMatchError(`Invalid semver: ${value}`)
1441
- }
1442
-
1443
- const parts = baseVersion.split('.')
1444
-
1445
- const parsePart = (part: string | undefined): number => {
1446
- if (part === undefined || part === '') {
1447
- return 0
1448
- }
1449
- return parseSemverNumericIdentifier(part, value)
1450
- }
1451
-
1452
- const major = parsePart(parts[0])
1453
- const minor = parsePart(parts[1])
1454
- const patch = parsePart(parts[2])
1455
-
1456
- return [major, minor, patch]
1457
- }
1458
-
1459
- /**
1460
- * Compare two semver tuples.
1461
- * Returns -1 if a < b, 0 if a == b, 1 if a > b
1462
- */
1463
- function compareSemverTuples(a: SemverTuple, b: SemverTuple): number {
1464
- for (let i = 0; i < 3; i++) {
1465
- if (a[i] < b[i]) return -1
1466
- if (a[i] > b[i]) return 1
1467
- }
1468
- return 0
1469
- }
1470
-
1471
- /**
1472
- * Compute bounds for tilde operator: ~X.Y.Z means >=X.Y.Z and <X.(Y+1).0
1473
- */
1474
- function computeTildeBounds(value: string): { lower: SemverTuple; upper: SemverTuple } {
1475
- const parsed = parseSemver(value)
1476
- const lower: SemverTuple = [parsed[0], parsed[1], parsed[2]]
1477
- const upper: SemverTuple = [parsed[0], parsed[1] + 1, 0]
1478
- return { lower, upper }
1479
- }
1480
-
1481
- /**
1482
- * Compute bounds for caret operator:
1483
- * - ^X.Y.Z where X > 0: >=X.Y.Z <(X+1).0.0
1484
- * - ^0.Y.Z where Y > 0: >=0.Y.Z <0.(Y+1).0
1485
- * - ^0.0.Z: >=0.0.Z <0.0.(Z+1)
1486
- */
1487
- function computeCaretBounds(value: string): { lower: SemverTuple; upper: SemverTuple } {
1488
- const parsed = parseSemver(value)
1489
- const [major, minor, patch] = parsed
1490
- const lower: SemverTuple = [major, minor, patch]
1491
-
1492
- let upper: SemverTuple
1493
- if (major > 0) {
1494
- upper = [major + 1, 0, 0]
1495
- } else if (minor > 0) {
1496
- upper = [0, minor + 1, 0]
1497
- } else {
1498
- upper = [0, 0, patch + 1]
1499
- }
1500
-
1501
- return { lower, upper }
1502
- }
1503
-
1504
- /**
1505
- * Compute bounds for wildcard operator:
1506
- * - "X.*" or "X" with wildcard: >=X.0.0 <(X+1).0.0
1507
- * - "X.Y.*": >=X.Y.0 <X.(Y+1).0
1508
- */
1509
- function computeWildcardBounds(value: string): { lower: SemverTuple; upper: SemverTuple } {
1510
- const text = String(value).trim().replace(/^[vV]/, '')
1511
-
1512
- // Remove trailing .* or *
1513
- const cleanedText = text.replace(/\.\*$/, '').replace(/\*$/, '')
1514
-
1515
- if (!cleanedText) {
1516
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`)
1517
- }
1518
-
1519
- const parts = cleanedText.split('.')
1520
- const parseWildcardPart = (part: string): number => {
1521
- try {
1522
- return parseSemverNumericIdentifier(part, value)
1523
- } catch {
1524
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`)
1525
- }
1526
- }
1527
- const major = parseWildcardPart(parts[0])
1528
-
1529
- let lower: SemverTuple
1530
- let upper: SemverTuple
1531
-
1532
- if (parts.length === 1) {
1533
- // X.* pattern
1534
- lower = [major, 0, 0]
1535
- upper = [major + 1, 0, 0]
1536
- } else {
1537
- // X.Y.* pattern
1538
- const minor = parseWildcardPart(parts[1])
1539
- lower = [major, minor, 0]
1540
- upper = [major, minor + 1, 0]
1541
- }
1542
-
1543
- return { lower, upper }
1544
- }
1545
-
1546
- function convertToDateTime(value: FlagPropertyValue | Date): Date {
1547
- if (value instanceof Date) {
1548
- return value
1549
- } else if (typeof value === 'string' || typeof value === 'number') {
1550
- const date = new Date(value)
1551
- if (!isNaN(date.valueOf())) {
1552
- return date
1553
- }
1554
- throw new InconclusiveMatchError(`${value} is in an invalid date format`)
1555
- } else {
1556
- throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`)
1557
- }
1558
- }
1559
-
1560
- function relativeDateParseForFeatureFlagMatching(value: string): Date | null {
1561
- const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/
1562
- const match = value.match(regex)
1563
- const parsedDt = new Date(new Date().toISOString())
1564
-
1565
- if (match) {
1566
- if (!match.groups) {
1567
- return null
1568
- }
1569
-
1570
- const number = parseInt(match.groups['number'])
1571
-
1572
- if (number >= 10000) {
1573
- // Guard against overflow, disallow numbers greater than 10_000
1574
- return null
1575
- }
1576
- const interval = match.groups['interval']
1577
- if (interval == 'h') {
1578
- parsedDt.setUTCHours(parsedDt.getUTCHours() - number)
1579
- } else if (interval == 'd') {
1580
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number)
1581
- } else if (interval == 'w') {
1582
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number * 7)
1583
- } else if (interval == 'm') {
1584
- parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number)
1585
- } else if (interval == 'y') {
1586
- parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number)
1587
- } else {
1588
- return null
1589
- }
1590
-
1591
- return parsedDt
1592
- } else {
1593
- return null
1594
- }
1595
- }
1596
-
1597
1188
  export {
1598
1189
  FeatureFlagsPoller,
1599
1190
  matchProperty,
package/src/types.ts CHANGED
@@ -121,9 +121,10 @@ export type FlagEvaluationOptions = BaseFlagEvaluationOptions & {
121
121
  export type AllFlagsOptions = BaseFlagEvaluationOptions & {
122
122
  /**
123
123
  * Restrict local evaluation, the `/flags` request, and the returned snapshot to these keys.
124
- * `evaluateFlags()` falls back remotely when a requested key is missing from local definitions
125
- * unless `onlyEvaluateLocally` is true. Remote evaluation responses are not cached, so a key
126
- * missing both locally and remotely costs one `/flags` request per `evaluateFlags()` call.
124
+ * An empty array returns an empty snapshot without evaluating flags; omitting this option
125
+ * evaluates all flags. `evaluateFlags()` falls back remotely when a requested key is missing
126
+ * from local definitions unless `onlyEvaluateLocally` is true. Remote evaluation responses are
127
+ * not cached, so a key missing both locally and remotely costs one `/flags` request per call.
127
128
  */
128
129
  flagKeys?: string[]
129
130
  }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '5.51.1'
1
+ export const version = '5.51.2'