Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/obsessiondb-auth-backfill.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chkit/plugin-obsessiondb": patch
---

Add device-code authentication (login/logout/whoami) and remote backfill routing via ObsessionDB backend.
5 changes: 5 additions & 0 deletions .changeset/plugin-command-hook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"chkit": patch
---

Add `onBeforePluginCommand` hook allowing plugins to intercept other plugins' commands.
170 changes: 170 additions & 0 deletions packages/cli/src/bin/plugin-runtime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { describe, expect, test } from 'bun:test'
import type { ResolvedChxConfig } from '@chkit/core'
import type { ChxPlugin } from '../plugins.js'
import { loadPluginRuntime } from './plugin-runtime.js'

function makeConfig(plugins: ChxPlugin[]): ResolvedChxConfig {
return {
schema: [],
outDir: '.chkit',
migrationsDir: 'migrations',
metaDir: '.chkit/meta',
plugins: plugins.map((plugin) => ({
plugin,
name: plugin.manifest.name,
enabled: true,
options: {},
})),
check: { unusedTables: true, unusedColumns: true },
safety: { allowDestructive: false },
}
}

function makeCommandContext() {
return {
config: makeConfig([]),
configPath: '/fake/clickhouse.config.ts',
jsonMode: false,
args: [],
flags: {},
print: () => {},
}
}

describe('onBeforePluginCommand', () => {
test('returning handled: true skips the original command', async () => {
let originalRan = false
const targetPlugin: ChxPlugin = {
manifest: { name: 'backfill', apiVersion: 1 },
commands: [
{
name: 'run',
run: () => {
originalRan = true
return 0
},
},
],
}

const interceptor: ChxPlugin = {
manifest: { name: 'obsessiondb', apiVersion: 1 },
hooks: {
onBeforePluginCommand: () => ({ handled: true, exitCode: 42 }),
},
}

const config = makeConfig([targetPlugin, interceptor])
const runtime = await loadPluginRuntime({
config,
configPath: '/fake/clickhouse.config.ts',
cliVersion: '1.0.0',
})

const exitCode = await runtime.runPluginCommand('backfill', 'run', makeCommandContext())

expect(exitCode).toBe(42)
expect(originalRan).toBe(false)
})

test('returning handled: false falls through to original command', async () => {
let originalRan = false
const targetPlugin: ChxPlugin = {
manifest: { name: 'backfill', apiVersion: 1 },
commands: [
{
name: 'run',
run: () => {
originalRan = true
return 0
},
},
],
}

const interceptor: ChxPlugin = {
manifest: { name: 'obsessiondb', apiVersion: 1 },
hooks: {
onBeforePluginCommand: () => ({ handled: false }),
},
}

const config = makeConfig([targetPlugin, interceptor])
const runtime = await loadPluginRuntime({
config,
configPath: '/fake/clickhouse.config.ts',
cliVersion: '1.0.0',
})

const exitCode = await runtime.runPluginCommand('backfill', 'run', makeCommandContext())

expect(exitCode).toBe(0)
expect(originalRan).toBe(true)
})

test('the owning plugin hook is NOT called for its own commands', async () => {
let hookCalled = false
const plugin: ChxPlugin = {
manifest: { name: 'backfill', apiVersion: 1 },
commands: [
{
name: 'run',
run: () => 0,
},
],
hooks: {
onBeforePluginCommand: () => {
hookCalled = true
return { handled: true, exitCode: 99 }
},
},
}

const config = makeConfig([plugin])
const runtime = await loadPluginRuntime({
config,
configPath: '/fake/clickhouse.config.ts',
cliVersion: '1.0.0',
})

const exitCode = await runtime.runPluginCommand('backfill', 'run', makeCommandContext())

expect(exitCode).toBe(0)
expect(hookCalled).toBe(false)
})

test('passes correct context to onBeforePluginCommand hook', async () => {
let receivedContext: Record<string, unknown> = {}
const targetPlugin: ChxPlugin = {
manifest: { name: 'backfill', apiVersion: 1 },
commands: [{ name: 'plan', run: () => 0 }],
}

const interceptor: ChxPlugin = {
manifest: { name: 'obsessiondb', apiVersion: 1 },
hooks: {
onBeforePluginCommand: (ctx) => {
receivedContext = { ...ctx }
return { handled: false }
},
},
}

const config = makeConfig([targetPlugin, interceptor])
const runtime = await loadPluginRuntime({
config,
configPath: '/fake/clickhouse.config.ts',
cliVersion: '1.0.0',
})

await runtime.runPluginCommand('backfill', 'plan', {
...makeCommandContext(),
args: ['--window', '7d'],
flags: { '--window': '7d' },
})

expect(receivedContext.targetPlugin).toBe('backfill')
expect(receivedContext.command).toBe('plan')
expect(receivedContext.args).toEqual(['--window', '7d'])
})
})
45 changes: 45 additions & 0 deletions packages/cli/src/bin/plugin-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import type {
ChxOnCheckResult,
ChxOnAfterApplyContext,
ChxOnBeforeApplyContext,
ChxOnBeforePluginCommandContext,
ChxOnBeforePluginCommandResult,
ChxOnCompleteContext,
ChxOnConfigLoadedContext,
ChxOnInitContext,
Expand Down Expand Up @@ -57,6 +59,11 @@ export interface PluginRuntime {
context: Omit<ChxOnCheckContext, 'options' | 'tableScope'> & { tableScope?: TableScope }
): Promise<ChxOnCheckResult[]>
runOnCheckReport(results: ChxOnCheckResult[], print: (line: string) => void): Promise<void>
runOnBeforePluginCommand(
pluginName: string,
commandName: string,
context: Omit<ChxOnBeforePluginCommandContext, 'targetPlugin' | 'command' | 'options'>
): Promise<ChxOnBeforePluginCommandResult>
runPluginCommand(
pluginName: string,
commandName: string,
Expand Down Expand Up @@ -210,6 +217,30 @@ export async function loadPluginRuntime(input: {
byName.set(plugin.manifest.name, item)
}

async function runBeforePluginCommandHooks(
pluginName: string,
commandName: string,
context: Omit<ChxOnBeforePluginCommandContext, 'targetPlugin' | 'command' | 'options'>
): Promise<ChxOnBeforePluginCommandResult> {
for (const item of loaded) {
if (item.plugin.manifest.name === pluginName) continue
const hook = item.plugin.hooks?.onBeforePluginCommand
if (!hook) continue
try {
const result = await hook({
...context,
targetPlugin: pluginName,
command: commandName,
options: item.options,
})
if (result.handled) return result
} catch (error) {
throw formatPluginError(item.plugin.manifest.name, 'onBeforePluginCommand', error)
}
}
return { handled: false }
}

return {
plugins: loaded,
getCommand(pluginName, commandName) {
Expand Down Expand Up @@ -345,11 +376,25 @@ export async function loadPluginRuntime(input: {
}
}
},
runOnBeforePluginCommand: runBeforePluginCommandHooks,
async runPluginCommand(pluginName, commandName, context) {
const item = byName.get(pluginName)
if (!item) return 1
const command = (item.plugin.commands ?? []).find((entry) => entry.name === commandName)
if (!command) return 1

// Run onBeforePluginCommand hooks — if any returns handled, skip the command
const beforeResult = await runBeforePluginCommandHooks(pluginName, commandName, {
config: context.config,
configPath: context.configPath,
jsonMode: context.jsonMode,
args: context.args,
flags: context.flags,
tableScope: context.tableScope ?? UNFILTERED_TABLE_SCOPE,
print: context.print,
})
if (beforeResult.handled) return beforeResult.exitCode

try {
const code = await command.run({
...context,
Expand Down
79 changes: 79 additions & 0 deletions packages/cli/src/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,85 @@ describe('plugin runtime', () => {
}
})

test('onBeforePluginCommand intercepts another plugin command', async () => {
const fixture = await createFixture()
const targetPath = join(fixture.dir, 'target-plugin.ts')
const interceptorPath = join(fixture.dir, 'interceptor-plugin.ts')
try {
await writeFile(
targetPath,
`import { definePlugin } from '${CLI_ENTRY}'\n\nexport default definePlugin({\n manifest: { name: 'target', apiVersion: 1 },\n commands: [\n {\n name: 'greet',\n description: 'Original greet',\n run({ print }) {\n print({ source: 'original' })\n return 0\n },\n },\n ],\n})\n`,
'utf8'
)

await writeFile(
interceptorPath,
`import { definePlugin } from '${CLI_ENTRY}'\n\nexport default definePlugin({\n manifest: { name: 'interceptor', apiVersion: 1 },\n hooks: {\n onBeforePluginCommand(context) {\n if (context.targetPlugin === 'target' && context.command === 'greet') {\n context.print({ source: 'intercepted', target: context.targetPlugin })\n return { handled: true, exitCode: 0 }\n }\n return { handled: false }\n },\n },\n})\n`,
'utf8'
)

await writeFile(
fixture.configPath,
`export default {\n schema: '${fixture.schemaPath}',\n outDir: '${join(fixture.dir, 'chkit')}',\n migrationsDir: '${fixture.migrationsDir}',\n metaDir: '${fixture.metaDir}',\n plugins: [\n { resolve: './target-plugin.ts' },\n { resolve: './interceptor-plugin.ts' },\n ],\n}\n`,
'utf8'
)

const result = runCli([
'plugin',
'target',
'greet',
'--config',
fixture.configPath,
'--json',
])
expect(result.exitCode).toBe(0)
const payload = JSON.parse(result.stdout) as { source: string; target: string }
expect(payload.source).toBe('intercepted')
expect(payload.target).toBe('target')
} finally {
await rm(fixture.dir, { recursive: true, force: true })
}
})

test('onBeforePluginCommand returning handled: false falls through to original', async () => {
const fixture = await createFixture()
const targetPath = join(fixture.dir, 'target-plugin.ts')
const interceptorPath = join(fixture.dir, 'interceptor-plugin.ts')
try {
await writeFile(
targetPath,
`import { definePlugin } from '${CLI_ENTRY}'\n\nexport default definePlugin({\n manifest: { name: 'target', apiVersion: 1 },\n commands: [\n {\n name: 'greet',\n description: 'Original greet',\n run({ print }) {\n print({ source: 'original' })\n return 0\n },\n },\n ],\n})\n`,
'utf8'
)

await writeFile(
interceptorPath,
`import { definePlugin } from '${CLI_ENTRY}'\n\nexport default definePlugin({\n manifest: { name: 'interceptor', apiVersion: 1 },\n hooks: {\n onBeforePluginCommand() {\n return { handled: false }\n },\n },\n})\n`,
'utf8'
)

await writeFile(
fixture.configPath,
`export default {\n schema: '${fixture.schemaPath}',\n outDir: '${join(fixture.dir, 'chkit')}',\n migrationsDir: '${fixture.migrationsDir}',\n metaDir: '${fixture.metaDir}',\n plugins: [\n { resolve: './target-plugin.ts' },\n { resolve: './interceptor-plugin.ts' },\n ],\n}\n`,
'utf8'
)

const result = runCli([
'plugin',
'target',
'greet',
'--config',
fixture.configPath,
'--json',
])
expect(result.exitCode).toBe(0)
const payload = JSON.parse(result.stdout) as { source: string }
expect(payload.source).toBe('original')
} finally {
await rm(fixture.dir, { recursive: true, force: true })
}
})

test('plugin pull schema command writes pulled schema artifact', async () => {
const fixture = await createFixture()
const pluginPath = join(fixture.dir, 'pull-plugin.ts')
Expand Down
20 changes: 20 additions & 0 deletions packages/cli/src/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,23 @@ export interface ChxOnCheckResult {
metadata?: Record<string, unknown>
}

export interface ChxOnBeforePluginCommandContext {
targetPlugin: string
command: string
config: ResolvedChxConfig
configPath: string
jsonMode: boolean
args: string[]
flags: ParsedFlags
options: Record<string, unknown>
tableScope: TableScope
print: (value: unknown) => void
}

export type ChxOnBeforePluginCommandResult =
| { handled: true; exitCode: number }
| { handled: false }

export interface ChxPluginCommandContext {
pluginName: string
config: ResolvedChxConfig
Expand All @@ -145,6 +162,9 @@ export interface ChxPluginCommand {
export interface ChxPluginHooks {
onInit?: (context: ChxOnInitContext) => void | Promise<void>
onComplete?: (context: ChxOnCompleteContext) => void | Promise<void>
onBeforePluginCommand?: (
context: ChxOnBeforePluginCommandContext
) => ChxOnBeforePluginCommandResult | Promise<ChxOnBeforePluginCommandResult>
onConfigLoaded?: (context: ChxOnConfigLoadedContext) => void | Promise<void>
onSchemaLoaded?: (
context: ChxOnSchemaLoadedContext
Expand Down
Loading
Loading