posthog-node 6.3.0 → 6.4.1

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 (36) hide show
  1. package/MIGRATION.md +3 -1
  2. package/dist/client.d.ts +14 -8
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +55 -12
  5. package/dist/client.mjs +56 -13
  6. package/dist/emails/emails.d.ts +3 -3
  7. package/dist/emails/emails.d.ts.map +1 -1
  8. package/dist/emails/emails.js +29 -9
  9. package/dist/emails/emails.mjs +30 -10
  10. package/dist/emails/types.d.ts +42 -15
  11. package/dist/emails/types.d.ts.map +1 -1
  12. package/dist/extensions/feature-flags/feature-flags-v2.d.ts +4 -0
  13. package/dist/extensions/feature-flags/feature-flags-v2.d.ts.map +1 -1
  14. package/dist/extensions/feature-flags/feature-flags-v2.js +5 -3
  15. package/dist/extensions/feature-flags/feature-flags-v2.mjs +5 -3
  16. package/dist/extensions/feature-flags/feature-flags.d.ts +14 -3
  17. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  18. package/dist/extensions/feature-flags/feature-flags.js +130 -41
  19. package/dist/extensions/feature-flags/feature-flags.mjs +128 -42
  20. package/dist/extensions/nestjs.d.ts.map +1 -1
  21. package/dist/extensions/nestjs.js +1 -0
  22. package/dist/extensions/nestjs.mjs +1 -0
  23. package/dist/types.d.ts +46 -2
  24. package/dist/types.d.ts.map +1 -1
  25. package/dist/version.d.ts +1 -1
  26. package/dist/version.js +1 -1
  27. package/dist/version.mjs +1 -1
  28. package/package.json +3 -3
  29. package/src/client.ts +116 -18
  30. package/src/emails/emails.ts +44 -14
  31. package/src/emails/types.ts +42 -15
  32. package/src/extensions/feature-flags/feature-flags-v2.ts +16 -5
  33. package/src/extensions/feature-flags/feature-flags.ts +340 -63
  34. package/src/extensions/nestjs.ts +12 -0
  35. package/src/types.ts +46 -2
  36. package/src/version.ts +1 -1
@@ -160,6 +160,10 @@ export type FeatureFlagEvaluationContext = {
160
160
  groups: Record<string, string>
161
161
  personProperties: Record<string, any>
162
162
  groupProperties: Record<string, Record<string, any>>
163
+ /** Person property keys known to be absent, without person-metadata keys. */
164
+ personPropertyKeysKnownAbsent?: ReadonlySet<string>
165
+ /** Group property keys known to be absent, by group type name. */
166
+ groupPropertyKeysKnownAbsent?: Record<string, ReadonlySet<string>>
163
167
  evaluationCache: Record<string, FeatureFlagValue>
164
168
  definitions?: FlagEvaluationSnapshot
165
169
  }
@@ -429,6 +433,7 @@ class FeatureFlagsPoller {
429
433
  const record = await evaluateConfigV2Definition(flag, parsed, {
430
434
  distinctId: evaluationContext.distinctId,
431
435
  properties: evaluationContext.personProperties,
436
+ knownAbsentKeys: evaluationContext.personPropertyKeysKnownAbsent,
432
437
  propertyMatchingVersion: evaluationContext.definitions!.propertyMatchingVersion,
433
438
  })
434
439
  if (matchValue !== undefined) {
@@ -473,8 +478,12 @@ class FeatureFlagsPoller {
473
478
  const flagFilters = flag.filters || {}
474
479
 
475
480
  // Enrollment is a person property, so it is read from the person properties on
476
- // group-aggregated flags too.
477
- if (flagFilters.feature_enrollment === true) {
481
+ // group-aggregated flags too. A listed enrollment key means not enrolled, even over a
482
+ // supplied value, so evaluation continues through holdouts and release conditions.
483
+ if (
484
+ flagFilters.feature_enrollment === true &&
485
+ !evaluationContext.personPropertyKeysKnownAbsent?.has(featureEnrollmentKey(flag))
486
+ ) {
478
487
  return matchFeatureEnrollment(flag, personProperties)
479
488
  }
480
489
 
@@ -492,14 +501,12 @@ class FeatureFlagsPoller {
492
501
  throw new InconclusiveMatchError('Flag has unknown group type index')
493
502
  }
494
503
 
495
- if (!(groupName in groups)) {
496
- this.logMsgIfDebug(() =>
497
- console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`)
498
- )
499
- return false
500
- }
504
+ // Without a usable key, matchFeatureFlagProperties skips each group condition, and conditions
505
+ // with their own person aggregation still run.
506
+ const groupKey = usableGroupKey(groups, groupName)
501
507
 
502
508
  if (
509
+ groupKey !== undefined &&
503
510
  flag.bucketing_identifier === 'device_id' &&
504
511
  (personProperties?.$device_id === undefined ||
505
512
  personProperties?.$device_id === null ||
@@ -511,7 +518,13 @@ class FeatureFlagsPoller {
511
518
  }
512
519
 
513
520
  const focusedGroupProperties = groupProperties[groupName]
514
- return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationContext)
521
+ return await this.matchFeatureFlagProperties(
522
+ flag,
523
+ groupKey ?? '',
524
+ focusedGroupProperties,
525
+ evaluationContext,
526
+ evaluationContext.groupPropertyKeysKnownAbsent?.[groupName]
527
+ )
515
528
  } else {
516
529
  const bucketingValue = this.getBucketingValueForFlag(flag, distinctId, personProperties)
517
530
  if (bucketingValue === undefined) {
@@ -524,10 +537,16 @@ class FeatureFlagsPoller {
524
537
  // also applies, and it outranks missing_context.
525
538
  throw new InconclusiveMatchError(
526
539
  `Can't compute feature flag: ${flag.key} without $device_id`,
527
- getDefinitionUnresolvedReason(flag, evaluationContext.definitions!) ?? 'missing_context'
540
+ getDefinitionUnresolvedReason(flag, evaluationContext.definitions!, true) ?? 'missing_context'
528
541
  )
529
542
  }
530
- return await this.matchFeatureFlagProperties(flag, bucketingValue, personProperties, evaluationContext)
543
+ return await this.matchFeatureFlagProperties(
544
+ flag,
545
+ bucketingValue,
546
+ personProperties,
547
+ evaluationContext,
548
+ evaluationContext.personPropertyKeysKnownAbsent
549
+ )
531
550
  }
532
551
  }
533
552
 
@@ -543,6 +562,14 @@ class FeatureFlagsPoller {
543
562
  return distinctId
544
563
  }
545
564
 
565
+ return this.getPersonBucketingValue(flag, distinctId, properties)
566
+ }
567
+
568
+ private getPersonBucketingValue(
569
+ flag: PostHogFeatureFlag,
570
+ distinctId: string,
571
+ properties: Record<string, any>
572
+ ): string | undefined {
546
573
  if (flag.bucketing_identifier === 'device_id') {
547
574
  const deviceId = properties?.$device_id
548
575
  if (deviceId === undefined || deviceId === null || deviceId === '') {
@@ -687,10 +714,32 @@ class FeatureFlagsPoller {
687
714
  flag: PostHogFeatureFlag,
688
715
  bucketingValue: string,
689
716
  properties: Record<string, any>,
690
- evaluationContext: FeatureFlagEvaluationContext
717
+ evaluationContext: FeatureFlagEvaluationContext,
718
+ knownAbsentKeys?: ReadonlySet<string>
691
719
  ): Promise<FeatureFlagValue> {
692
720
  evaluationContext = this.withEvaluationSnapshot(evaluationContext)
693
721
  const flagFilters = flag.filters || {}
722
+ const flagAggregation = flagFilters.aggregation_group_type_index
723
+ const { distinctId, groups, groupProperties, personProperties } = evaluationContext
724
+
725
+ // The server hashes an empty identifier for the holdout of a group flag without a usable key,
726
+ // so only the server can tell whether that holdout excludes this flag.
727
+ if (flagAggregation != undefined && holdoutCanExclude(flagFilters.holdout)) {
728
+ const flagGroupName = evaluationContext.definitions!.groupTypeMapping[String(flagAggregation)]
729
+ if (!flagGroupName || usableGroupKey(groups, flagGroupName) === undefined) {
730
+ // The release conditions are never checked, so a cause in the definition also applies.
731
+ let definitionReason: UnresolvedFlagReason | undefined
732
+ try {
733
+ definitionReason = getDefinitionUnresolvedReason(flag, evaluationContext.definitions!, true)
734
+ } catch {
735
+ // A malformed definition must not turn the server fallback into an evaluation error.
736
+ }
737
+ throw new InconclusiveMatchError(
738
+ `Can't compute the holdout of group feature flag ${flag.key} without a group key`,
739
+ definitionReason ?? 'missing_context'
740
+ )
741
+ }
742
+ }
694
743
 
695
744
  // Holdouts are resolved before the release conditions, so a held-out value is excluded
696
745
  // from the flag's targeting rather than being bucketed into a variant.
@@ -700,47 +749,53 @@ class FeatureFlagsPoller {
700
749
  }
701
750
 
702
751
  const flagConditions = flagFilters.groups || []
703
- const flagAggregation = flagFilters.aggregation_group_type_index
704
752
  const earlyExitEnabled = flagFilters.early_exit ?? false
705
- const { groups, groupProperties } = evaluationContext
706
753
  let inconclusiveReason: UnresolvedFlagReason | undefined = undefined
707
754
  let regexError: InconclusiveMatchError | undefined
708
755
  const deferredRegexValues = new Set<FeatureFlagValue>()
709
756
  let result = undefined
710
757
 
711
758
  for (const condition of flagConditions) {
712
- let effectiveBucketingValue = bucketingValue
759
+ let effectiveBucketingValue: string | undefined = bucketingValue
713
760
  try {
714
- // Per-condition aggregation overrides only when the condition explicitly
715
- // sets its own aggregation_group_type_index (mixed targeting).
716
- // When absent, use the properties/bucketing already resolved by the caller.
717
- const conditionAggregation =
718
- condition.aggregation_group_type_index !== undefined
719
- ? condition.aggregation_group_type_index
720
- : flagAggregation
761
+ // A condition uses its own aggregation_group_type_index when it sets one (an explicit null
762
+ // is person aggregation), else the flag's. When it matches the flag's, use the
763
+ // properties/bucketing already resolved by the caller.
764
+ const conditionAggregation = conditionAggregationOf(condition, flagAggregation)
721
765
 
722
766
  let effectiveProperties = properties
723
-
724
- // Mixed-override path: condition-level aggregation differs from flag-level.
725
- // This assumes flag-level aggregation is null/undefined for mixed flags.
726
- if (conditionAggregation !== flagAggregation) {
727
- if (conditionAggregation !== null && conditionAggregation !== undefined) {
728
- const groupName = evaluationContext.definitions!.groupTypeMapping[String(conditionAggregation)]
729
- if (!groupName || !(groupName in groups)) {
730
- this.logMsgIfDebug(() =>
731
- console.debug(
732
- `[FEATURE FLAGS] Skipping group condition for flag '${flag.key}': group type index ${conditionAggregation} not available`
733
- )
767
+ let effectiveKnownAbsentKeys = knownAbsentKeys
768
+ let knownAbsentKeysGroupTypeIndex: number | null | undefined = flagAggregation
769
+
770
+ if (conditionAggregation != undefined) {
771
+ // Each group condition needs a usable key for its own group type, else it is skipped.
772
+ const groupName = evaluationContext.definitions!.groupTypeMapping[String(conditionAggregation)]
773
+ const groupKey = groupName ? usableGroupKey(groups, groupName) : undefined
774
+ if (!groupName || groupKey === undefined) {
775
+ this.logMsgIfDebug(() =>
776
+ console.debug(
777
+ `[FEATURE FLAGS] Skipping group condition for flag '${flag.key}': group type index ${conditionAggregation} not available`
734
778
  )
735
- continue
736
- }
779
+ )
780
+ continue
781
+ }
782
+ if (conditionAggregation !== flagAggregation) {
737
783
  if (!(groupName in groupProperties)) {
738
784
  inconclusiveReason = pickUnresolvedReason(inconclusiveReason, 'missing_context')
739
785
  continue
740
786
  }
741
787
  effectiveProperties = groupProperties[groupName]
742
- effectiveBucketingValue = groups[groupName]
788
+ effectiveKnownAbsentKeys = evaluationContext.groupPropertyKeysKnownAbsent?.[groupName]
789
+ knownAbsentKeysGroupTypeIndex = conditionAggregation
790
+ effectiveBucketingValue = groupKey
743
791
  }
792
+ } else if (flagAggregation != undefined) {
793
+ // A person condition in a group flag reads person properties and buckets as a person
794
+ // flag. Without a $device_id, isConditionMatch still checks its filters first.
795
+ effectiveProperties = personProperties
796
+ effectiveKnownAbsentKeys = evaluationContext.personPropertyKeysKnownAbsent
797
+ knownAbsentKeysGroupTypeIndex = null
798
+ effectiveBucketingValue = this.getPersonBucketingValue(flag, distinctId, personProperties)
744
799
  }
745
800
 
746
801
  const matchResult = await this.isConditionMatch(
@@ -748,7 +803,9 @@ class FeatureFlagsPoller {
748
803
  effectiveBucketingValue,
749
804
  condition,
750
805
  effectiveProperties,
751
- evaluationContext
806
+ evaluationContext,
807
+ effectiveKnownAbsentKeys,
808
+ knownAbsentKeysGroupTypeIndex
752
809
  )
753
810
  if (matchResult === 'match') {
754
811
  const variantOverride = condition.variant
@@ -756,7 +813,7 @@ class FeatureFlagsPoller {
756
813
  if (variantOverride && flagVariants.some((variant) => variant.key === variantOverride)) {
757
814
  result = variantOverride
758
815
  } else {
759
- result = (await this.getMatchingVariant(flag, effectiveBucketingValue)) || true
816
+ result = (await this.getMatchingVariant(flag, effectiveBucketingValue!)) || true
760
817
  }
761
818
  break
762
819
  } else if (earlyExitEnabled && matchResult === 'out_of_rollout_bound') {
@@ -774,7 +831,7 @@ class FeatureFlagsPoller {
774
831
  // The fallback skips later conditions, so a higher reason in them comes from the definition.
775
832
  let definitionReason: UnresolvedFlagReason | undefined
776
833
  try {
777
- definitionReason = getDefinitionUnresolvedReason(flag, evaluationContext.definitions!)
834
+ definitionReason = getDefinitionUnresolvedReason(flag, evaluationContext.definitions!, true)
778
835
  } catch {
779
836
  // A malformed definition must not turn the server fallback into an evaluation error.
780
837
  }
@@ -787,7 +844,8 @@ class FeatureFlagsPoller {
787
844
  // Evaluation error (bad regex, invalid date, missing property, etc.)
788
845
  // Track that we had an inconclusive match, but try other conditions
789
846
  inconclusiveReason = pickUnresolvedReason(inconclusiveReason, e.reason)
790
- if (Symbol.for('posthog.requiresServerRegexEvaluation') in e) {
847
+ // isConditionMatch drops the regex uncertainty when there is no bucketing value.
848
+ if (Symbol.for('posthog.requiresServerRegexEvaluation') in e && effectiveBucketingValue !== undefined) {
791
849
  regexError = e
792
850
  if (
793
851
  earlyExitEnabled &&
@@ -831,10 +889,14 @@ class FeatureFlagsPoller {
831
889
 
832
890
  async isConditionMatch(
833
891
  flag: PostHogFeatureFlag,
834
- bucketingValue: string,
892
+ /** Undefined when the condition needs a $device_id that was not passed. */
893
+ bucketingValue: string | undefined,
835
894
  condition: FeatureFlagCondition,
836
895
  properties: Record<string, any>,
837
- evaluationContext: FeatureFlagEvaluationContext
896
+ evaluationContext: FeatureFlagEvaluationContext,
897
+ knownAbsentKeys?: ReadonlySet<string>,
898
+ /** The group type index `knownAbsentKeys` belong to, or null/undefined for person keys. */
899
+ knownAbsentKeysGroupTypeIndex?: number | null
838
900
  ): Promise<ConditionMatchResult> {
839
901
  evaluationContext = this.withEvaluationSnapshot(evaluationContext)
840
902
  const definitions = evaluationContext.definitions!
@@ -848,23 +910,57 @@ class FeatureFlagsPoller {
848
910
  let inconclusiveReason: UnresolvedFlagReason | undefined = undefined
849
911
  let regexError: InconclusiveMatchError | undefined
850
912
  let serverEvaluationError: RequiresServerEvaluation | undefined = undefined
913
+ // In a group condition, person filters and person cohort leaves read the person properties
914
+ // and person listing, as the flags service does. Other filters keep reading the group.
915
+ const conditionAggregation = conditionAggregationOf(condition, flag.filters?.aggregation_group_type_index)
916
+ const personFilterScope: PersonFilterScope | undefined =
917
+ conditionAggregation != null
918
+ ? {
919
+ properties: evaluationContext.personProperties,
920
+ knownAbsentKeys: evaluationContext.personPropertyKeysKnownAbsent,
921
+ }
922
+ : undefined
851
923
  for (const prop of condition.properties) {
852
924
  const propertyType = prop.type
925
+ const readsPerson = personFilterScope !== undefined && propertyType === 'person'
926
+ let filterProperties = readsPerson ? personFilterScope.properties : properties
927
+ let filterKnownAbsentKeys = readsPerson
928
+ ? personFilterScope.knownAbsentKeys
929
+ : knownAbsentKeysForFilter(prop, knownAbsentKeys, knownAbsentKeysGroupTypeIndex)
853
930
  let matches = false
854
931
 
855
932
  try {
933
+ const groupSource =
934
+ propertyType === 'group' ? groupFilterSource(prop, conditionAggregation, evaluationContext) : undefined
935
+ if (groupSource === 'no_match') {
936
+ return 'no_match'
937
+ } else if (groupSource !== undefined) {
938
+ filterProperties = groupSource.properties
939
+ filterKnownAbsentKeys =
940
+ groupSource.missingIsAbsent && !Object.prototype.hasOwnProperty.call(filterProperties, prop.key)
941
+ ? new Set([prop.key])
942
+ : groupSource.knownAbsentKeys
943
+ }
944
+
856
945
  if (propertyType === 'cohort') {
946
+ // In a group condition, the cohort's other leaves read the group properties without a
947
+ // listing, since a cohort's scope is the person.
857
948
  matches = await matchCohort(
858
949
  prop,
859
950
  properties,
860
951
  definitions.cohorts,
861
952
  this.debugMode,
862
953
  (depProp) => this.evaluateFlagDependency(depProp, properties, evaluationContext),
863
- definitions.propertyMatchingVersion
954
+ definitions.propertyMatchingVersion,
955
+ personFilterScope ? undefined : knownAbsentKeys,
956
+ personFilterScope
864
957
  )
865
958
  } else if (propertyType === 'flag') {
866
959
  matches = await this.evaluateFlagDependency(prop, properties, evaluationContext)
867
- } else if (!Object.prototype.hasOwnProperty.call(properties, prop.key)) {
960
+ } else if (
961
+ !filterKnownAbsentKeys?.has(prop.key) &&
962
+ !Object.prototype.hasOwnProperty.call(filterProperties, prop.key)
963
+ ) {
868
964
  // Same result as matchProperty for an absent key, without the cost of throwing for
869
965
  // every missing filter now that the loop no longer stops at the first one.
870
966
  assertPropertyFilterTypeSupported(prop)
@@ -872,7 +968,13 @@ class FeatureFlagsPoller {
872
968
  inconclusiveReason = pickUnresolvedReason(inconclusiveReason, 'missing_context')
873
969
  continue
874
970
  } else {
875
- matches = matchProperty(prop, properties, warnFunction, definitions.propertyMatchingVersion)
971
+ matches = matchProperty(
972
+ prop,
973
+ filterProperties,
974
+ warnFunction,
975
+ definitions.propertyMatchingVersion,
976
+ filterKnownAbsentKeys
977
+ )
876
978
  }
877
979
  } catch (e) {
878
980
  if (e instanceof RequiresServerEvaluation) {
@@ -909,15 +1011,23 @@ class FeatureFlagsPoller {
909
1011
  throw serverEvaluationError
910
1012
  }
911
1013
  if (inconclusiveReason) {
912
- throw preserveRegexUncertainty(
913
- new InconclusiveMatchError(`Can't determine if a condition of flag ${flag.key} matches`, inconclusiveReason),
914
- regexError
1014
+ const error = new InconclusiveMatchError(
1015
+ `Can't determine if a condition of flag ${flag.key} matches`,
1016
+ bucketingValue === undefined
1017
+ ? pickUnresolvedReason(inconclusiveReason, 'missing_context')
1018
+ : inconclusiveReason
915
1019
  )
1020
+ throw bucketingValue === undefined ? error : preserveRegexUncertainty(error, regexError)
916
1021
  }
1022
+ }
917
1023
 
918
- if (rolloutPercentage == undefined) {
919
- return 'match'
920
- }
1024
+ // Property filters (if any) matched, so only now does the missing bucketing value matter.
1025
+ if (bucketingValue === undefined) {
1026
+ throw new InconclusiveMatchError(`Can't compute feature flag: ${flag.key} without $device_id`, 'missing_context')
1027
+ }
1028
+
1029
+ if ((condition.properties || []).length > 0 && rolloutPercentage == undefined) {
1030
+ return 'match'
921
1031
  }
922
1032
 
923
1033
  // Property filters (if any) matched; only the rollout check remains. A failure here means the
@@ -1463,13 +1573,45 @@ class FeatureFlagsPoller {
1463
1573
  }
1464
1574
  }
1465
1575
 
1576
+ /** Whether a group key counts as a key: a non-empty string or a number, as on the server. */
1577
+ export function isUsableGroupKey(groupKey: unknown): groupKey is string | number {
1578
+ return (
1579
+ (typeof groupKey === 'string' && groupKey !== '') || (typeof groupKey === 'number' && Number.isFinite(groupKey))
1580
+ )
1581
+ }
1582
+
1583
+ /** The key of the group type, or undefined when it is omitted or unusable and so counts as no group key. */
1584
+ function usableGroupKey(groups: Record<string, unknown>, groupName: string): string | undefined {
1585
+ const groupKey = groups[groupName]
1586
+ return isUsableGroupKey(groupKey) ? String(groupKey) : undefined
1587
+ }
1588
+
1589
+ /** The condition's own aggregation when it sets one (null is person aggregation), else the flag's. */
1590
+ function conditionAggregationOf(
1591
+ condition: FeatureFlagCondition,
1592
+ flagAggregation: number | null | undefined
1593
+ ): number | null | undefined {
1594
+ return condition.aggregation_group_type_index !== undefined ? condition.aggregation_group_type_index : flagAggregation
1595
+ }
1596
+
1597
+ /** Whether getHoldoutVariant could return a holdout variant for some bucketing value. */
1598
+ function holdoutCanExclude(holdout: { id: number; exclusion_percentage: number } | null | undefined): boolean {
1599
+ if (holdout == null || holdout.id == null || holdout.exclusion_percentage == null) {
1600
+ return false
1601
+ }
1602
+ const percentage = Number(holdout.exclusion_percentage)
1603
+ return Number.isFinite(percentage) && percentage > 0
1604
+ }
1605
+
1466
1606
  /**
1467
1607
  * The unresolved reason that comes from the flag's definition alone, so it is known when
1468
1608
  * definitions load. Matches the reason local evaluation reports for the same cause.
1469
1609
  */
1470
1610
  function getDefinitionUnresolvedReason(
1471
1611
  flag: PostHogFeatureFlag,
1472
- definitions: FlagEvaluationSnapshot
1612
+ definitions: FlagEvaluationSnapshot,
1613
+ /** True when evaluation already continued past enrollment, for a known-absent enrollment key. */
1614
+ ignoreFeatureEnrollment = false
1473
1615
  ): UnresolvedFlagReason | undefined {
1474
1616
  if (!isConfigVersion1(flag)) {
1475
1617
  return configV2UnresolvedReason(flag, definitions.parsedConfigV2Definitions)
@@ -1482,7 +1624,7 @@ function getDefinitionUnresolvedReason(
1482
1624
  }
1483
1625
  const flagFilters = flag.filters || {}
1484
1626
  // Enrollment decides the flag before the group aggregation and release conditions are read.
1485
- if (flagFilters.feature_enrollment === true) {
1627
+ if (flagFilters.feature_enrollment === true && !ignoreFeatureEnrollment) {
1486
1628
  return undefined
1487
1629
  }
1488
1630
  const aggregation = flagFilters.aggregation_group_type_index
@@ -1490,16 +1632,24 @@ function getDefinitionUnresolvedReason(
1490
1632
  return 'unsupported_definition'
1491
1633
  }
1492
1634
  const usesUnsupportedProperty = (flagFilters.groups || []).some((condition) =>
1493
- (condition.properties || []).some((property) => isUnsupportedProperty(property, definitions, new Set()))
1635
+ (condition.properties || []).some(
1636
+ (property) =>
1637
+ isUnsupportedProperty(property, definitions, new Set()) ||
1638
+ isGroupFilterWithoutGroupType(property, conditionAggregationOf(condition, aggregation))
1639
+ )
1494
1640
  )
1495
1641
  return usesUnsupportedProperty ? 'unsupported_definition' : undefined
1496
1642
  }
1497
1643
 
1644
+ function featureEnrollmentKey(flag: PostHogFeatureFlag): string {
1645
+ return `$feature_enrollment/${flag.key}`
1646
+ }
1647
+
1498
1648
  // An early-access feature flag returns the person's enrollment at once: `true` or `"true"` means
1499
1649
  // enrolled, and any other value that was passed, `null` included, means opted out. Without the
1500
1650
  // enrollment property the flag can't be resolved locally.
1501
1651
  function matchFeatureEnrollment(flag: PostHogFeatureFlag, personProperties: Record<string, any>): boolean {
1502
- const enrollmentKey = `$feature_enrollment/${flag.key}`
1652
+ const enrollmentKey = featureEnrollmentKey(flag)
1503
1653
  const enrollment = personProperties[enrollmentKey]
1504
1654
  // `undefined` is omitted from JSON, so /flags would read the stored enrollment.
1505
1655
  if (enrollment === undefined) {
@@ -1564,6 +1714,97 @@ function isUnsupportedPropertyGroup(
1564
1714
  )
1565
1715
  }
1566
1716
 
1717
+ /** A group filter without `group_type_index` in a person condition has no group type to read. */
1718
+ function isGroupFilterWithoutGroupType(
1719
+ property: FlagProperty & { group_type_index?: number | null },
1720
+ conditionAggregation: number | null | undefined
1721
+ ): boolean {
1722
+ return property.type === 'group' && property.group_type_index == null && conditionAggregation == null
1723
+ }
1724
+
1725
+ type GroupFilterSource = {
1726
+ properties: Record<string, any>
1727
+ knownAbsentKeys?: ReadonlySet<string>
1728
+ /** The properties are complete, so a key missing from them is absent. */
1729
+ missingIsAbsent: boolean
1730
+ }
1731
+
1732
+ /**
1733
+ * Where a group filter reads its properties when that differs from the condition's properties, as
1734
+ * the flags service routes it: a filter of another group type reads that group type, and one
1735
+ * without `group_type_index` in a person condition is unsupported. Undefined means the condition's
1736
+ * properties apply.
1737
+ */
1738
+ function groupFilterSource(
1739
+ property: FlagProperty & { group_type_index?: number | null },
1740
+ conditionAggregation: number | null | undefined,
1741
+ evaluationContext: FeatureFlagEvaluationContext
1742
+ ): GroupFilterSource | 'no_match' | undefined {
1743
+ if (isGroupFilterWithoutGroupType(property, conditionAggregation)) {
1744
+ throw new InconclusiveMatchError(
1745
+ `Can't evaluate group filter '${property.key}' without a group_type_index in a person condition locally`,
1746
+ 'unsupported_definition'
1747
+ )
1748
+ }
1749
+ const index = property.group_type_index
1750
+ if (index == null || index === conditionAggregation) {
1751
+ return undefined
1752
+ }
1753
+ const { groups, groupProperties, groupPropertyKeysKnownAbsent } = evaluationContext
1754
+ const groupName = evaluationContext.definitions!.groupTypeMapping[String(index)]
1755
+ if (!groupName) {
1756
+ // The flags service can't tell which supplied group has this index, so with any group context
1757
+ // the filter doesn't match. Without it, the filter reads no properties.
1758
+ return hasGroupContext(groups, groupProperties) ? 'no_match' : { properties: {}, missingIsAbsent: true }
1759
+ }
1760
+ return {
1761
+ properties:
1762
+ (Object.prototype.hasOwnProperty.call(groupProperties, groupName) ? groupProperties[groupName] : undefined) ?? {},
1763
+ knownAbsentKeys: groupPropertyKeysKnownAbsent?.[groupName],
1764
+ // Without a usable key there is no group to load properties for, so the supplied ones are complete.
1765
+ missingIsAbsent: usableGroupKey(groups, groupName) === undefined,
1766
+ }
1767
+ }
1768
+
1769
+ /** A usable group key, or a group property other than an unusable `$group_key`, as the flags service decides. */
1770
+ function hasGroupContext(
1771
+ groups: Record<string, unknown>,
1772
+ groupProperties: Record<string, Record<string, any>>
1773
+ ): boolean {
1774
+ return (
1775
+ Object.values(groups).some(isUsableGroupKey) ||
1776
+ Object.values(groupProperties).some((properties) =>
1777
+ Object.entries(properties || {}).some(
1778
+ // The /flags request is JSON, which leaves out these values, so they give no context there either.
1779
+ ([key, value]) =>
1780
+ value !== undefined &&
1781
+ typeof value !== 'function' &&
1782
+ typeof value !== 'symbol' &&
1783
+ (key !== '$group_key' || isUsableGroupKey(value))
1784
+ )
1785
+ )
1786
+ )
1787
+ }
1788
+
1789
+ /**
1790
+ * Person keys apply only to person filters and group keys only to group filters of their own group
1791
+ * type. A group filter without `group_type_index` belongs to the condition's group type. Other filter
1792
+ * types, such as `person_metadata`, never resolve from a listing.
1793
+ */
1794
+ function knownAbsentKeysForFilter(
1795
+ property: FlagProperty & { group_type_index?: number | null },
1796
+ knownAbsentKeys: ReadonlySet<string> | undefined,
1797
+ knownAbsentKeysGroupTypeIndex: number | null | undefined
1798
+ ): ReadonlySet<string> | undefined {
1799
+ if (knownAbsentKeysGroupTypeIndex == null) {
1800
+ return property.type === 'person' ? knownAbsentKeys : undefined
1801
+ }
1802
+ return property.type === 'group' &&
1803
+ (property.group_type_index ?? knownAbsentKeysGroupTypeIndex) === knownAbsentKeysGroupTypeIndex
1804
+ ? knownAbsentKeys
1805
+ : undefined
1806
+ }
1807
+
1567
1808
  // Filter types matched against the person or group properties the caller passes. Cohort and
1568
1809
  // flag filters have their own matching. Any other type, such as `person_metadata` (a value the
1569
1810
  // server reads from the persons table, not from person properties), can't be evaluated locally:
@@ -1584,10 +1825,15 @@ function matchProperty(
1584
1825
  property: FeatureFlagCondition['properties'][number],
1585
1826
  propertyValues: Record<string, any>,
1586
1827
  warnFunction?: (msg: string) => void,
1587
- propertyMatchingVersion?: number
1828
+ propertyMatchingVersion?: number,
1829
+ knownAbsentKeys?: ReadonlySet<string>
1588
1830
  ): boolean {
1589
1831
  assertPropertyFilterTypeSupported(property)
1590
- return matchFeatureFlagProperty(property, propertyValues, { warnFunction, propertyMatchingVersion })
1832
+ return matchFeatureFlagProperty(property, propertyValues, {
1833
+ warnFunction,
1834
+ propertyMatchingVersion,
1835
+ knownAbsentKeys,
1836
+ })
1591
1837
  }
1592
1838
 
1593
1839
  function parseSemver(value: string): [number, number, number] {
@@ -1604,13 +1850,21 @@ function checkCohortExists(cohortId: string, cohortProperties: FeatureFlagsPolle
1604
1850
 
1605
1851
  type FlagDependencyEvaluator = (prop: FlagProperty) => Promise<boolean>
1606
1852
 
1853
+ /** The person properties and person listing that person filters read in a group condition. */
1854
+ type PersonFilterScope = {
1855
+ properties: Record<string, any>
1856
+ knownAbsentKeys?: ReadonlySet<string>
1857
+ }
1858
+
1607
1859
  async function matchCohort(
1608
1860
  property: FeatureFlagCondition['properties'][number],
1609
1861
  propertyValues: Record<string, any>,
1610
1862
  cohortProperties: FeatureFlagsPoller['cohorts'],
1611
1863
  debugMode: boolean = false,
1612
1864
  flagDependencyEvaluator?: FlagDependencyEvaluator,
1613
- propertyMatchingVersion?: number
1865
+ propertyMatchingVersion?: number,
1866
+ knownAbsentKeys?: ReadonlySet<string>,
1867
+ personFilterScope?: PersonFilterScope
1614
1868
  ): Promise<boolean> {
1615
1869
  const cohortId = String(property.value)
1616
1870
  checkCohortExists(cohortId, cohortProperties)
@@ -1622,7 +1876,9 @@ async function matchCohort(
1622
1876
  cohortProperties,
1623
1877
  debugMode,
1624
1878
  flagDependencyEvaluator,
1625
- propertyMatchingVersion
1879
+ propertyMatchingVersion,
1880
+ knownAbsentKeys,
1881
+ personFilterScope
1626
1882
  )
1627
1883
  return property.operator === 'not_in' ? !inCohort : inCohort
1628
1884
  }
@@ -1633,7 +1889,9 @@ async function matchPropertyGroup(
1633
1889
  cohortProperties: FeatureFlagsPoller['cohorts'],
1634
1890
  debugMode: boolean = false,
1635
1891
  flagDependencyEvaluator?: FlagDependencyEvaluator,
1636
- propertyMatchingVersion?: number
1892
+ propertyMatchingVersion?: number,
1893
+ knownAbsentKeys?: ReadonlySet<string>,
1894
+ personFilterScope?: PersonFilterScope
1637
1895
  ): Promise<boolean> {
1638
1896
  // The backend's canonical empty PropertyGroup is {}.
1639
1897
  if (!propertyGroup || Object.keys(propertyGroup).length === 0) {
@@ -1663,7 +1921,9 @@ async function matchPropertyGroup(
1663
1921
  cohortProperties,
1664
1922
  debugMode,
1665
1923
  flagDependencyEvaluator,
1666
- propertyMatchingVersion
1924
+ propertyMatchingVersion,
1925
+ knownAbsentKeys,
1926
+ personFilterScope
1667
1927
  )
1668
1928
  if (propertyGroupType === 'AND') {
1669
1929
  if (!matches) {
@@ -1710,7 +1970,9 @@ async function matchPropertyGroup(
1710
1970
  cohortProperties,
1711
1971
  debugMode,
1712
1972
  flagDependencyEvaluator,
1713
- propertyMatchingVersion
1973
+ propertyMatchingVersion,
1974
+ knownAbsentKeys,
1975
+ personFilterScope
1714
1976
  )
1715
1977
  } else if (prop.type === 'flag') {
1716
1978
  if (!flagDependencyEvaluator) {
@@ -1719,8 +1981,23 @@ async function matchPropertyGroup(
1719
1981
  )
1720
1982
  }
1721
1983
  matches = await flagDependencyEvaluator(prop)
1984
+ } else if (personFilterScope && prop.type === 'person') {
1985
+ matches = matchProperty(
1986
+ prop,
1987
+ personFilterScope.properties,
1988
+ undefined,
1989
+ propertyMatchingVersion,
1990
+ personFilterScope.knownAbsentKeys
1991
+ )
1722
1992
  } else {
1723
- matches = matchProperty(prop, propertyValues, undefined, propertyMatchingVersion)
1993
+ // Cohorts only receive person keys, so they apply only to person leaves.
1994
+ matches = matchProperty(
1995
+ prop,
1996
+ propertyValues,
1997
+ undefined,
1998
+ propertyMatchingVersion,
1999
+ knownAbsentKeysForFilter(prop, knownAbsentKeys, null)
2000
+ )
1724
2001
  }
1725
2002
 
1726
2003
  const negation = prop.negation || false
@@ -67,6 +67,18 @@ function getExceptionStatus(exception: unknown): number | undefined {
67
67
  const status = (exception as any).getStatus()
68
68
  return typeof status === 'number' ? status : undefined
69
69
  }
70
+ // Nest also accepts http-errors instances, which have status fields instead of getStatus().
71
+ if (
72
+ exception instanceof Error &&
73
+ 'statusCode' in exception &&
74
+ typeof exception.statusCode === 'number' &&
75
+ 'status' in exception &&
76
+ exception.status === exception.statusCode &&
77
+ 'expose' in exception &&
78
+ typeof exception.expose === 'boolean'
79
+ ) {
80
+ return exception.statusCode
81
+ }
70
82
  return undefined
71
83
  }
72
84