@kubb/oas 4.32.4 → 4.33.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.d.ts CHANGED
@@ -32,6 +32,12 @@ type ResponseObject = ResponseObject$1;
32
32
  type MediaTypeObject = MediaTypeObject$1;
33
33
  //#endregion
34
34
  //#region src/Oas.d.ts
35
+ /**
36
+ * Prefix used to create synthetic `$ref` values for anonymous (inline) discriminator schemas.
37
+ * The suffix is the schema index within the discriminator's `oneOf`/`anyOf` array.
38
+ * @example `#kubb-inline-0`
39
+ */
40
+ declare const KUBB_INLINE_REF_PREFIX = "#kubb-inline-";
35
41
  type OasOptions = {
36
42
  contentType?: contentType;
37
43
  discriminator?: 'strict' | 'inherit';
@@ -71,6 +77,23 @@ declare class Oas extends BaseOas {
71
77
  };
72
78
  }
73
79
  //#endregion
80
+ //#region src/resolveServerUrl.d.ts
81
+ type ServerVariable = {
82
+ default?: string | number;
83
+ enum?: (string | number)[];
84
+ };
85
+ type ServerObject = {
86
+ url: string;
87
+ variables?: Record<string, ServerVariable>;
88
+ };
89
+ /**
90
+ * Resolves an OpenAPI server URL by substituting `{variable}` placeholders
91
+ * with values from `overrides` (user-provided) or the spec-defined defaults.
92
+ *
93
+ * Throws if an override value is not in the variable's `enum` list.
94
+ */
95
+ declare function resolveServerUrl(server: ServerObject, overrides?: Record<string, string>): string;
96
+ //#endregion
74
97
  //#region src/utils.d.ts
75
98
  declare function isOpenApiV3_1Document(doc: any): doc is OpenAPIV3_1$1.Document;
76
99
  declare function isParameterObject(obj: ParameterObject | SchemaObject$1): obj is ParameterObject;
@@ -130,5 +153,5 @@ declare function parseFromConfig(config: Config, oasClass?: typeof Oas): Promise
130
153
  */
131
154
  declare function validate(document: Document): Promise<_readme_openapi_parser0.ValidationResult>;
132
155
  //#endregion
133
- export { DiscriminatorObject, Document, HttpMethod, HttpMethods, MediaTypeObject, Oas, type OasTypes, type OpenAPIV3, type OpenAPIV3_1, Operation, ReferenceObject, ResponseObject, SchemaObject, contentType, getDefaultValue, isAllOptional, isDiscriminator, isNullable, isOpenApiV3_1Document, isOptional, isParameterObject, isReference, isRequired, merge, parse, parseFromConfig, validate };
156
+ export { DiscriminatorObject, Document, HttpMethod, HttpMethods, KUBB_INLINE_REF_PREFIX, MediaTypeObject, Oas, type OasTypes, type OpenAPIV3, type OpenAPIV3_1, Operation, ReferenceObject, ResponseObject, SchemaObject, contentType, getDefaultValue, isAllOptional, isDiscriminator, isNullable, isOpenApiV3_1Document, isOptional, isParameterObject, isReference, isRequired, merge, parse, parseFromConfig, resolveServerUrl, validate };
134
157
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -4,13 +4,182 @@ import BaseOas from "oas";
4
4
  import { matchesMimeType } from "oas/utils";
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
- import { pascalCase } from "@kubb/core/transformers";
8
- import { URLPath } from "@kubb/core/utils";
9
7
  import { bundle } from "@readme/openapi-parser";
10
8
  import { isRef } from "oas/types";
11
9
  import OASNormalize from "oas-normalize";
12
10
  import { isPlainObject, mergeDeep } from "remeda";
13
11
  import swagger2openapi from "swagger2openapi";
12
+ //#region ../../internals/utils/src/casing.ts
13
+ /**
14
+ * Shared implementation for camelCase and PascalCase conversion.
15
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
16
+ * and capitalizes each word according to `pascal`.
17
+ *
18
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
19
+ */
20
+ function toCamelOrPascal(text, pascal) {
21
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
22
+ if (word.length > 1 && word === word.toUpperCase()) return word;
23
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
24
+ return word.charAt(0).toUpperCase() + word.slice(1);
25
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
26
+ }
27
+ /**
28
+ * Splits `text` on `.` and applies `transformPart` to each segment.
29
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
30
+ * Segments are joined with `/` to form a file path.
31
+ */
32
+ function applyToFileParts(text, transformPart) {
33
+ const parts = text.split(".");
34
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
35
+ }
36
+ /**
37
+ * Converts `text` to camelCase.
38
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
39
+ *
40
+ * @example
41
+ * camelCase('hello-world') // 'helloWorld'
42
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
43
+ */
44
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
45
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
46
+ prefix,
47
+ suffix
48
+ } : {}));
49
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
50
+ }
51
+ /**
52
+ * Converts `text` to PascalCase.
53
+ * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
54
+ *
55
+ * @example
56
+ * pascalCase('hello-world') // 'HelloWorld'
57
+ * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
58
+ */
59
+ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
60
+ if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
61
+ prefix,
62
+ suffix
63
+ }) : camelCase(part));
64
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
65
+ }
66
+ //#endregion
67
+ //#region ../../internals/utils/src/reserved.ts
68
+ /**
69
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
70
+ */
71
+ function isValidVarName(name) {
72
+ try {
73
+ new Function(`var ${name}`);
74
+ } catch {
75
+ return false;
76
+ }
77
+ return true;
78
+ }
79
+ //#endregion
80
+ //#region ../../internals/utils/src/urlPath.ts
81
+ /**
82
+ * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
83
+ *
84
+ * @example
85
+ * const p = new URLPath('/pet/{petId}')
86
+ * p.URL // '/pet/:petId'
87
+ * p.template // '`/pet/${petId}`'
88
+ */
89
+ var URLPath = class {
90
+ /** The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`. */
91
+ path;
92
+ #options;
93
+ constructor(path, options = {}) {
94
+ this.path = path;
95
+ this.#options = options;
96
+ }
97
+ /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */
98
+ get URL() {
99
+ return this.toURLPath();
100
+ }
101
+ /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`). */
102
+ get isURL() {
103
+ try {
104
+ return !!new URL(this.path).href;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+ /**
110
+ * Converts the OpenAPI path to a TypeScript template literal string.
111
+ *
112
+ * @example
113
+ * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
114
+ * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
115
+ */
116
+ get template() {
117
+ return this.toTemplateString();
118
+ }
119
+ /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set. */
120
+ get object() {
121
+ return this.toObject();
122
+ }
123
+ /** Returns a map of path parameter names, or `undefined` when the path has no parameters. */
124
+ get params() {
125
+ return this.getParams();
126
+ }
127
+ #transformParam(raw) {
128
+ const param = isValidVarName(raw) ? raw : camelCase(raw);
129
+ return this.#options.casing === "camelcase" ? camelCase(param) : param;
130
+ }
131
+ /** Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name. */
132
+ #eachParam(fn) {
133
+ for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
134
+ const raw = match[1];
135
+ fn(raw, this.#transformParam(raw));
136
+ }
137
+ }
138
+ toObject({ type = "path", replacer, stringify } = {}) {
139
+ const object = {
140
+ url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
141
+ params: this.getParams()
142
+ };
143
+ if (stringify) {
144
+ if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
145
+ if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
146
+ return `{ url: '${object.url}' }`;
147
+ }
148
+ return object;
149
+ }
150
+ /**
151
+ * Converts the OpenAPI path to a TypeScript template literal string.
152
+ * An optional `replacer` can transform each extracted parameter name before interpolation.
153
+ *
154
+ * @example
155
+ * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
156
+ */
157
+ toTemplateString({ prefix = "", replacer } = {}) {
158
+ return `\`${prefix}${this.path.split(/\{([^}]+)\}/).map((part, i) => {
159
+ if (i % 2 === 0) return part;
160
+ const param = this.#transformParam(part);
161
+ return `\${${replacer ? replacer(param) : param}}`;
162
+ }).join("")}\``;
163
+ }
164
+ /**
165
+ * Extracts all `{param}` segments from the path and returns them as a key-value map.
166
+ * An optional `replacer` transforms each parameter name in both key and value positions.
167
+ * Returns `undefined` when no path parameters are found.
168
+ */
169
+ getParams(replacer) {
170
+ const params = {};
171
+ this.#eachParam((_raw, param) => {
172
+ const key = replacer ? replacer(param) : param;
173
+ params[key] = key;
174
+ });
175
+ return Object.keys(params).length > 0 ? params : void 0;
176
+ }
177
+ /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */
178
+ toURLPath() {
179
+ return this.path.replace(/\{([^}]+)\}/g, ":$1");
180
+ }
181
+ };
182
+ //#endregion
14
183
  //#region ../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs
15
184
  var tslib_es6_exports = /* @__PURE__ */ __exportAll({
16
185
  __addDisposableResource: () => __addDisposableResource,
@@ -4610,6 +4779,12 @@ function resolveCollisions(schemasWithMeta) {
4610
4779
  }
4611
4780
  //#endregion
4612
4781
  //#region src/Oas.ts
4782
+ /**
4783
+ * Prefix used to create synthetic `$ref` values for anonymous (inline) discriminator schemas.
4784
+ * The suffix is the schema index within the discriminator's `oneOf`/`anyOf` array.
4785
+ * @example `#kubb-inline-0`
4786
+ */
4787
+ const KUBB_INLINE_REF_PREFIX = "#kubb-inline-";
4613
4788
  var Oas = class extends BaseOas {
4614
4789
  #options = { discriminator: "strict" };
4615
4790
  document;
@@ -4708,7 +4883,7 @@ var Oas = class extends BaseOas {
4708
4883
  }
4709
4884
  } else {
4710
4885
  const discriminatorValue = getDiscriminatorValue(schemaItem);
4711
- if (discriminatorValue) existingMapping[discriminatorValue] = `#kubb-inline-${index}`;
4886
+ if (discriminatorValue) existingMapping[discriminatorValue] = `${KUBB_INLINE_REF_PREFIX}${index}`;
4712
4887
  }
4713
4888
  });
4714
4889
  };
@@ -4915,6 +5090,25 @@ var Oas = class extends BaseOas {
4915
5090
  }
4916
5091
  };
4917
5092
  //#endregion
5093
+ //#region src/resolveServerUrl.ts
5094
+ /**
5095
+ * Resolves an OpenAPI server URL by substituting `{variable}` placeholders
5096
+ * with values from `overrides` (user-provided) or the spec-defined defaults.
5097
+ *
5098
+ * Throws if an override value is not in the variable's `enum` list.
5099
+ */
5100
+ function resolveServerUrl(server, overrides) {
5101
+ if (!server.variables) return server.url;
5102
+ let url = server.url;
5103
+ for (const [key, variable] of Object.entries(server.variables)) {
5104
+ const value = overrides?.[key] ?? (variable.default != null ? String(variable.default) : void 0);
5105
+ if (value === void 0) continue;
5106
+ if (variable.enum?.length && !variable.enum.some((e) => String(e) === value)) throw new Error(`Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(", ")}.`);
5107
+ url = url.replaceAll(`{${key}}`, value);
5108
+ }
5109
+ return url;
5110
+ }
5111
+ //#endregion
4918
5112
  //#region src/types.ts
4919
5113
  const HttpMethods = {
4920
5114
  GET: "get",
@@ -4927,6 +5121,6 @@ const HttpMethods = {
4927
5121
  TRACE: "trace"
4928
5122
  };
4929
5123
  //#endregion
4930
- export { HttpMethods, Oas, getDefaultValue, isAllOptional, isDiscriminator, isNullable, isOpenApiV3_1Document, isOptional, isParameterObject, isReference, isRequired, merge, parse, parseFromConfig, validate };
5124
+ export { HttpMethods, KUBB_INLINE_REF_PREFIX, Oas, getDefaultValue, isAllOptional, isDiscriminator, isNullable, isOpenApiV3_1Document, isOptional, isParameterObject, isReference, isRequired, merge, parse, parseFromConfig, resolveServerUrl, validate };
4931
5125
 
4932
5126
  //# sourceMappingURL=index.js.map