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.

feat(hog): generate typed SDKs with hog schema (#125521)

Rafael Audibertdcf05213850b
diff --git a/hog/README.md b/hog/README.md
index 0198082d5b87..10965651a85d 100644
--- a/hog/README.md
+++ b/hog/README.md
@@ -29,6 +29,8 @@ The commands `posthog-cli` keeps under `exp` (`query`, `endpoints`, `logs`, `tas
| `hog error-tracking release` | Finds or creates the release for this build. `-o text` prints just its ID. |
| `hog error-tracking download <id/ref>` | Downloads a symbol set from PostHog and unpacks it. |
| `hog error-tracking extract <file>` | Unpacks a symbol set file. |
+| `hog schema pull` | Generates a typed SDK (TypeScript, Go or Python) from your event definitions, and records it in `posthog.json`. |
+| `hog schema status` | Checks each generated SDK against PostHog. Exits with code 1 when one is missing or out of date. |
| `hog config check`, `hog config schema` | Check `posthog.json` against its schema, or print the schema. |
| `hog commands` | Lists every command, its arguments, options and scopes. |
| Everything else | Not ported yet. Exits with code 1 and prints the `posthog-cli` command to run instead, with the same arguments. |
@@ -41,7 +43,6 @@ First, the commands that make hog a complete CLI:
- [ ] `hog api skill` and `hog api agents-md`, which install PostHog agent skills and the AGENTS.md snippet.
- [ ] `hog endpoints`: `list`, `get`, `open`, `run`, `push`, `pull` and `diff`.
-- [ ] `hog schema`: `pull` and `status`, which download event definitions and generate a typed SDK.
Then, once the commands above work:
@@ -86,6 +87,9 @@ Point `$schema` at the published schema to get validation in your editor:
}
```
+`hog schema pull` keeps its entries under `languages` in the snake case posthog-cli uses, so either CLI can regenerate an SDK the other set up.
+posthog-cli rewrites `posthog.json` with only `languages` when it pulls, so it drops the other settings. Restore them from version control after running it.
+
`posthog.schema.json` is generated from `src/core/config.ts` with `pnpm --filter @posthog/hog schema`.
## Error tracking
diff --git a/hog/posthog.schema.json b/hog/posthog.schema.json
index 45c94a52b71c..0ed10faf91d5 100644
--- a/hog/posthog.schema.json
+++ b/hog/posthog.schema.json
@@ -66,12 +66,38 @@
"description": "Settings for `hog error-tracking`."
},
"languages": {
- "description": "Typed SDK settings that `posthog-cli exp schema pull` writes. hog leaves them alone.",
+ "description": "The typed SDKs `hog schema pull` generates, by language. posthog-cli reads the same entries.",
"type": "object",
"propertyNames": {
"type": "string"
},
- "additionalProperties": {}
+ "additionalProperties": {
+ "type": "object",
+ "properties": {
+ "output_path": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Where the generated module goes, relative to posthog.json."
+ },
+ "schema_hash": {
+ "description": "The hash of the event definitions the module was generated from.",
+ "type": "string"
+ },
+ "updated_at": {
+ "description": "When the module was last generated.",
+ "type": "string"
+ },
+ "event_count": {
+ "description": "How many events the module types.",
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ }
+ },
+ "required": ["output_path"],
+ "additionalProperties": false,
+ "description": "One generated SDK. `hog schema pull` writes it."
+ }
}
},
"additionalProperties": false,
diff --git a/hog/src/cli.test.ts b/hog/src/cli.test.ts
index 2dc45c75d6f4..30184bc753b7 100644
--- a/hog/src/cli.test.ts
+++ b/hog/src/cli.test.ts
@@ -115,6 +115,8 @@ describe('hog', () => {
'error-tracking release',
'error-tracking download',
'error-tracking extract',
+ 'schema pull',
+ 'schema status',
'config check',
'config schema',
'commands',
diff --git a/hog/src/commands/index.ts b/hog/src/commands/index.ts
index 08a3093a7868..72a8155c179b 100644
--- a/hog/src/commands/index.ts
+++ b/hog/src/commands/index.ts
@@ -7,12 +7,14 @@ import config from './config'
import errorTracking from './error-tracking'
import { LEGACY_COMMANDS } from './legacy'
import query from './query'
+import schema from './schema'
export const COMMANDS: CommandTree = {
auth,
query,
api,
'error-tracking': errorTracking,
+ schema,
config,
commands,
...LEGACY_COMMANDS,
diff --git a/hog/src/commands/legacy.ts b/hog/src/commands/legacy.ts
index 48e8a151a243..3af0e3e1ede0 100644
--- a/hog/src/commands/legacy.ts
+++ b/hog/src/commands/legacy.ts
@@ -7,9 +7,5 @@ export const LEGACY_COMMANDS: CommandTree = {
use: 'posthog-cli exp logs',
}),
tasks: defineLegacy({ description: 'List, track and update PostHog tasks', use: 'posthog-cli exp task' }),
- schema: defineLegacy({
- description: 'Download event definitions and generate a typed SDK',
- use: 'posthog-cli exp schema',
- }),
update: defineLegacy({ description: 'Update hog to the latest version', use: 'posthog-cli update' }),
}
diff --git a/hog/src/commands/schema/index.ts b/hog/src/commands/schema/index.ts
new file mode 100644
index 000000000000..cdedcb7d9662
--- /dev/null
+++ b/hog/src/commands/schema/index.ts
@@ -0,0 +1,9 @@
+import { defineGroup } from '@/core/command'
+
+import pull from './pull'
+import status from './status'
+
+export default defineGroup({
+ description: 'Generate a typed PostHog SDK from your event definitions',
+ commands: { pull, status },
+})
diff --git a/hog/src/commands/schema/pull.ts b/hog/src/commands/schema/pull.ts
new file mode 100644
index 000000000000..3606d7bb44ba
--- /dev/null
+++ b/hog/src/commands/schema/pull.ts
@@ -0,0 +1,159 @@
+import { defineCommand } from '@/core/command'
+import { updateConfig, type SchemaLanguage } from '@/core/config'
+import { EXIT_USAGE, HogError } from '@/core/errors'
+import { plural } from '@/core/text'
+
+import {
+ absolutePath,
+ chosenFile,
+ configRoot,
+ fetchDefinitions,
+ isLanguage,
+ LANGUAGE_INFO,
+ LANGUAGES,
+ storedPath,
+ type Language,
+} from './shared'
+
+interface PulledLanguage {
+ language: Language
+ file: string
+ status: 'written' | 'unchanged'
+ eventCount: number
+ schemaHash: string
+}
+
+export default defineCommand({
+ description: 'Generate a typed PostHog SDK from your event definitions',
+ options: {
+ language: {
+ type: 'string',
+ short: 'l',
+ choices: LANGUAGES,
+ description: 'The language to generate. Without it, hog regenerates every language in posthog.json',
+ },
+ file: {
+ type: 'string',
+ placeholder: 'path',
+ description: 'Where to write the module. posthog.json remembers it for the next run',
+ },
+ },
+ scopes: ['event_definition:read'],
+ notes: 'hog writes the module only when the event definitions changed or the file is missing, and records the language, path and schema hash in posthog.json. posthog-cli reads the same entries.',
+ examples: [
+ 'hog schema pull --language typescript --file src/lib/',
+ 'hog schema pull',
+ 'hog schema pull -l python --file app/posthog_typed.py',
+ ],
+
+ async run({ options, ctx }) {
+ const loaded = await ctx.config()
+ const configured = loaded?.config.languages ?? {}
+ const root = configRoot(ctx, loaded)
+
+ let languages: Language[]
+ if (options.language) {
+ languages = [options.language]
+ } else if (Object.keys(configured).length > 0) {
+ languages = Object.keys(configured).filter(isLanguage)
+ } else if (ctx.prompts) {
+ languages = [
+ await ctx.prompts.select(
+ 'Which language should hog generate?',
+ LANGUAGES.map((value) => ({ value, label: LANGUAGE_INFO[value].name }))
+ ),
+ ]
+ } else {
+ throw new HogError(
+ 'language_required',
+ 'posthog.json has no languages yet, so hog needs to know which one to generate.',
+ `Pass --language ${LANGUAGES.join(', --language ')}.`,
+ EXIT_USAGE
+ )
+ }
+ if (options.file !== undefined && languages.length !== 1) {
+ throw new HogError(
+ 'usage_error',
+ '--file names one module, but hog is generating several languages.',
+ 'Pass --language too.',
+ EXIT_USAGE
+ )
+ }
+
+ const pulled: PulledLanguage[] = []
+ const entries: Partial<Record<Language, SchemaLanguage>> = {}
+ for (const language of languages) {
+ const saved = configured[language]
+ let file: string
+ if (options.file !== undefined) {
+ file = await chosenFile(ctx, options.file, language)
+ } else if (saved) {
+ file = absolutePath(root, saved.output_path)
+ } else {
+ const fallback = LANGUAGE_INFO[language].defaultFile
+ const answer = ctx.prompts
+ ? await ctx.prompts.text(
+ `Where should hog write the ${LANGUAGE_INFO[language].name} module? Your app imports PostHog from it.`,
+ { initialValue: fallback }
+ )
+ : fallback
+ file = await chosenFile(ctx, answer || fallback, language)
+ }
+
+ const definitions = await fetchDefinitions(ctx, language)
+ const outputPath = storedPath(root, file)
+ // The module carries the time PostHog generated it, so only the hash says whether the events changed.
+ const unchanged =
+ saved?.output_path === outputPath &&
+ saved.schema_hash === definitions.schema_hash &&
+ (await ctx.runtime.exists(file))
+ if (!unchanged) {
+ await ctx.runtime.writeFile(file, definitions.content)
+ entries[language] = {
+ output_path: outputPath,
+ schema_hash: definitions.schema_hash,
+ updated_at: new Date(ctx.runtime.now()).toISOString(),
+ event_count: definitions.event_count,
+ }
+ }
+ pulled.push({
+ language,
+ file: outputPath,
+ status: unchanged ? 'unchanged' : 'written',
+ eventCount: definitions.event_count,
+ schemaHash: definitions.schema_hash,
+ })
+ }
+
+ if (Object.keys(entries).length === 0) {
+ return { config: loaded?.path ?? null, configUpdated: false, languages: pulled }
+ }
+ const config = await updateConfig(ctx.runtime, loaded, (raw) => {
+ raw.languages = { ...(raw.languages as object | undefined), ...entries }
+ })
+ return { config: storedPath(ctx.runtime.cwd(), config), configUpdated: true, languages: pulled }
+ },
+
+ human({ result, out }) {
+ for (const pulled of result.languages) {
+ const { name, nextSteps } = LANGUAGE_INFO[pulled.language]
+ const events = plural(pulled.eventCount, 'event')
+ if (pulled.status === 'unchanged') {
+ out.line(`${out.style('Up to date', 'green', 'bold')} ${name} in ${pulled.file} (${events})`)
+ continue
+ }
+ out.line(`${out.style('Generated', 'green', 'bold')} ${name} in ${pulled.file} (${events})`)
+ out.line()
+ out.line(out.style('Next steps:', 'bold'))
+ nextSteps(pulled.file).forEach((step, index) => out.line(` ${index + 1}. ${step}`))
+ out.line()
+ }
+ if (result.configUpdated) {
+ out.line(out.style(`Saved the settings in ${result.config}`, 'dim'))
+ }
+ },
+
+ agent({ result, out }) {
+ out.jsonLines(result.languages)
+ },
+})
diff --git a/hog/src/commands/schema/schema.test.ts b/hog/src/commands/schema/schema.test.ts
new file mode 100644
index 000000000000..850f99d5948f
--- /dev/null
+++ b/hog/src/commands/schema/schema.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, test } from 'bun:test'
+
+import { runHog, TEST_CREDENTIALS } from '@/testing'
+
+const AGENT = { ...TEST_CREDENTIALS, CLAUDECODE: '1' }
+
+const definitions = (content: string) => (url: string) =>
+ url.endsWith('/event_definitions/typescript/')
+ ? { status: 200, body: { content, event_count: 3, schema_hash: 'hash-new' } }
+ : { status: 404, body: { detail: 'Not found.' } }
+
+// The file posthog-cli 0.18 writes, plus a section hog owns.
+const OLD_CONFIG = JSON.stringify({
+ errorTracking: { release: { name: 'web' } },
+ languages: {
+ typescript: {
+ output_path: 'src/lib/posthog-typed.ts',
+ schema_hash: 'hash-old',
+ updated_at: '2026-01-01T00:00:00+00:00',
+ event_count: 2,
+ },
+ },
+})
+
+describe('hog schema', () => {
+ test('pull regenerates the languages a posthog-cli posthog.json lists and keeps the rest of the file', async () => {
+ const result = await runHog(['schema', 'pull'], {
+ env: AGENT,
+ cwd: '/work/app',
+ files: { '/work/posthog.json': OLD_CONFIG, '/work/src/lib/posthog-typed.ts': 'old' },
+ respond: definitions('new'),
+ })
+ expect(result.exitCode).toBe(0)
+ expect(result.files['/work/src/lib/posthog-typed.ts']).toBe('new')
+ expect(JSON.parse(result.files['/work/posthog.json']!)).toEqual({
+ errorTracking: { release: { name: 'web' } },
+ languages: {
+ typescript: {
+ output_path: 'src/lib/posthog-typed.ts',
+ schema_hash: 'hash-new',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ event_count: 3,
+ },
+ },
+ })
+ })
+
+ test('pull leaves an up-to-date module and posthog.json alone', async () => {
+ const config = JSON.stringify({
+ languages: { typescript: { output_path: 'out.ts', schema_hash: 'hash-new', event_count: 3 } },
+ })
+ const result = await runHog(['schema', 'pull'], {
+ env: AGENT,
+ files: { '/work/posthog.json': config, '/work/out.ts': 'same' },
+ respond: definitions('same'),
+ })
+ expect(result.stdout).toContain('"status":"unchanged"')
+ expect(result.files['/work/posthog.json']).toBe(config)
+ })
+
+ test.each([
+ ['a folder gets the default file name', 'src/', '/work/src/posthog-typed.ts', 'src/posthog-typed.ts'],
+ ['a sibling folder stays relative', '../web/typed.ts', '/web/typed.ts', '../web/typed.ts'],
+ ])('pull into %s and starts a posthog.json', async (_name, file, written, stored) => {
+ const result = await runHog(['schema', 'pull', '--language', 'typescript', '--file', file], {
+ env: AGENT,
+ respond: definitions('generated'),
+ })
+
+ expect(result.files[written]).toBe('generated')
+ expect(JSON.parse(result.files['/work/posthog.json']!)).toMatchObject({
+ $schema: expect.stringContaining('posthog.schema.json'),
+ languages: { typescript: { output_path: stored } },
+ })
+ })
+
+ test('pull asks an agent for --language instead of prompting', async () => {
+ const result = await runHog(['schema', 'pull'], { env: AGENT })
+ expect(result.exitCode).toBe(2)
+ expect(result.error().code).toBe('language_required')
+ expect(result.requests).toEqual([])
+ })
+
+ test.each([
+ ['the events have not changed', 'hash-new', { '/work/out.ts': '' }, 'up_to_date', 0],
+ ['the events changed', 'hash-old', { '/work/out.ts': '' }, 'outdated', 1],
+ ['the module is gone', 'hash-new', {}, 'missing', 1],
+ ])('status when %s', async (_name, hash, files, status, exitCode) => {
+ const config = JSON.stringify({ languages: { typescript: { output_path: 'out.ts', schema_hash: hash } } })
+ const result = await runHog(['schema', 'status'], {
+ env: AGENT,
+ files: { '/work/posthog.json': config, ...files },
+ respond: definitions(''),
+ })
+ expect(result.exitCode).toBe(exitCode)
+ expect(result.json()).toMatchObject({ language: 'typescript', file: 'out.ts', status })
+ })
+})
diff --git a/hog/src/commands/schema/shared.ts b/hog/src/commands/schema/shared.ts
new file mode 100644
index 000000000000..f75c46887e42
--- /dev/null
+++ b/hog/src/commands/schema/shared.ts
@@ -0,0 +1,81 @@
+import { isAbsolute, join, relative, resolve } from 'node:path'
+
+import type { LoadedConfig } from '@/core/config'
+import type { Context } from '@/core/context'
+
+export const LANGUAGES = ['typescript', 'golang', 'python'] as const
+export type Language = (typeof LANGUAGES)[number]
+
+interface LanguageInfo {
+ name: string
+ // Python modules can't have hyphens in their names.
+ defaultFile: string
+ nextSteps: (file: string) => string[]
+}
+
+export const LANGUAGE_INFO: Record<Language, LanguageInfo> = {
+ typescript: {
+ name: 'TypeScript',
+ defaultFile: 'posthog-typed.ts',
+ nextSteps: (file) => [
+ `Import PostHog from the generated module: import posthog from './${file}'`,
+ "Known events get autocomplete and type checks: posthog.capture('event_name', { property: 'value' })",
+ "captureRaw() skips the type checks: posthog.captureRaw('dynamic_event_name', { whatever: 'data' })",
+ ],
+ },
+ golang: {
+ name: 'Go',
+ defaultFile: 'posthog-typed.go',
+ nextSteps: (file) => [
+ 'Install the PostHog Go SDK if you have not yet: go get github.com/posthog/posthog-go',
+ `Move ${file} into a folder named typed, or change the package line at the top of the file`,
+ 'Capture typed events: client.Enqueue(typed.EventNameCapture("user_id", requiredProp))',
+ ],
+ },
+ python: {
+ name: 'Python',
+ defaultFile: 'posthog_typed.py',
+ nextSteps: (file) => [
+ `Import the typed client from ${file}: from posthog_typed import PosthogTyped`,
+ 'Create it like the PostHog client: client = PosthogTyped("<project token>", host="<host>")',
+ 'Capture typed events: client.capture_event_name(required_property="value", distinct_id="user_123")',
+ ],
+ },
+}
+
+export function isLanguage(value: string): value is Language {
+ return (LANGUAGES as readonly string[]).includes(value)
+}
+
+export interface Definitions {
+ content: string
+ event_count: number
+ schema_hash: string
+}
+
+export function fetchDefinitions(ctx: Context, language: Language): Promise<Definitions> {
+ return ctx.posthog().then((api) => api.get<Definitions>(`event_definitions/${language}/`))
+}
+
+// posthog.json stores paths relative to its own folder. A new file goes in the working folder.
+export function configRoot(ctx: Context, loaded: LoadedConfig | undefined): string {
+ return loaded?.root ?? ctx.runtime.cwd()
+}
+
+export function absolutePath(root: string, path: string): string {
+ return isAbsolute(path) ? path : resolve(root, path)
+}
+
+// A sibling folder stays relative, as posthog-cli stored it, so the file works in any checkout.
+export function storedPath(root: string, path: string): string {
+ const rel = relative(root, path)
+ return isAbsolute(rel) ? path : rel
+}
+
+// Resolves a path the caller typed. A folder, or a path that ends with a slash, gets the
+// language's default file name.
+export async function chosenFile(ctx: Context, path: string, language: Language): Promise<string> {
+ const absolute = absolutePath(ctx.runtime.cwd(), path)
+ const asFolder = /[\\/]$/.test(path) || (await ctx.runtime.isDirectory(absolute))
+ return asFolder ? join(absolute, LANGUAGE_INFO[language].defaultFile) : absolute
+}
diff --git a/hog/src/commands/schema/status.ts b/hog/src/commands/schema/status.ts
new file mode 100644
index 000000000000..f921f9bc094a
--- /dev/null
+++ b/hog/src/commands/schema/status.ts
@@ -0,0 +1,85 @@
+import { defineCommand } from '@/core/command'
+import { plural } from '@/core/text'
+
+import { absolutePath, configRoot, fetchDefinitions, isLanguage, LANGUAGE_INFO } from './shared'
+
+interface LanguageStatus {
+ language: string
+ file: string
+ // `outdated` means the event definitions changed since the module was generated.
+ status: 'up_to_date' | 'outdated' | 'missing' | 'unknown_language'
+ eventCount: number | null
+ updatedAt: string | null
+}
+
+export default defineCommand({
+ description: 'Check whether the typed SDKs in posthog.json match your event definitions',
+ scopes: ['event_definition:read'],
+ notes: 'Compares the schema hash in posthog.json with the event definitions in PostHog now. Exits with code 1 when a module is missing or out of date, or posthog.json has no languages, so CI can catch a stale SDK.',
+ examples: ['hog schema status'],
+
+ async run({ ctx }) {
+ const loaded = await ctx.config()
+ const root = configRoot(ctx, loaded)
+ const languages: LanguageStatus[] = []
+ for (const [language, saved] of Object.entries(loaded?.config.languages ?? {})) {
+ const file = absolutePath(root, saved.output_path)
+ const base = {
+ language,
+ file: saved.output_path,
+ eventCount: saved.event_count ?? null,
+ updatedAt: saved.updated_at ?? null,
+ }
+ if (!isLanguage(language)) {
+ languages.push({ ...base, status: 'unknown_language' })
+ continue
+ }
+ if (!(await ctx.runtime.exists(file))) {
+ languages.push({ ...base, status: 'missing' })
+ continue
+ }
+ const definitions = await fetchDefinitions(ctx, language)
+ languages.push({
+ ...base,
+ status: saved.schema_hash === definitions.schema_hash ? 'up_to_date' : 'outdated',
+ eventCount: definitions.event_count,
+ })
+ }
+ return { config: loaded?.path ?? null, languages }
+ },
+
+ human({ result, out }) {
+ if (result.languages.length === 0) {
+ out.line(out.style('No typed SDKs yet.', 'yellow', 'bold'))
+ out.line(`Run ${out.style('hog schema pull --language typescript', 'bold')} to generate one.`)
+ return
+ }
+ const labels = {
+ up_to_date: 'up to date',
+ outdated: 'out of date',
+ missing: 'file missing',
+ unknown_language: 'unknown language',
+ }
+ out.table(
+ ['language', 'file', 'status', 'events', 'updated'],
+ result.languages.map((entry) => [
+ isLanguage(entry.language) ? LANGUAGE_INFO[entry.language].name : entry.language,
+ entry.file,
+ labels[entry.status],
+ entry.eventCount,
+ entry.updatedAt,
+ ])
+ )
+ const stale = result.languages.filter((entry) => entry.status === 'outdated' || entry.status === 'missing')
+ if (stale.length > 0) {
+ out.line(`${plural(stale.length, 'module')} to update. Run ${out.style('hog schema pull', 'bold')}.`)
+ }
+ },
+
+ agent({ result, out }) {
+ out.jsonLines(result.languages)
+ },
+
+ exitCode: (result) =>
+ result.languages.length > 0 && result.languages.every((entry) => entry.status === 'up_to_date') ? 0 : 1,
+})
diff --git a/hog/src/core/config.ts b/hog/src/core/config.ts
index d7b435b378c8..7d032654d99d 100644
--- a/hog/src/core/config.ts
+++ b/hog/src/core/config.ts
@@ -48,14 +48,26 @@ const ErrorTracking = z
})
.describe('Settings for `hog error-tracking`.')
+// Snake case, because posthog-cli writes and reads the same entries in `exp schema pull`.
+const SchemaLanguage = z
+ .strictObject({
+ output_path: z.string().min(1).describe('Where the generated module goes, relative to posthog.json.'),
+ schema_hash: z.string().optional().describe('The hash of the event definitions the module was generated from.'),
+ updated_at: z.string().optional().describe('When the module was last generated.'),
+ event_count: z.number().int().optional().describe('How many events the module types.'),
+ })
+ .describe('One generated SDK. `hog schema pull` writes it.')
+
+export type SchemaLanguage = z.infer<typeof SchemaLanguage>
+
export const PostHogConfig = z
.strictObject({
$schema: z.string().optional().describe('The JSON schema for this file.'),
errorTracking: ErrorTracking.optional(),
languages: z
- .record(z.string(), z.unknown())
+ .record(z.string(), SchemaLanguage)
.optional()
- .describe('Typed SDK settings that `posthog-cli exp schema pull` writes. hog leaves them alone.'),
+ .describe('The typed SDKs `hog schema pull` generates, by language. posthog-cli reads the same entries.'),
})
.describe('Settings for the PostHog CLI. Never put API keys here: use `hog auth login` or environment variables.')
@@ -133,3 +145,17 @@ export async function loadConfig(runtime: Runtime): Promise<LoadedConfig | undef
}
return { path, root: dirname(path), config }
}
+
+// Changes one part of posthog.json and keeps everything else as written, including keys hog
+// doesn't know. Creates the file in the working folder when there is none.
+export async function updateConfig(
+ runtime: Runtime,
+ loaded: LoadedConfig | undefined,
+ change: (raw: Record<string, unknown>) => void
+): Promise<string> {
+ const path = loaded?.path ?? join(runtime.cwd(), CONFIG_FILE)
+ const raw: Record<string, unknown> = loaded ? JSON.parse(await runtime.readFile(path)) : { $schema: SCHEMA_URL }
+ change(raw)
+ await runtime.writeFile(path, `${JSON.stringify(raw, null, 2)}\n`)
+ return path
+}
diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.ts
index ed8b4ec4c581..b230812760b0 100644
--- a/hog/src/core/runtime.ts
+++ b/hog/src/core/runtime.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto'
-import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
+import { access, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname } from 'node:path'
@@ -27,6 +27,9 @@ export interface Runtime {
cwd: () => string
exists: (path: string) => Promise<boolean>
readFile: (path: string) => Promise<string>
+ isDirectory: (path: string) => Promise<boolean>
+ // Writes a project file, such as a generated SDK, and creates the folders above it.
+ writeFile: (path: string, contents: string) => Promise<void>
writePrivateFile: (path: string, contents: string) => Promise<void>
removeFile: (path: string) => Promise<void>
readStdin: () => Promise<string>
@@ -81,6 +84,15 @@ export function processRuntime(): Runtime {
() => false
),
readFile: (path) => readFile(path, 'utf8'),
+ isDirectory: (path) =>
+ stat(path).then(
+ (stats) => stats.isDirectory(),
+ () => false
+ ),
+ writeFile: async (path, contents) => {
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, contents)
+ },
// A rename is atomic, so a crash never leaves a half-written file. The temporary name is
// random and `wx` refuses an existing path, so nobody can plant a symlink there first.
writePrivateFile: async (path, contents) => {
diff --git a/hog/src/testing.ts b/hog/src/testing.ts
index 03339fa92bb8..a45e7c27a63f 100644
--- a/hog/src/testing.ts
+++ b/hog/src/testing.ts
@@ -1,4 +1,4 @@
-import { existsSync, readFileSync } from 'node:fs'
+import { existsSync, readFileSync, statSync } from 'node:fs'
import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
@@ -99,6 +99,13 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
}
return contents
},
+ isDirectory: async (path) =>
+ options.useDisk
+ ? existsSync(path) && statSync(path).isDirectory()
+ : Object.keys(files).some((file) => file.startsWith(`${path.replace(/\/$/, '')}/`)),
+ writeFile: async (path, contents) => {
+ files[path] = contents
+ },
writePrivateFile: async (path, contents) => {
files[path] = contents
},