@kubb/cli 5.2.2 → 5.2.3

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.
Files changed (47) hide show
  1. package/dist/{Telemetry-DKfJQxnC.cjs → Telemetry-C-y1OMHs.cjs} +23 -1
  2. package/dist/Telemetry-C-y1OMHs.cjs.map +1 -0
  3. package/dist/{Telemetry-BCTY-Nzq.js → Telemetry-DIDDCARm.js} +12 -2
  4. package/dist/Telemetry-DIDDCARm.js.map +1 -0
  5. package/dist/{generate-ZWvsWer2.cjs → generate-CAP2Nea2.cjs} +3 -3
  6. package/dist/{generate-ZWvsWer2.cjs.map → generate-CAP2Nea2.cjs.map} +1 -1
  7. package/dist/{generate-FnqkFRDH.js → generate-CY7z7Z2y.js} +3 -3
  8. package/dist/{generate-FnqkFRDH.js.map → generate-CY7z7Z2y.js.map} +1 -1
  9. package/dist/index.cjs +7 -7
  10. package/dist/index.js +7 -7
  11. package/dist/{init-BQ0JXhap.js → init-BbSXTXhL.js} +2 -2
  12. package/dist/{init-BQ0JXhap.js.map → init-BbSXTXhL.js.map} +1 -1
  13. package/dist/{init-onrLNkdI.cjs → init-Pe5W5sVJ.cjs} +2 -2
  14. package/dist/{init-onrLNkdI.cjs.map → init-Pe5W5sVJ.cjs.map} +1 -1
  15. package/dist/package-D56GrO3S.js +6 -0
  16. package/dist/package-D56GrO3S.js.map +1 -0
  17. package/dist/{package-B45PcHOn.cjs → package-eWXYqkSG.cjs} +2 -2
  18. package/dist/package-eWXYqkSG.cjs.map +1 -0
  19. package/dist/{run-DhIqGkoY.js → run-BrTjLmeE.js} +4 -4
  20. package/dist/{run-DhIqGkoY.js.map → run-BrTjLmeE.js.map} +1 -1
  21. package/dist/{run-DOKY1xdi.js → run-COgITOQ7.js} +15 -6
  22. package/dist/run-COgITOQ7.js.map +1 -0
  23. package/dist/{run-Bwj2qS0v.cjs → run-CRu3GefH.cjs} +3 -3
  24. package/dist/{run-Bwj2qS0v.cjs.map → run-CRu3GefH.cjs.map} +1 -1
  25. package/dist/{run-CinpPEto.js → run-D6q8pRdT.js} +3 -3
  26. package/dist/{run-CinpPEto.js.map → run-D6q8pRdT.js.map} +1 -1
  27. package/dist/{run-DWselriZ.cjs → run-DoxJFSav.cjs} +15 -6
  28. package/dist/run-DoxJFSav.cjs.map +1 -0
  29. package/dist/{run-g2mZr8BS.js → run-F8-SmxgM.js} +3 -3
  30. package/dist/{run-g2mZr8BS.js.map → run-F8-SmxgM.js.map} +1 -1
  31. package/dist/{run-gpEaRaDp.cjs → run-U-2mO4sy.cjs} +4 -4
  32. package/dist/{run-gpEaRaDp.cjs.map → run-U-2mO4sy.cjs.map} +1 -1
  33. package/dist/{run-DuRIXbnI.cjs → run-_zc-3Bvw.cjs} +3 -3
  34. package/dist/{run-DuRIXbnI.cjs.map → run-_zc-3Bvw.cjs.map} +1 -1
  35. package/dist/{utils-CzoNURwq.js → utils-DOpJIiJM.js} +77 -3
  36. package/dist/{utils-CzoNURwq.js.map → utils-DOpJIiJM.js.map} +1 -1
  37. package/dist/{utils-B0SrWoNh.cjs → utils-DT_n0UZH.cjs} +88 -2
  38. package/dist/utils-DT_n0UZH.cjs.map +1 -0
  39. package/package.json +7 -7
  40. package/dist/Telemetry-BCTY-Nzq.js.map +0 -1
  41. package/dist/Telemetry-DKfJQxnC.cjs.map +0 -1
  42. package/dist/package-B45PcHOn.cjs.map +0 -1
  43. package/dist/package-CDmvOHxC.js +0 -6
  44. package/dist/package-CDmvOHxC.js.map +0 -1
  45. package/dist/run-DOKY1xdi.js.map +0 -1
  46. package/dist/run-DWselriZ.cjs.map +0 -1
  47. package/dist/utils-B0SrWoNh.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"run-gpEaRaDp.cjs","names":["runtime","readFile","rm","process","path","homedir","mkdir","writeFile","process","x","startPairing","path","hostname","styleText","createSpinner","pollForPairingToken","PairingCanceledError","KUBB_CONFIG_FILENAME","isCIEnvironment","canUseTTY","prompts","getConfigs","runConnection","setupReporters","logLevelMap","cliReporter","createFileStorage","sendTelemetry","buildTelemetryEvent","toError","defaultStudioUrl"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.ts","../src/runners/studio/run.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { clean, read } from '@internals/utils'\n\n/**\n * Root for everything the CLI persists between runs: the paired credential, the machine secret,\n * the last Studio config, and the live-session registry. `KUBB_HOME` relocates all of it.\n */\nexport function getKubbHome(): string {\n return process.env.KUBB_HOME ?? path.join(homedir(), '.kubb')\n}\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowWrite?: boolean; allowConfigEdit?: boolean; allowInput?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const raw = await read(getCredentialsPath()).catch(() => null)\n if (!raw) {\n return null\n }\n\n try {\n return JSON.parse(raw) as Credentials\n } catch {\n return null\n }\n}\n\n/**\n * Writes the credential with owner-only permissions. The file holds a bearer token, so the mode\n * is set at creation time rather than left to the process umask or fixed up afterward, which\n * would leave the token briefly readable under the umask's default mode.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n const file = getCredentialsPath()\n\n await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })\n await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 0o600 })\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await clean(getCredentialsPath())\n}\n","import { hostname } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport {\n createFileStorage,\n type ClientOptions,\n defaultStudioUrl,\n type InvalidAgentTokenError,\n PairingCanceledError,\n pollForPairingToken,\n runConnection,\n setStorage,\n startPairing,\n} from '@kubb/studio'\nimport { x } from 'tinyexec'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/studio.ts'\nimport setupReporters from '../../loggers/utils.ts'\nimport { createSpinner, logBlock, logIntro, logOutro } from '../../loggers/output.ts'\nimport { canUseTTY, isCIEnvironment } from '../../utils/env.ts'\nimport { getConfigs } from '../generate/utils.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getKubbHome, readCredentials, writeCredentials } from './credentials.ts'\n\nconst ACTIONS = ['connect', 'login', 'logout', 'status'] as const\n\nexport type StudioAction = (typeof ACTIONS)[number]\n\ntype Permission = 'allowWrite' | 'allowConfigEdit' | 'allowInput' | 'allowExec'\n\nexport type StudioOptions = {\n action: StudioAction\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<Permission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\n/**\n * Opens a URL in the user's browser. Best effort: a failure just means the user follows the\n * printed link instead.\n *\n * `start` is a `cmd.exe` builtin, not an executable on PATH, so Windows runs it through `cmd`.\n * The empty string is the window-title argument `start` expects before the URL.\n */\nasync function openInBrowser(url: string): Promise<void> {\n try {\n if (process.platform === 'win32') {\n await x('cmd', ['/c', 'start', '', url])\n } else {\n await x(process.platform === 'darwin' ? 'open' : 'xdg-open', [url])\n }\n } catch {}\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nasync function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const session = await startPairing({ studioUrl, name: path.basename(process.cwd()), hostname: hostname(), signal })\n\n console.log(`\\nOpen ${styleText('cyan', session.verification_uri)} and approve the code ${styleText('bold', session.user_code)}`)\n\n if (autoOpen) {\n await openInBrowser(session.verification_uri_complete)\n }\n\n const spinner = createSpinner()\n spinner.start('Waiting for approval')\n\n try {\n const { token, agent } = await pollForPairingToken({ studioUrl, session, signal })\n spinner.stop(`Paired as ${agent.name}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n throw error\n }\n}\n\n/**\n * What each permission is asked as, in the order the questions appear.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: Permission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n question: (project: string, configPath: string) => string\n}> = [\n { key: 'allowWrite', label: 'write generated files', question: (project) => `Let Kubb Studio write generated files into ${project}?` },\n {\n key: 'allowConfigEdit',\n label: 'edit kubb.config.ts',\n question: (_project, configPath) => `Let Kubb Studio change plugin options in ${configPath}?`,\n },\n {\n key: 'allowInput',\n label: 'use a Studio spec',\n question: () => 'Let Kubb Studio generate from an OpenAPI spec it sends, instead of the one on disk?',\n },\n {\n key: 'allowExec',\n label: 'run formatter, linter, postGenerate',\n question: () => 'Let Kubb Studio run the formatter, the linter, and output.postGenerate?',\n },\n]\n\n/**\n * One row per permission, for the connect banner and `kubb studio status`. A list rather than a\n * joined line: four labels this long read as one run-on sentence side by side.\n */\nexport function formatPermissionRows(granted: Record<Permission, boolean>): Array<string> {\n return PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✔') : styleText('red', '✘')} ${label}`)\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and new answers are stored unless `persist` is false.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n /**\n * Stores new answers in `~/.kubb/credentials.json`.\n * Pass `false` for `KUBB_AGENT_TOKEN` sessions so a temporary token is not written back to disk.\n */\n persist = true,\n): Promise<Record<Permission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted: Record<Permission, boolean> = { allowWrite: false, allowConfigEdit: false, allowInput: false, allowExec: false }\n const answers: Partial<Record<Permission, boolean>> = {}\n\n for (const { key, question } of PERMISSIONS) {\n if (options.permission[key] || typeof remembered?.[key] === 'boolean') {\n granted[key] = options.permission[key] || remembered?.[key] === true\n continue\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n granted[key] = false\n continue\n }\n\n granted[key] = (await prompts.confirm({ message: question(project, configPath), initialValue: false })) === true\n answers[key] = granted[key]\n }\n\n if (persist && Object.keys(answers).length) {\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n }\n\n return granted\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does.\n * Returns the first config.\n */\nasync function loadConfigs(options: StudioOptions): Promise<{ configPath: string; config: Config }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n const [config] = configs\n\n if (!config) {\n throw new Error('Config not defined, create a kubb.config.ts or pass it with --config')\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, config }\n}\n\n/**\n * Why a rejected token could not be recovered automatically: it came from `KUBB_AGENT_TOKEN`, no\n * browser is available to re-pair with, or the token this run already re-paired for was rejected\n * again.\n */\ntype RejectedTokenReason = 'envToken' | 'nonInteractive' | 'reauthExhausted'\n\n/**\n * Explains a rejected token to the operator. Builds the error and nothing else, so each caller\n * decides what happens to the credentials.\n */\nfunction explainRejectedToken(error: InvalidAgentTokenError, reason: RejectedTokenReason): Error {\n if (reason === 'envToken') {\n return new Error(`${error.message} Pair again and update KUBB_AGENT_TOKEN.`)\n }\n\n if (reason === 'reauthExhausted') {\n return new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n }\n\n return new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n}\n\n/**\n * One `kubb studio` connect run: pairing if needed, connecting, and pairing again whenever Studio\n * rejects the token. Reached through `connect()`, which is what the command runs.\n */\nclass StudioConnection {\n readonly #options: StudioOptions\n readonly #configPath: string\n readonly #shutdown = new AbortController()\n readonly #requestShutdown = (): void => this.#shutdown.abort()\n // `bun-types` narrows `process.on`/`process.off` to its own event union, which omits Node's\n // process signal events, so the listener is installed and removed through the plain emitter API.\n readonly #processEvents = process as unknown as NodeJS.EventEmitter\n\n // Known once `run()` resolves the initial credentials, before anything else reads this field.\n #credentials!: Credentials\n // Whether the \"Press Ctrl+C\" hint already printed, so a reconnect never repeats it.\n #hinted = false\n // One automatic re-pair per run, whether the rejection lands at startup or once the session is\n // live. A token rejected right after a fresh login is a hard failure, not a reason to keep\n // pairing.\n #hasReauthenticated = false\n // Resolved by `run()` from the flags and the project's saved answers, before anything reads it.\n #granted!: Record<Permission, boolean>\n\n constructor(options: StudioOptions, configPath: string) {\n this.#options = options\n this.#configPath = configPath\n }\n\n #reportDisconnected(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n logOutro('Disconnected')\n }\n\n /**\n * Connects and streams generation events until the process is stopped or Studio rejects the\n * token.\n *\n * One `AbortController` covers the whole run: it cancels an in-flight pairing poll on Ctrl+C and\n * ends the wait in `#connectAndWait`. Its signal listeners are armed once here, so a retried\n * pairing cannot leave a duplicate behind.\n */\n async run(): Promise<void> {\n this.#processEvents.once('SIGINT', this.#requestShutdown)\n this.#processEvents.once('SIGTERM', this.#requestShutdown)\n\n try {\n this.#credentials = await this.#resolveInitialCredentials()\n\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n this.#printBanner()\n\n const outcome = await runConnection({\n credentials: this.#credentials,\n signal: this.#shutdown.signal,\n clientOptions: () => this.#clientOptions(),\n onTokenRejected: ({ error, live }) => this.#handleRejection(error, live),\n })\n\n if (outcome === 'shutdown') {\n this.#reportDisconnected()\n }\n } catch (error) {\n // Canceling the very first pairing (before anything was ever connected) is Ctrl+C working as\n // intended, not a failure to report.\n if (error instanceof PairingCanceledError) {\n return\n }\n\n throw error\n } finally {\n this.#processEvents.off('SIGINT', this.#requestShutdown)\n this.#processEvents.off('SIGTERM', this.#requestShutdown)\n }\n }\n\n async #resolveInitialCredentials(): Promise<Credentials> {\n const envToken = process.env.KUBB_AGENT_TOKEN\n const stored = envToken ? null : await readCredentials()\n\n // A credential is only reused for the Studio it was issued by, so switching `--url` re-pairs\n // instead of sending one instance's token to another.\n const resolved = envToken\n ? { studioUrl: this.#options.studioUrl, token: envToken, agentId: '', agentSlug: '' }\n : stored?.studioUrl === this.#options.studioUrl\n ? stored\n : null\n\n if (resolved) {\n return resolved\n }\n\n if (isCIEnvironment()) {\n throw new Error(`Not paired with ${this.#options.studioUrl}. Set KUBB_AGENT_TOKEN, or run \\`kubb studio login\\` on a machine with a browser.`)\n }\n\n return login(this.#options, { signal: this.#shutdown.signal })\n }\n\n #printBanner(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n const detail = (label: string, value: string) => `${styleText('dim', label.padEnd(7))} ${value}`\n\n logBlock([\n detail('Studio', styleText('cyan', this.#options.studioUrl)),\n detail('Project', path.basename(process.cwd())),\n detail('Config', path.relative(process.cwd(), this.#configPath) || this.#configPath),\n '',\n styleText('dim', 'Permissions'),\n ...formatPermissionRows(this.#granted),\n ])\n }\n\n /**\n * What every connection attempt opens with. Rebuilt per attempt, so a re-pair that changed the\n * granted permissions takes effect on the next one.\n */\n #clientOptions(): Omit<ClientOptions, 'token' | 'onAuthRequired'> {\n return {\n studioUrl: this.#options.studioUrl,\n configPath: this.#configPath,\n version: this.#options.version,\n // Reloaded on every generate, so an edit to kubb.config.ts is picked up without reconnecting.\n loadConfig: async () => (await loadConfigs(this.#options)).config,\n client: { kind: 'cli' },\n root: process.cwd(),\n permissions: this.#granted,\n // The loggers `kubb generate` installs, so one place renders the session events and the\n // generations it drives.\n installLogger: async (hooks) => {\n await setupReporters(hooks, { logLevel: logLevelMap[this.#options.logLevel ?? 'info'], reporters: [cliReporter] })\n\n // `client.connect()` resolves once the agent is registered, not once a session is open, so\n // this is the only point that knows the connection is live. Registered after the loggers so\n // it lands under their \"Connected to ...\" line, and once, since every reconnect fires again.\n hooks.hook('studio:connected', () => {\n if (this.#hinted || this.#options.logLevel === 'silent') {\n return\n }\n this.#hinted = true\n\n logBlock(styleText('dim', 'Press Ctrl+C to disconnect'))\n })\n },\n }\n }\n\n /**\n * Throws when a rejected token cannot be replaced by pairing again: this run already paired once\n * and was rejected anyway, or there is no browser to approve a new pairing.\n */\n #assertCanReauthenticate(error: InvalidAgentTokenError): void {\n if (this.#hasReauthenticated) {\n throw explainRejectedToken(error, 'reauthExhausted')\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n throw explainRejectedToken(error, 'nonInteractive')\n }\n }\n\n /**\n * Studio rejected the token, either before a session ever opened or once one was already live.\n * Keeping a rejected token only produces 401s on every run, so it is forgotten and paired again.\n * Returns the credential to reconnect with, or null when the run is over.\n */\n async #handleRejection(error: InvalidAgentTokenError, live: boolean): Promise<Credentials | null> {\n // An operator-supplied token is never replaced automatically.\n if (process.env.KUBB_AGENT_TOKEN) {\n throw explainRejectedToken(error, 'envToken')\n }\n\n // A token dead at startup is forgotten either way. A live one is only forgotten once this run\n // knows it can pair again, so a CI run keeps the credential it could not replace.\n if (!live) {\n await clearCredentials()\n }\n\n this.#assertCanReauthenticate(error)\n\n console.log(styleText('yellow', live ? `${error.message} Studio needs you to approve access again.` : `${error.message} Pairing again...`))\n\n if (live) {\n await clearCredentials()\n }\n\n const credentials = await this.#reauthenticate()\n\n // Nothing was ever connected at startup, so there is no session to report the end of.\n if (!credentials && live) {\n this.#reportDisconnected()\n }\n\n return credentials\n }\n\n /**\n * Re-pairs and stores the resulting credentials. Returns null when the operator canceled it.\n */\n async #reauthenticate(): Promise<Credentials | null> {\n try {\n this.#credentials = await login(this.#options, { signal: this.#shutdown.signal, previousCredentials: this.#credentials })\n } catch (loginError) {\n if (loginError instanceof PairingCanceledError) {\n return null\n }\n throw loginError\n }\n\n this.#hasReauthenticated = true\n\n // The approved agent may be a different identity, whose saved permissions did not carry\n // forward. Resolving again asks for whatever this credential does not already hold, instead\n // of handing the new agent what the previous one was granted.\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n return this.#credentials\n }\n}\n\n/**\n * Connects this project to Studio and streams generation events until the process is stopped or\n * Studio rejects the token.\n */\nexport async function connect(options: StudioOptions): Promise<void> {\n // Resolved before any network call to Studio (pairing included), so a project with no config\n // fails fast instead of starting a device-authorization flow it can never use.\n const { configPath } = await loadConfigs(options)\n\n await new StudioConnection(options, configPath).run()\n}\n\n/**\n * Reports the paired agent and any saved permissions for the current project.\n */\nasync function status(options: StudioOptions): Promise<void> {\n const credentials = await readCredentials()\n\n if (!credentials) {\n console.log('Not paired. Run `kubb studio login`.')\n\n return\n }\n\n console.log(`Paired with ${credentials.studioUrl} as ${styleText('cyan', credentials.agentSlug || credentials.agentId)}`)\n\n if (credentials.studioUrl !== options.studioUrl) {\n console.log(styleText('yellow', `Connecting to ${options.studioUrl} needs pairing again.`))\n }\n\n const remembered = credentials.projects?.[process.cwd()]\n\n if (!remembered) {\n console.log(styleText('dim', 'No saved permissions for this project. Run `kubb studio` to connect and choose.'))\n\n return\n }\n\n console.log(styleText('dim', 'Saved permissions'))\n\n for (const row of formatPermissionRows({\n allowWrite: remembered.allowWrite === true,\n allowConfigEdit: remembered.allowConfigEdit === true,\n allowInput: remembered.allowInput === true,\n allowExec: remembered.allowExec === true,\n })) {\n console.log(row)\n }\n}\n\n/**\n * Runs a `kubb studio` action and reports the outcome to telemetry.\n */\nasync function run(options: StudioOptions): Promise<void> {\n // The machine secret lives here and pairing binds it, so storage is installed before anything\n // reads `getMachineToken()`, which `startPairing` does, before any client exists.\n setStorage(createFileStorage(path.join(getKubbHome(), 'cache')))\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'studio', kubbVersion: options.version, hrStart, status }))\n\n try {\n if (options.logLevel !== 'silent') {\n logIntro({\n title: `Kubb Studio ${styleText('dim', `v${options.version}`)}`,\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n // Only `connect` stays open long enough to close the block again with `logOutro`.\n block: options.action === 'connect',\n })\n }\n\n switch (options.action) {\n case 'login':\n await login(options)\n break\n case 'logout':\n await clearCredentials()\n console.log('Signed out of Kubb Studio.')\n break\n case 'status':\n await status(options)\n break\n case 'connect':\n await connect(options)\n break\n default:\n throw new Error(`Unknown action \"${options.action}\", expected one of ${ACTIONS.join(', ')}`)\n }\n\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n\n/**\n * Maps the parsed `kubb studio` flags onto {@link run}. Loaded on demand by `index.ts`, so the\n * Studio client stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async ({ values }) => {\n await run({\n action: (values.action ?? 'connect') as StudioAction,\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: {\n allowWrite: values.allowWrite,\n allowConfigEdit: values.allowConfigEdit,\n allowInput: values.allowInput,\n allowExec: values.allowExec,\n },\n autoOpen: values.open,\n logLevel: values.logLevel,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAIA,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,QAAA,GAAOC,iBAAAA,SAAAA,CAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;AAsGA,eAAsB,MAAM,MAA6B;CACvD,QAAA,GAAOC,iBAAAA,GAAAA,CAAG,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;AAClD;;;;;;;ACrIA,SAAgB,cAAsB;CACpC,OAAOC,aAAAA,QAAQ,IAAI,aAAaC,UAAAA,QAAK,MAAA,GAAKC,QAAAA,QAAAA,CAAQ,GAAG,OAAO;AAC9D;AAEA,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAOD,UAAAA,QAAK,KAAK,YAAY,GAAG,oBAAoB;AACtD;;;;;;A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A,UAAAA,CAAU,UAAU,2DAA2D;GAExF,OAAO,QAAQ,WAAW;EAC5B,CAAC;EAGH,QAAQ,QAAQ,QAAhB;GACE,KAAK;IACH,MAAM,MAAM,OAAO;IACnB;GACF,KAAK;IACH,MAAM,iBAAiB;IACvB,QAAQ,IAAI,4BAA4B;IACxC;GACF,KAAK;IACH,MAAM,OAAO,OAAO;IACpB;GACF,KAAK;IACH,MAAM,QAAQ,OAAO;IACrB;GACF,SACE,MAAM,IAAI,MAAM,mBAAmB,QAAQ,OAAO,qBAAqB,QAAQ,KAAK,IAAI,GAAG;EAC/F;EAEA,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAMgB,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF;;;;;AAMA,MAAa,SAA0E,OAAO,EAAE,aAAa;CAC3G,MAAM,IAAI;EACR,QAAS,OAAO,UAAU;EAC1B,SAAA,gBAAA;EACA,YAAY,OAAO;EACnB,WAAW,OAAO,OAAOC,aAAAA;EACzB,YAAY;GACV,YAAY,OAAO;GACnB,iBAAiB,OAAO;GACxB,YAAY,OAAO;GACnB,WAAW,OAAO;EACpB;EACA,UAAU,OAAO;EACjB,UAAU,OAAO;CACnB,CAAC;AACH"}
1
+ {"version":3,"file":"run-U-2mO4sy.cjs","names":["runtime","readFile","rm","process","path","homedir","mkdir","writeFile","process","x","startPairing","path","hostname","styleText","createSpinner","pollForPairingToken","PairingCanceledError","KUBB_CONFIG_FILENAME","isCIEnvironment","canUseTTY","prompts","getConfigs","runConnection","setupReporters","logLevelMap","cliReporter","createFileStorage","sendTelemetry","buildTelemetryEvent","toError","defaultStudioUrl"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.ts","../src/runners/studio/run.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { clean, read } from '@internals/utils'\n\n/**\n * Root for everything the CLI persists between runs: the paired credential, the machine secret,\n * the last Studio config, and the live-session registry. `KUBB_HOME` relocates all of it.\n */\nexport function getKubbHome(): string {\n return process.env.KUBB_HOME ?? path.join(homedir(), '.kubb')\n}\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowWrite?: boolean; allowConfigEdit?: boolean; allowInput?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const raw = await read(getCredentialsPath()).catch(() => null)\n if (!raw) {\n return null\n }\n\n try {\n return JSON.parse(raw) as Credentials\n } catch {\n return null\n }\n}\n\n/**\n * Writes the credential with owner-only permissions. The file holds a bearer token, so the mode\n * is set at creation time rather than left to the process umask or fixed up afterward, which\n * would leave the token briefly readable under the umask's default mode.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n const file = getCredentialsPath()\n\n await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })\n await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 0o600 })\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await clean(getCredentialsPath())\n}\n","import { hostname } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport {\n createFileStorage,\n type ClientOptions,\n defaultStudioUrl,\n type InvalidAgentTokenError,\n PairingCanceledError,\n pollForPairingToken,\n runConnection,\n setStorage,\n startPairing,\n} from '@kubb/studio'\nimport { x } from 'tinyexec'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/studio.ts'\nimport setupReporters from '../../loggers/utils.ts'\nimport { createSpinner, logBlock, logIntro, logOutro } from '../../loggers/output.ts'\nimport { canUseTTY, isCIEnvironment } from '../../utils/env.ts'\nimport { getConfigs } from '../generate/utils.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getKubbHome, readCredentials, writeCredentials } from './credentials.ts'\n\nconst ACTIONS = ['connect', 'login', 'logout', 'status'] as const\n\nexport type StudioAction = (typeof ACTIONS)[number]\n\ntype Permission = 'allowWrite' | 'allowConfigEdit' | 'allowInput' | 'allowExec'\n\nexport type StudioOptions = {\n action: StudioAction\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<Permission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\n/**\n * Opens a URL in the user's browser. Best effort: a failure just means the user follows the\n * printed link instead.\n *\n * `start` is a `cmd.exe` builtin, not an executable on PATH, so Windows runs it through `cmd`.\n * The empty string is the window-title argument `start` expects before the URL.\n */\nasync function openInBrowser(url: string): Promise<void> {\n try {\n if (process.platform === 'win32') {\n await x('cmd', ['/c', 'start', '', url])\n } else {\n await x(process.platform === 'darwin' ? 'open' : 'xdg-open', [url])\n }\n } catch {}\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nasync function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const session = await startPairing({ studioUrl, name: path.basename(process.cwd()), hostname: hostname(), signal })\n\n console.log(`\\nOpen ${styleText('cyan', session.verification_uri)} and approve the code ${styleText('bold', session.user_code)}`)\n\n if (autoOpen) {\n await openInBrowser(session.verification_uri_complete)\n }\n\n const spinner = createSpinner()\n spinner.start('Waiting for approval')\n\n try {\n const { token, agent } = await pollForPairingToken({ studioUrl, session, signal })\n spinner.stop(`Paired as ${agent.name}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n throw error\n }\n}\n\n/**\n * What each permission is asked as, in the order the questions appear.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: Permission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n question: (project: string, configPath: string) => string\n}> = [\n { key: 'allowWrite', label: 'write generated files', question: (project) => `Let Kubb Studio write generated files into ${project}?` },\n {\n key: 'allowConfigEdit',\n label: 'edit kubb.config.ts',\n question: (_project, configPath) => `Let Kubb Studio change plugin options in ${configPath}?`,\n },\n {\n key: 'allowInput',\n label: 'use a Studio spec',\n question: () => 'Let Kubb Studio generate from an OpenAPI spec it sends, instead of the one on disk?',\n },\n {\n key: 'allowExec',\n label: 'run formatter, linter, postGenerate',\n question: () => 'Let Kubb Studio run the formatter, the linter, and output.postGenerate?',\n },\n]\n\n/**\n * One row per permission, for the connect banner and `kubb studio status`. A list rather than a\n * joined line: four labels this long read as one run-on sentence side by side.\n */\nexport function formatPermissionRows(granted: Record<Permission, boolean>): Array<string> {\n return PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✔') : styleText('red', '✘')} ${label}`)\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and new answers are stored unless `persist` is false.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n /**\n * Stores new answers in `~/.kubb/credentials.json`.\n * Pass `false` for `KUBB_AGENT_TOKEN` sessions so a temporary token is not written back to disk.\n */\n persist = true,\n): Promise<Record<Permission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted: Record<Permission, boolean> = { allowWrite: false, allowConfigEdit: false, allowInput: false, allowExec: false }\n const answers: Partial<Record<Permission, boolean>> = {}\n\n for (const { key, question } of PERMISSIONS) {\n if (options.permission[key] || typeof remembered?.[key] === 'boolean') {\n granted[key] = options.permission[key] || remembered?.[key] === true\n continue\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n granted[key] = false\n continue\n }\n\n granted[key] = (await prompts.confirm({ message: question(project, configPath), initialValue: false })) === true\n answers[key] = granted[key]\n }\n\n if (persist && Object.keys(answers).length) {\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n }\n\n return granted\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does.\n * Returns the first config.\n */\nasync function loadConfigs(options: StudioOptions): Promise<{ configPath: string; config: Config }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n const [config] = configs\n\n if (!config) {\n throw new Error('Config not defined, create a kubb.config.ts or pass it with --config')\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, config }\n}\n\n/**\n * Why a rejected token could not be recovered automatically: it came from `KUBB_AGENT_TOKEN`, no\n * browser is available to re-pair with, or the token this run already re-paired for was rejected\n * again.\n */\ntype RejectedTokenReason = 'envToken' | 'nonInteractive' | 'reauthExhausted'\n\n/**\n * Explains a rejected token to the operator. Builds the error and nothing else, so each caller\n * decides what happens to the credentials.\n */\nfunction explainRejectedToken(error: InvalidAgentTokenError, reason: RejectedTokenReason): Error {\n if (reason === 'envToken') {\n return new Error(`${error.message} Pair again and update KUBB_AGENT_TOKEN.`)\n }\n\n if (reason === 'reauthExhausted') {\n return new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n }\n\n return new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n}\n\n/**\n * One `kubb studio` connect run: pairing if needed, connecting, and pairing again whenever Studio\n * rejects the token. Reached through `connect()`, which is what the command runs.\n */\nclass StudioConnection {\n readonly #options: StudioOptions\n readonly #configPath: string\n readonly #shutdown = new AbortController()\n readonly #requestShutdown = (): void => this.#shutdown.abort()\n // `bun-types` narrows `process.on`/`process.off` to its own event union, which omits Node's\n // process signal events, so the listener is installed and removed through the plain emitter API.\n readonly #processEvents = process as unknown as NodeJS.EventEmitter\n\n // Known once `run()` resolves the initial credentials, before anything else reads this field.\n #credentials!: Credentials\n // Whether the \"Press Ctrl+C\" hint already printed, so a reconnect never repeats it.\n #hinted = false\n // One automatic re-pair per run, whether the rejection lands at startup or once the session is\n // live. A token rejected right after a fresh login is a hard failure, not a reason to keep\n // pairing.\n #hasReauthenticated = false\n // Resolved by `run()` from the flags and the project's saved answers, before anything reads it.\n #granted!: Record<Permission, boolean>\n\n constructor(options: StudioOptions, configPath: string) {\n this.#options = options\n this.#configPath = configPath\n }\n\n #reportDisconnected(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n logOutro('Disconnected')\n }\n\n /**\n * Connects and streams generation events until the process is stopped or Studio rejects the\n * token.\n *\n * One `AbortController` covers the whole run: it cancels an in-flight pairing poll on Ctrl+C and\n * ends the wait in `#connectAndWait`. Its signal listeners are armed once here, so a retried\n * pairing cannot leave a duplicate behind.\n */\n async run(): Promise<void> {\n this.#processEvents.once('SIGINT', this.#requestShutdown)\n this.#processEvents.once('SIGTERM', this.#requestShutdown)\n\n try {\n this.#credentials = await this.#resolveInitialCredentials()\n\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n this.#printBanner()\n\n const outcome = await runConnection({\n credentials: this.#credentials,\n signal: this.#shutdown.signal,\n clientOptions: () => this.#clientOptions(),\n onTokenRejected: ({ error, live }) => this.#handleRejection(error, live),\n })\n\n if (outcome === 'shutdown') {\n this.#reportDisconnected()\n }\n } catch (error) {\n // Canceling the very first pairing (before anything was ever connected) is Ctrl+C working as\n // intended, not a failure to report.\n if (error instanceof PairingCanceledError) {\n return\n }\n\n throw error\n } finally {\n this.#processEvents.off('SIGINT', this.#requestShutdown)\n this.#processEvents.off('SIGTERM', this.#requestShutdown)\n }\n }\n\n async #resolveInitialCredentials(): Promise<Credentials> {\n const envToken = process.env.KUBB_AGENT_TOKEN\n const stored = envToken ? null : await readCredentials()\n\n // A credential is only reused for the Studio it was issued by, so switching `--url` re-pairs\n // instead of sending one instance's token to another.\n const resolved = envToken\n ? { studioUrl: this.#options.studioUrl, token: envToken, agentId: '', agentSlug: '' }\n : stored?.studioUrl === this.#options.studioUrl\n ? stored\n : null\n\n if (resolved) {\n return resolved\n }\n\n if (isCIEnvironment()) {\n throw new Error(`Not paired with ${this.#options.studioUrl}. Set KUBB_AGENT_TOKEN, or run \\`kubb studio login\\` on a machine with a browser.`)\n }\n\n return login(this.#options, { signal: this.#shutdown.signal })\n }\n\n #printBanner(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n const detail = (label: string, value: string) => `${styleText('dim', label.padEnd(7))} ${value}`\n\n logBlock([\n detail('Studio', styleText('cyan', this.#options.studioUrl)),\n detail('Project', path.basename(process.cwd())),\n detail('Config', path.relative(process.cwd(), this.#configPath) || this.#configPath),\n '',\n styleText('dim', 'Permissions'),\n ...formatPermissionRows(this.#granted),\n ])\n }\n\n /**\n * What every connection attempt opens with. Rebuilt per attempt, so a re-pair that changed the\n * granted permissions takes effect on the next one.\n */\n #clientOptions(): Omit<ClientOptions, 'token' | 'onAuthRequired'> {\n return {\n studioUrl: this.#options.studioUrl,\n configPath: this.#configPath,\n version: this.#options.version,\n // Reloaded on every generate, so an edit to kubb.config.ts is picked up without reconnecting.\n loadConfig: async () => (await loadConfigs(this.#options)).config,\n client: { kind: 'cli' },\n root: process.cwd(),\n permissions: this.#granted,\n // The loggers `kubb generate` installs, so one place renders the session events and the\n // generations it drives.\n installLogger: async (hooks) => {\n await setupReporters(hooks, { logLevel: logLevelMap[this.#options.logLevel ?? 'info'], reporters: [cliReporter] })\n\n // `client.connect()` resolves once the agent is registered, not once a session is open, so\n // this is the only point that knows the connection is live. Registered after the loggers so\n // it lands under their \"Connected to ...\" line, and once, since every reconnect fires again.\n hooks.hook('studio:connected', () => {\n if (this.#hinted || this.#options.logLevel === 'silent') {\n return\n }\n this.#hinted = true\n\n logBlock(styleText('dim', 'Press Ctrl+C to disconnect'))\n })\n },\n }\n }\n\n /**\n * Throws when a rejected token cannot be replaced by pairing again: this run already paired once\n * and was rejected anyway, or there is no browser to approve a new pairing.\n */\n #assertCanReauthenticate(error: InvalidAgentTokenError): void {\n if (this.#hasReauthenticated) {\n throw explainRejectedToken(error, 'reauthExhausted')\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n throw explainRejectedToken(error, 'nonInteractive')\n }\n }\n\n /**\n * Studio rejected the token, either before a session ever opened or once one was already live.\n * Keeping a rejected token only produces 401s on every run, so it is forgotten and paired again.\n * Returns the credential to reconnect with, or null when the run is over.\n */\n async #handleRejection(error: InvalidAgentTokenError, live: boolean): Promise<Credentials | null> {\n // An operator-supplied token is never replaced automatically.\n if (process.env.KUBB_AGENT_TOKEN) {\n throw explainRejectedToken(error, 'envToken')\n }\n\n // A token dead at startup is forgotten either way. A live one is only forgotten once this run\n // knows it can pair again, so a CI run keeps the credential it could not replace.\n if (!live) {\n await clearCredentials()\n }\n\n this.#assertCanReauthenticate(error)\n\n console.log(styleText('yellow', live ? `${error.message} Studio needs you to approve access again.` : `${error.message} Pairing again...`))\n\n if (live) {\n await clearCredentials()\n }\n\n const credentials = await this.#reauthenticate()\n\n // Nothing was ever connected at startup, so there is no session to report the end of.\n if (!credentials && live) {\n this.#reportDisconnected()\n }\n\n return credentials\n }\n\n /**\n * Re-pairs and stores the resulting credentials. Returns null when the operator canceled it.\n */\n async #reauthenticate(): Promise<Credentials | null> {\n try {\n this.#credentials = await login(this.#options, { signal: this.#shutdown.signal, previousCredentials: this.#credentials })\n } catch (loginError) {\n if (loginError instanceof PairingCanceledError) {\n return null\n }\n throw loginError\n }\n\n this.#hasReauthenticated = true\n\n // The approved agent may be a different identity, whose saved permissions did not carry\n // forward. Resolving again asks for whatever this credential does not already hold, instead\n // of handing the new agent what the previous one was granted.\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n return this.#credentials\n }\n}\n\n/**\n * Connects this project to Studio and streams generation events until the process is stopped or\n * Studio rejects the token.\n */\nexport async function connect(options: StudioOptions): Promise<void> {\n // Resolved before any network call to Studio (pairing included), so a project with no config\n // fails fast instead of starting a device-authorization flow it can never use.\n const { configPath } = await loadConfigs(options)\n\n await new StudioConnection(options, configPath).run()\n}\n\n/**\n * Reports the paired agent and any saved permissions for the current project.\n */\nasync function status(options: StudioOptions): Promise<void> {\n const credentials = await readCredentials()\n\n if (!credentials) {\n console.log('Not paired. Run `kubb studio login`.')\n\n return\n }\n\n console.log(`Paired with ${credentials.studioUrl} as ${styleText('cyan', credentials.agentSlug || credentials.agentId)}`)\n\n if (credentials.studioUrl !== options.studioUrl) {\n console.log(styleText('yellow', `Connecting to ${options.studioUrl} needs pairing again.`))\n }\n\n const remembered = credentials.projects?.[process.cwd()]\n\n if (!remembered) {\n console.log(styleText('dim', 'No saved permissions for this project. Run `kubb studio` to connect and choose.'))\n\n return\n }\n\n console.log(styleText('dim', 'Saved permissions'))\n\n for (const row of formatPermissionRows({\n allowWrite: remembered.allowWrite === true,\n allowConfigEdit: remembered.allowConfigEdit === true,\n allowInput: remembered.allowInput === true,\n allowExec: remembered.allowExec === true,\n })) {\n console.log(row)\n }\n}\n\n/**\n * Runs a `kubb studio` action and reports the outcome to telemetry.\n */\nasync function run(options: StudioOptions): Promise<void> {\n // The machine secret lives here and pairing binds it, so storage is installed before anything\n // reads `getMachineToken()`, which `startPairing` does, before any client exists.\n setStorage(createFileStorage(path.join(getKubbHome(), 'cache')))\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'studio', kubbVersion: options.version, hrStart, status }))\n\n try {\n if (options.logLevel !== 'silent') {\n logIntro({\n title: `Kubb Studio ${styleText('dim', `v${options.version}`)}`,\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n // Only `connect` stays open long enough to close the block again with `logOutro`.\n block: options.action === 'connect',\n })\n }\n\n switch (options.action) {\n case 'login':\n await login(options)\n break\n case 'logout':\n await clearCredentials()\n console.log('Signed out of Kubb Studio.')\n break\n case 'status':\n await status(options)\n break\n case 'connect':\n await connect(options)\n break\n default:\n throw new Error(`Unknown action \"${options.action}\", expected one of ${ACTIONS.join(', ')}`)\n }\n\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n\n/**\n * Maps the parsed `kubb studio` flags onto {@link run}. Loaded on demand by `index.ts`, so the\n * Studio client stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async ({ values }) => {\n await run({\n action: (values.action ?? 'connect') as StudioAction,\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: {\n allowWrite: values.allowWrite,\n allowConfigEdit: values.allowConfigEdit,\n allowInput: values.allowInput,\n allowExec: values.allowExec,\n },\n autoOpen: values.open,\n logLevel: values.logLevel,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAIA,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,QAAA,GAAOC,iBAAAA,SAAAA,CAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;AAsGA,eAAsB,MAAM,MAA6B;CACvD,QAAA,GAAOC,iBAAAA,GAAAA,CAAG,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;AAClD;;;;;;;ACrIA,SAAgB,cAAsB;CACpC,OAAOC,aAAAA,QAAQ,IAAI,aAAaC,UAAAA,QAAK,MAAA,GAAKC,QAAAA,QAAAA,CAAQ,GAAG,OAAO;AAC9D;AAEA,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAOD,UAAAA,QAAK,KAAK,YAAY,GAAG,oBAAoB;AACtD;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,MAAM,MAAM,MAAM,KAAK,mBAAmB,CAAC,CAAC,CAAC,YAAY,IAAI;CAC7D,IAAI,CAAC,KACH,OAAO;CAGT,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,eAAsB,iBAAiB,aAAyC;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AO;IACpB;GACF,KAAK;IACH,MAAM,QAAQ,OAAO;IACrB;GACF,SACE,MAAM,IAAI,MAAM,mBAAmB,QAAQ,OAAO,qBAAqB,QAAQ,KAAK,IAAI,GAAG;EAC/F;EAEA,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAMgB,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF;;;;;AAMA,MAAa,SAA0E,OAAO,EAAE,aAAa;CAC3G,MAAM,IAAI;EACR,QAAS,OAAO,UAAU;EAC1B,SAAA,gBAAA;EACA,YAAY,OAAO;EACnB,WAAW,OAAO,OAAOC,aAAAA;EACzB,YAAY;GACV,YAAY,OAAO;GACnB,iBAAiB,OAAO;GACxB,YAAY,OAAO;GACnB,WAAW,OAAO;EACpB;EACA,UAAU,OAAO;EACjB,UAAU,OAAO;CACnB,CAAC;AACH"}
@@ -1,7 +1,7 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-qbf5tadS.cjs");
2
2
  const require_errors = require("./errors-C-wEou02.cjs");
3
- const require_Telemetry = require("./Telemetry-DKfJQxnC.cjs");
4
- const require_package = require("./package-B45PcHOn.cjs");
3
+ const require_Telemetry = require("./Telemetry-C-y1OMHs.cjs");
4
+ const require_package = require("./package-eWXYqkSG.cjs");
5
5
  let node_util = require("node:util");
6
6
  let node_process = require("node:process");
7
7
  node_process = require_rolldown_runtime.__toESM(node_process, 1);
@@ -38,4 +38,4 @@ const runner = async () => {
38
38
  //#endregion
39
39
  exports.runner = runner;
40
40
 
41
- //# sourceMappingURL=run-DuRIXbnI.cjs.map
41
+ //# sourceMappingURL=run-_zc-3Bvw.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-DuRIXbnI.cjs","names":["process","sendTelemetry","buildTelemetryEvent","styleText","toError"],"sources":["../src/runners/mcp/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type * as McpModule from '@kubb/mcp'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/mcp.ts'\n\ntype McpOptions = {\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Starts the `@kubb/mcp` server over stdio and reports the outcome to telemetry.\n */\nexport async function run({ version }: McpOptions): Promise<void> {\n const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'mcp', kubbVersion: version, hrStart, status }))\n\n try {\n console.log(styleText('cyan', '⏳ Starting MCP server...'))\n console.warn(styleText('yellow', 'This feature is still under development, use with caution'))\n\n await startMcpServer()\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n\n/**\n * Loaded on demand by `index.ts`, so `@kubb/mcp` stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async () => {\n await run({ version })\n}\n"],"mappings":";;;;;;;;;;;AAmBA,eAAsB,IAAI,EAAE,WAAsC;CAChE,MAAM,EAAE,KAAK,mBAAoB,MAAM,OAAO;CAE9C,MAAM,UAAUA,aAAAA,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiCC,kBAAAA,cAAcC,kBAAAA,oBAAoB;EAAE,SAAS;EAAO,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAE7I,IAAI;EACF,QAAQ,KAAA,GAAIC,UAAAA,UAAAA,CAAU,QAAQ,0BAA0B,CAAC;EACzD,QAAQ,MAAA,GAAKA,UAAAA,UAAAA,CAAU,UAAU,2DAA2D,CAAC;EAE7F,MAAM,eAAe;EACrB,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAMC,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF;;;;AAKA,MAAa,SAA0E,YAAY;CACjG,MAAM,IAAI,EAAE,SAAA,gBAAA,QAAQ,CAAC;AACvB"}
1
+ {"version":3,"file":"run-_zc-3Bvw.cjs","names":["process","sendTelemetry","buildTelemetryEvent","styleText","toError"],"sources":["../src/runners/mcp/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type * as McpModule from '@kubb/mcp'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/mcp.ts'\n\ntype McpOptions = {\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Starts the `@kubb/mcp` server over stdio and reports the outcome to telemetry.\n */\nexport async function run({ version }: McpOptions): Promise<void> {\n const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'mcp', kubbVersion: version, hrStart, status }))\n\n try {\n console.log(styleText('cyan', '⏳ Starting MCP server...'))\n console.warn(styleText('yellow', 'This feature is still under development, use with caution'))\n\n await startMcpServer()\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n\n/**\n * Loaded on demand by `index.ts`, so `@kubb/mcp` stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async () => {\n await run({ version })\n}\n"],"mappings":";;;;;;;;;;;AAmBA,eAAsB,IAAI,EAAE,WAAsC;CAChE,MAAM,EAAE,KAAK,mBAAoB,MAAM,OAAO;CAE9C,MAAM,UAAUA,aAAAA,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiCC,kBAAAA,cAAcC,kBAAAA,oBAAoB;EAAE,SAAS;EAAO,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAE7I,IAAI;EACF,QAAQ,KAAA,GAAIC,UAAAA,UAAAA,CAAU,QAAQ,0BAA0B,CAAC;EACzD,QAAQ,MAAA,GAAKA,UAAAA,UAAAA,CAAU,UAAU,2DAA2D,CAAC;EAE7F,MAAM,eAAe;EACrB,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAMC,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF;;;;AAKA,MAAa,SAA0E,YAAY;CACjG,MAAM,IAAI,EAAE,SAAA,gBAAA,QAAQ,CAAC;AACvB"}
@@ -1,6 +1,6 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
2
  import { t as toError } from "./errors-C8yNfV7w.js";
3
- import { s as WATCHER_IGNORED_PATHS } from "./Telemetry-BCTY-Nzq.js";
3
+ import { c as URL_WATCHER_TIMEOUT_MS, l as WATCHER_IGNORED_PATHS, s as URL_WATCHER_INTERVAL_MS } from "./Telemetry-DIDDCARm.js";
4
4
  import { i as getAgentName, t as canUseTTY } from "./env-DqPKEL59.js";
5
5
  import { styleText } from "node:util";
6
6
  import { randomUUID } from "node:crypto";
@@ -1160,7 +1160,81 @@ async function startWatcher(path, cb, log = {
1160
1160
  }, 100);
1161
1161
  });
1162
1162
  }
1163
+ /**
1164
+ * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a
1165
+ * readable 2xx body within the timeout. The caller seeds `startUrlWatcher` with the result, so
1166
+ * the watcher compares polls against the content the initial build ran on.
1167
+ */
1168
+ async function fetchUrlBody(url, timeoutMs = URL_WATCHER_TIMEOUT_MS) {
1169
+ try {
1170
+ const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
1171
+ if (!response.ok) return void 0;
1172
+ return await response.text();
1173
+ } catch {
1174
+ return;
1175
+ }
1176
+ }
1177
+ /**
1178
+ * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document
1179
+ * emits no filesystem events, so this is the URL counterpart of `startWatcher`.
1180
+ *
1181
+ * `initialBody` seeds the change detection, so an edit landing between the initial build and the
1182
+ * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported
1183
+ * once per outage and polling continues; after it recovers, a rebuild happens only when the body
1184
+ * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.
1185
+ * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.
1186
+ *
1187
+ * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)
1188
+ * can shut the watcher down without signaling the process.
1189
+ */
1190
+ function startUrlWatcher(url, cb, options = {}) {
1191
+ const { log = {
1192
+ info: console.log,
1193
+ error: console.log
1194
+ }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options;
1195
+ let lastBody = initialBody;
1196
+ let offline = false;
1197
+ let timer = null;
1198
+ let controller = null;
1199
+ let stopped = false;
1200
+ const stop = () => {
1201
+ stopped = true;
1202
+ if (timer) clearTimeout(timer);
1203
+ controller?.abort();
1204
+ };
1205
+ process$1.once("SIGINT", stop);
1206
+ process$1.once("SIGTERM", stop);
1207
+ const runBuild = createSerialRunner({
1208
+ run: () => cb([url]),
1209
+ onError: () => log.error(styleText("red", "Watcher failed"))
1210
+ });
1211
+ const poll = async () => {
1212
+ controller = new AbortController();
1213
+ try {
1214
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]);
1215
+ const response = await fetch(url, { signal });
1216
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1217
+ const body = await response.text();
1218
+ if (offline) {
1219
+ offline = false;
1220
+ log.info(styleText("yellow", `${url} is reachable again`));
1221
+ }
1222
+ const changed = lastBody !== void 0 && body !== lastBody;
1223
+ if (changed) log.info(styleText("yellow", styleText("bold", `Change detected: ${url}`)));
1224
+ if (changed || lastBody === void 0) runBuild();
1225
+ lastBody = body;
1226
+ } catch {
1227
+ if (!offline && !stopped) {
1228
+ offline = true;
1229
+ log.error(styleText("red", `Cannot reach ${url}, polling until it responds again`));
1230
+ }
1231
+ }
1232
+ if (!stopped) timer = setTimeout(() => void poll(), intervalMs);
1233
+ };
1234
+ poll();
1235
+ return stop;
1236
+ }
1163
1237
  //#endregion
1164
- export { startWatcher as a, FORMATTER_PREFERENCE as c, formatters as d, linters as f, runPostGenerate as i, LINTER_PREFERENCE as l, isNewerVersion as n, selectReporters as o, runHook as r, setupReporters as s, getConfigs as t, detectTool as u };
1238
+ export { runPostGenerate as a, selectReporters as c, LINTER_PREFERENCE as d, detectTool as f, runHook as i, setupReporters as l, linters as m, getConfigs as n, startUrlWatcher as o, formatters as p, isNewerVersion as r, startWatcher as s, fetchUrlBody as t, FORMATTER_PREFERENCE as u };
1165
1239
 
1166
- //# sourceMappingURL=utils-CzoNURwq.js.map
1240
+ //# sourceMappingURL=utils-DOpJIiJM.js.map