@kubb/core 5.8.0 → 5.8.2

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/index.cjs CHANGED
@@ -1,11 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_KubbDriver = require("./KubbDriver-DXDTb9_c.cjs");
2
+ const require_KubbDriver = require("./KubbDriver-DxWuvJWV.cjs");
3
+ let verkit = require("verkit");
3
4
  let node_util = require("node:util");
4
5
  let node_process = require("node:process");
5
6
  node_process = require_KubbDriver.__toESM(node_process, 1);
6
7
  let tinyexec = require("tinyexec");
7
8
  let node_fs_promises = require("node:fs/promises");
8
9
  let node_path = require("node:path");
10
+ node_path = require_KubbDriver.__toESM(node_path, 1);
9
11
  let node_crypto = require("node:crypto");
10
12
  let node_fs = require("node:fs");
11
13
  let node_os = require("node:os");
@@ -14,60 +16,7 @@ let unstorage = require("unstorage");
14
16
  let unstorage_drivers_fs = require("unstorage/drivers/fs");
15
17
  unstorage_drivers_fs = require_KubbDriver.__toESM(unstorage_drivers_fs, 1);
16
18
  let node_url = require("node:url");
17
- //#region src/createAdapter.ts
18
- /**
19
- * Defines a custom adapter that translates a spec format into Kubb's universal
20
- * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
21
- * handles OpenAPI/Swagger documents.
22
- *
23
- * Adapters must return an `InputNode` from `parse`. That node is what every
24
- * plugin in the build consumes.
25
- *
26
- * @example
27
- * ```ts
28
- * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
29
- * import { ast } from '@kubb/ast'
30
- *
31
- * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
32
- *
33
- * export const myAdapter = createAdapter<MyAdapter>((options) => ({
34
- * name: 'my-adapter',
35
- * options,
36
- * document: null,
37
- * async parse(_source) {
38
- * // Convert the source (path or inline data) into an InputNode.
39
- * return ast.factory.createInput()
40
- * },
41
- * async validate() {
42
- * // Throw here when the spec is invalid.
43
- * },
44
- * }))
45
- * ```
46
- */
47
- function createAdapter(build) {
48
- return (options) => build(options ?? {});
49
- }
50
- //#endregion
51
- //#region src/applyConfigDefaults.ts
52
- /**
53
- * Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback
54
- * adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already
55
- * registered. Both entry points construct their own adapter, barrel plugin, and output defaults
56
- * (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,
57
- * so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.
58
- */
59
- function applyConfigDefaults(config, { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }) {
60
- const plugins = config.plugins?.some((plugin) => plugin.name === barrelPluginName) ? config.plugins ?? [] : [...config.plugins ?? [], barrelPlugin];
61
- return {
62
- adapter: config.adapter ?? defaultAdapter,
63
- plugins,
64
- output: {
65
- ...defaultOutput,
66
- ...config.output
67
- }
68
- };
69
- }
70
- //#endregion
19
+ let node_module = require("node:module");
71
20
  //#region ../../internals/utils/src/isCIEnvironment.ts
72
21
  /**
73
22
  * Returns `true` when a known CI provider has set its environment variable.
@@ -206,6 +155,38 @@ function tokenize(command) {
206
155
  return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
207
156
  }
208
157
  //#endregion
158
+ //#region src/createAdapter.ts
159
+ function createAdapter(input) {
160
+ if (typeof input === "function") return require_KubbDriver.createExtensionFactory({
161
+ kind: "adapter",
162
+ build: (options) => input(options)
163
+ });
164
+ return require_KubbDriver.defineExtension({
165
+ kind: "adapter",
166
+ ...input
167
+ });
168
+ }
169
+ //#endregion
170
+ //#region src/applyConfigDefaults.ts
171
+ /**
172
+ * Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback
173
+ * adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already
174
+ * registered. Both entry points construct their own adapter, barrel plugin, and output defaults
175
+ * (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,
176
+ * so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.
177
+ */
178
+ function applyConfigDefaults(config, { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }) {
179
+ const plugins = config.plugins?.some((plugin) => plugin.name === barrelPluginName) ? config.plugins ?? [] : [...config.plugins ?? [], barrelPlugin];
180
+ return {
181
+ adapter: config.adapter ?? defaultAdapter,
182
+ plugins,
183
+ output: {
184
+ ...defaultOutput,
185
+ ...config.output
186
+ }
187
+ };
188
+ }
189
+ //#endregion
209
190
  //#region src/outputManifest.ts
210
191
  /**
211
192
  * Bumped when the stored shape changes, so an older cache is discarded instead of misread.
@@ -1298,9 +1279,9 @@ function defineGenerator(generator) {
1298
1279
  //#endregion
1299
1280
  //#region src/defineParser.ts
1300
1281
  function defineParser(input) {
1301
- if (typeof input === "function") return require_KubbDriver.defineExtension({
1282
+ if (typeof input === "function") return require_KubbDriver.createExtensionFactory({
1302
1283
  kind: "parser",
1303
- build: ({ options }) => {
1284
+ build: (options) => {
1304
1285
  const parser = input(options);
1305
1286
  return {
1306
1287
  ...parser,
@@ -1308,15 +1289,10 @@ function defineParser(input) {
1308
1289
  };
1309
1290
  }
1310
1291
  });
1311
- const { meta, setup } = input;
1312
1292
  return require_KubbDriver.defineExtension({
1313
1293
  kind: "parser",
1314
- meta,
1315
- build: ({ options }) => ({
1316
- ...setup(options),
1317
- name: meta.name,
1318
- meta
1319
- })
1294
+ meta: input.meta,
1295
+ build: "build" in input ? input.build : input.setup
1320
1296
  });
1321
1297
  }
1322
1298
  //#endregion
@@ -1370,6 +1346,118 @@ const memoryStorage = createStorage(() => {
1370
1346
  };
1371
1347
  });
1372
1348
  //#endregion
1349
+ //#region src/manifest.ts
1350
+ const EXTENSION_KINDS = /* @__PURE__ */ new Set([
1351
+ "plugin",
1352
+ "adapter",
1353
+ "parser"
1354
+ ]);
1355
+ const OPTION_TYPES = /* @__PURE__ */ new Set([
1356
+ "select",
1357
+ "boolean",
1358
+ "text",
1359
+ "number",
1360
+ "list"
1361
+ ]);
1362
+ const PACKAGE_NAME = /^(?:@[a-z0-9~][a-z0-9._~-]*\/)?[a-z0-9~][a-z0-9._~-]*$/;
1363
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1364
+ const REGISTRY_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
1365
+ /** Option path segments that would reach an object's prototype when Studio writes the value by path. */
1366
+ const UNSAFE_KEYS = /* @__PURE__ */ new Set([
1367
+ "__proto__",
1368
+ "constructor",
1369
+ "prototype"
1370
+ ]);
1371
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1372
+ const isOptionalString = (value) => value === void 0 || typeof value === "string";
1373
+ const isFilledString = (value) => typeof value === "string" && value !== "";
1374
+ /** Serializes with sorted object keys, so equal JSON values give equal strings whatever their key order. */
1375
+ const canonicalJSON = (value) => JSON.stringify(value, (_key, item) => isObject(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
1376
+ /**
1377
+ * Whether `name` is a valid npm package name, such as `@kubb/plugin-ts`. Rejects paths, URLs,
1378
+ * `node:` specifiers, and names that start with `-`, so the result is safe to pass to `import()` or
1379
+ * a package manager.
1380
+ */
1381
+ function isPackageName(name) {
1382
+ return typeof name === "string" && name.length <= 214 && PACKAGE_NAME.test(name);
1383
+ }
1384
+ /** Checks the shape of one manifest option, including that its path cannot reach a prototype. */
1385
+ function isOption(value) {
1386
+ if (!isObject(value)) return false;
1387
+ const { key, path, label, description, type, choices, itemCase } = value;
1388
+ return isFilledString(key) && Array.isArray(path) && path.length > 0 && path.every((segment) => isFilledString(segment) && !UNSAFE_KEYS.has(segment)) && isFilledString(label) && isOptionalString(description) && OPTION_TYPES.has(type) && (choices === void 0 || Array.isArray(choices) && choices.every((choice) => isObject(choice) && "value" in choice && isOptionalString(choice.label))) && (itemCase === void 0 || itemCase === "upper");
1389
+ }
1390
+ /**
1391
+ * What is wrong with the options of a well-formed manifest, beyond their shape: keys are unique, a
1392
+ * select has choices, and a select's default is one of its choice values. Empty when they pass.
1393
+ */
1394
+ function manifestProblems({ options = [] }) {
1395
+ const seen = /* @__PURE__ */ new Set();
1396
+ return options.flatMap((option) => {
1397
+ const problems = seen.has(option.key) ? [`option "${option.key}" is declared more than once`] : [];
1398
+ seen.add(option.key);
1399
+ if (option.type !== "select") return problems;
1400
+ if (!option.choices?.length) return [...problems, `option "${option.key}" is a select without choices`];
1401
+ return !("default" in option) || option.choices.some((choice) => canonicalJSON(choice.value) === canonicalJSON(option.default)) ? problems : [...problems, `option "${option.key}" has a default that is not one of its choices`];
1402
+ });
1403
+ }
1404
+ /**
1405
+ * Checks a parsed `kubb-extension.json` or a registry response before Kubb or Studio uses it: the
1406
+ * fields Kubb reads, every option's shape (including option paths that cannot reach a prototype),
1407
+ * and `manifestProblems`. A malformed manifest is skipped instead of trusted.
1408
+ */
1409
+ function isExtensionManifest(value) {
1410
+ if (!isObject(value)) return false;
1411
+ const { kind, name, export: exportName, displayName, description, compatibility, options } = value;
1412
+ return EXTENSION_KINDS.has(kind) && isPackageName(name) && typeof exportName === "string" && IDENTIFIER.test(exportName) && typeof displayName === "string" && typeof description === "string" && (compatibility === void 0 || isObject(compatibility) && Object.entries(compatibility).every(([key, range]) => (key === "kubb" || key === "node") && typeof range === "string")) && (options === void 0 || Array.isArray(options) && options.every(isOption)) && manifestProblems(value).length === 0;
1413
+ }
1414
+ /**
1415
+ * Checks one entry of a registry's `index.json` or `<owner>/<slug>.json`: a full `<owner>/<slug>` id,
1416
+ * an npm artifact pinned to a valid version, and a valid manifest of the entry's kind.
1417
+ */
1418
+ function isRegistryEntry(value) {
1419
+ if (!isObject(value)) return false;
1420
+ const { id, kind, type, artifact, manifest } = value;
1421
+ return typeof id === "string" && REGISTRY_ID.test(id) && EXTENSION_KINDS.has(kind) && (type === "official" || type === "community") && isObject(artifact) && artifact.kind === "npm" && isPackageName(artifact.package) && typeof artifact.version === "string" && (0, verkit.isValid)(artifact.version) && isExtensionManifest(manifest) && manifest.kind === kind;
1422
+ }
1423
+ //#endregion
1424
+ //#region src/installedPackages.ts
1425
+ /** Reads and parses a JSON file. Throws when it is missing or not JSON. */
1426
+ const readJSON = async (file) => JSON.parse(await (0, node_fs_promises.readFile)(file, "utf8"));
1427
+ /**
1428
+ * The `dependencies` and `devDependencies` of the project at `root`, plus `packages`, with the
1429
+ * installed version and the valid `kubb-extension.json` each one ships, when it does. A package
1430
+ * also counts as installed when it resolves from one of the `resolveFrom` packages, such as `kubb`
1431
+ * for the extensions it ships with.
1432
+ */
1433
+ async function readInstalledPackages({ root, packages = [], resolveFrom = [] }) {
1434
+ const project = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
1435
+ const requires = [project, ...resolveFrom.flatMap((name) => {
1436
+ try {
1437
+ return [(0, node_module.createRequire)(project.resolve(`${name}/package.json`))];
1438
+ } catch {
1439
+ return [];
1440
+ }
1441
+ })];
1442
+ const packageJSON = await readJSON(node_path.default.join(root, "package.json")).catch(() => null);
1443
+ const dependencies = [packageJSON?.dependencies, packageJSON?.devDependencies].flatMap((record) => typeof record === "object" && record !== null ? Object.keys(record) : []);
1444
+ return Promise.all([.../* @__PURE__ */ new Set([...dependencies, ...packages])].filter(isPackageName).map(async (name) => {
1445
+ const dir = requires.flatMap((require$1) => require$1.resolve.paths(name) ?? []).map((dir) => node_path.default.join(dir, name)).find((dir) => (0, node_fs.existsSync)(node_path.default.join(dir, "package.json")));
1446
+ if (!dir) return { package: name };
1447
+ try {
1448
+ const { version } = await readJSON(node_path.default.join(dir, "package.json"));
1449
+ const manifest = await readJSON(node_path.default.join(dir, "kubb-extension.json")).catch(() => void 0);
1450
+ return {
1451
+ package: name,
1452
+ version: typeof version === "string" ? version : void 0,
1453
+ manifest: isExtensionManifest(manifest) ? manifest : void 0
1454
+ };
1455
+ } catch {
1456
+ return { package: name };
1457
+ }
1458
+ }));
1459
+ }
1460
+ //#endregion
1373
1461
  exports.Diagnostics = require_KubbDriver.Diagnostics;
1374
1462
  exports.Hookable = require_KubbDriver.Hookable;
1375
1463
  exports.KubbDriver = require_KubbDriver.KubbDriver;
@@ -1379,6 +1467,7 @@ exports.addMacro = require_KubbDriver.addMacro;
1379
1467
  exports.applyConfigDefaults = applyConfigDefaults;
1380
1468
  exports.assertPluginOption = require_KubbDriver.assertPluginOption;
1381
1469
  exports.cacheStorage = cacheStorage;
1470
+ exports.checkCompatibility = require_KubbDriver.checkCompatibility;
1382
1471
  exports.cliReporter = cliReporter;
1383
1472
  exports.createAdapter = createAdapter;
1384
1473
  exports.createCliReporter = createCliReporter;
@@ -1387,6 +1476,7 @@ exports.createRenderer = createRenderer;
1387
1476
  exports.createReporter = createReporter;
1388
1477
  exports.createResolver = require_KubbDriver.createResolver;
1389
1478
  exports.createStorage = createStorage;
1479
+ exports.defineExtension = require_KubbDriver.defineExtension;
1390
1480
  exports.defineGenerator = defineGenerator;
1391
1481
  exports.defineParser = defineParser;
1392
1482
  exports.definePlugin = require_KubbDriver.definePlugin;
@@ -1395,11 +1485,16 @@ exports.fsStorage = fsStorage;
1395
1485
  exports.getInputKind = require_KubbDriver.getInputKind;
1396
1486
  exports.htmlReporter = htmlReporter;
1397
1487
  exports.injectFile = require_KubbDriver.injectFile;
1488
+ exports.isExtensionManifest = isExtensionManifest;
1489
+ exports.isPackageName = isPackageName;
1490
+ exports.isRegistryEntry = isRegistryEntry;
1398
1491
  exports.jsonReporter = jsonReporter;
1399
1492
  exports.kubbContext = require_KubbDriver.kubbContext;
1400
1493
  exports.kubbStorage = kubbStorage;
1401
1494
  exports.logLevel = logLevel;
1495
+ exports.manifestProblems = manifestProblems;
1402
1496
  exports.memoryStorage = memoryStorage;
1497
+ exports.readInstalledPackages = readInstalledPackages;
1403
1498
  exports.requirePlugin = require_KubbDriver.requirePlugin;
1404
1499
  exports.resolveCacheDir = resolveCacheDir;
1405
1500
  exports.resolveKubbDir = resolveKubbDir;