@kubb/adapter-oas 5.18.8 → 5.19.1

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
@@ -7,10 +7,10 @@ var __name = (target, value) => __defProp(target, "name", {
7
7
  });
8
8
  let _kubb_core = require("@kubb/core");
9
9
  let _kubb_kit = require("@kubb/kit");
10
+ let node_fs_promises = require("node:fs/promises");
10
11
  let node_path = require("node:path");
11
12
  let node_url = require("node:url");
12
13
  let node_fs = require("node:fs");
13
- let node_fs_promises = require("node:fs/promises");
14
14
  let _scalar_openapi_upgrader = require("@scalar/openapi-upgrader");
15
15
  let api_ref_bundler = require("api-ref-bundler");
16
16
  let js_yaml = require("js-yaml");
@@ -21,7 +21,7 @@ var compatibility = {
21
21
  "node": ">=22.22"
22
22
  };
23
23
  // package.json
24
- var version = "5.18.8";
24
+ var version = "5.19.1";
25
25
  // src/constants.ts
26
26
  /**
27
27
  * Default parser options applied when no explicit options are provided.
@@ -229,6 +229,47 @@ function patchDiscriminatorNode(node, entry) {
229
229
  members: newMembers
230
230
  };
231
231
  }
232
+ // ../../internals/utils/src/promise.ts
233
+ /**
234
+ * Returns the value cached under `key` in `store`, computing and storing it on the first call.
235
+ * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
236
+ * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
237
+ *
238
+ * @example
239
+ * `const refs = memo(refCache, node, () => collectRefs(node))`
240
+ */
241
+ function memo(store, key, compute) {
242
+ const cached = store.get(key);
243
+ if (cached !== void 0 || store.has(key)) return cached;
244
+ const value = compute();
245
+ store.set(key, value);
246
+ return value;
247
+ }
248
+ function createStore({ weak, max } = {}) {
249
+ if (weak) return /* @__PURE__ */ new WeakMap();
250
+ const entry = /* @__PURE__ */ new Map();
251
+ if (max === void 0) return entry;
252
+ const set = (key, value) => {
253
+ if (entry.size >= max) entry.clear();
254
+ entry.set(key, value);
255
+ };
256
+ if (max !== 1) return {
257
+ has: (key) => entry.has(key),
258
+ get: (key) => entry.get(key),
259
+ set
260
+ };
261
+ const touch = (key) => {
262
+ if (!entry.has(key)) return false;
263
+ set(key, entry.get(key));
264
+ return true;
265
+ };
266
+ return {
267
+ has: touch,
268
+ get: (key) => touch(key) ? entry.get(key) : void 0,
269
+ set
270
+ };
271
+ }
272
+ memo.create = createStore;
232
273
  // ../../internals/utils/src/casing.ts
233
274
  /**
234
275
  * Shared implementation for camelCase and PascalCase conversion.
@@ -243,16 +284,10 @@ function convert(text, pascal) {
243
284
  return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
244
285
  }).join("").replace(/[^a-zA-Z0-9]/g, "");
245
286
  }
246
- const cache = /* @__PURE__ */ new Map();
247
- const cacheLimit = 1e5;
287
+ const cache = memo.create({ max: 1e5 });
248
288
  function toCamelOrPascal(text, pascal) {
249
289
  const key = `${pascal ? "P" : "c"}${text}`;
250
- const cached = cache.get(key);
251
- if (cached !== void 0) return cached;
252
- const result = convert(text, pascal);
253
- if (cache.size >= cacheLimit) cache.clear();
254
- cache.set(key, result);
255
- return result;
290
+ return memo(cache, key, () => convert(text, pascal));
256
291
  }
257
292
  /**
258
293
  * Converts `text` to PascalCase.
@@ -370,42 +405,27 @@ async function read(path) {
370
405
  if (runtime.isBun) return Bun.file(path).text();
371
406
  return new Promise((resolvePromise, reject) => (0, node_fs.readFile)(path, { encoding: "utf8" }, (error, data) => error ? reject(error) : resolvePromise(data)));
372
407
  }
373
- // ../../internals/utils/src/promise.ts
374
408
  /**
375
- * Returns the value cached under `key` in `store`, computing and storing it on the first call.
376
- * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
377
- * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
409
+ * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved
410
+ * to absolute paths first, so relative and `..`-containing inputs compare correctly.
411
+ *
412
+ * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that
413
+ * it does not contain the project root, and before loading a path a caller supplied, check that it
414
+ * did not escape the directory it is allowed to read from.
378
415
  *
379
416
  * @example
380
- * `const refs = memo(refCache, node, () => collectRefs(node))`
381
- */
382
- function memo(store, key, compute) {
383
- const cached = store.get(key);
384
- if (cached !== void 0 || store.has(key)) return cached;
385
- const value = compute();
386
- store.set(key, value);
387
- return value;
417
+ * isPathInside('./src/gen', '.') // true — nested inside the root
418
+ * isPathInside('.', '.') // true — the same directory counts as inside
419
+ * isPathInside('.', './src/gen') // false — the root is not inside its own output
420
+ * isPathInside('../other', '.') // false — escapes the root
421
+ */
422
+ function isPathInside(path, parent) {
423
+ const resolvedPath = (0, node_path.resolve)(path);
424
+ const resolvedParent = (0, node_path.resolve)(parent);
425
+ if (resolvedPath === resolvedParent) return true;
426
+ const rel = (0, node_path.relative)(resolvedParent, resolvedPath);
427
+ return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
388
428
  }
389
- function createStore({ type }) {
390
- if (type === "weak") return /* @__PURE__ */ new WeakMap();
391
- const entry = /* @__PURE__ */ new Map();
392
- if (type === "map") return entry;
393
- const set = (key, value) => {
394
- entry.clear();
395
- entry.set(key, value);
396
- };
397
- const touch = (key) => {
398
- if (!entry.has(key)) return false;
399
- set(key, entry.get(key));
400
- return true;
401
- };
402
- return {
403
- has: touch,
404
- get: (key) => touch(key) ? entry.get(key) : void 0,
405
- set
406
- };
407
- }
408
- memo.create = createStore;
409
429
  // src/oas.ts
410
430
  /**
411
431
  * Returns `true` when a schema should be treated as nullable.
@@ -544,7 +564,7 @@ function isJsonMimeType(mimeType) {
544
564
  */
545
565
  function createRefs(document) {
546
566
  const pointerCache = /* @__PURE__ */ new Map();
547
- const resolvedNodeCache = /* @__PURE__ */ new Map();
567
+ const resolvedNodeCache = memo.create();
548
568
  const resolvingRefs = /* @__PURE__ */ new Set();
549
569
  function walkPointer($ref) {
550
570
  const trimmed = $ref.trim();
@@ -594,7 +614,7 @@ function createRefs(document) {
594
614
  */
595
615
  function resolveNode(refPath, parse) {
596
616
  if (resolvingRefs.has(refPath)) return null;
597
- if (!resolvedNodeCache.has(refPath)) {
617
+ return memo(resolvedNodeCache, refPath, () => {
598
618
  let resolved = null;
599
619
  try {
600
620
  const referenced = resolve(refPath);
@@ -604,9 +624,8 @@ function createRefs(document) {
604
624
  resolvingRefs.delete(refPath);
605
625
  }
606
626
  } catch {}
607
- resolvedNodeCache.set(refPath, resolved);
608
- }
609
- return resolvedNodeCache.get(refPath) ?? null;
627
+ return resolved;
628
+ });
610
629
  }
611
630
  /**
612
631
  * Resolves a `$ref` value without mutating anything: when `value` holds a `$ref`, returns the
@@ -713,8 +732,8 @@ function pick(declarations, pointer) {
713
732
  * enclosing anchor, so a relative `$id` base or a recursively extended schema is not followed, upgrade when a spec needs that.
714
733
  */
715
734
  function resolveSchemaIds(document) {
716
- const targets = /* @__PURE__ */ new Map();
717
- const declare = (key, pointer) => targets.set(key, [...targets.get(key) ?? [], pointer]);
735
+ const targets = memo.create();
736
+ const declare = (key, pointer) => memo(targets, key, () => []).push(pointer);
718
737
  walk(document, "#", (node, pointer) => {
719
738
  if (typeof node["$id"] === "string") declare(node["$id"], pointer);
720
739
  for (const key of ["$anchor", "$dynamicAnchor"]) if (typeof node[key] === "string") declare(`#${node[key]}`, pointer);
@@ -732,7 +751,7 @@ function resolveSchemaIds(document) {
732
751
  }
733
752
  // src/sourceLocator.ts
734
753
  const flowGap = /(?:[\s,]|#[^\n]*)*/y;
735
- const indexes = memo.create({ type: "last" });
754
+ const indexes = memo.create({ max: 1 });
736
755
  function toKeyText(text) {
737
756
  if (!/^[-+.~\d]|^(?:null|true|false)$/i.test(text)) return text;
738
757
  try {
@@ -1099,6 +1118,16 @@ function getBaseUri(pathOrUrl, root) {
1099
1118
  }
1100
1119
  }
1101
1120
  /**
1121
+ * Whether `filePath` is inside one of `folders`. Links are followed first, so a link inside a
1122
+ * folder cannot point outside it.
1123
+ */
1124
+ async function isInsideFolders(filePath, folders) {
1125
+ const real = (item) => (0, node_fs_promises.realpath)((0, node_path.resolve)(item)).catch(() => (0, node_path.resolve)(item));
1126
+ const target = await real(filePath);
1127
+ const realFolders = await Promise.all(folders.map(real));
1128
+ return [...folders, ...realFolders].some((folder) => isPathInside(target, folder));
1129
+ }
1130
+ /**
1102
1131
  * Bundles a multi-file OpenAPI document into a single document via `api-ref-bundler`.
1103
1132
  *
1104
1133
  * External file schemas are hoisted into named `components.schemas` entries, so a property
@@ -1115,6 +1144,7 @@ function getBaseUri(pathOrUrl, root) {
1115
1144
  * against the OpenAPI 3.2 `$self` when the document sets one. Every other file or URL read,
1116
1145
  * including one that fails, lands in `sources`. A `$ref` that cannot be read reports
1117
1146
  * `KUBB_REF_NOT_FOUND` at the key that holds it, as a warning when it sits inside an `x-` extension.
1147
+ * So does any local file from a URL input, and a local file outside every `fileRefs` folder.
1118
1148
  *
1119
1149
  * @example Local file
1120
1150
  * `const document = await bundleDocument('./openapi.yaml')`
@@ -1122,20 +1152,24 @@ function getBaseUri(pathOrUrl, root) {
1122
1152
  * @example Remote URL
1123
1153
  * `const document = await bundleDocument('https://example.com/openapi.yaml')`
1124
1154
  */
1125
- async function bundleDocument(pathOrUrl, { document, sources = [] } = {}) {
1126
- const cache = /* @__PURE__ */ new Map();
1155
+ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs } = {}) {
1156
+ const cache = memo.create();
1127
1157
  const toKey = (sourcePath) => urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath;
1158
+ const folders = urlRegExp.test(pathOrUrl) ? [] : fileRefs;
1159
+ const refused = /* @__PURE__ */ new Set();
1128
1160
  let entry = pathOrUrl;
1129
1161
  let entryDocument = document;
1130
- const resolver = (sourcePath) => {
1131
- if (entryDocument !== void 0 && toKey(sourcePath) === toKey(entry)) return Promise.resolve(entryDocument);
1162
+ const resolver = async (sourcePath) => {
1163
+ if (entryDocument !== void 0 && toKey(sourcePath) === toKey(entry)) return entryDocument;
1132
1164
  const key = toKey(sourcePath);
1133
- const cached = cache.get(key);
1134
- if (cached) return cached;
1135
- sources.push(key);
1136
- const result = resolveSource(sourcePath, { remember: key === toKey(pathOrUrl) });
1137
- cache.set(key, result);
1138
- return result;
1165
+ if (key !== toKey(pathOrUrl) && !urlRegExp.test(sourcePath) && folders && !await isInsideFolders(sourcePath, folders)) {
1166
+ refused.add(sourcePath);
1167
+ throw new Error(`Refused ${sourcePath}`);
1168
+ }
1169
+ return memo(cache, key, () => {
1170
+ sources.push(key);
1171
+ return resolveSource(sourcePath, { remember: key === toKey(pathOrUrl) });
1172
+ });
1139
1173
  };
1140
1174
  const root = await resolver(pathOrUrl);
1141
1175
  const scan = resolveTargets(root);
@@ -1147,11 +1181,12 @@ async function bundleDocument(pathOrUrl, { document, sources = [] } = {}) {
1147
1181
  entryDocument = root;
1148
1182
  return await (0, api_ref_bundler.bundle)(entry, resolver, { hooks: { onError: (message, { path, state }) => {
1149
1183
  const pointer = toKey(state.baseFile) === toKey(entry) ? `#/${path.map((token) => escapePointerToken(String(token))).join("/")}` : void 0;
1184
+ const refusedPath = [...refused].find((sourcePath) => message.includes(sourcePath));
1150
1185
  const diagnostic = {
1151
1186
  code: _kubb_kit.Diagnostics.code.refNotFound,
1152
1187
  severity: isExtensionPath(path) ? "warning" : "error",
1153
- message: `Could not bundle an external \`$ref\`. ${message}.`,
1154
- help: "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1188
+ message: refusedPath ? `Refused an external \`$ref\` to the local file ${refusedPath}.` : `Could not bundle an external \`$ref\`. ${message}.`,
1189
+ help: refusedPath ? folders?.length ? "This run only reads local files inside the folders its host allows, such as the project. Move the file there or inline the schema. On your own agent, `--allow-file-refs` lifts the limit." : "This input reads no local file. Inline the schema, or serve the file from a URL." : "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1155
1190
  ...pointer && { location: {
1156
1191
  kind: "schema",
1157
1192
  pointer
@@ -1178,7 +1213,7 @@ const inlineInputName = "<inline input>";
1178
1213
  * const document = await parseFromConfig({ type: 'data', data: '{"openapi":"3.0.0",...}' })
1179
1214
  * ```
1180
1215
  */
1181
- async function parseFromConfig(source, sources = []) {
1216
+ async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1182
1217
  const raw = await (async () => {
1183
1218
  if (source.type === "data") {
1184
1219
  const data = typeof source.data === "string" ? parseYaml(source.data, {
@@ -1188,14 +1223,18 @@ async function parseFromConfig(source, sources = []) {
1188
1223
  const isObject = Boolean(data) && typeof data === "object";
1189
1224
  if (source.root && isObject) return bundleDocument((0, node_path.join)(source.root, inlineInputName), {
1190
1225
  document: data,
1191
- sources
1226
+ sources,
1227
+ fileRefs
1192
1228
  });
1193
1229
  const scan = resolveTargets(data);
1194
1230
  if (isObject) scans.set(data, scan);
1195
1231
  return data;
1196
1232
  }
1197
1233
  await assertInputExists(source.path);
1198
- return bundleDocument(source.path, { sources });
1234
+ return bundleDocument(source.path, {
1235
+ sources,
1236
+ fileRefs
1237
+ });
1199
1238
  })();
1200
1239
  if (raw && typeof raw === "object") {
1201
1240
  const document = raw;
@@ -1511,13 +1550,8 @@ function getSchemas(document, { contentType }, refs) {
1511
1550
  pointer: `${ref}/content/${escapePointerToken(extracted.contentType)}/schema`
1512
1551
  }];
1513
1552
  }))];
1514
- const normalizedNames = /* @__PURE__ */ new Map();
1515
- for (const item of candidates) {
1516
- const key = pascalCase(item.originalName);
1517
- const bucket = normalizedNames.get(key) ?? [];
1518
- bucket.push(item);
1519
- normalizedNames.set(key, bucket);
1520
- }
1553
+ const normalizedNames = memo.create();
1554
+ for (const item of candidates) memo(normalizedNames, pascalCase(item.originalName), () => []).push(item);
1521
1555
  const schemas = {};
1522
1556
  const renames = /* @__PURE__ */ new Map();
1523
1557
  const pointers = /* @__PURE__ */ new Map();
@@ -1915,7 +1949,7 @@ let formatTally;
1915
1949
  * thousands of warnings that say the same thing. `fn` must be synchronous.
1916
1950
  */
1917
1951
  function groupUnsupportedFormats(fn) {
1918
- formatTally = /* @__PURE__ */ new Map();
1952
+ formatTally = memo.create();
1919
1953
  try {
1920
1954
  return fn();
1921
1955
  } finally {
@@ -1926,7 +1960,7 @@ function groupUnsupportedFormats(fn) {
1926
1960
  }
1927
1961
  function tallyFormat(format, pointer) {
1928
1962
  if (!formatTally) return reportUnsupportedFormat(format, [pointer]);
1929
- formatTally.set(format, (formatTally.get(format) ?? /* @__PURE__ */ new Set()).add(pointer));
1963
+ memo(formatTally, format, () => /* @__PURE__ */ new Set()).add(pointer);
1930
1964
  }
1931
1965
  function reportUnsupportedFormat(format, pointers) {
1932
1966
  const count = pointers.length;
@@ -1983,10 +2017,10 @@ function visit(node, pointer) {
1983
2017
  */
1984
2018
  function reportDuplicateDiscriminators(node, propertyName, pointer) {
1985
2019
  const keyword = node.strategy === "any" ? "anyOf" : "oneOf";
1986
- const membersByValue = /* @__PURE__ */ new Map();
2020
+ const membersByValue = memo.create();
1987
2021
  for (const [index, member] of (node.members ?? []).entries()) {
1988
2022
  const label = memberName(member) ?? `${keyword}/${index}`;
1989
- for (const value of memberValues(member, propertyName)) membersByValue.set(value, [...membersByValue.get(value) ?? [], label]);
2023
+ for (const value of memberValues(member, propertyName)) memo(membersByValue, value, () => []).push(label);
1990
2024
  }
1991
2025
  const duplicates = [...membersByValue].filter(([, members]) => members.length > 1);
1992
2026
  if (!duplicates.length) return;
@@ -4054,7 +4088,7 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4054
4088
  async settle() {
4055
4089
  await Promise.all(pendingValidations.splice(0));
4056
4090
  },
4057
- async parse(source, { signal } = {}) {
4091
+ async parse(source, { signal, fileRefs } = {}) {
4058
4092
  signal?.throwIfAborted();
4059
4093
  const cached = inputCache.get(source);
4060
4094
  if (cached) {
@@ -4064,7 +4098,7 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4064
4098
  const read = [];
4065
4099
  sources = read;
4066
4100
  const promise = (async () => {
4067
- const document = await parseFromConfig(source, read);
4101
+ const document = await parseFromConfig(source, read, { fileRefs });
4068
4102
  signal?.throwIfAborted();
4069
4103
  assertDocument(document);
4070
4104
  if (validate) pendingValidations.push(validateDocumentInWorker(document));