@kubb/adapter-oas 5.24.1 → 5.25.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.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import "./rolldown-runtime-BowF1xt-.js";
2
- import { defineExtension, pascalCase } from "@kubb/core";
2
+ import { defineExtension, isPublicAddress, pascalCase } from "@kubb/core";
3
3
  import { Diagnostics, Url, ast, childName, enumPrimitive, enumPropName, macroDedupeUnion, macroDiscriminatorEnum, macroEnumName, mergeAdjacentObjectsLazy } from "@kubb/kit";
4
4
  import { access, realpath } from "node:fs/promises";
5
- import { dirname, isAbsolute, join, relative, resolve } from "node:path";
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { readFile } from "node:fs";
8
8
  import { upgrade } from "@scalar/openapi-upgrader";
9
9
  import { bundle } from "api-ref-bundler";
10
+ import { lookup } from "node:dns/promises";
11
+ import { isIP } from "node:net";
10
12
  import { COLLECTION_STYLE, CORE_SCHEMA, EVENT_ID, SCALAR_STYLE, constructFromEvents, load, parseEvents } from "js-yaml";
11
13
  import { parse as parse$1 } from "yaml";
12
14
  // kubb-extension.json
@@ -15,7 +17,7 @@ var compatibility = {
15
17
  "node": ">=22.22"
16
18
  };
17
19
  // package.json
18
- var version = "5.24.1";
20
+ var version = "5.25.1";
19
21
  // src/constants.ts
20
22
  /**
21
23
  * Default parser options applied when no explicit options are provided.
@@ -387,7 +389,7 @@ function isPathInside(path, parent) {
387
389
  const resolvedParent = resolve(parent);
388
390
  if (resolvedPath === resolvedParent) return true;
389
391
  const rel = relative(resolvedParent, resolvedPath);
390
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
392
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
391
393
  }
392
394
  // src/oas.ts
393
395
  const legacyDocuments = /* @__PURE__ */ new WeakSet();
@@ -555,7 +557,12 @@ function createRefs(document) {
555
557
  applicable: true,
556
558
  value: pointerCache.get(pointer)
557
559
  };
558
- const current = pointer.split("/").filter(Boolean).map((token) => unescapePointerToken(globalThis.decodeURIComponent(token))).reduce((obj, key) => obj?.[key], document);
560
+ let current;
561
+ try {
562
+ current = pointer.split("/").filter(Boolean).map((token) => unescapePointerToken(globalThis.decodeURIComponent(token))).reduce((obj, key) => obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0, document);
563
+ } catch {
564
+ current = void 0;
565
+ }
559
566
  if (current) pointerCache.set(pointer, current);
560
567
  return {
561
568
  applicable: true,
@@ -588,21 +595,26 @@ function createRefs(document) {
588
595
  /**
589
596
  * Resolves a `$ref` to its parsed node via `parse`, guarding against cycles and memoizing per
590
597
  * instance. Returns `null` when the ref is currently being resolved (a cycle) or cannot be
591
- * resolved (e.g. a minimal document in a unit test).
598
+ * resolved (e.g. a minimal document in a unit test). An error from `parse` is thrown, so a bug
599
+ * in a converter is not mistaken for a missing ref.
592
600
  */
593
601
  function resolveNode(refPath, parse) {
594
602
  if (resolvingRefs.has(refPath)) return null;
595
603
  return memo(resolvedNodeCache, refPath, () => {
596
- let resolved = null;
604
+ let referenced;
597
605
  try {
598
- const referenced = resolve(refPath);
599
- if (referenced) {
600
- resolvingRefs.add(refPath);
601
- resolved = parse({ schema: referenced });
602
- resolvingRefs.delete(refPath);
603
- }
604
- } catch {}
605
- return resolved;
606
+ referenced = resolve(refPath);
607
+ } catch (error) {
608
+ if (Diagnostics.isError(error) && error.diagnostic.code === Diagnostics.code.refNotFound) return null;
609
+ throw error;
610
+ }
611
+ if (!referenced) return null;
612
+ resolvingRefs.add(refPath);
613
+ try {
614
+ return parse({ schema: referenced });
615
+ } finally {
616
+ resolvingRefs.delete(refPath);
617
+ }
606
618
  });
607
619
  }
608
620
  /**
@@ -905,6 +917,31 @@ const locate = (source, location) => {
905
917
  };
906
918
  // src/load/source.ts
907
919
  const urlRegExp = /^https?:\/+/i;
920
+ /** How long one request for a document or a `$ref` may take before Kubb gives up on it. */
921
+ const FETCH_TIMEOUT_MS = 3e4;
922
+ /**
923
+ * Whether `url` names a host that is loopback, private, link-local, or another address that is not
924
+ * public. A host that does not resolve, or not within the request timeout, counts as not public,
925
+ * because the check cannot prove it public. `signal` cancels the lookup.
926
+ *
927
+ * shortcut: the name is resolved again when `fetch` connects, so a host that changes its answer in
928
+ * between can still reach a private address. Upgrade to a pinned lookup, like `@kubb/studio`'s
929
+ * `publicFetch`, if a sandbox needs that guarantee.
930
+ */
931
+ async function isPrivateHost(url, { signal } = {}) {
932
+ const host = url.hostname.replace(/^\[|\]$/g, "");
933
+ if (isIP(host)) return !isPublicAddress(host);
934
+ const deadline = withTimeout(signal);
935
+ deadline.throwIfAborted();
936
+ const stopped = new Promise((_, reject) => deadline.addEventListener("abort", () => reject(deadline.reason), { once: true }));
937
+ const addresses = await Promise.race([lookup(host, { all: true }), stopped]).catch(() => []);
938
+ signal?.throwIfAborted();
939
+ return addresses.length === 0 || addresses.some(({ address }) => !isPublicAddress(address));
940
+ }
941
+ function withTimeout(signal) {
942
+ const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS);
943
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
944
+ }
908
945
  /**
909
946
  * Node reports every connection failure as `TypeError: fetch failed` and keeps the useful part
910
947
  * (`connect ECONNREFUSED 127.0.0.1:8000`) on `cause`, one level deeper again when a host resolves
@@ -921,24 +958,34 @@ function helpForStatus(status) {
921
958
  if (status >= 500) return "The server failed while serving the document. Check that it is healthy, then run Kubb again.";
922
959
  return "Open the URL in a browser or with `curl` to see what the server returns, then point `input` at a URL that serves the OpenAPI document.";
923
960
  }
924
- async function fetchSource(url) {
961
+ async function fetchSource(url, { signal, publicOnly }) {
962
+ const deadline = withTimeout(signal);
925
963
  try {
926
- return await fetch(url);
964
+ const response = await fetch(url, {
965
+ signal: deadline,
966
+ redirect: publicOnly ? "error" : "follow"
967
+ });
968
+ return {
969
+ response,
970
+ body: response.ok ? await response.text() : ""
971
+ };
927
972
  } catch (error) {
973
+ if (signal?.aborted) throw signal.reason;
974
+ const reason = deadline.aborted ? `no answer within ${FETCH_TIMEOUT_MS / 1e3} seconds` : describeFetchFailure(error);
928
975
  throw new Diagnostics.Error({
929
976
  code: Diagnostics.code.inputUnreachable,
930
977
  severity: "error",
931
- message: `Cannot reach ${url.href}: ${describeFetchFailure(error)}`,
978
+ message: `Cannot reach ${url.href}: ${reason}`,
932
979
  help: "Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`.",
933
980
  location: { kind: "config" },
934
981
  cause: error instanceof Error ? error : void 0
935
982
  });
936
983
  }
937
984
  }
938
- async function readSource(sourcePath) {
985
+ async function readSource(sourcePath, options) {
939
986
  if (urlRegExp.test(sourcePath)) {
940
987
  const url = new URL(sourcePath);
941
- const response = await fetchSource(url);
988
+ const { response, body } = await fetchSource(url, options);
942
989
  if (!response.ok) {
943
990
  const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);
944
991
  throw new Diagnostics.Error({
@@ -949,7 +996,7 @@ async function readSource(sourcePath) {
949
996
  location: { kind: "config" }
950
997
  });
951
998
  }
952
- return response.text();
999
+ return body;
953
1000
  }
954
1001
  return read(sourcePath);
955
1002
  }
@@ -957,8 +1004,8 @@ async function readSource(sourcePath) {
957
1004
  * Reads and parses one source file or URL referenced during bundling: YAML/JSON is parsed into an
958
1005
  * object, Markdown is returned as-is (bundled inline rather than dereferenced).
959
1006
  */
960
- async function resolveSource(sourcePath, { remember } = {}) {
961
- const data = await readSource(sourcePath);
1007
+ async function resolveSource(sourcePath, { remember, ...options } = {}) {
1008
+ const data = await readSource(sourcePath, options);
962
1009
  if (sourcePath.toLowerCase().endsWith(".md")) return data;
963
1010
  const pathname = urlRegExp.test(sourcePath) ? new URL(sourcePath).pathname : sourcePath;
964
1011
  return parseYaml(data, {
@@ -1122,6 +1169,9 @@ async function isInsideFolders(filePath, folders) {
1122
1169
  * including one that fails, lands in `sources`. A `$ref` that cannot be read reports
1123
1170
  * `KUBB_REF_NOT_FOUND` at the key that holds it, as a warning when it sits inside an `x-` extension.
1124
1171
  * So does any local file from a URL input, and a local file outside every `fileRefs` folder.
1172
+ * With `fileRefs` set, a `$ref` URL on a host that is not public is refused too, and a redirect
1173
+ * fails, so a document sent to a sandboxed host cannot make it request internal addresses.
1174
+ * `signal` cancels every request.
1125
1175
  *
1126
1176
  * @example Local file
1127
1177
  * `const document = await bundleDocument('./openapi.yaml')`
@@ -1129,23 +1179,37 @@ async function isInsideFolders(filePath, folders) {
1129
1179
  * @example Remote URL
1130
1180
  * `const document = await bundleDocument('https://example.com/openapi.yaml')`
1131
1181
  */
1132
- async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs } = {}) {
1182
+ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs, signal } = {}) {
1133
1183
  const cache = memo.create();
1134
1184
  const toKey = (sourcePath) => urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath;
1135
1185
  const folders = urlRegExp.test(pathOrUrl) ? [] : fileRefs;
1186
+ const publicOnly = fileRefs !== void 0;
1136
1187
  const refused = /* @__PURE__ */ new Set();
1188
+ const refusedHelp = (refusedPath) => {
1189
+ if (urlRegExp.test(refusedPath)) return "This run only fetches `$ref` URLs on public hosts. Inline the schema, or serve it from a public URL. On your own agent, `--allow-file-refs` lifts the limit.";
1190
+ if (folders?.length) return "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.";
1191
+ return "This input reads no local file. Inline the schema, or serve the file from a URL.";
1192
+ };
1137
1193
  let entry = pathOrUrl;
1138
1194
  let entryDocument = document;
1139
1195
  const resolver = async (sourcePath) => {
1140
1196
  if (entryDocument !== void 0 && toKey(sourcePath) === toKey(entry)) return entryDocument;
1141
1197
  const key = toKey(sourcePath);
1142
- if (key !== toKey(pathOrUrl) && !urlRegExp.test(sourcePath) && folders && !await isInsideFolders(sourcePath, folders)) {
1198
+ const isRef = key !== toKey(pathOrUrl);
1199
+ const isUrl = urlRegExp.test(sourcePath);
1200
+ const refusedUrl = isRef && isUrl && publicOnly && await isPrivateHost(new URL(sourcePath), { signal });
1201
+ const refusedFile = isRef && !isUrl && folders !== void 0 && !await isInsideFolders(sourcePath, folders);
1202
+ if (refusedUrl || refusedFile) {
1143
1203
  refused.add(sourcePath);
1144
1204
  throw new Error(`Refused ${sourcePath}`);
1145
1205
  }
1146
1206
  return memo(cache, key, () => {
1147
1207
  sources.push(key);
1148
- return resolveSource(sourcePath, { remember: key === toKey(pathOrUrl) });
1208
+ return resolveSource(sourcePath, {
1209
+ remember: !isRef,
1210
+ signal,
1211
+ publicOnly: publicOnly && isRef
1212
+ });
1149
1213
  });
1150
1214
  };
1151
1215
  const root = await resolver(pathOrUrl);
@@ -1157,13 +1221,14 @@ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs } =
1157
1221
  entry = getBaseUri(pathOrUrl, root);
1158
1222
  entryDocument = root;
1159
1223
  return await bundle(entry, resolver, { hooks: { onError: (message, { path, state }) => {
1224
+ signal?.throwIfAborted();
1160
1225
  const pointer = toKey(state.baseFile) === toKey(entry) ? `#/${path.map((token) => escapePointerToken(String(token))).join("/")}` : void 0;
1161
1226
  const refusedPath = [...refused].find((sourcePath) => message.includes(sourcePath));
1162
1227
  const diagnostic = {
1163
1228
  code: Diagnostics.code.refNotFound,
1164
1229
  severity: isExtensionPath(path) ? "warning" : "error",
1165
- message: refusedPath ? `Refused an external \`$ref\` to the local file ${refusedPath}.` : `Could not bundle an external \`$ref\`. ${message}.`,
1166
- 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`.",
1230
+ message: refusedPath ? `Refused an external \`$ref\` to ${urlRegExp.test(refusedPath) ? "a host that is not public" : "the local file"} ${refusedPath}.` : `Could not bundle an external \`$ref\`. ${message}.`,
1231
+ help: refusedPath ? refusedHelp(refusedPath) : "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1167
1232
  ...pointer && { location: {
1168
1233
  kind: "schema",
1169
1234
  pointer
@@ -1190,7 +1255,7 @@ const inlineInputName = "<inline input>";
1190
1255
  * const document = await parseFromConfig({ type: 'data', data: '{"openapi":"3.0.0",...}' })
1191
1256
  * ```
1192
1257
  */
1193
- async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1258
+ async function parseFromConfig(source, sources = [], { fileRefs, signal } = {}) {
1194
1259
  const raw = await (async () => {
1195
1260
  if (source.type === "data") {
1196
1261
  const data = typeof source.data === "string" ? parseYaml(source.data, {
@@ -1201,7 +1266,8 @@ async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1201
1266
  if (source.root && isObject) return bundleDocument(join(source.root, inlineInputName), {
1202
1267
  document: data,
1203
1268
  sources,
1204
- fileRefs
1269
+ fileRefs,
1270
+ signal
1205
1271
  });
1206
1272
  const scan = resolveTargets(data);
1207
1273
  if (isObject) scans.set(data, scan);
@@ -1210,7 +1276,8 @@ async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1210
1276
  await assertInputExists(source.path);
1211
1277
  return bundleDocument(source.path, {
1212
1278
  sources,
1213
- fileRefs
1279
+ fileRefs,
1280
+ signal
1214
1281
  });
1215
1282
  })();
1216
1283
  return upgradeDocument(raw, { pathRefs: scans.get(raw)?.pathRefs ?? true });
@@ -2257,7 +2324,47 @@ function getOperations(document, refs) {
2257
2324
  pathItem
2258
2325
  });
2259
2326
  }
2260
- return operations;
2327
+ return withUniqueOperationIds(operations);
2328
+ }
2329
+ function suffixed(id, taken, counts) {
2330
+ const count = (counts.get(id) ?? 1) + 1;
2331
+ counts.set(id, count);
2332
+ const candidate = `${id}_${count}`;
2333
+ return taken.has(pascalCase(candidate)) ? suffixed(id, taken, counts) : candidate;
2334
+ }
2335
+ function withUniqueOperationIds(operations) {
2336
+ const taken = new Set(operations.flatMap(({ schema }) => typeof schema.operationId === "string" && schema.operationId ? [pascalCase(schema.operationId)] : []));
2337
+ const claimed = /* @__PURE__ */ new Set();
2338
+ const counts = /* @__PURE__ */ new Map();
2339
+ return operations.map((operation) => {
2340
+ const operationId = getOperationId(operation);
2341
+ const name = pascalCase(operationId);
2342
+ if (!claimed.has(name)) {
2343
+ claimed.add(name);
2344
+ taken.add(name);
2345
+ return operation;
2346
+ }
2347
+ const unique = suffixed(operationId, taken, counts);
2348
+ taken.add(pascalCase(unique));
2349
+ claimed.add(pascalCase(unique));
2350
+ Diagnostics.report({
2351
+ code: Diagnostics.code.duplicateOperationId,
2352
+ severity: "warning",
2353
+ message: `operationId "${operationId}" of ${operation.method.toUpperCase()} ${operation.path} is already used, so it is renamed to "${unique}".`,
2354
+ help: "Give each operation its own `operationId`.",
2355
+ location: {
2356
+ kind: "operation",
2357
+ pointer: getOperationPointer(operation)
2358
+ }
2359
+ });
2360
+ return {
2361
+ ...operation,
2362
+ schema: {
2363
+ ...operation.schema,
2364
+ operationId: unique
2365
+ }
2366
+ };
2367
+ });
2261
2368
  }
2262
2369
  /** Property names whose schema has a truthy `readOnly` or `writeOnly` flag; `$ref` entries are skipped. */
2263
2370
  function collectPropertyKeysByFlag(schema, flag) {
@@ -3136,9 +3243,13 @@ function inheritScalarType(members, { schema, type }) {
3136
3243
  function convertUnion(context) {
3137
3244
  if (context.schema.enum?.length) {
3138
3245
  const { enum: values, ...union } = context.schema;
3246
+ const nullable = context.nullable || [...union.oneOf ?? [], ...union.anyOf ?? []].some((member) => {
3247
+ const resolved = isReference(member) ? context.refs.resolve(member.$ref, { report: false }) : member;
3248
+ return !!resolved && !isReference(resolved) && isNullable(resolved, context.document);
3249
+ });
3139
3250
  const enumSchema = {
3140
3251
  type: union.type,
3141
- enum: isLegacyDocument(context.document) ? [...values, null] : values
3252
+ enum: nullable && isLegacyDocument(context.document) ? [...values, null] : values
3142
3253
  };
3143
3254
  const members = [convertUnion({
3144
3255
  ...context,
@@ -4148,7 +4259,7 @@ const adapterOas = defineExtension({
4148
4259
  const document = await parseFromConfig({
4149
4260
  type: "path",
4150
4261
  path: input
4151
- });
4262
+ }, [], { fileRefs: options?.fileRefs });
4152
4263
  assertDocument(document);
4153
4264
  await validateDocument(document, options);
4154
4265
  },
@@ -4160,15 +4271,24 @@ const adapterOas = defineExtension({
4160
4271
  const cached = inputCache.get(source);
4161
4272
  if (cached) {
4162
4273
  sources = cached.sources;
4274
+ parsedDocument = cached.document;
4163
4275
  return cached.promise;
4164
4276
  }
4165
4277
  const read = [];
4166
4278
  sources = read;
4279
+ const entry = {
4280
+ sources: read,
4281
+ document: null
4282
+ };
4167
4283
  const promise = (async () => {
4168
- const document = await parseFromConfig(source, read, { fileRefs });
4284
+ const document = await parseFromConfig(source, read, {
4285
+ fileRefs,
4286
+ signal
4287
+ });
4169
4288
  signal?.throwIfAborted();
4170
4289
  assertDocument(document);
4171
4290
  if (validate) pendingValidations.push(validateDocumentInWorker(document));
4291
+ entry.document = document;
4172
4292
  parsedDocument = document;
4173
4293
  const refs = createRefs(document);
4174
4294
  const { schemas, renames, pointers } = getSchemas(document, { contentType }, refs);
@@ -4186,10 +4306,7 @@ const adapterOas = defineExtension({
4186
4306
  parseSchema
4187
4307
  }));
4188
4308
  })();
4189
- inputCache.set(source, {
4190
- promise,
4191
- sources: read
4192
- });
4309
+ inputCache.set(source, Object.assign(entry, { promise }));
4193
4310
  return promise.catch((error) => {
4194
4311
  if (signal?.aborted) inputCache.delete(source);
4195
4312
  throw error;