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
export interface SemanticVersion {
    major: number
    minor?: number
    patch?: number
    extra?: string
}

export function parseVersion(version: string): SemanticVersion {
    // Regex to parse a semver string, can be just major, major.minor or major.minor.patch
    // if there is a hyphen thing ignore anything afterwards
    // strip a leading v if it exists
    const split = version.split('-', 2)
    version = split[0]
    const extra = split[1]
    const match = version.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/)
    if (!match) {
        throw new Error(`Invalid semver string: ${version}`)
    }
    const [, major, minor, patch] = match
    const majorInt = parseInt(major, 10)
    const minorInt = minor != null ? parseInt(minor, 10) : undefined
    const patchInt = patch != null ? parseInt(patch, 10) : undefined

    if (isNaN(majorInt) || (minorInt != null && isNaN(minorInt)) || (patchInt != null && isNaN(patchInt))) {
        throw new Error(`Invalid semver string: ${version}`)
    }
    return { major: majorInt, minor: minorInt, patch: patchInt, extra }
}

// Validates a version string against the same shape the backend's `parse_semver` enforces
// (feature flag `validate_filters`), so a non-semver value (an email, a hex string) is caught
// inline before a save 400s. Intentionally stricter than the backend on component format: the
// backend coerces each component with Python's `int()`, which tolerates things like a leading
// `+` or `_` digit separators, while this only accepts plain digits. Kept separate from
// `parseVersion` because that one accepts a leading `v`, which the backend's `int()` rejects.
// `allowWildcard` handles patterns like `1.2.*` by dropping the trailing `.`/`*`, matching the
// backend's `rstrip('.*')` for the wildcard operator.
// Mirrors STRICT_SEMVER_REGEX in posthog/hogql/property.py, which matches the flag service's
// semver parser: a full X.Y.Z with no leading zeros, an optional `v` and an optional `-`/`+` suffix.
// The exact and ordering operators compare the whole version, so a short `2.0` never equals `2.0.0`.
const STRICT_SEMVER_PATTERN = /^\s*v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:[-+]\S*)?\s*$/

export function isStrictSemverValue(value: string): boolean {
    return STRICT_SEMVER_PATTERN.test(value)
}

export function isValidSemverValue(value: string, options?: { allowWildcard?: boolean }): boolean {
    let candidate = value.trim()
    if (options?.allowWildcard) {
        candidate = candidate.replace(/[.*]+$/, '')
    }
    // Strip any pre-release / build suffix (everything after the first hyphen), matching the backend.
    const base = candidate.split('-')[0]
    const parts = base.split('.')
    if (parts[0] === '') {
        return false
    }
    // Missing minor/patch default to "0" (e.g. "1" -> 1.0.0); extra parts are ignored, as on the backend.
    const [major, minor = '0', patch = '0'] = parts
    return [major, minor, patch].every((part) => /^\d+$/.test(part))
}

export interface SemanticVersionDiff {
    kind: 'major' | 'minor' | 'patch' | 'extra'
    diff: number
}

export function diffVersions(a: string | SemanticVersion, b: string | SemanticVersion): SemanticVersionDiff | null {
    const pa = typeof a === 'string' ? parseVersion(a) : a
    const pb = typeof b === 'string' ? parseVersion(b) : b

    if (pa.major !== pb.major) {
        return { kind: 'major', diff: pa.major - pb.major }
    }
    if (pa.minor !== pb.minor) {
        return { kind: 'minor', diff: (pa.minor ?? 0) - (pb.minor ?? 0) }
    }
    if (pa.patch !== pb.patch) {
        return { kind: 'patch', diff: (pa.patch ?? 0) - (pb.patch ?? 0) }
    }
    if (pa.extra !== pb.extra) {
        // not having an extra is treated as a higher version than having an extra
        if (pa.extra) {
            if (pb.extra) {
                // we don't really use these, if we ever do we should improve this logic to better compare them,
                // for now just do a simple string comparison rather than trying to parse alpha/beta/rc/etc
                return { kind: 'extra', diff: pa.extra.localeCompare(pb.extra) }
            }

            return { kind: 'extra', diff: -1 }
        }
        if (pb.extra) {
            return { kind: 'extra', diff: 1 }
        }
        return null
    }
    return null
}

export function compareVersion(a: string | SemanticVersion, b: string | SemanticVersion): number {
    const diff = diffVersions(a, b)
    if (!diff) {
        return 0
    }
    return diff.diff
}

export function createVersionChecker(requiredVersion: string | SemanticVersion) {
    return (version: string | SemanticVersion): boolean => {
        const diff = diffVersions(version, requiredVersion)
        return !diff || diff.diff > 0
    }
}