Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

10.8 KB
Raw Blame
import { MakeLogicType, kea } from 'kea'

import api from 'lib/api'
import { toParams } from 'lib/utils/url'
import { validateFeatureFlagKey } from 'scenes/feature-flags/featureFlagLogic'
import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
import { teamLogic } from 'scenes/teamLogic'

import type { Experiment, FeatureFlagType } from '~/types'

import { experimentsLogic } from 'products/experiments/frontend/scenes/experimentsLogic'

import type { ExperimentsResult } from '../../../../../products/experiments/frontend/scenes/experimentsLogic'
import type { ExperimentIdType } from '../../../types'
import type { FeatureFlagsResult } from '../../feature-flags/featureFlagsLogic'

export type FeatureFlagKeyValidation = {
    valid: boolean
    error: string | null
    existingFlag?: FeatureFlagType
    /** The key this result validated, so consumers can detect a stale result after the key changed. */
    key?: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variantsPanelLogicValues {
    experiments: ExperimentsResult // experimentsLogic
    featureFlags: FeatureFlagsResult // featureFlagsLogic
    currentProjectId: number | string // teamLogic
    featureFlagKeyError: string | null
    featureFlagKeyForAutocomplete: string | null
    featureFlagKeyValidation: FeatureFlagKeyValidation | null
    featureFlagKeyValidationLoading: boolean
    linkedFeatureFlag: FeatureFlagType | null
    mode: 'create' | 'link'
    unavailableFeatureFlagKeys: Set<string>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variantsPanelLogicActions {
    clearFeatureFlagKeyValidation: () => {
        value: true
    }
    clearFeatureFlagKeyValidationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    clearFeatureFlagKeyValidationSuccess: (
        featureFlagKeyValidation: null,
        payload?: {
            value: true
        }
    ) => {
        featureFlagKeyValidation: null
        payload?: {
            value: true
        }
    }
    setFeatureFlagKeyForAutocomplete: (key: string | null) => {
        key: string | null
    }
    setLinkedFeatureFlag: (flag: FeatureFlagType | null) => {
        flag: FeatureFlagType | null
    }
    setMode: (mode: 'create' | 'link') => {
        mode: 'create' | 'link'
    }
    validateFeatureFlagKey: (key: string) => {
        key: string
    }
    validateFeatureFlagKeyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    validateFeatureFlagKeySuccess: (
        featureFlagKeyValidation:
            | {
                  error: string
                  existingFlag: any
                  key: string
                  valid: false
              }
            | {
                  error: string
                  existingFlag?: undefined
                  key: string
                  valid: false
              }
            | {
                  error: null
                  existingFlag?: undefined
                  key: string
                  valid: true
              },
        payload?: {
            key: string
        }
    ) => {
        featureFlagKeyValidation:
            | {
                  error: string
                  existingFlag: any
                  key: string
                  valid: false
              }
            | {
                  error: string
                  existingFlag?: undefined
                  key: string
                  valid: false
              }
            | {
                  error: null
                  existingFlag?: undefined
                  key: string
                  valid: true
              }
        payload?: {
            key: string
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variantsPanelLogicProps {
    disabled: boolean
    experiment: Experiment
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variantsPanelLogicMeta {
    key: ExperimentIdType
    __keaTypeGenInternalSelectorTypes: {
        unavailableFeatureFlagKeys: (featureFlags: FeatureFlagsResult, experiments: ExperimentsResult) => Set<string>
    }
}

export type variantsPanelLogicType = MakeLogicType<
    variantsPanelLogicValues,
    variantsPanelLogicActions,
    variantsPanelLogicProps,
    variantsPanelLogicMeta
>

export const variantsPanelLogic = kea<variantsPanelLogicType>({
    key: (props) => props.experiment?.id || 'new',
    path: (key) => ['scenes', 'experiments', 'create', 'panels', 'variantsPanelLogic', key],
    props: {
        experiment: {} as Experiment,
        disabled: false as boolean,
    } as {
        experiment: Experiment
        disabled: boolean
    },
    connect: {
        values: [
            featureFlagsLogic,
            ['featureFlags'],
            experimentsLogic,
            ['experiments'],
            teamLogic,
            ['currentProjectId'],
        ],
        actions: [],
    },
    actions: {
        setMode: (mode: 'create' | 'link') => ({ mode }),
        validateFeatureFlagKey: (key: string) => ({ key }),
        clearFeatureFlagKeyValidation: true,
        setLinkedFeatureFlag: (flag: FeatureFlagType | null) => ({ flag }),
        setFeatureFlagKeyForAutocomplete: (key: string | null) => ({ key }),
    },
    reducers: ({ props }) => ({
        featureFlagKeyError: [
            null as string | null,
            {
                setFeatureFlagKeyError: (_, { error }) => error,
            },
        ],
        mode: [
            // if disabled, we've default to 'link' mode
            (props.disabled ? 'link' : 'create') as 'create' | 'link',
            {
                setMode: (state: 'create' | 'link', { mode }: { mode: 'create' | 'link' }) => {
                    // Prevent mode changes when editing
                    if (props.disabled) {
                        return state
                    }
                    return mode
                },
            },
        ],
        linkedFeatureFlag: [
            // Initialize from experiment.feature_flag when disabled
            (props.disabled && props.experiment.feature_flag
                ? props.experiment.feature_flag
                : null) as FeatureFlagType | null,
            {
                setLinkedFeatureFlag: (_, { flag }) => flag,
            },
        ],
        featureFlagKeyForAutocomplete: [
            // Initialize from experiment.feature_flag_key when available
            (props.experiment.feature_flag_key || null) as string | null,
            {
                setFeatureFlagKeyForAutocomplete: (_, { key }) => key,
            },
        ],
    }),
    loaders: ({ values }) => ({
        featureFlagKeyValidation: [
            null as FeatureFlagKeyValidation | null,
            {
                validateFeatureFlagKey: async ({ key }) => {
                    // First do client-side validation
                    const clientError = validateFeatureFlagKey(key)
                    if (clientError) {
                        return { valid: false, error: clientError, key }
                    }

                    // Check if key already exists in our unavailable keys set
                    if (values.unavailableFeatureFlagKeys.has(key)) {
                        const existingFlag = values.featureFlags.results.find(
                            (flag: FeatureFlagType) => flag.key === key
                        )
                        return {
                            valid: false,
                            error: 'A feature flag with this key already exists.',
                            existingFlag,
                            key,
                        }
                    }

                    // Double-check with API for recently created flags.
                    // Filter by exact `key`, not `search`: the API rejects search terms over 200 characters, but keys can have up to 400.
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsList() from 'products/feature_flags/frontend/generated/api' instead.
                    const response = await api.get(
                        `api/projects/${values.currentProjectId}/feature_flags/?${toParams({ key })}`
                    )

                    if (response.results.length > 0) {
                        const exactMatch = response.results.find((flag: FeatureFlagType) => flag.key === key)
                        if (exactMatch) {
                            return {
                                valid: false,
                                error: 'A feature flag with this key already exists.',
                                existingFlag: exactMatch,
                                key,
                            }
                        }
                    }

                    return { valid: true, error: null, key }
                },
                clearFeatureFlagKeyValidation: () => null,
            },
        ],
    }),
    selectors: {
        // TRICKY: we do not load all feature flags here, just the latest ones.
        unavailableFeatureFlagKeys: [
            (s) => [s.featureFlags, s.experiments],
            (
                featureFlags: import('scenes/feature-flags/featureFlagsLogic').FeatureFlagsResult,
                experiments: import('products/experiments/frontend/scenes/experimentsLogic').ExperimentsResult
            ) => {
                return new Set([
                    ...featureFlags.results.map((flag) => flag.key),
                    ...experiments.results.map((experiment) => experiment.feature_flag_key),
                ])
            },
        ],
    },
    listeners: ({ props, actions }) => ({
        setMode: ({ mode }) => {
            if (mode === 'link') {
                // When switching to link mode, clear validation
                // In link mode, we're using an existing flag, so the key validation doesn't apply
                actions.clearFeatureFlagKeyValidation()
            } else if (mode === 'create' && props.experiment.feature_flag_key) {
                // When switching from link to create, validate the current key to show it's taken
                // Note: We use values.experiment (from createExperimentLogic connection) instead of props.experiment
                // because props are captured at mount time and don't update when the parent logic changes state
                actions.validateFeatureFlagKey(props.experiment.feature_flag_key)
            }
        },
        setLinkedFeatureFlag: () => {
            // When selecting a linked flag, clear validation
            // The linked flag's key already exists (that's the point!), so validation doesn't apply
            actions.clearFeatureFlagKeyValidation()
        },
    }),
})