@kubb/cli 5.9.2 → 5.9.4
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/dist/Telemetry-ByFeVTz5.cjs +314 -0
- package/dist/Telemetry-ByFeVTz5.cjs.map +1 -0
- package/dist/Telemetry-E_BBHmnT.js +259 -0
- package/dist/Telemetry-E_BBHmnT.js.map +1 -0
- package/dist/background-CZ2nVKwB.js +1 -0
- package/dist/{background-Bh4FDWa3.cjs → background-DdUVvDwi.cjs} +7 -6
- package/dist/{background-Bh4FDWa3.cjs.map → background-DdUVvDwi.cjs.map} +1 -1
- package/dist/{background-B0YbkZ0s.js → background-H30JH70B.js} +3 -2
- package/dist/{background-B0YbkZ0s.js.map → background-H30JH70B.js.map} +1 -1
- package/dist/{reporters-B4rZOlo8.cjs → config-Ck2JHe5r.cjs} +36 -4
- package/dist/config-Ck2JHe5r.cjs.map +1 -0
- package/dist/{reporters-H21Jvrff.js → config-DxePdyxe.js} +29 -3
- package/dist/config-DxePdyxe.js.map +1 -0
- package/dist/credentials-C8tjAhTo.js +1 -0
- package/dist/credentials-CZK6zPLv.js +62 -0
- package/dist/credentials-CZK6zPLv.js.map +1 -0
- package/dist/credentials-DDaKqtJn.cjs +113 -0
- package/dist/credentials-DDaKqtJn.cjs.map +1 -0
- package/dist/index.cjs +702 -207
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +697 -206
- package/dist/index.js.map +1 -1
- package/dist/{output-BnK0scpX.cjs → output-Cd3Kmvo0.cjs} +141 -66
- package/dist/output-Cd3Kmvo0.cjs.map +1 -0
- package/dist/{output-qFt4vV7K.js → output-DS5hyqwL.js} +173 -129
- package/dist/output-DS5hyqwL.js.map +1 -0
- package/dist/{registry-B7BvdrGE.js → registry-CSXUuuCy.js} +2 -2
- package/dist/{registry-B7BvdrGE.js.map → registry-CSXUuuCy.js.map} +1 -1
- package/dist/{registry-DER9aRyg.cjs → registry-CrvQxnxy.cjs} +6 -6
- package/dist/{registry-DER9aRyg.cjs.map → registry-CrvQxnxy.cjs.map} +1 -1
- package/dist/rolldown-runtime-CPE0t6oh.cjs +53 -0
- package/dist/{run-BcMMYk7G.js → run-BPD5Vaon.js} +5 -7
- package/dist/{run-BcMMYk7G.js.map → run-BPD5Vaon.js.map} +1 -1
- package/dist/{run-e8gMz1M_.cjs → run-C0Tfrddq.cjs} +5 -6
- package/dist/{run-e8gMz1M_.cjs.map → run-C0Tfrddq.cjs.map} +1 -1
- package/dist/{run-fg0ycsS_.cjs → run-CbN00IHp.cjs} +16 -18
- package/dist/{run-fg0ycsS_.cjs.map → run-CbN00IHp.cjs.map} +1 -1
- package/dist/{run-KLPSFEv-.js → run-CecrPSop.js} +2 -3
- package/dist/{run-KLPSFEv-.js.map → run-CecrPSop.js.map} +1 -1
- package/dist/{run-BCswmM8Q.js → run-Ck04_W4q.js} +2 -3
- package/dist/{run-BCswmM8Q.js.map → run-Ck04_W4q.js.map} +1 -1
- package/dist/{run-BQQhNg8I.js → run-DcP1czVQ.js} +25 -84
- package/dist/run-DcP1czVQ.js.map +1 -0
- package/dist/{run-D8EJ2hKI.cjs → run-Dyc52IzX.cjs} +5 -6
- package/dist/{run-D8EJ2hKI.cjs.map → run-Dyc52IzX.cjs.map} +1 -1
- package/dist/{run-C8dyBAPb.cjs → run-QqLDhthl.cjs} +46 -158
- package/dist/run-QqLDhthl.cjs.map +1 -0
- package/dist/run-WkXSXG2V.js +1 -0
- package/dist/{snapshot-B45A4RfA.cjs → snapshot-NGLcfG6E.cjs} +17 -26
- package/dist/snapshot-NGLcfG6E.cjs.map +1 -0
- package/dist/{snapshot-C0WaZZiF.js → snapshot-iEjgROga.js} +15 -24
- package/dist/snapshot-iEjgROga.js.map +1 -0
- package/dist/studioWorker.js +2 -2
- package/package.json +7 -8
- package/dist/Telemetry-B_C4MVJd.cjs +0 -231
- package/dist/Telemetry-B_C4MVJd.cjs.map +0 -1
- package/dist/Telemetry-DER8LIO5.js +0 -207
- package/dist/Telemetry-DER8LIO5.js.map +0 -1
- package/dist/agent-BPIqnEl2.js +0 -59
- package/dist/agent-BPIqnEl2.js.map +0 -1
- package/dist/agent-DElUuYuy.cjs +0 -120
- package/dist/agent-DElUuYuy.cjs.map +0 -1
- package/dist/background-DSKoOwcG.js +0 -1
- package/dist/commands-BegVe5Mt.js +0 -81
- package/dist/commands-BegVe5Mt.js.map +0 -1
- package/dist/commands-hXDwA0zn.cjs +0 -87
- package/dist/commands-hXDwA0zn.cjs.map +0 -1
- package/dist/config-B6UIKcl1.js +0 -117
- package/dist/config-B6UIKcl1.js.map +0 -1
- package/dist/config-Bo9ro7vg.cjs +0 -129
- package/dist/config-Bo9ro7vg.cjs.map +0 -1
- package/dist/constants-Cii4HX64.js +0 -12
- package/dist/constants-Cii4HX64.js.map +0 -1
- package/dist/constants-Df449N47.cjs +0 -29
- package/dist/constants-Df449N47.cjs.map +0 -1
- package/dist/errors-BdA8M78q.cjs +0 -43
- package/dist/errors-BdA8M78q.cjs.map +0 -1
- package/dist/errors-DmC83ALX.js +0 -32
- package/dist/errors-DmC83ALX.js.map +0 -1
- package/dist/output-BnK0scpX.cjs.map +0 -1
- package/dist/output-qFt4vV7K.js.map +0 -1
- package/dist/reporters-B4rZOlo8.cjs.map +0 -1
- package/dist/reporters-H21Jvrff.js.map +0 -1
- package/dist/run-89YfZJuo.cjs +0 -67
- package/dist/run-89YfZJuo.cjs.map +0 -1
- package/dist/run-8HrdMihy.js +0 -1
- package/dist/run-BQQhNg8I.js.map +0 -1
- package/dist/run-BYff_byB.js +0 -71
- package/dist/run-BYff_byB.js.map +0 -1
- package/dist/run-C8dyBAPb.cjs.map +0 -1
- package/dist/run-CJHsZZB8.js +0 -178
- package/dist/run-CJHsZZB8.js.map +0 -1
- package/dist/run-Ca_OX3WZ.js +0 -105
- package/dist/run-Ca_OX3WZ.js.map +0 -1
- package/dist/run-Ct6kzKpg.cjs +0 -109
- package/dist/run-Ct6kzKpg.cjs.map +0 -1
- package/dist/run-DL2wLwBZ.cjs +0 -182
- package/dist/run-DL2wLwBZ.cjs.map +0 -1
- package/dist/run-Dej-hm91.js +0 -65
- package/dist/run-Dej-hm91.js.map +0 -1
- package/dist/run-DpAMfkm5.cjs +0 -72
- package/dist/run-DpAMfkm5.cjs.map +0 -1
- package/dist/snapshot-B45A4RfA.cjs.map +0 -1
- package/dist/snapshot-C0WaZZiF.js.map +0 -1
- package/dist/utils-BHW8kA8P.js +0 -83
- package/dist/utils-BHW8kA8P.js.map +0 -1
- package/dist/utils-BzQ46pgd.cjs +0 -109
- package/dist/utils-BzQ46pgd.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-DL2wLwBZ.cjs","names":["process","styleText","clack","fetchRegistryIndex","registryUrl","incompatibility","fs","path","detectPackageManager","createSpinner","initPackageJson","initDefaults","toRegistryId","missingPluginDependencies","KUBB_PACKAGE_NAME","installSpec","installPackages","KUBB_CONFIG_FILENAME","addToConfig"],"sources":["../../../internals/shared/src/init.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, type PluginOption } from './constants.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = [\n `import { defineConfig } from 'kubb/config'`,\n ...selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`),\n ].join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport { generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, KUBB_PACKAGE_NAME } from '@internals/shared'\nimport type { RegistryEntry } from '@kubb/core'\nimport { createSpinner, logError, logInfo, logIntro, logOutro } from '../../loggers/output.ts'\nimport { addToConfig } from '../add/run.ts'\nimport { fetchRegistryIndex, incompatibility, installSpec, registryUrl, toRegistryId } from '../../utils/registry.ts'\nimport { detectPackageManager, initPackageJson, installPackages, missingPluginDependencies } from './utils.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<NoInfer<T> | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // The plugins come from the Kubb registry, like `kubb add`, so read it before changing anything\n const plugins = (await fetchRegistryIndex({ registry: registryUrl() })).filter((entry) => entry.kind === 'plugin' && !incompatibility(entry.manifest))\n const byId = new Map(plugins.map((entry) => [entry.id, entry]))\n\n // Check/create package.json, detect package manager once after the block\n if (!fs.existsSync(path.join(cwd, 'package.json'))) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = initDefaults.plugins.flatMap((slug) => byId.get(toRegistryId(slug)) ?? [])\n const pluginLabel = (entries: Array<RegistryEntry>) => styleText('cyan', entries.map((entry) => entry.manifest.displayName).join(', '))\n\n const selectedPlugins: Array<RegistryEntry> = await (async () => {\n if (pluginsFlag) {\n const ids = pluginsFlag\n .split(',')\n .map((id) => id.trim())\n .filter(Boolean)\n const unknown = ids.filter((id) => !byId.has(toRegistryId(id)))\n if (unknown.length) throw new Error(`Not in the Kubb registry: ${unknown.join(', ')}. Browse the plugins at https://kubb.dev/extensions.`)\n const entries = ids.map((id) => byId.get(toRegistryId(id))!)\n logInfo(`Using plugins: ${pluginLabel(entries)}`)\n return entries\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: plugins.map(({ id, manifest }) => ({ value: id, label: manifest.displayName, hint: manifest.category })),\n initialValues: defaultPlugins.map((entry) => entry.id),\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return plugins.filter((entry) => (values as Array<string>).includes(entry.id))\n })()\n\n // Check the selection against the plugins' manifests before installing anything\n const missing = missingPluginDependencies({\n selected: selectedPlugins.map((entry) => entry.manifest.name),\n manifests: selectedPlugins.map((entry) => entry.manifest),\n })\n if (missing.length) {\n throw new Error(`${missing.join('\\n')}\\nAdd the missing plugins and run kubb init again.`)\n }\n\n // Install `kubb` at the running CLI's version and each plugin at the version the registry pins\n const packagesToInstall = [`${KUBB_PACKAGE_NAME}@${version}`, ...selectedPlugins.map((entry) => installSpec(entry.artifact))]\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins: [], inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n // Add each plugin the way `kubb add` does\n for (const entry of selectedPlugins) {\n const reason = await dryRun.run(() => addToConfig({ detail: entry, configFile: configPath }), {\n message: `add ${entry.manifest.export}() to ${KUBB_CONFIG_FILENAME}`,\n resolve: () => undefined,\n })\n if (reason) throw new Error(`Could not add ${entry.manifest.export}() to ${KUBB_CONFIG_FILENAME}: ${reason}`)\n }\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\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nC,MAAM,SAAS,MAAM,OAAO,UAAUC,YAAAA,YAAY;IAAE,QAAQ;IAAO,YAAY;GAAW,CAAC,GAAG;IAC5F,SAAS,OAAO,MAAM,SAAS,OAAO,QAAQD,kBAAAA;IAC9C,eAAe,KAAA;GACjB,CAAC;GACD,IAAI,QAAQ,MAAM,IAAI,MAAM,iBAAiB,MAAM,SAAS,OAAO,QAAQA,kBAAAA,qBAAqB,IAAI,QAAQ;EAC9G;EAEA,cAAc,KAAK,WAAWA,kBAAAA,sBAAsB;EAEpD,eAAA,UAAA,GACEhB,UAAAA,UAAAA,CAAU,SAAS,YAAY,IAC7B,UAAA,GACAA,UAAAA,UAAAA,CAAU,OAAO,aAAa,IAC9B,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,2CAA2C,WAAW,IACxE,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,4CAA4C,IAC9D,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,iCAAiC,YAAY,IAC/D,UAAA,GACAA,UAAAA,UAAAA,CAAU,OAAO,SAAS,eAAe,KAAK,WAAW,SAAS,CACtE;CACF,SAAS,OAAO;EACd,eAAA,UAAA,GAASA,UAAAA,UAAAA,CAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,eAAA,SAAS,MAAM,OAAO;EAExB,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
package/dist/run-Dej-hm91.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import "./rolldown-runtime-CRm0XQPb.js";
|
|
2
|
-
import { t as getErrorMessage } from "./errors-DmC83ALX.js";
|
|
3
|
-
import { a as logInfo, d as logWarn, i as logError, l as logStep, o as logIntro, r as logBlock, s as logOutro } from "./output-qFt4vV7K.js";
|
|
4
|
-
import { a as isOutdated, i as installSpec, n as fetchRegistryIndex, o as registryUrl, r as incompatibility, s as toRegistryId } from "./registry-B7BvdrGE.js";
|
|
5
|
-
import { r as installPackages, t as detectPackageManager } from "./utils-BHW8kA8P.js";
|
|
6
|
-
import { styleText } from "node:util";
|
|
7
|
-
import process from "node:process";
|
|
8
|
-
import { readInstalledPackages } from "@kubb/core";
|
|
9
|
-
import * as clack from "@clack/prompts";
|
|
10
|
-
//#region src/runners/update/run.ts
|
|
11
|
-
/**
|
|
12
|
-
* Moves installed extensions to the version the registry pins. Lists the proposals, asks, then
|
|
13
|
-
* installs them. With `check`, only lists them.
|
|
14
|
-
*/
|
|
15
|
-
async function run({ ids, check, yes }) {
|
|
16
|
-
const cwd = process.cwd();
|
|
17
|
-
logIntro({ title: styleText("bgCyan", styleText("black", " Kubb Update ")) });
|
|
18
|
-
try {
|
|
19
|
-
const wanted = new Set(ids.map(toRegistryId));
|
|
20
|
-
const [entries, installed] = await Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })]);
|
|
21
|
-
const versions = new Map(installed.map((item) => [item.package, item.version]));
|
|
22
|
-
const tracked = entries.filter((entry) => versions.has(entry.artifact.package) && (!wanted.size || wanted.has(entry.id)));
|
|
23
|
-
for (const id of wanted) if (!tracked.some((entry) => entry.id === id)) logWarn(`${id} is not installed, or not in the registry.`);
|
|
24
|
-
const proposals = tracked.filter((entry) => {
|
|
25
|
-
if (!isOutdated({
|
|
26
|
-
installed: versions.get(entry.artifact.package),
|
|
27
|
-
latest: entry.artifact.version
|
|
28
|
-
})) return false;
|
|
29
|
-
const problem = incompatibility(entry.manifest);
|
|
30
|
-
if (problem) logWarn(`Skipped ${entry.id}: ${problem}`);
|
|
31
|
-
return !problem;
|
|
32
|
-
});
|
|
33
|
-
if (!proposals.length) {
|
|
34
|
-
logOutro(ids.length ? `No updates for ${ids.join(", ")}.` : "Every installed extension is up to date.");
|
|
35
|
-
return;
|
|
36
|
-
}
|
|
37
|
-
const plural = proposals.length === 1 ? "" : "s";
|
|
38
|
-
logBlock(proposals.map(({ artifact }) => `${artifact.package} ${versions.get(artifact.package) ?? "not installed"} -> ${styleText("green", artifact.version)}`));
|
|
39
|
-
if (check) {
|
|
40
|
-
logOutro(`${proposals.length} update${plural} available. Run \`kubb update\` to install.`);
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
const confirmed = yes || await clack.confirm({
|
|
44
|
-
message: `Install ${proposals.length} update${plural}?`,
|
|
45
|
-
initialValue: true
|
|
46
|
-
});
|
|
47
|
-
if (clack.isCancel(confirmed) || !confirmed) {
|
|
48
|
-
clack.cancel("Operation canceled.");
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
const packageManager = detectPackageManager(cwd);
|
|
52
|
-
const specs = proposals.map(({ artifact }) => installSpec(artifact));
|
|
53
|
-
logStep(`Installing ${specs.join(", ")} with ${packageManager.name}`);
|
|
54
|
-
await installPackages(specs, packageManager, cwd);
|
|
55
|
-
logInfo(`Updated ${specs.length} extension${plural}`);
|
|
56
|
-
logOutro(styleText("green", "Done"));
|
|
57
|
-
} catch (error) {
|
|
58
|
-
logError(getErrorMessage(error));
|
|
59
|
-
process.exitCode = 1;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
//#endregion
|
|
63
|
-
export { run };
|
|
64
|
-
|
|
65
|
-
//# sourceMappingURL=run-Dej-hm91.js.map
|
package/dist/run-Dej-hm91.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-Dej-hm91.js","names":[],"sources":["../src/runners/update/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { getErrorMessage } from '@internals/utils'\nimport { readInstalledPackages } from '@kubb/core'\nimport { logBlock, logError, logInfo, logIntro, logOutro, logStep, logWarn } from '../../loggers/output.ts'\nimport { fetchRegistryIndex, incompatibility, installSpec, isOutdated, registryUrl, toRegistryId } from '../../utils/registry.ts'\nimport { detectPackageManager, installPackages } from '../init/utils.ts'\n\nexport type UpdateOptions = {\n /**\n * Registry ids to update. Empty updates every installed extension the registry lists.\n */\n ids: Array<string>\n check: boolean\n yes: boolean\n}\n\n/**\n * Moves installed extensions to the version the registry pins. Lists the proposals, asks, then\n * installs them. With `check`, only lists them.\n */\nexport async function run({ ids, check, yes }: UpdateOptions): Promise<void> {\n const cwd = process.cwd()\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Update ')) })\n\n try {\n const wanted = new Set(ids.map(toRegistryId))\n const [entries, installed] = await Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })])\n const versions = new Map(installed.map((item) => [item.package, item.version]))\n\n const tracked = entries.filter((entry) => versions.has(entry.artifact.package) && (!wanted.size || wanted.has(entry.id)))\n for (const id of wanted) {\n if (!tracked.some((entry) => entry.id === id)) logWarn(`${id} is not installed, or not in the registry.`)\n }\n\n const proposals = tracked.filter((entry) => {\n if (!isOutdated({ installed: versions.get(entry.artifact.package), latest: entry.artifact.version })) return false\n const problem = incompatibility(entry.manifest)\n if (problem) logWarn(`Skipped ${entry.id}: ${problem}`)\n return !problem\n })\n\n if (!proposals.length) {\n logOutro(ids.length ? `No updates for ${ids.join(', ')}.` : 'Every installed extension is up to date.')\n return\n }\n\n const plural = proposals.length === 1 ? '' : 's'\n logBlock(\n proposals.map(({ artifact }) => `${artifact.package} ${versions.get(artifact.package) ?? 'not installed'} -> ${styleText('green', artifact.version)}`),\n )\n\n if (check) {\n logOutro(`${proposals.length} update${plural} available. Run \\`kubb update\\` to install.`)\n return\n }\n\n const confirmed = yes || (await clack.confirm({ message: `Install ${proposals.length} update${plural}?`, initialValue: true }))\n if (clack.isCancel(confirmed) || !confirmed) {\n clack.cancel('Operation canceled.')\n return\n }\n\n const packageManager = detectPackageManager(cwd)\n const specs = proposals.map(({ artifact }) => installSpec(artifact))\n logStep(`Installing ${specs.join(', ')} with ${packageManager.name}`)\n await installPackages(specs, packageManager, cwd)\n\n logInfo(`Updated ${specs.length} extension${plural}`)\n logOutro(styleText('green', 'Done'))\n } catch (error) {\n logError(getErrorMessage(error))\n process.exitCode = 1\n }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SAAS,OAAO,KAAK,gBAAgB,MAAM,UAAU,SAAS,SAAS,OAAO,GAAG,CACxJ;EAEA,IAAI,OAAO;GACT,SAAS,GAAG,UAAU,OAAO,SAAS,OAAO,4CAA4C;GACzF;EACF;EAEA,MAAM,YAAY,OAAQ,MAAM,MAAM,QAAQ;GAAE,SAAS,WAAW,UAAU,OAAO,SAAS,OAAO;GAAI,cAAc;EAAK,CAAC;EAC7H,IAAI,MAAM,SAAS,SAAS,KAAK,CAAC,WAAW;GAC3C,MAAM,OAAO,qBAAqB;GAClC;EACF;EAEA,MAAM,iBAAiB,qBAAqB,GAAG;EAC/C,MAAM,QAAQ,UAAU,KAAK,EAAE,eAAe,YAAY,QAAQ,CAAC;EACnE,QAAQ,cAAc,MAAM,KAAK,IAAI,EAAE,QAAQ,eAAe,MAAM;EACpE,MAAM,gBAAgB,OAAO,gBAAgB,GAAG;EAEhD,QAAQ,WAAW,MAAM,OAAO,YAAY,QAAQ;EACpD,SAAS,UAAU,SAAS,MAAM,CAAC;CACrC,SAAS,OAAO;EACd,SAAS,gBAAgB,KAAK,CAAC;EAC/B,QAAQ,WAAW;CACrB;AACF"}
|
package/dist/run-DpAMfkm5.cjs
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
const require_agent = require("./agent-DElUuYuy.cjs");
|
|
2
|
-
const require_errors = require("./errors-BdA8M78q.cjs");
|
|
3
|
-
const require_output = require("./output-BnK0scpX.cjs");
|
|
4
|
-
const require_registry = require("./registry-DER9aRyg.cjs");
|
|
5
|
-
let node_util = require("node:util");
|
|
6
|
-
let node_process = require("node:process");
|
|
7
|
-
node_process = require_agent.__toESM(node_process, 1);
|
|
8
|
-
let _kubb_core = require("@kubb/core");
|
|
9
|
-
//#region src/runners/list/run.ts
|
|
10
|
-
/**
|
|
11
|
-
* The installed packages that ship a `kubb-extension.json` or have a registry entry, with the
|
|
12
|
-
* version the registry pins.
|
|
13
|
-
*/
|
|
14
|
-
async function listExtensions({ cwd, registry }) {
|
|
15
|
-
const [installed, entries] = await Promise.all([(0, _kubb_core.readInstalledPackages)({ root: cwd }), require_registry.fetchRegistryIndex({ registry }).catch((error) => {
|
|
16
|
-
require_output.logWarn(`Showing installed extensions only: ${require_errors.getErrorMessage(error)}`);
|
|
17
|
-
return [];
|
|
18
|
-
})]);
|
|
19
|
-
const byPackage = new Map(entries.map((entry) => [entry.artifact.package, entry]));
|
|
20
|
-
return installed.flatMap(({ package: name, version, manifest }) => {
|
|
21
|
-
const entry = byPackage.get(name);
|
|
22
|
-
if (!entry && !manifest) return [];
|
|
23
|
-
const latest = entry?.artifact.version;
|
|
24
|
-
return [{
|
|
25
|
-
id: entry?.id,
|
|
26
|
-
package: name,
|
|
27
|
-
installed: version,
|
|
28
|
-
registry: latest,
|
|
29
|
-
update: !!latest && require_registry.isOutdated({
|
|
30
|
-
installed: version,
|
|
31
|
-
latest
|
|
32
|
-
})
|
|
33
|
-
}];
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
/** Prints the installed extensions as a table. */
|
|
37
|
-
async function run() {
|
|
38
|
-
try {
|
|
39
|
-
const rows = await listExtensions({
|
|
40
|
-
cwd: node_process.default.cwd(),
|
|
41
|
-
registry: require_registry.registryUrl()
|
|
42
|
-
});
|
|
43
|
-
if (!rows.length) {
|
|
44
|
-
require_output.logOutro("No installed extensions found.");
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
const header = [
|
|
48
|
-
"ID",
|
|
49
|
-
"PACKAGE",
|
|
50
|
-
"INSTALLED",
|
|
51
|
-
"REGISTRY",
|
|
52
|
-
"UPDATE"
|
|
53
|
-
];
|
|
54
|
-
const cells = rows.map((row) => [
|
|
55
|
-
row.id ?? "-",
|
|
56
|
-
row.package,
|
|
57
|
-
row.installed ?? "-",
|
|
58
|
-
row.registry ?? "-",
|
|
59
|
-
row.update ? "yes" : "no"
|
|
60
|
-
]);
|
|
61
|
-
const widths = header.map((title, index) => Math.max(title.length, ...cells.map((cell) => cell[index].length)));
|
|
62
|
-
const line = (cell) => cell.map((value, index) => value.padEnd(widths[index])).join(" ").trimEnd();
|
|
63
|
-
require_output.logBlock([(0, node_util.styleText)("dim", line(header)), ...cells.map(line)]);
|
|
64
|
-
} catch (error) {
|
|
65
|
-
require_output.logError(require_errors.getErrorMessage(error));
|
|
66
|
-
node_process.default.exitCode = 1;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
//#endregion
|
|
70
|
-
exports.run = run;
|
|
71
|
-
|
|
72
|
-
//# sourceMappingURL=run-DpAMfkm5.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-DpAMfkm5.cjs","names":["readInstalledPackages","fetchRegistryIndex","getErrorMessage","isOutdated","process","registryUrl","styleText"],"sources":["../src/runners/list/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { getErrorMessage } from '@internals/utils'\nimport { readInstalledPackages, type RegistryEntry } from '@kubb/core'\nimport { logBlock, logError, logOutro, logWarn } from '../../loggers/output.ts'\nimport { fetchRegistryIndex, isOutdated, registryUrl } from '../../utils/registry.ts'\n\nexport type ListRow = {\n id?: string\n package: string\n installed?: string\n registry?: string\n update: boolean\n}\n\n/**\n * The installed packages that ship a `kubb-extension.json` or have a registry entry, with the\n * version the registry pins.\n */\nexport async function listExtensions({ cwd, registry }: { cwd: string; registry: string }): Promise<Array<ListRow>> {\n const [installed, entries] = await Promise.all([\n readInstalledPackages({ root: cwd }),\n fetchRegistryIndex({ registry }).catch((error: unknown): Array<RegistryEntry> => {\n logWarn(`Showing installed extensions only: ${getErrorMessage(error)}`)\n return []\n }),\n ])\n const byPackage = new Map(entries.map((entry) => [entry.artifact.package, entry]))\n\n return installed.flatMap(({ package: name, version, manifest }): Array<ListRow> => {\n const entry = byPackage.get(name)\n if (!entry && !manifest) return []\n const latest = entry?.artifact.version\n return [{ id: entry?.id, package: name, installed: version, registry: latest, update: !!latest && isOutdated({ installed: version, latest }) }]\n })\n}\n\n/** Prints the installed extensions as a table. */\nexport async function run(): Promise<void> {\n try {\n const rows = await listExtensions({ cwd: process.cwd(), registry: registryUrl() })\n if (!rows.length) {\n logOutro('No installed extensions found.')\n return\n }\n\n const header = ['ID', 'PACKAGE', 'INSTALLED', 'REGISTRY', 'UPDATE']\n const cells = rows.map((row) => [row.id ?? '-', row.package, row.installed ?? '-', row.registry ?? '-', row.update ? 'yes' : 'no'])\n const widths = header.map((title, index) => Math.max(title.length, ...cells.map((cell) => cell[index]!.length)))\n const line = (cell: Array<string>) =>\n cell\n .map((value, index) => value.padEnd(widths[index]!))\n .join(' ')\n .trimEnd()\n\n logBlock([styleText('dim', line(header)), ...cells.map(line)])\n } catch (error) {\n logError(getErrorMessage(error))\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,eAAsB,eAAe,EAAE,KAAK,YAAwE;CAClH,MAAM,CAAC,WAAW,WAAW,MAAM,QAAQ,IAAI,EAAA,GAC7CA,WAAAA,sBAAAA,CAAsB,EAAE,MAAM,IAAI,CAAC,GACnCC,iBAAAA,mBAAmB,EAAE,SAAS,CAAC,CAAC,CAAC,OAAO,UAAyC;EAC/E,eAAA,QAAQ,sCAAsCC,eAAAA,gBAAgB,KAAK,GAAG;EACtE,OAAO,CAAC;CACV,CAAC,CACH,CAAC;CACD,MAAM,YAAY,IAAI,IAAI,QAAQ,KAAK,UAAU,CAAC,MAAM,SAAS,SAAS,KAAK,CAAC,CAAC;CAEjF,OAAO,UAAU,SAAS,EAAE,SAAS,MAAM,SAAS,eAA+B;EACjF,MAAM,QAAQ,UAAU,IAAI,IAAI;EAChC,IAAI,CAAC,SAAS,CAAC,UAAU,OAAO,CAAC;EACjC,MAAM,SAAS,OAAO,SAAS;EAC/B,OAAO,CAAC;GAAE,IAAI,OAAO;GAAI,SAAS;GAAM,WAAW;GAAS,UAAU;GAAQ,QAAQ,CAAC,CAAC,UAAUC,iBAAAA,WAAW;IAAE,WAAW;IAAS;GAAO,CAAC;EAAE,CAAC;CAChJ,CAAC;AACH;;AAGA,eAAsB,MAAqB;CACzC,IAAI;EACF,MAAM,OAAO,MAAM,eAAe;GAAE,KAAKC,aAAAA,QAAQ,IAAI;GAAG,UAAUC,iBAAAA,YAAY;EAAE,CAAC;EACjF,IAAI,CAAC,KAAK,QAAQ;GAChB,eAAA,SAAS,gCAAgC;GACzC;EACF;EAEA,MAAM,SAAS;GAAC;GAAM;GAAW;GAAa;GAAY;EAAQ;EAClE,MAAM,QAAQ,KAAK,KAAK,QAAQ;GAAC,IAAI,MAAM;GAAK,IAAI;GAAS,IAAI,aAAa;GAAK,IAAI,YAAY;GAAK,IAAI,SAAS,QAAQ;EAAI,CAAC;EAClI,MAAM,SAAS,OAAO,KAAK,OAAO,UAAU,KAAK,IAAI,MAAM,QAAQ,GAAG,MAAM,KAAK,SAAS,KAAK,MAAM,CAAE,MAAM,CAAC,CAAC;EAC/G,MAAM,QAAQ,SACZ,KACG,KAAK,OAAO,UAAU,MAAM,OAAO,OAAO,MAAO,CAAC,CAAC,CACnD,KAAK,IAAI,CAAC,CACV,QAAQ;EAEb,eAAA,SAAS,EAAA,GAACC,UAAAA,UAAAA,CAAU,OAAO,KAAK,MAAM,CAAC,GAAG,GAAG,MAAM,IAAI,IAAI,CAAC,CAAC;CAC/D,SAAS,OAAO;EACd,eAAA,SAASJ,eAAAA,gBAAgB,KAAK,CAAC;EAC/B,aAAA,QAAA,WAAmB;CACrB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-B45A4RfA.cjs","names":["runtime","readFile","readFileSync","process","join","dirname","process","styleText","loadConfigs","logLevelMap","Hookable","cliReporter","createPlainLogger","createSnapshot","defaultStudioUrl","run"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.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 { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { read } from '@internals/utils'\nimport { cliReporter, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot, defaultStudioUrl } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { logBlock } from '../../loggers/output.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, run, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory) throw new Error(`No package.json with a name and a version found above ${process.cwd()}`)\n\n return findPackageJson(parent)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: SnapshotOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) return { name: options.name, version: options.packageVersion }\n\n const found = await findPackageJson(process.cwd())\n return { name: options.name ?? found.name, version: options.packageVersion ?? found.version }\n}\n\nfunction resolveToken(options: SnapshotOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n\n return added.length + changed.length + removed.length\n ? `${added.length} added, ${changed.length} changed, ${removed.length} removed ${against}`\n : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n\n return describeChanges(changes, `since ${changes.base.commit?.slice(0, 7) ?? changes.base.createdAt}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `against ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n ...(result.branchChanges ? [`${styleText('dim', 'Branch'.padEnd(10))} ${formatBranchChanges(result.branchChanges)}`] : []),\n ...(result.changes ? [`${styleText('dim', 'Changes'.padEnd(10))} ${formatChanges(result.changes)}`] : []),\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = resolveToken(options)\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, { logLevel, reporters: [cliReporter], logger: createPlainLogger(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n step('Generating the snapshot')\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n }\n if (!options.json) {\n printSummary(result)\n }\n } catch (error) {\n step('Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = async ({ values }) => {\n const options: SnapshotOptions = {\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n baseId: values.baseId,\n name: values.name,\n packageVersion: values.packageVersion,\n json: values.json,\n }\n await run({ options, action: () => snapshot(options), json: options.json })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAIA,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,QAAA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ACzB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,IAAI,OAAO;EACX,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,gBAAgB,OAAO;EACvB,MAAM,OAAO;CACf;CACA,MAAMC,YAAAA,IAAI;EAAE;EAAS,cAAc,SAAS,OAAO;EAAG,MAAM,QAAQ;CAAK,CAAC;AAC5E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-C0WaZZiF.js","names":["logLevel","logLevelMap"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.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 { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { read } from '@internals/utils'\nimport { cliReporter, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot, defaultStudioUrl } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { logBlock } from '../../loggers/output.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, run, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory) throw new Error(`No package.json with a name and a version found above ${process.cwd()}`)\n\n return findPackageJson(parent)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: SnapshotOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) return { name: options.name, version: options.packageVersion }\n\n const found = await findPackageJson(process.cwd())\n return { name: options.name ?? found.name, version: options.packageVersion ?? found.version }\n}\n\nfunction resolveToken(options: SnapshotOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n\n return added.length + changed.length + removed.length\n ? `${added.length} added, ${changed.length} changed, ${removed.length} removed ${against}`\n : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n\n return describeChanges(changes, `since ${changes.base.commit?.slice(0, 7) ?? changes.base.createdAt}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `against ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n ...(result.branchChanges ? [`${styleText('dim', 'Branch'.padEnd(10))} ${formatBranchChanges(result.branchChanges)}`] : []),\n ...(result.changes ? [`${styleText('dim', 'Changes'.padEnd(10))} ${formatChanges(result.changes)}`] : []),\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = resolveToken(options)\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, { logLevel, reporters: [cliReporter], logger: createPlainLogger(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n step('Generating the snapshot')\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n }\n if (!options.json) {\n printSummary(result)\n }\n } catch (error) {\n step('Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = async ({ values }) => {\n const options: SnapshotOptions = {\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n baseId: values.baseId,\n name: values.name,\n packageVersion: values.packageVersion,\n json: values.json,\n }\n await run({ options, action: () => snapshot(options), json: options.json })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,OAAO,SAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;AChBA,SAAS,sBAAsB,WAA8D;CAC3F,IAAI,CAAC,WACH;CAGF,IAAI;EACF,MAAM,QAAQ,KAAK,MAAM,aAAa,WAAW,MAAM,CAAC;EACxD,OAAO,MAAM,cAAc,SAAS,MAAM,eAAe,KAAA;CAC3D,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,cAAc,KAAqB;CACjD,OAAO,IACJ,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,MAAM,GAAG,EAAE,CAAC,CACZ,QAAQ,YAAY,EAAE;AAC3B;;;;;;AAOA,SAAgB,SAAS,MAA0C,QAAQ,KAAuB;CAChG,IAAI,IAAI,gBAAgB;EACtB,MAAM,cAAc,sBAAsB,IAAI,iBAAiB;EAC/D,MAAM,eAAe,IAAI,wBAAwB,IAAI,qBAAqB;EAC1E,MAAM,SAAS,IAAI,YAAY,WAAW,aAAa,IAAI,IAAI,WAAW,MAAM,EAAoB,IAAI,KAAA;EAExG,MAAM,QAAQ,aAAa,WAAW,SAAS,cAAc,WAAW,IAAI,kBAAkB;EAC9F,MAAM,aAAa,aAAa,MAAM;EAEtC,OAAO;GACL,IAAI,MAAM,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;CACR;AACF;AAEA,MAAa,SAAuE,OAAO,EAAE,aAAa;CACxG,MAAM,UAA2B;EAC/B,YAAY,OAAO;EACnB,WAAW,OAAO,OAAO;EACzB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,IAAI,OAAO;EACX,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,gBAAgB,OAAO;EACvB,MAAM,OAAO;CACf;CACA,MAAM,IAAI;EAAE;EAAS,cAAc,SAAS,OAAO;EAAG,MAAM,QAAQ;CAAK,CAAC;AAC5E"}
|
package/dist/utils-BHW8kA8P.js
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
import "./rolldown-runtime-CRm0XQPb.js";
|
|
2
|
-
import process from "node:process";
|
|
3
|
-
import { x } from "tinyexec";
|
|
4
|
-
import path from "node:path";
|
|
5
|
-
import fs from "node:fs";
|
|
6
|
-
//#region src/runners/init/utils.ts
|
|
7
|
-
/** Metadata for each supported package manager, keyed by its short name. */
|
|
8
|
-
const packageManagers = {
|
|
9
|
-
pnpm: {
|
|
10
|
-
name: "pnpm",
|
|
11
|
-
lockFiles: ["pnpm-lock.yaml"],
|
|
12
|
-
initCommand: ["init"],
|
|
13
|
-
installCommand: ["add", "-D"]
|
|
14
|
-
},
|
|
15
|
-
yarn: {
|
|
16
|
-
name: "yarn",
|
|
17
|
-
lockFiles: ["yarn.lock"],
|
|
18
|
-
initCommand: ["init", "-y"],
|
|
19
|
-
installCommand: ["add", "-D"]
|
|
20
|
-
},
|
|
21
|
-
bun: {
|
|
22
|
-
name: "bun",
|
|
23
|
-
lockFiles: ["bun.lock", "bun.lockb"],
|
|
24
|
-
initCommand: ["init", "-y"],
|
|
25
|
-
installCommand: ["add", "-d"]
|
|
26
|
-
},
|
|
27
|
-
npm: {
|
|
28
|
-
name: "npm",
|
|
29
|
-
lockFiles: ["package-lock.json"],
|
|
30
|
-
initCommand: ["init", "-y"],
|
|
31
|
-
installCommand: ["install", "--save-dev"]
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
/** Detects the package manager for `cwd`: the `packageManager` field in `package.json`, then a lock file, then `npm`. */
|
|
35
|
-
function detectPackageManager(cwd = process.cwd()) {
|
|
36
|
-
const packageJsonPath = path.join(cwd, "package.json");
|
|
37
|
-
if (fs.existsSync(packageJsonPath)) try {
|
|
38
|
-
const pmField = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")).packageManager;
|
|
39
|
-
if (typeof pmField === "string") {
|
|
40
|
-
const name = pmField.split("@")[0];
|
|
41
|
-
if (name && name in packageManagers) return packageManagers[name];
|
|
42
|
-
}
|
|
43
|
-
} catch {}
|
|
44
|
-
for (const pm of Object.values(packageManagers)) if (pm.lockFiles.some((lockFile) => fs.existsSync(path.join(cwd, lockFile)))) return pm;
|
|
45
|
-
return packageManagers.npm;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Initializes a new `package.json` at `cwd` using the detected package manager.
|
|
49
|
-
*/
|
|
50
|
-
async function initPackageJson(cwd, packageManager) {
|
|
51
|
-
await x(packageManager.name, [...packageManager.initCommand], {
|
|
52
|
-
nodeOptions: {
|
|
53
|
-
cwd,
|
|
54
|
-
stdio: "inherit"
|
|
55
|
-
},
|
|
56
|
-
throwOnError: true
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Installs the given packages at `cwd` using the detected package manager.
|
|
61
|
-
*/
|
|
62
|
-
async function installPackages(packages, packageManager, cwd = process.cwd()) {
|
|
63
|
-
await x(packageManager.name, [...packageManager.installCommand, ...packages], {
|
|
64
|
-
nodeOptions: {
|
|
65
|
-
cwd,
|
|
66
|
-
stdio: "inherit"
|
|
67
|
-
},
|
|
68
|
-
throwOnError: true
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* What the installed manifests of the `selected` plugins say is missing from the selection: a
|
|
73
|
-
* `dependencies` entry, or a `client` plugin next to a `consumer`. Empty when nothing is missing.
|
|
74
|
-
* `optionalDependencies` are skipped, since `kubb init` writes the default options.
|
|
75
|
-
*/
|
|
76
|
-
function missingPluginDependencies({ selected, manifests }) {
|
|
77
|
-
const hasClient = manifests.some((manifest) => manifest.role === "client");
|
|
78
|
-
return manifests.flatMap((manifest) => [...(manifest.dependencies ?? []).filter((name) => !selected.includes(name)).map((name) => `${manifest.name} needs ${name}.`), ...manifest.role === "consumer" && !hasClient ? [`${manifest.name} needs a client plugin, such as plugin-axios or plugin-fetch.`] : []]);
|
|
79
|
-
}
|
|
80
|
-
//#endregion
|
|
81
|
-
export { missingPluginDependencies as i, initPackageJson as n, installPackages as r, detectPackageManager as t };
|
|
82
|
-
|
|
83
|
-
//# sourceMappingURL=utils-BHW8kA8P.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils-BHW8kA8P.js","names":[],"sources":["../src/runners/init/utils.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport type { ExtensionManifest } from '@kubb/core'\nimport { x } from 'tinyexec'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/** Metadata describing a package manager's lock file and commands. */\nexport type PackageManagerInfo = {\n /** Identifier used in CLI commands, e.g. `pnpm`, `yarn`. */\n name: PackageManagerName\n /** Lock file names that identify this package manager in a project root. */\n lockFiles: ReadonlyArray<string>\n /** Subcommands passed to the package manager binary to create a `package.json`. */\n initCommand: ReadonlyArray<string>\n /** Subcommands passed to the package manager binary to install a dev dependency. */\n installCommand: ReadonlyArray<string>\n}\n\n/** Metadata for each supported package manager, keyed by its short name. */\nexport const packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFiles: ['pnpm-lock.yaml'],\n initCommand: ['init'],\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFiles: ['yarn.lock'],\n initCommand: ['init', '-y'],\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFiles: ['bun.lock', 'bun.lockb'],\n initCommand: ['init', '-y'],\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFiles: ['package-lock.json'],\n initCommand: ['init', '-y'],\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/** Minimal shape of `package.json` fields read during detection. */\ntype PackageJson = {\n /** The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`). */\n packageManager?: string\n}\n\n/** Detects the package manager for `cwd`: the `packageManager` field in `package.json`, then a lock file, then `npm`. */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = path.join(cwd, 'package.json')\n if (fs.existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (pm.lockFiles.some((lockFile) => fs.existsSync(path.join(cwd, lockFile)))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n await x(packageManager.name, [...packageManager.initCommand], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * What the installed manifests of the `selected` plugins say is missing from the selection: a\n * `dependencies` entry, or a `client` plugin next to a `consumer`. Empty when nothing is missing.\n * `optionalDependencies` are skipped, since `kubb init` writes the default options.\n */\nexport function missingPluginDependencies({ selected, manifests }: { selected: Array<string>; manifests: Array<ExtensionManifest> }): Array<string> {\n const hasClient = manifests.some((manifest) => manifest.role === 'client')\n return manifests.flatMap((manifest) => [\n ...(manifest.dependencies ?? []).filter((name) => !selected.includes(name)).map((name) => `${manifest.name} needs ${name}.`),\n ...(manifest.role === 'consumer' && !hasClient ? [`${manifest.name} needs a client plugin, such as plugin-axios or plugin-fetch.`] : []),\n ])\n}\n"],"mappings":";;;;;;;AAqBA,MAAa,kBAAkE;CAC7E,MAAM;EACJ,MAAM;EACN,WAAW,CAAC,gBAAgB;EAC5B,aAAa,CAAC,MAAM;EACpB,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,MAAM;EACJ,MAAM;EACN,WAAW,CAAC,WAAW;EACvB,aAAa,CAAC,QAAQ,IAAI;EAC1B,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,KAAK;EACH,MAAM;EACN,WAAW,CAAC,YAAY,WAAW;EACnC,aAAa,CAAC,QAAQ,IAAI;EAC1B,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,KAAK;EACH,MAAM;EACN,WAAW,CAAC,mBAAmB;EAC/B,aAAa,CAAC,QAAQ,IAAI;EAC1B,gBAAgB,CAAC,WAAW,YAAY;CAC1C;AACF;;AASA,SAAgB,qBAAqB,MAAc,QAAQ,IAAI,GAAuB;CACpF,MAAM,kBAAkB,KAAK,KAAK,KAAK,cAAc;CACrD,IAAI,GAAG,WAAW,eAAe,GAC/B,IAAI;EAEF,MAAM,UADc,KAAK,MAAM,GAAG,aAAa,iBAAiB,OAAO,CAC7C,CAAC,CAAC;EAC5B,IAAI,OAAO,YAAY,UAAU;GAC/B,MAAM,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC;GAChC,IAAI,QAAQ,QAAQ,iBAClB,OAAO,gBAAgB;EAE3B;CACF,QAAQ,CAER;CAGF,KAAK,MAAM,MAAM,OAAO,OAAO,eAAe,GAC5C,IAAI,GAAG,UAAU,MAAM,aAAa,GAAG,WAAW,KAAK,KAAK,KAAK,QAAQ,CAAC,CAAC,GACzE,OAAO;CAIX,OAAO,gBAAgB;AACzB;;;;AAKA,eAAsB,gBAAgB,KAAa,gBAAmD;CACpG,MAAM,EAAE,eAAe,MAAM,CAAC,GAAG,eAAe,WAAW,GAAG;EAC5D,aAAa;GAAE;GAAK,OAAO;EAAU;EACrC,cAAc;CAChB,CAAC;AACH;;;;AAKA,eAAsB,gBAAgB,UAAyB,gBAAoC,MAAc,QAAQ,IAAI,GAAkB;CAC7I,MAAM,EAAE,eAAe,MAAM,CAAC,GAAG,eAAe,gBAAgB,GAAG,QAAQ,GAAG;EAC5E,aAAa;GAAE;GAAK,OAAO;EAAU;EACrC,cAAc;CAChB,CAAC;AACH;;;;;;AAOA,SAAgB,0BAA0B,EAAE,UAAU,aAA8F;CAClJ,MAAM,YAAY,UAAU,MAAM,aAAa,SAAS,SAAS,QAAQ;CACzE,OAAO,UAAU,SAAS,aAAa,CACrC,IAAI,SAAS,gBAAgB,CAAC,EAAA,CAAG,QAAQ,SAAS,CAAC,SAAS,SAAS,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,GAAG,SAAS,KAAK,SAAS,KAAK,EAAE,GAC3H,GAAI,SAAS,SAAS,cAAc,CAAC,YAAY,CAAC,GAAG,SAAS,KAAK,8DAA8D,IAAI,CAAC,CACxI,CAAC;AACH"}
|
package/dist/utils-BzQ46pgd.cjs
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
const require_agent = require("./agent-DElUuYuy.cjs");
|
|
2
|
-
let node_process = require("node:process");
|
|
3
|
-
node_process = require_agent.__toESM(node_process, 1);
|
|
4
|
-
let tinyexec = require("tinyexec");
|
|
5
|
-
let node_path = require("node:path");
|
|
6
|
-
node_path = require_agent.__toESM(node_path, 1);
|
|
7
|
-
let node_fs = require("node:fs");
|
|
8
|
-
node_fs = require_agent.__toESM(node_fs, 1);
|
|
9
|
-
//#region src/runners/init/utils.ts
|
|
10
|
-
/** Metadata for each supported package manager, keyed by its short name. */
|
|
11
|
-
const packageManagers = {
|
|
12
|
-
pnpm: {
|
|
13
|
-
name: "pnpm",
|
|
14
|
-
lockFiles: ["pnpm-lock.yaml"],
|
|
15
|
-
initCommand: ["init"],
|
|
16
|
-
installCommand: ["add", "-D"]
|
|
17
|
-
},
|
|
18
|
-
yarn: {
|
|
19
|
-
name: "yarn",
|
|
20
|
-
lockFiles: ["yarn.lock"],
|
|
21
|
-
initCommand: ["init", "-y"],
|
|
22
|
-
installCommand: ["add", "-D"]
|
|
23
|
-
},
|
|
24
|
-
bun: {
|
|
25
|
-
name: "bun",
|
|
26
|
-
lockFiles: ["bun.lock", "bun.lockb"],
|
|
27
|
-
initCommand: ["init", "-y"],
|
|
28
|
-
installCommand: ["add", "-d"]
|
|
29
|
-
},
|
|
30
|
-
npm: {
|
|
31
|
-
name: "npm",
|
|
32
|
-
lockFiles: ["package-lock.json"],
|
|
33
|
-
initCommand: ["init", "-y"],
|
|
34
|
-
installCommand: ["install", "--save-dev"]
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
/** Detects the package manager for `cwd`: the `packageManager` field in `package.json`, then a lock file, then `npm`. */
|
|
38
|
-
function detectPackageManager(cwd = node_process.default.cwd()) {
|
|
39
|
-
const packageJsonPath = node_path.default.join(cwd, "package.json");
|
|
40
|
-
if (node_fs.default.existsSync(packageJsonPath)) try {
|
|
41
|
-
const pmField = JSON.parse(node_fs.default.readFileSync(packageJsonPath, "utf-8")).packageManager;
|
|
42
|
-
if (typeof pmField === "string") {
|
|
43
|
-
const name = pmField.split("@")[0];
|
|
44
|
-
if (name && name in packageManagers) return packageManagers[name];
|
|
45
|
-
}
|
|
46
|
-
} catch {}
|
|
47
|
-
for (const pm of Object.values(packageManagers)) if (pm.lockFiles.some((lockFile) => node_fs.default.existsSync(node_path.default.join(cwd, lockFile)))) return pm;
|
|
48
|
-
return packageManagers.npm;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Initializes a new `package.json` at `cwd` using the detected package manager.
|
|
52
|
-
*/
|
|
53
|
-
async function initPackageJson(cwd, packageManager) {
|
|
54
|
-
await (0, tinyexec.x)(packageManager.name, [...packageManager.initCommand], {
|
|
55
|
-
nodeOptions: {
|
|
56
|
-
cwd,
|
|
57
|
-
stdio: "inherit"
|
|
58
|
-
},
|
|
59
|
-
throwOnError: true
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Installs the given packages at `cwd` using the detected package manager.
|
|
64
|
-
*/
|
|
65
|
-
async function installPackages(packages, packageManager, cwd = node_process.default.cwd()) {
|
|
66
|
-
await (0, tinyexec.x)(packageManager.name, [...packageManager.installCommand, ...packages], {
|
|
67
|
-
nodeOptions: {
|
|
68
|
-
cwd,
|
|
69
|
-
stdio: "inherit"
|
|
70
|
-
},
|
|
71
|
-
throwOnError: true
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* What the installed manifests of the `selected` plugins say is missing from the selection: a
|
|
76
|
-
* `dependencies` entry, or a `client` plugin next to a `consumer`. Empty when nothing is missing.
|
|
77
|
-
* `optionalDependencies` are skipped, since `kubb init` writes the default options.
|
|
78
|
-
*/
|
|
79
|
-
function missingPluginDependencies({ selected, manifests }) {
|
|
80
|
-
const hasClient = manifests.some((manifest) => manifest.role === "client");
|
|
81
|
-
return manifests.flatMap((manifest) => [...(manifest.dependencies ?? []).filter((name) => !selected.includes(name)).map((name) => `${manifest.name} needs ${name}.`), ...manifest.role === "consumer" && !hasClient ? [`${manifest.name} needs a client plugin, such as plugin-axios or plugin-fetch.`] : []]);
|
|
82
|
-
}
|
|
83
|
-
//#endregion
|
|
84
|
-
Object.defineProperty(exports, "detectPackageManager", {
|
|
85
|
-
enumerable: true,
|
|
86
|
-
get: function() {
|
|
87
|
-
return detectPackageManager;
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
Object.defineProperty(exports, "initPackageJson", {
|
|
91
|
-
enumerable: true,
|
|
92
|
-
get: function() {
|
|
93
|
-
return initPackageJson;
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
Object.defineProperty(exports, "installPackages", {
|
|
97
|
-
enumerable: true,
|
|
98
|
-
get: function() {
|
|
99
|
-
return installPackages;
|
|
100
|
-
}
|
|
101
|
-
});
|
|
102
|
-
Object.defineProperty(exports, "missingPluginDependencies", {
|
|
103
|
-
enumerable: true,
|
|
104
|
-
get: function() {
|
|
105
|
-
return missingPluginDependencies;
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
//# sourceMappingURL=utils-BzQ46pgd.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils-BzQ46pgd.cjs","names":["process","path","fs","x"],"sources":["../src/runners/init/utils.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport type { ExtensionManifest } from '@kubb/core'\nimport { x } from 'tinyexec'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/** Metadata describing a package manager's lock file and commands. */\nexport type PackageManagerInfo = {\n /** Identifier used in CLI commands, e.g. `pnpm`, `yarn`. */\n name: PackageManagerName\n /** Lock file names that identify this package manager in a project root. */\n lockFiles: ReadonlyArray<string>\n /** Subcommands passed to the package manager binary to create a `package.json`. */\n initCommand: ReadonlyArray<string>\n /** Subcommands passed to the package manager binary to install a dev dependency. */\n installCommand: ReadonlyArray<string>\n}\n\n/** Metadata for each supported package manager, keyed by its short name. */\nexport const packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFiles: ['pnpm-lock.yaml'],\n initCommand: ['init'],\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFiles: ['yarn.lock'],\n initCommand: ['init', '-y'],\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFiles: ['bun.lock', 'bun.lockb'],\n initCommand: ['init', '-y'],\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFiles: ['package-lock.json'],\n initCommand: ['init', '-y'],\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/** Minimal shape of `package.json` fields read during detection. */\ntype PackageJson = {\n /** The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`). */\n packageManager?: string\n}\n\n/** Detects the package manager for `cwd`: the `packageManager` field in `package.json`, then a lock file, then `npm`. */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = path.join(cwd, 'package.json')\n if (fs.existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (pm.lockFiles.some((lockFile) => fs.existsSync(path.join(cwd, lockFile)))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n await x(packageManager.name, [...packageManager.initCommand], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * What the installed manifests of the `selected` plugins say is missing from the selection: a\n * `dependencies` entry, or a `client` plugin next to a `consumer`. Empty when nothing is missing.\n * `optionalDependencies` are skipped, since `kubb init` writes the default options.\n */\nexport function missingPluginDependencies({ selected, manifests }: { selected: Array<string>; manifests: Array<ExtensionManifest> }): Array<string> {\n const hasClient = manifests.some((manifest) => manifest.role === 'client')\n return manifests.flatMap((manifest) => [\n ...(manifest.dependencies ?? []).filter((name) => !selected.includes(name)).map((name) => `${manifest.name} needs ${name}.`),\n ...(manifest.role === 'consumer' && !hasClient ? [`${manifest.name} needs a client plugin, such as plugin-axios or plugin-fetch.`] : []),\n ])\n}\n"],"mappings":";;;;;;;;;;AAqBA,MAAa,kBAAkE;CAC7E,MAAM;EACJ,MAAM;EACN,WAAW,CAAC,gBAAgB;EAC5B,aAAa,CAAC,MAAM;EACpB,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,MAAM;EACJ,MAAM;EACN,WAAW,CAAC,WAAW;EACvB,aAAa,CAAC,QAAQ,IAAI;EAC1B,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,KAAK;EACH,MAAM;EACN,WAAW,CAAC,YAAY,WAAW;EACnC,aAAa,CAAC,QAAQ,IAAI;EAC1B,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,KAAK;EACH,MAAM;EACN,WAAW,CAAC,mBAAmB;EAC/B,aAAa,CAAC,QAAQ,IAAI;EAC1B,gBAAgB,CAAC,WAAW,YAAY;CAC1C;AACF;;AASA,SAAgB,qBAAqB,MAAcA,aAAAA,QAAQ,IAAI,GAAuB;CACpF,MAAM,kBAAkBC,UAAAA,QAAK,KAAK,KAAK,cAAc;CACrD,IAAIC,QAAAA,QAAG,WAAW,eAAe,GAC/B,IAAI;EAEF,MAAM,UADc,KAAK,MAAMA,QAAAA,QAAG,aAAa,iBAAiB,OAAO,CAC7C,CAAC,CAAC;EAC5B,IAAI,OAAO,YAAY,UAAU;GAC/B,MAAM,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC;GAChC,IAAI,QAAQ,QAAQ,iBAClB,OAAO,gBAAgB;EAE3B;CACF,QAAQ,CAER;CAGF,KAAK,MAAM,MAAM,OAAO,OAAO,eAAe,GAC5C,IAAI,GAAG,UAAU,MAAM,aAA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