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.

4.7 KB
Raw Blame
import { combineUrl } from 'kea-router'

import { urls } from 'scenes/urls'

import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'

import type { EmailDraftRequestApi } from '../generated/api.schemas'
import { DRAFT_SOURCE_PARAM } from '../MessageAudience/aiEmailDraft'
import { EMAIL_PREFILL_PARAM, MessageDraft } from '../MessageAudience/messageDrafts'

// pinned: URL search params, other products link to /broadcasts/new with these
export const AUDIENCE_PREFILL_PARAM = 'audience'
export const NAME_PREFILL_PARAM = 'name'
export const SOURCE_PREFILL_PARAM = 'source'
export const SOURCE_RECORD_PREFILL_PARAM = 'source_record'

export interface BroadcastPrefill {
    properties: AnyPropertyFilter[]
    name?: string
    /** The product surface the person came from, reported on the launch event. */
    source?: string
    /** The record the email is about, as "<kind>:<id>". Saved on the broadcast so a later one can warn it was already sent. */
    sourceRecord?: string
    email?: MessageDraft
    draftSource?: EmailDraftRequestApi
}

export function urlForNewBroadcastWithAudience({
    properties,
    name,
    source,
    sourceRecord,
    email,
    draftSource,
}: BroadcastPrefill): string {
    return combineUrl(urls.broadcastNew(), {
        [AUDIENCE_PREFILL_PARAM]: JSON.stringify(properties),
        ...(name ? { [NAME_PREFILL_PARAM]: name } : {}),
        ...(source ? { [SOURCE_PREFILL_PARAM]: source } : {}),
        ...(sourceRecord ? { [SOURCE_RECORD_PREFILL_PARAM]: sourceRecord } : {}),
        ...(email ? { [EMAIL_PREFILL_PARAM]: JSON.stringify(email) } : {}),
        ...(draftSource ? { [DRAFT_SOURCE_PARAM]: JSON.stringify(draftSource) } : {}),
    }).url
}

/** The audience a link asked for, or null when it is missing or any filter in it can't be applied. */
export function parseBroadcastAudiencePrefill(raw: unknown): AnyPropertyFilter[] | null {
    let value = raw
    if (typeof raw === 'string') {
        try {
            value = JSON.parse(raw)
        } catch {
            return null
        }
    }
    if (!Array.isArray(value) || value.length === 0) {
        return null
    }
    const filters = value.map(toAudienceFilter)
    return filters.every((filter): filter is AnyPropertyFilter => filter !== null) ? filters : null
}

const PERSON_OPERATORS: string[] = Object.values(PropertyOperator)
const COHORT_OPERATORS: string[] = [PropertyOperator.In, PropertyOperator.NotIn]

function isFilterValue(value: unknown): boolean {
    return (
        typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)) || typeof value === 'boolean'
    )
}

// Rebuilt from known fields only: the backend drops a filter with a field it rejects, which would widen the
// audience to everyone while the wizard still shows the filter.
function toAudienceFilter(filter: unknown): AnyPropertyFilter | null {
    if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
        return null
    }
    const { key, type, operator, value, cohort_name } = filter as Record<string, unknown>
    if (typeof key !== 'string' || key === '') {
        return null
    }
    if (type === PropertyFilterType.Cohort) {
        if (key !== 'id' || typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
            return null
        }
        if (operator !== undefined && (typeof operator !== 'string' || !COHORT_OPERATORS.includes(operator))) {
            return null
        }
        return {
            key: 'id',
            type: PropertyFilterType.Cohort,
            value,
            operator: (operator as PropertyOperator | undefined) ?? PropertyOperator.In,
            ...(typeof cohort_name === 'string' ? { cohort_name } : {}),
        }
    }
    if (type !== PropertyFilterType.Person || typeof operator !== 'string' || !PERSON_OPERATORS.includes(operator)) {
        return null
    }
    if (operator === PropertyOperator.IsSet || operator === PropertyOperator.IsNotSet) {
        return { key, type: PropertyFilterType.Person, operator: operator as PropertyOperator }
    }
    const hasValue = Array.isArray(value)
        ? value.length > 0 && value.every(isFilterValue)
        : isFilterValue(value) && value !== ''
    if (!hasValue) {
        return null
    }
    return {
        key,
        type: PropertyFilterType.Person,
        operator: operator as PropertyOperator,
        value: value as string | number | boolean | (string | number | boolean)[],
    } as AnyPropertyFilter
}

const SOURCE_RECORD_PATTERN = /^[a-z_]+:[A-Za-z0-9_-]+$/

export function parseSourceRecordPrefill(raw: unknown): string | undefined {
    return typeof raw === 'string' && raw.length <= 255 && SOURCE_RECORD_PATTERN.test(raw) ? raw : undefined
}