@kubb/cli 5.0.0-beta.75 → 5.0.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -26
- package/dist/agent-DPLjUza1.cjs +70 -0
- package/dist/agent-DPLjUza1.cjs.map +1 -0
- package/dist/agent-DTeGTNl7.js +68 -0
- package/dist/agent-DTeGTNl7.js.map +1 -0
- package/dist/{chunk--u3MIqq1.js → chunk-BvFE5Tac.js} +1 -0
- package/dist/constants-B2JTeRBb.js +42 -0
- package/dist/constants-B2JTeRBb.js.map +1 -0
- package/dist/constants-BINTA5VZ.cjs +77 -0
- package/dist/constants-BINTA5VZ.cjs.map +1 -0
- package/dist/constants-BYGmiFs0.cjs +139 -0
- package/dist/constants-BYGmiFs0.cjs.map +1 -0
- package/dist/constants-DSJ-Xrbv.js +116 -0
- package/dist/constants-DSJ-Xrbv.js.map +1 -0
- package/dist/define-Bdn8j5VM.cjs.map +1 -1
- package/dist/{define-Ctii4bel.js → define-m_fp-Aqm.js} +2 -2
- package/dist/{define-Ctii4bel.js.map → define-m_fp-Aqm.js.map} +1 -1
- package/dist/{errors-CjPmyZHy.js → errors-CINO1EIv.js} +2 -2
- package/dist/{errors-CjPmyZHy.js.map → errors-CINO1EIv.js.map} +1 -1
- package/dist/errors-CLCjoSg0.cjs.map +1 -1
- package/dist/{generate-DDCwNQNo.cjs → generate-CiBa5UMJ.cjs} +10 -4
- package/dist/generate-CiBa5UMJ.cjs.map +1 -0
- package/dist/{generate-YPtfjsg4.js → generate-DzC1brc9.js} +12 -6
- package/dist/generate-DzC1brc9.js.map +1 -0
- package/dist/index.cjs +20 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +22 -13
- package/dist/index.js.map +1 -1
- package/dist/init-BVYkUQ-b.cjs +53 -0
- package/dist/init-BVYkUQ-b.cjs.map +1 -0
- package/dist/init-BYlb-ua0.js +53 -0
- package/dist/init-BYlb-ua0.js.map +1 -0
- package/dist/mcp-Bm2Q7YdS.js +39 -0
- package/dist/mcp-Bm2Q7YdS.js.map +1 -0
- package/dist/mcp-CiNoagVX.cjs +39 -0
- package/dist/mcp-CiNoagVX.cjs.map +1 -0
- package/dist/{package-D5arPDnh.cjs → package-BvBzYG6c.cjs} +2 -2
- package/dist/package-BvBzYG6c.cjs.map +1 -0
- package/dist/package-s8PvCnk-.js +6 -0
- package/dist/package-s8PvCnk-.js.map +1 -0
- package/dist/{agent-Ev5hU5hH.js → run-BzpYYOQs.js} +53 -44
- package/dist/run-BzpYYOQs.js.map +1 -0
- package/dist/run-CCZ24VKk.js +51 -0
- package/dist/run-CCZ24VKk.js.map +1 -0
- package/dist/{init-eNRlotJK.js → run-CF97BWVa.js} +102 -147
- package/dist/run-CF97BWVa.js.map +1 -0
- package/dist/run-CQbj3ley.cjs +52 -0
- package/dist/run-CQbj3ley.cjs.map +1 -0
- package/dist/{generate-Cg8yufrw.js → run-CXTVu3Wl.js} +322 -337
- package/dist/run-CXTVu3Wl.js.map +1 -0
- package/dist/run-D0hmRpHy.js +49 -0
- package/dist/run-D0hmRpHy.js.map +1 -0
- package/dist/{agent-B_pirbeB.cjs → run-DwdAwnLG.cjs} +51 -42
- package/dist/run-DwdAwnLG.cjs.map +1 -0
- package/dist/run-Lr0Ctnu0.cjs +50 -0
- package/dist/run-Lr0Ctnu0.cjs.map +1 -0
- package/dist/{generate-K8MJ9aQF.cjs → run-QyqW2rPC.cjs} +319 -334
- package/dist/run-QyqW2rPC.cjs.map +1 -0
- package/dist/{init-CZ5Xq2Hd.cjs → run-YsoCk5we.cjs} +100 -145
- package/dist/run-YsoCk5we.cjs.map +1 -0
- package/dist/shell-475fQKaX.cjs.map +1 -1
- package/dist/{shell-DLzN4fRo.js → shell-CN6DNqeC.js} +2 -2
- package/dist/{shell-DLzN4fRo.js.map → shell-CN6DNqeC.js.map} +1 -1
- package/dist/{telemetry-DN95_2pF.cjs → telemetry-B2iWkY5e.cjs} +5 -7
- package/dist/telemetry-B2iWkY5e.cjs.map +1 -0
- package/dist/{telemetry-LgT_sdPe.js → telemetry-BkektVz6.js} +6 -8
- package/dist/telemetry-BkektVz6.js.map +1 -0
- package/dist/validate-BYuHYBhg.cjs +26 -0
- package/dist/validate-BYuHYBhg.cjs.map +1 -0
- package/dist/validate-Da2LIDVc.js +26 -0
- package/dist/validate-Da2LIDVc.js.map +1 -0
- package/package.json +22 -14
- package/src/commands/agent/start.ts +10 -7
- package/src/commands/agent.ts +3 -1
- package/src/commands/generate.ts +5 -3
- package/src/commands/init.ts +34 -3
- package/src/commands/mcp.ts +28 -4
- package/src/commands/validate.ts +6 -4
- package/src/constants.ts +2 -58
- package/src/index.ts +5 -3
- package/src/loggers/clackLogger.ts +45 -43
- package/src/loggers/fileSystemLogger.ts +26 -13
- package/src/loggers/githubActionsLogger.ts +13 -25
- package/src/loggers/plainLogger.ts +12 -23
- package/src/loggers/types.ts +6 -0
- package/src/loggers/utils.ts +155 -9
- package/src/runners/agent/run.ts +113 -0
- package/src/runners/agent/utils.ts +98 -0
- package/src/runners/generate/run.ts +276 -0
- package/src/runners/generate/utils.ts +209 -0
- package/src/runners/init/run.ts +211 -0
- package/src/{utils/packageManager.ts → runners/init/utils.ts} +10 -0
- package/src/runners/mcp/run.ts +55 -0
- package/src/runners/validate/run.ts +63 -0
- package/src/{utils/telemetry.ts → telemetry.ts} +12 -5
- package/dist/agent-BEgI2HXH.cjs +0 -58
- package/dist/agent-BEgI2HXH.cjs.map +0 -1
- package/dist/agent-B_pirbeB.cjs.map +0 -1
- package/dist/agent-CTdJEHEs.js +0 -56
- package/dist/agent-CTdJEHEs.js.map +0 -1
- package/dist/agent-Ev5hU5hH.js.map +0 -1
- package/dist/constants-CnDXa1R6.cjs +0 -148
- package/dist/constants-CnDXa1R6.cjs.map +0 -1
- package/dist/constants-aL3CP_Wq.js +0 -95
- package/dist/constants-aL3CP_Wq.js.map +0 -1
- package/dist/generate-Cg8yufrw.js.map +0 -1
- package/dist/generate-DDCwNQNo.cjs.map +0 -1
- package/dist/generate-K8MJ9aQF.cjs.map +0 -1
- package/dist/generate-YPtfjsg4.js.map +0 -1
- package/dist/init-Bu95ML_u.cjs +0 -25
- package/dist/init-Bu95ML_u.cjs.map +0 -1
- package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
- package/dist/init-eNRlotJK.js.map +0 -1
- package/dist/init-ooJeOBGt.js +0 -25
- package/dist/init-ooJeOBGt.js.map +0 -1
- package/dist/mcp-C-d5N1wZ.js +0 -16
- package/dist/mcp-C-d5N1wZ.js.map +0 -1
- package/dist/mcp-CLcDV4Jm.cjs +0 -41
- package/dist/mcp-CLcDV4Jm.cjs.map +0 -1
- package/dist/mcp-D7EIR9fR.js +0 -40
- package/dist/mcp-D7EIR9fR.js.map +0 -1
- package/dist/mcp-Dpu8vzzj.cjs +0 -16
- package/dist/mcp-Dpu8vzzj.cjs.map +0 -1
- package/dist/package-D5arPDnh.cjs.map +0 -1
- package/dist/package-DqZsMLZ9.js +0 -6
- package/dist/package-DqZsMLZ9.js.map +0 -1
- package/dist/telemetry-DN95_2pF.cjs.map +0 -1
- package/dist/telemetry-LgT_sdPe.js.map +0 -1
- package/dist/validate-CIR3_lZI.js +0 -25
- package/dist/validate-CIR3_lZI.js.map +0 -1
- package/dist/validate-DcqUb4DM.cjs +0 -25
- package/dist/validate-DcqUb4DM.cjs.map +0 -1
- package/dist/validate-kLJoT_hi.js +0 -33
- package/dist/validate-kLJoT_hi.js.map +0 -1
- package/dist/validate-yKKzqEZ5.cjs +0 -34
- package/dist/validate-yKKzqEZ5.cjs.map +0 -1
- package/src/runners/agent.ts +0 -149
- package/src/runners/generate.ts +0 -333
- package/src/runners/init.ts +0 -296
- package/src/runners/mcp.ts +0 -45
- package/src/runners/validate.ts +0 -39
- package/src/types.ts +0 -11
- package/src/utils/Writables.ts +0 -17
- package/src/utils/executeHooks.ts +0 -45
- package/src/utils/flags.ts +0 -9
- package/src/utils/getConfig.ts +0 -10
- package/src/utils/getCosmiConfig.ts +0 -80
- package/src/utils/getSummary.ts +0 -68
- package/src/utils/runHook.ts +0 -91
- package/src/utils/watcher.ts +0 -19
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { styleText } from 'node:util'
|
|
5
|
+
import * as clack from '@clack/prompts'
|
|
6
|
+
import { spawnAsync, getErrorMessage } from '@internals/utils'
|
|
7
|
+
import { agentDefaults } from '../../constants.ts'
|
|
8
|
+
import { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'
|
|
9
|
+
import { isPortAvailable, resolveAgentStartEnvironment } from './utils.ts'
|
|
10
|
+
|
|
11
|
+
type AgentStartOptions = {
|
|
12
|
+
/**
|
|
13
|
+
* TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
|
|
14
|
+
*/
|
|
15
|
+
port: string | undefined
|
|
16
|
+
/**
|
|
17
|
+
* Hostname the HTTP server binds to.
|
|
18
|
+
*
|
|
19
|
+
* @default 'localhost'
|
|
20
|
+
*/
|
|
21
|
+
host: string
|
|
22
|
+
/**
|
|
23
|
+
* Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
|
|
24
|
+
*/
|
|
25
|
+
configPath: string | undefined
|
|
26
|
+
/**
|
|
27
|
+
* Grants the agent permission to write generated files to the filesystem.
|
|
28
|
+
*/
|
|
29
|
+
allowWrite: boolean
|
|
30
|
+
/**
|
|
31
|
+
* Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
|
|
32
|
+
*/
|
|
33
|
+
allowAll: boolean
|
|
34
|
+
/**
|
|
35
|
+
* Current `@kubb/cli` version string, used for the telemetry payload.
|
|
36
|
+
*/
|
|
37
|
+
version: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Spawns the Kubb Agent HTTP server as a Node.js subprocess.
|
|
42
|
+
* Resolves config from CLI flags and environment variables, validates the port, and exits with code 1 on failure.
|
|
43
|
+
*/
|
|
44
|
+
export async function run({ port, host, configPath, allowWrite, allowAll, version }: AgentStartOptions): Promise<void> {
|
|
45
|
+
const hrStart = process.hrtime()
|
|
46
|
+
const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'agent', kubbVersion: version, hrStart, status }))
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
// Load .env file into process.env using Node.js built-in (v20.12.0+)
|
|
50
|
+
try {
|
|
51
|
+
process.loadEnvFile()
|
|
52
|
+
} catch {
|
|
53
|
+
// .env file may not exist; ignore
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Resolve the @kubb/agent package path — createRequire is CJS/ESM compatible (import.meta.resolve is ESM-only)
|
|
57
|
+
const require = createRequire(import.meta.url)
|
|
58
|
+
let agentPkgPath: string
|
|
59
|
+
try {
|
|
60
|
+
agentPkgPath = require.resolve('@kubb/agent/package.json')
|
|
61
|
+
} catch (_e) {
|
|
62
|
+
console.error(styleText('red', 'The @kubb/agent package is not installed.'))
|
|
63
|
+
console.error('')
|
|
64
|
+
console.error('Install it with:')
|
|
65
|
+
console.error(styleText('cyan', ' npm install @kubb/agent'))
|
|
66
|
+
console.error(styleText('cyan', ' # or'))
|
|
67
|
+
console.error(styleText('cyan', ' pnpm install @kubb/agent'))
|
|
68
|
+
console.error('')
|
|
69
|
+
process.exit(1)
|
|
70
|
+
}
|
|
71
|
+
const agentDir = path.dirname(agentPkgPath)
|
|
72
|
+
const serverPath = path.join(agentDir, agentDefaults.serverEntryPath)
|
|
73
|
+
|
|
74
|
+
const resolvedEnv = resolveAgentStartEnvironment({
|
|
75
|
+
port,
|
|
76
|
+
host,
|
|
77
|
+
configPath,
|
|
78
|
+
allowWrite,
|
|
79
|
+
allowAll,
|
|
80
|
+
})
|
|
81
|
+
const numericPort = Number(resolvedEnv.port)
|
|
82
|
+
|
|
83
|
+
if (!Number.isInteger(numericPort) || numericPort <= 0) {
|
|
84
|
+
throw new Error(`Invalid port "${resolvedEnv.port}". Provide a positive integer with --port or PORT.`)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
clack.log.step(styleText('cyan', 'Starting agent server...'))
|
|
88
|
+
clack.log.info(styleText('dim', `Config: ${resolvedEnv.agentConfigPath}`))
|
|
89
|
+
clack.log.info(styleText('dim', `Host: ${resolvedEnv.host}`))
|
|
90
|
+
clack.log.info(styleText('dim', `Port: ${resolvedEnv.port}`))
|
|
91
|
+
if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) {
|
|
92
|
+
clack.log.warn(styleText('yellow', 'Filesystem writes disabled. Use --allow-write or --allow-all to enable.'))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (!(await isPortAvailable(numericPort, resolvedEnv.host))) {
|
|
96
|
+
clack.log.error(styleText('red', `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`))
|
|
97
|
+
process.exit(1)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Spawns the server as a detached background process so the CLI can exit independently.
|
|
101
|
+
await spawnAsync('node', [serverPath], {
|
|
102
|
+
env: resolvedEnv.env,
|
|
103
|
+
cwd: process.cwd(),
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
await report('success')
|
|
107
|
+
} catch (error) {
|
|
108
|
+
await report('failed')
|
|
109
|
+
clack.log.error(styleText('red', 'Failed to start agent server'))
|
|
110
|
+
clack.log.error(getErrorMessage(error))
|
|
111
|
+
process.exit(1)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import net from 'node:net'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { agentDefaults } from '../../constants.ts'
|
|
5
|
+
|
|
6
|
+
type AgentStartEnvironmentInput = {
|
|
7
|
+
/**
|
|
8
|
+
* TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
|
|
9
|
+
*/
|
|
10
|
+
port: string | undefined
|
|
11
|
+
/**
|
|
12
|
+
* Hostname the HTTP server binds to.
|
|
13
|
+
*/
|
|
14
|
+
host: string
|
|
15
|
+
/**
|
|
16
|
+
* Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
|
|
17
|
+
*/
|
|
18
|
+
configPath: string | undefined
|
|
19
|
+
/**
|
|
20
|
+
* Grants the agent permission to write generated files to the filesystem.
|
|
21
|
+
*/
|
|
22
|
+
allowWrite: boolean
|
|
23
|
+
/**
|
|
24
|
+
* Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
|
|
25
|
+
*/
|
|
26
|
+
allowAll: boolean
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type ResolvedAgentStartEnvironment = {
|
|
30
|
+
/**
|
|
31
|
+
* Final port string after merging CLI flag, `PORT` env var, and the default.
|
|
32
|
+
*/
|
|
33
|
+
port: string
|
|
34
|
+
/**
|
|
35
|
+
* Final hostname after merging CLI flag, `HOST` env var, and the default.
|
|
36
|
+
*/
|
|
37
|
+
host: string
|
|
38
|
+
/**
|
|
39
|
+
* Effective write-permission flag, accounting for `allowAll` and `KUBB_AGENT_ALLOW_WRITE`.
|
|
40
|
+
*/
|
|
41
|
+
allowWrite: boolean
|
|
42
|
+
/**
|
|
43
|
+
* Effective all-permissions flag, accounting for `KUBB_AGENT_ALLOW_ALL`.
|
|
44
|
+
*/
|
|
45
|
+
allowAll: boolean
|
|
46
|
+
/**
|
|
47
|
+
* Absolute path to the Kubb config file passed to the agent subprocess.
|
|
48
|
+
*/
|
|
49
|
+
agentConfigPath: string
|
|
50
|
+
/**
|
|
51
|
+
* Merged `process.env` object with all resolved agent environment variables applied.
|
|
52
|
+
*/
|
|
53
|
+
env: NodeJS.ProcessEnv
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.
|
|
58
|
+
*/
|
|
59
|
+
export function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }: AgentStartEnvironmentInput): ResolvedAgentStartEnvironment {
|
|
60
|
+
const resolvedPort = port ?? process.env.PORT ?? agentDefaults.port
|
|
61
|
+
const resolvedHost = host !== agentDefaults.host ? host : (process.env.HOST ?? agentDefaults.host)
|
|
62
|
+
const resolvedAllowAll = allowAll || process.env.KUBB_AGENT_ALLOW_ALL === 'true'
|
|
63
|
+
const resolvedAllowWrite = resolvedAllowAll || allowWrite || process.env.KUBB_AGENT_ALLOW_WRITE === 'true'
|
|
64
|
+
const agentRoot = process.env.KUBB_AGENT_ROOT ?? process.cwd()
|
|
65
|
+
const agentConfigPath = path.resolve(process.cwd(), configPath || process.env.KUBB_AGENT_CONFIG || agentDefaults.configFile)
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
port: resolvedPort,
|
|
69
|
+
host: resolvedHost,
|
|
70
|
+
allowWrite: resolvedAllowWrite,
|
|
71
|
+
allowAll: resolvedAllowAll,
|
|
72
|
+
agentConfigPath,
|
|
73
|
+
env: {
|
|
74
|
+
...process.env,
|
|
75
|
+
PORT: resolvedPort,
|
|
76
|
+
HOST: resolvedHost,
|
|
77
|
+
KUBB_AGENT_ROOT: agentRoot,
|
|
78
|
+
KUBB_AGENT_CONFIG: agentConfigPath,
|
|
79
|
+
KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),
|
|
80
|
+
KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),
|
|
81
|
+
KUBB_AGENT_TOKEN: process.env.KUBB_AGENT_TOKEN,
|
|
82
|
+
KUBB_AGENT_RETRY_TIMEOUT: process.env.KUBB_AGENT_RETRY_TIMEOUT ?? agentDefaults.retryTimeout,
|
|
83
|
+
KUBB_STUDIO_URL: process.env.KUBB_STUDIO_URL ?? agentDefaults.studioUrl,
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function isPortAvailable(port: number, host: string): Promise<boolean> {
|
|
89
|
+
return new Promise((resolve) => {
|
|
90
|
+
const server = net.createServer()
|
|
91
|
+
server.once('error', () => resolve(false))
|
|
92
|
+
server.once('listening', () => {
|
|
93
|
+
server.close()
|
|
94
|
+
resolve(true)
|
|
95
|
+
})
|
|
96
|
+
server.listen(port, host)
|
|
97
|
+
})
|
|
98
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { styleText } from 'node:util'
|
|
5
|
+
import * as clack from '@clack/prompts'
|
|
6
|
+
import type { AsyncEventEmitter } from '@internals/utils'
|
|
7
|
+
import { AsyncEventEmitter as AsyncEventEmitterClass, detectFormatter, detectLinter, executeIfOnline, formatters, linters, toError } from '@internals/utils'
|
|
8
|
+
import { type Config, createKubb, isInputPath, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'
|
|
9
|
+
import { version } from '../../../package.json'
|
|
10
|
+
import { KUBB_NPM_PACKAGE_URL } from '../../constants.ts'
|
|
11
|
+
import { setupLogger, type HookSinkFactory } from '../../loggers/utils.ts'
|
|
12
|
+
import { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'
|
|
13
|
+
import { executeHooks, getConfigs, startWatcher } from './utils.ts'
|
|
14
|
+
|
|
15
|
+
type GenerateProps = {
|
|
16
|
+
input?: string
|
|
17
|
+
config: Config
|
|
18
|
+
hooks: AsyncEventEmitter<KubbHooks>
|
|
19
|
+
logLevel: number
|
|
20
|
+
makeSink?: HookSinkFactory
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type ToolMap = typeof formatters | typeof linters
|
|
24
|
+
|
|
25
|
+
type RunToolPassOptions = {
|
|
26
|
+
toolValue: string
|
|
27
|
+
detect: () => Promise<string | null>
|
|
28
|
+
toolMap: ToolMap
|
|
29
|
+
toolLabel: string
|
|
30
|
+
successPrefix: string
|
|
31
|
+
noToolMessage: string
|
|
32
|
+
configName: string | undefined
|
|
33
|
+
outputPath: string
|
|
34
|
+
logLevel: number
|
|
35
|
+
hooks: AsyncEventEmitter<KubbHooks>
|
|
36
|
+
onStart: () => Promise<void>
|
|
37
|
+
onEnd: () => Promise<void>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Registers a one-shot `kubb:hook:end` listener for `hookId` BEFORE the caller emits `kubb:hook:start`,
|
|
42
|
+
* avoiding the race where a synchronous emitter fires end before the listener is attached.
|
|
43
|
+
*/
|
|
44
|
+
function waitForHookEnd(hooks: AsyncEventEmitter<KubbHooks>, hookId: string, onSuccess: () => Promise<void>, fallbackErrorMessage: string): Promise<void> {
|
|
45
|
+
return new Promise<void>((resolve, reject) => {
|
|
46
|
+
const handler = (ctx: { id?: string; command: string; args?: readonly string[]; success: boolean; error: Error | null }) => {
|
|
47
|
+
if (ctx.id !== hookId) return
|
|
48
|
+
hooks.off('kubb:hook:end', handler)
|
|
49
|
+
if (!ctx.success) {
|
|
50
|
+
reject(ctx.error ?? new Error(fallbackErrorMessage))
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
onSuccess().then(resolve).catch(reject)
|
|
54
|
+
}
|
|
55
|
+
hooks.on('kubb:hook:end', handler)
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function runToolPass({
|
|
60
|
+
toolValue,
|
|
61
|
+
detect,
|
|
62
|
+
toolMap,
|
|
63
|
+
toolLabel,
|
|
64
|
+
successPrefix,
|
|
65
|
+
noToolMessage,
|
|
66
|
+
configName,
|
|
67
|
+
outputPath,
|
|
68
|
+
logLevel,
|
|
69
|
+
hooks,
|
|
70
|
+
onStart,
|
|
71
|
+
onEnd,
|
|
72
|
+
}: RunToolPassOptions) {
|
|
73
|
+
await onStart()
|
|
74
|
+
|
|
75
|
+
let resolvedTool = toolValue
|
|
76
|
+
if (resolvedTool === 'auto') {
|
|
77
|
+
const detected = await detect()
|
|
78
|
+
if (!detected) {
|
|
79
|
+
await hooks.emit('kubb:warn', { message: noToolMessage })
|
|
80
|
+
} else {
|
|
81
|
+
resolvedTool = detected
|
|
82
|
+
await hooks.emit('kubb:info', { message: `Auto-detected ${toolLabel}: ${styleText('dim', resolvedTool)}` })
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
let toolError: Error | undefined
|
|
87
|
+
|
|
88
|
+
if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in toolMap) {
|
|
89
|
+
const toolConfig = toolMap[resolvedTool as keyof ToolMap]
|
|
90
|
+
const hookId = createHash('sha256').update([configName, resolvedTool].filter(Boolean).join('-')).digest('hex')
|
|
91
|
+
|
|
92
|
+
const successMessage = [
|
|
93
|
+
`${successPrefix} with ${styleText('dim', resolvedTool)}`,
|
|
94
|
+
logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,
|
|
95
|
+
'successfully',
|
|
96
|
+
]
|
|
97
|
+
.filter(Boolean)
|
|
98
|
+
.join(' ')
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
const hookEndPromise = waitForHookEnd(hooks, hookId, () => hooks.emit('kubb:success', { message: successMessage }), toolConfig.errorMessage)
|
|
102
|
+
|
|
103
|
+
await hooks.emit('kubb:hook:start', { id: hookId, command: toolConfig.command, args: toolConfig.args(outputPath) })
|
|
104
|
+
|
|
105
|
+
await hookEndPromise
|
|
106
|
+
} catch (caughtError) {
|
|
107
|
+
const err = toError(caughtError)
|
|
108
|
+
await hooks.emit('kubb:error', { error: err })
|
|
109
|
+
toolError = err
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
await onEnd()
|
|
114
|
+
|
|
115
|
+
if (toolError) {
|
|
116
|
+
throw toolError
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function generate(options: GenerateProps): Promise<void> {
|
|
121
|
+
const { input, hooks, logLevel, makeSink } = options
|
|
122
|
+
|
|
123
|
+
const hrStart = process.hrtime()
|
|
124
|
+
const inputPath = input ?? (options.config.input && 'path' in options.config.input ? options.config.input.path : undefined)
|
|
125
|
+
|
|
126
|
+
const config: Config = {
|
|
127
|
+
...options.config,
|
|
128
|
+
input: inputPath ? { ...options.config.input, path: inputPath } : options.config.input,
|
|
129
|
+
...options.config.output,
|
|
130
|
+
} satisfies Config
|
|
131
|
+
|
|
132
|
+
const kubb = createKubb(config, { hooks })
|
|
133
|
+
await kubb.setup()
|
|
134
|
+
|
|
135
|
+
await hooks.emit('kubb:generation:start', { config })
|
|
136
|
+
await hooks.emit('kubb:info', { message: config.name ? `Setup generation ${styleText('bold', config.name)}` : 'Setup generation', info: inputPath })
|
|
137
|
+
await hooks.emit('kubb:info', { message: config.name ? `Build generation ${styleText('bold', config.name)}` : 'Build generation', info: inputPath })
|
|
138
|
+
|
|
139
|
+
const { files, failedPlugins, pluginTimings, error, driver } = await kubb.safeBuild()
|
|
140
|
+
|
|
141
|
+
await hooks.emit('kubb:info', { message: 'Load summary' })
|
|
142
|
+
|
|
143
|
+
const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))
|
|
144
|
+
|
|
145
|
+
const reportTelemetry = (status: 'success' | 'failed') =>
|
|
146
|
+
sendTelemetry(buildTelemetryEvent({ command: 'generate', kubbVersion: version, plugins: telemetryPlugins, hrStart, filesCreated: files.length, status }))
|
|
147
|
+
|
|
148
|
+
if (failedPlugins.size > 0 || error) {
|
|
149
|
+
const allErrors = [error, ...Array.from(failedPlugins, (it) => it.error)].filter(Boolean) as Error[]
|
|
150
|
+
|
|
151
|
+
for (const err of allErrors) {
|
|
152
|
+
await hooks.emit('kubb:error', { error: err })
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
await hooks.emit('kubb:generation:end', { config, files, sources: kubb.sources })
|
|
156
|
+
await hooks.emit('kubb:generation:summary', {
|
|
157
|
+
config,
|
|
158
|
+
failedPlugins,
|
|
159
|
+
filesCreated: files.length,
|
|
160
|
+
status: 'failed',
|
|
161
|
+
hrStart,
|
|
162
|
+
pluginTimings: logLevel >= logLevelMap.verbose ? pluginTimings : undefined,
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
await reportTelemetry('failed')
|
|
166
|
+
process.exit(1)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
await hooks.emit('kubb:success', { message: 'Generation succeeded', info: inputPath })
|
|
170
|
+
await hooks.emit('kubb:generation:end', { config, files, sources: kubb.sources })
|
|
171
|
+
|
|
172
|
+
const outputPath = path.resolve(config.root, config.output.path)
|
|
173
|
+
|
|
174
|
+
const toolPasses = [
|
|
175
|
+
config.output.format && {
|
|
176
|
+
toolValue: config.output.format,
|
|
177
|
+
detect: detectFormatter,
|
|
178
|
+
toolMap: formatters,
|
|
179
|
+
toolLabel: 'formatter',
|
|
180
|
+
successPrefix: 'Formatting',
|
|
181
|
+
noToolMessage: 'No formatter found (oxfmt, biome, or prettier). Skipping formatting.',
|
|
182
|
+
onStart: () => hooks.emit('kubb:format:start'),
|
|
183
|
+
onEnd: () => hooks.emit('kubb:format:end'),
|
|
184
|
+
},
|
|
185
|
+
config.output.lint && {
|
|
186
|
+
toolValue: config.output.lint,
|
|
187
|
+
detect: detectLinter,
|
|
188
|
+
toolMap: linters,
|
|
189
|
+
toolLabel: 'linter',
|
|
190
|
+
successPrefix: 'Linting',
|
|
191
|
+
noToolMessage: 'No linter found (oxlint, biome, or eslint). Skipping linting.',
|
|
192
|
+
onStart: () => hooks.emit('kubb:lint:start'),
|
|
193
|
+
onEnd: () => hooks.emit('kubb:lint:end'),
|
|
194
|
+
},
|
|
195
|
+
].filter(Boolean) as Omit<RunToolPassOptions, 'configName' | 'outputPath' | 'logLevel' | 'hooks'>[]
|
|
196
|
+
|
|
197
|
+
for (const pass of toolPasses) {
|
|
198
|
+
await runToolPass({ ...pass, configName: config.name, outputPath, logLevel, hooks })
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (config.hooks) {
|
|
202
|
+
await hooks.emit('kubb:hooks:start')
|
|
203
|
+
await executeHooks({ configHooks: config.hooks, hooks, makeSink })
|
|
204
|
+
await hooks.emit('kubb:hooks:end')
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
await hooks.emit('kubb:generation:summary', { config, failedPlugins, filesCreated: files.length, status: 'success', hrStart, pluginTimings })
|
|
208
|
+
|
|
209
|
+
await reportTelemetry('success')
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
type GenerateCommandOptions = {
|
|
213
|
+
input?: string
|
|
214
|
+
configPath?: string
|
|
215
|
+
logLevel: string
|
|
216
|
+
watch: boolean
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function checkForUpdate(hooks: AsyncEventEmitter<KubbHooks>): Promise<void> {
|
|
220
|
+
await executeIfOnline(async () => {
|
|
221
|
+
try {
|
|
222
|
+
const res = await fetch(KUBB_NPM_PACKAGE_URL)
|
|
223
|
+
const data = (await res.json()) as { version: string }
|
|
224
|
+
if (data.version && version < data.version) {
|
|
225
|
+
await hooks.emit('kubb:version:new', { currentVersion: version, latestVersion: data.version })
|
|
226
|
+
}
|
|
227
|
+
} catch {
|
|
228
|
+
// Ignore network errors
|
|
229
|
+
}
|
|
230
|
+
})
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Runs the full Kubb generation lifecycle for the given CLI options.
|
|
235
|
+
* Sets up the logger, checks for a newer version, loads configs, and calls `generate` for each config entry.
|
|
236
|
+
*/
|
|
237
|
+
export async function run({ input, configPath, logLevel: logLevelKey, watch }: GenerateCommandOptions): Promise<void> {
|
|
238
|
+
const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info
|
|
239
|
+
const hooks = new AsyncEventEmitterClass<KubbHooks>()
|
|
240
|
+
|
|
241
|
+
const makeSink = await setupLogger(hooks, { logLevel })
|
|
242
|
+
|
|
243
|
+
await checkForUpdate(hooks)
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
const { configs, configPath: resolvedConfigPath } = await getConfigs({ configPath, input })
|
|
247
|
+
const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)
|
|
248
|
+
|
|
249
|
+
await hooks.emit('kubb:config:start')
|
|
250
|
+
await hooks.emit('kubb:info', { message: 'Config loaded', info: relativeConfigPath })
|
|
251
|
+
await hooks.emit('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })
|
|
252
|
+
await hooks.emit('kubb:config:end', { configs })
|
|
253
|
+
await hooks.emit('kubb:lifecycle:start', { version })
|
|
254
|
+
|
|
255
|
+
for (const config of configs) {
|
|
256
|
+
if (isInputPath(config) && watch) {
|
|
257
|
+
await startWatcher(
|
|
258
|
+
[input || config.input.path],
|
|
259
|
+
async (paths) => {
|
|
260
|
+
hooks.removeAll()
|
|
261
|
+
await generate({ input, config, logLevel, hooks, makeSink })
|
|
262
|
+
clack.log.step(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))
|
|
263
|
+
},
|
|
264
|
+
{ info: (msg) => clack.log.info(msg), error: (msg) => clack.log.error(msg) },
|
|
265
|
+
)
|
|
266
|
+
} else {
|
|
267
|
+
await generate({ input, config, logLevel, hooks, makeSink })
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
await hooks.emit('kubb:lifecycle:end')
|
|
272
|
+
} catch (error) {
|
|
273
|
+
await hooks.emit('kubb:error', { error: toError(error) })
|
|
274
|
+
process.exit(1)
|
|
275
|
+
}
|
|
276
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { styleText } from 'node:util'
|
|
3
|
+
import type { AsyncEventEmitter } from '@internals/utils'
|
|
4
|
+
import { toError, tokenize } from '@internals/utils'
|
|
5
|
+
import type { CLIOptions, Config, KubbHooks, PossibleConfig } from '@kubb/core'
|
|
6
|
+
import { cosmiconfig } from 'cosmiconfig'
|
|
7
|
+
import { createJiti } from 'jiti'
|
|
8
|
+
import { NonZeroExitError, x } from 'tinyexec'
|
|
9
|
+
import type { HookSinkOptions } from '../../loggers/utils.ts'
|
|
10
|
+
import { WATCHER_IGNORED_PATHS } from '../../constants.ts'
|
|
11
|
+
|
|
12
|
+
type CosmiconfigResult = {
|
|
13
|
+
filepath: string
|
|
14
|
+
isEmpty?: boolean
|
|
15
|
+
config: PossibleConfig<CLIOptions>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const jiti = createJiti(import.meta.url, {
|
|
19
|
+
jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },
|
|
20
|
+
moduleCache: false,
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
const tsLoader = (configFile: string) => jiti.import(configFile, { default: true })
|
|
24
|
+
|
|
25
|
+
const MODULE_NAME = 'kubb'
|
|
26
|
+
|
|
27
|
+
const BASE_SEARCH_PLACES = [
|
|
28
|
+
'package.json',
|
|
29
|
+
`.${MODULE_NAME}rc`,
|
|
30
|
+
`.${MODULE_NAME}rc.json`,
|
|
31
|
+
`.${MODULE_NAME}rc.yaml`,
|
|
32
|
+
`.${MODULE_NAME}rc.yml`,
|
|
33
|
+
`.${MODULE_NAME}rc.ts`,
|
|
34
|
+
`.${MODULE_NAME}rc.mts`,
|
|
35
|
+
`.${MODULE_NAME}rc.cts`,
|
|
36
|
+
`.${MODULE_NAME}rc.js`,
|
|
37
|
+
`.${MODULE_NAME}rc.mjs`,
|
|
38
|
+
`.${MODULE_NAME}rc.cjs`,
|
|
39
|
+
`${MODULE_NAME}.config.ts`,
|
|
40
|
+
`${MODULE_NAME}.config.mts`,
|
|
41
|
+
`${MODULE_NAME}.config.cts`,
|
|
42
|
+
`${MODULE_NAME}.config.js`,
|
|
43
|
+
`${MODULE_NAME}.config.mjs`,
|
|
44
|
+
`${MODULE_NAME}.config.cjs`,
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
const SEARCH_PLACES = ['', '.config/', 'configs/'].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`))
|
|
48
|
+
|
|
49
|
+
async function getCosmiConfig(configFile?: string): Promise<CosmiconfigResult> {
|
|
50
|
+
const explorer = cosmiconfig(MODULE_NAME, {
|
|
51
|
+
cache: false,
|
|
52
|
+
searchPlaces: SEARCH_PLACES,
|
|
53
|
+
loaders: { '.ts': tsLoader, '.mts': tsLoader, '.cts': tsLoader },
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
let result: CosmiconfigResult
|
|
57
|
+
try {
|
|
58
|
+
result = (configFile ? await explorer.load(configFile) : await explorer.search()) as CosmiconfigResult
|
|
59
|
+
} catch (error) {
|
|
60
|
+
throw new Error('Config failed loading', { cause: error })
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (!result?.config || result.isEmpty) {
|
|
64
|
+
throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return result
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type GetConfigsOptions = {
|
|
71
|
+
/**
|
|
72
|
+
* Explicit path to the Kubb config file. When omitted, cosmiconfig searches from the current directory.
|
|
73
|
+
*/
|
|
74
|
+
configPath?: string
|
|
75
|
+
/**
|
|
76
|
+
* Optional OpenAPI input path that overrides `config.input.path` for this run.
|
|
77
|
+
*/
|
|
78
|
+
input?: string
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type GetConfigsResult = {
|
|
82
|
+
/**
|
|
83
|
+
* Absolute path to the resolved config file.
|
|
84
|
+
*/
|
|
85
|
+
configPath: string
|
|
86
|
+
/**
|
|
87
|
+
* Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.
|
|
88
|
+
*/
|
|
89
|
+
configs: Array<Config>
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
|
|
94
|
+
* Every config in the result is guaranteed to have a `plugins` array.
|
|
95
|
+
*/
|
|
96
|
+
export async function getConfigs({ configPath, input }: GetConfigsOptions): Promise<GetConfigsResult> {
|
|
97
|
+
const result = await getCosmiConfig(configPath)
|
|
98
|
+
const resolved = await (typeof result.config === 'function' ? result.config({ input } as CLIOptions) : result.config)
|
|
99
|
+
const userConfigs = Array.isArray(resolved) ? resolved : [resolved]
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
configPath: result.filepath,
|
|
103
|
+
configs: userConfigs.map((item) => ({ ...item, plugins: item.plugins ?? [] }) as Config),
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
type ExecuteHooksOptions = {
|
|
108
|
+
configHooks: NonNullable<Config['hooks']>
|
|
109
|
+
hooks: AsyncEventEmitter<KubbHooks>
|
|
110
|
+
makeSink?: (commandWithArgs: string) => HookSinkOptions | undefined
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Runs the `done` hooks defined in a Kubb config in sequence.
|
|
115
|
+
*/
|
|
116
|
+
export async function executeHooks({ configHooks, hooks, makeSink }: ExecuteHooksOptions): Promise<void> {
|
|
117
|
+
const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean)
|
|
118
|
+
|
|
119
|
+
for (const command of commands) {
|
|
120
|
+
const [cmd, ...args] = tokenize(command)
|
|
121
|
+
if (!cmd) continue
|
|
122
|
+
|
|
123
|
+
const hookId = createHash('sha256').update(command).digest('hex')
|
|
124
|
+
const commandWithArgs = [cmd, ...args].join(' ')
|
|
125
|
+
|
|
126
|
+
await hooks.emit('kubb:hook:start', { id: hookId, command: cmd, args })
|
|
127
|
+
|
|
128
|
+
const { stream = false, onLine, onStdout, onStderr } = makeSink?.(commandWithArgs) ?? {}
|
|
129
|
+
await runHook({ id: hookId, command: cmd, args, commandWithArgs, context: hooks, stream, sink: { onLine, onStdout, onStderr } })
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
type RunHookOptions = {
|
|
134
|
+
id: string
|
|
135
|
+
command: string
|
|
136
|
+
args?: readonly string[]
|
|
137
|
+
commandWithArgs: string
|
|
138
|
+
context: AsyncEventEmitter<KubbHooks>
|
|
139
|
+
stream?: boolean
|
|
140
|
+
sink?: HookSinkOptions
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function runHook({ id, command, args, commandWithArgs, context, stream = false, sink }: RunHookOptions): Promise<void> {
|
|
144
|
+
const emitEnd = (success: boolean, error: Error | null) => context.emit('kubb:hook:end', { command, args, id, success, error })
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
const proc = x(command, [...(args ?? [])], {
|
|
148
|
+
nodeOptions: { detached: process.platform !== 'win32' },
|
|
149
|
+
throwOnError: true,
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
if (stream && sink?.onLine) {
|
|
153
|
+
for await (const line of proc) {
|
|
154
|
+
sink.onLine(line)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const result = await proc
|
|
159
|
+
await context.emit('kubb:debug', { date: new Date(), logs: [result.stdout.trimEnd()] })
|
|
160
|
+
await context.emit('kubb:success', { message: `${styleText('dim', commandWithArgs)} successfully executed` })
|
|
161
|
+
await emitEnd(true, null)
|
|
162
|
+
} catch (err) {
|
|
163
|
+
if (!(err instanceof NonZeroExitError)) {
|
|
164
|
+
const error = toError(err)
|
|
165
|
+
await emitEnd(false, error)
|
|
166
|
+
await context.emit('kubb:error', { error })
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const stderr = err.output?.stderr ?? ''
|
|
171
|
+
const stdout = err.output?.stdout ?? ''
|
|
172
|
+
|
|
173
|
+
await context.emit('kubb:debug', { date: new Date(), logs: [stdout, stderr].filter(Boolean) })
|
|
174
|
+
|
|
175
|
+
if (stderr) sink?.onStderr?.(stderr)
|
|
176
|
+
if (stdout) sink?.onStdout?.(stdout)
|
|
177
|
+
|
|
178
|
+
const error = new Error(`Hook execute failed: ${commandWithArgs}`)
|
|
179
|
+
await emitEnd(false, error)
|
|
180
|
+
await context.emit('kubb:error', { error })
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
type WatcherLog = {
|
|
185
|
+
info: (message: string) => void
|
|
186
|
+
error: (message: string) => void
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Starts a file watcher on the given paths and calls `cb` on any change.
|
|
191
|
+
* Ignores `.git` and `node_modules` directories.
|
|
192
|
+
*/
|
|
193
|
+
export async function startWatcher(
|
|
194
|
+
path: string[],
|
|
195
|
+
cb: (path: string[]) => Promise<void>,
|
|
196
|
+
log: WatcherLog = { info: console.log, error: console.log },
|
|
197
|
+
): Promise<void> {
|
|
198
|
+
const { watch } = await import('chokidar')
|
|
199
|
+
const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS })
|
|
200
|
+
|
|
201
|
+
watcher.on('all', async (type, file) => {
|
|
202
|
+
log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))
|
|
203
|
+
try {
|
|
204
|
+
await cb(path)
|
|
205
|
+
} catch (_e) {
|
|
206
|
+
log.error(styleText('red', 'Watcher failed'))
|
|
207
|
+
}
|
|
208
|
+
})
|
|
209
|
+
}
|