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.

1.4 KB
Raw Blame
import { FetchResponse } from '~/common/utils/request'
import { ProcessedPluginEvent, RetryError } from '~/plugin-scaffold'

import { LegacyDestinationPluginMeta } from '../../types'

export type PatternsMeta = LegacyDestinationPluginMeta & {
    config: {
        webhookUrl: string
        allowedEventTypes: string
    }
    global: {
        allowedEventTypesSet: Set<string>
    }
}

// Plugin method that runs on plugin load
export async function setupPlugin({ config, global }: PatternsMeta): Promise<void> {
    if (config.allowedEventTypes) {
        let allowedEventTypes = config.allowedEventTypes.split(',')
        allowedEventTypes = allowedEventTypes.map((eventType: string) => eventType.trim())
        global.allowedEventTypesSet = new Set(allowedEventTypes)
    }
    return Promise.resolve()
}

// Plugin method to export events
export const onEvent = async (event: ProcessedPluginEvent, { config, global, fetch }: PatternsMeta): Promise<void> => {
    if (global.allowedEventTypesSet) {
        if (!global.allowedEventTypesSet.has(event.event)) {
            return
        }
    }

    const response: FetchResponse = await fetch(config.webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify([event]),
    })

    if (response.status != 200) {
        const data = await response.text()
        throw new RetryError(`Export events failed: ${data}`)
    }
}