@readme/oas-to-har 39.0.1 → 40.0.0

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,1326 +1,1196 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1
+ // \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
2
26
 
3
- var _chunk6CVT7KVTcjs = require('./chunk-6CVT7KVT.cjs');
4
-
5
- // src/index.ts
6
- var _dataurls = require('@readme/data-urls');
7
- var _extensions = require('oas/extensions');
8
- var _operation = require('oas/operation');
9
- var _types = require('oas/types');
10
- var _utils = require('oas/utils');
11
- var _removeundefinedobjects = require('remove-undefined-objects'); var _removeundefinedobjects2 = _interopRequireDefault(_removeundefinedobjects);
27
+ const require_lib_configure_security = require("./lib/configure-security.cjs");
28
+ let _readme_data_urls = require("@readme/data-urls");
29
+ let oas_extensions = require("oas/extensions");
30
+ let oas_operation = require("oas/operation");
31
+ let oas_types = require("oas/types");
32
+ let oas_utils = require("oas/utils");
33
+ let remove_undefined_objects = require("remove-undefined-objects");
34
+ remove_undefined_objects = __toESM(remove_undefined_objects, 1);
35
+ let qs = require("qs");
36
+ qs = __toESM(qs, 1);
12
37
 
13
38
  // src/lib/lodash.ts
39
+ /**
40
+ * A janky, poorly typed replacement for `lodash.get`.
41
+ *
42
+ * @see {@link https://youmightnotneed.com/lodash#get}
43
+ */
14
44
  function get(object, path) {
15
- if (!path) return void 0;
16
- const pathArray = String(path).match(/([^[.\]])+/g);
17
- const result = _optionalChain([pathArray, 'optionalAccess', _ => _.reduce, 'call', _2 => _2((prevObj, key) => _optionalChain([prevObj, 'optionalAccess', _3 => _3[key]]), object)]);
18
- return result;
45
+ if (!path) return void 0;
46
+ return String(path).match(/([^[.\]])+/g)?.reduce((prevObj, key) => prevObj?.[key], object);
19
47
  }
48
+ /**
49
+ * A janky, poorly typed replacement for `lodash.set`.
50
+ *
51
+ * @see {@link https://youmightnotneed.com/lodash#set}
52
+ */
20
53
  function set(object, path, value) {
21
- const pathArray = Array.isArray(path) ? path : String(path).match(/([^[.\]])+/g);
22
- return _optionalChain([pathArray, 'optionalAccess', _4 => _4.reduce, 'call', _5 => _5((acc, key, i) => {
23
- if (acc[key] === void 0) {
24
- acc[key] = {};
25
- }
26
- if (i === pathArray.length - 1) {
27
- acc[key] = value;
28
- }
29
- return acc[key];
30
- }, object)]);
54
+ const pathArray = Array.isArray(path) ? path : String(path).match(/([^[.\]])+/g);
55
+ return pathArray?.reduce((acc, key, i) => {
56
+ if (acc[key] === void 0) acc[key] = {};
57
+ if (i === pathArray.length - 1) acc[key] = value;
58
+ return acc[key];
59
+ }, object);
31
60
  }
32
61
 
33
- // src/lib/style-formatting/index.ts
34
-
35
- var _qs = require('qs'); var _qs2 = _interopRequireDefault(_qs);
36
-
37
62
  // src/lib/utils.ts
38
-
39
-
63
+ /**
64
+ * Determine if a schema `type` is, or contains, a specific discriminator.
65
+ *
66
+ */
40
67
  function hasSchemaType(schema, discriminator) {
41
- if (Array.isArray(schema.type)) {
42
- return schema.type.includes(discriminator);
43
- }
44
- return schema.type === discriminator;
68
+ if (Array.isArray(schema.type)) return schema.type.includes(discriminator);
69
+ return schema.type === discriminator;
45
70
  }
71
+ /**
72
+ * When we only have a schema fragment (no request payload), peel a single top-level polymorphic
73
+ * schema to its first branch so we can enumerate its properties.
74
+ *
75
+ */
46
76
  function unwrapFirstPolymorphicBranch(obj) {
47
- if (obj.oneOf && Array.isArray(obj.oneOf) && obj.oneOf.length) {
48
- return unwrapFirstPolymorphicBranch(obj.oneOf[0]);
49
- }
50
- if (obj.anyOf && Array.isArray(obj.anyOf) && obj.anyOf.length) {
51
- return unwrapFirstPolymorphicBranch(obj.anyOf[0]);
52
- }
53
- return obj;
77
+ if (obj.oneOf && Array.isArray(obj.oneOf) && obj.oneOf.length) return unwrapFirstPolymorphicBranch(obj.oneOf[0]);
78
+ if (obj.anyOf && Array.isArray(obj.anyOf) && obj.anyOf.length) return unwrapFirstPolymorphicBranch(obj.anyOf[0]);
79
+ return obj;
54
80
  }
55
81
  function getSubschemas(schema, api, opts, seenRefs = /* @__PURE__ */ new Set()) {
56
- let subSchemaDataSize = 0;
57
- if (opts.parentIsArray) {
58
- const parentData = get(opts.payload, opts.parentKey || "");
59
- if (parentData === void 0 || !Array.isArray(parentData)) {
60
- return false;
61
- }
62
- subSchemaDataSize = parentData.length;
63
- }
64
- let subschemas = [];
65
- if (subSchemaDataSize > 0) {
66
- for (let idx = 0; idx < subSchemaDataSize; idx += 1) {
67
- const foundSubschemas = getSubschemas(
68
- schema,
69
- api,
70
- {
71
- ...opts,
72
- parentIsArray: false,
73
- parentKey: opts.parentKey ? [opts.parentKey, idx].join(".") : String(idx)
74
- },
75
- seenRefs
76
- );
77
- if (foundSubschemas) {
78
- subschemas = subschemas.concat(foundSubschemas);
79
- }
80
- }
81
- } else {
82
- let resolvedSchema = schema;
83
- if (schema && _types.isRef.call(void 0, schema)) {
84
- if (seenRefs.has(schema.$ref)) {
85
- return subschemas;
86
- }
87
- seenRefs.add(schema.$ref);
88
- resolvedSchema = _utils.dereferenceRef.call(void 0, schema, api);
89
- if (!resolvedSchema || _types.isRef.call(void 0, resolvedSchema)) {
90
- return subschemas;
91
- }
92
- }
93
- const baseKey = _nullishCoalesce(opts.parentKey, () => ( ""));
94
- if (resolvedSchema.properties && typeof resolvedSchema.properties === "object") {
95
- for (const [propName, propSchema] of Object.entries(resolvedSchema.properties)) {
96
- if (propSchema && typeof propSchema === "object") {
97
- let resolved;
98
- if (_types.isRef.call(void 0, propSchema)) {
99
- if (seenRefs.has(propSchema.$ref)) {
100
- continue;
101
- }
102
- seenRefs.add(propSchema.$ref);
103
- resolved = _utils.dereferenceRef.call(void 0, propSchema, api);
104
- } else {
105
- resolved = propSchema;
106
- }
107
- if (resolved && !_types.isRef.call(void 0, resolved)) {
108
- subschemas.push({
109
- key: baseKey ? [baseKey, propName].join(".") : propName,
110
- schema: resolved
111
- });
112
- }
113
- }
114
- }
115
- }
116
- if (!("properties" in resolvedSchema) && typeof resolvedSchema === "object" && !("type" in resolvedSchema && resolvedSchema.type !== "object")) {
117
- for (const [propName, propSchema] of Object.entries(resolvedSchema)) {
118
- if (propSchema && (Array.isArray(propSchema) || typeof propSchema === "object" && propSchema !== null)) {
119
- const raw = unwrapFirstPolymorphicBranch(propSchema);
120
- const resolved = _types.isRef.call(void 0, raw) ? _utils.dereferenceRef.call(void 0, raw, api) : raw;
121
- const toPush = resolved && !_types.isRef.call(void 0, resolved) ? resolved : raw;
122
- if (toPush && typeof toPush === "object") {
123
- subschemas.push({
124
- key: baseKey ? [baseKey, propName].join(".") : propName,
125
- schema: toPush
126
- });
127
- }
128
- }
129
- }
130
- }
131
- if ("items" in resolvedSchema && resolvedSchema.items !== void 0 && resolvedSchema.items !== true) {
132
- const itemsSchema = resolvedSchema.items;
133
- let resolved;
134
- if (_types.isRef.call(void 0, itemsSchema)) {
135
- if (!seenRefs.has(itemsSchema.$ref)) {
136
- seenRefs.add(itemsSchema.$ref);
137
- resolved = _utils.dereferenceRef.call(void 0, itemsSchema, api);
138
- }
139
- } else {
140
- resolved = itemsSchema;
141
- }
142
- if (resolved && !_types.isRef.call(void 0, resolved)) {
143
- subschemas.push({
144
- key: baseKey,
145
- schema: resolved,
146
- parentIsArray: true
147
- });
148
- }
149
- }
150
- }
151
- return subschemas;
82
+ let subSchemaDataSize = 0;
83
+ if (opts.parentIsArray) {
84
+ const parentData = get(opts.payload, opts.parentKey || "");
85
+ if (parentData === void 0 || !Array.isArray(parentData)) return false;
86
+ subSchemaDataSize = parentData.length;
87
+ }
88
+ let subschemas = [];
89
+ if (subSchemaDataSize > 0) for (let idx = 0; idx < subSchemaDataSize; idx += 1) {
90
+ const foundSubschemas = getSubschemas(schema, api, {
91
+ ...opts,
92
+ parentIsArray: false,
93
+ parentKey: opts.parentKey ? [opts.parentKey, idx].join(".") : String(idx)
94
+ }, seenRefs);
95
+ if (foundSubschemas) subschemas = subschemas.concat(foundSubschemas);
96
+ }
97
+ else {
98
+ let resolvedSchema = schema;
99
+ if (schema && (0, oas_types.isRef)(schema)) {
100
+ if (seenRefs.has(schema.$ref)) return subschemas;
101
+ seenRefs.add(schema.$ref);
102
+ resolvedSchema = (0, oas_utils.dereferenceRef)(schema, api);
103
+ if (!resolvedSchema || (0, oas_types.isRef)(resolvedSchema)) return subschemas;
104
+ }
105
+ const baseKey = opts.parentKey ?? "";
106
+ if (resolvedSchema.properties && typeof resolvedSchema.properties === "object") {
107
+ for (const [propName, propSchema] of Object.entries(resolvedSchema.properties)) if (propSchema && typeof propSchema === "object") {
108
+ let resolved;
109
+ if ((0, oas_types.isRef)(propSchema)) {
110
+ if (seenRefs.has(propSchema.$ref)) continue;
111
+ seenRefs.add(propSchema.$ref);
112
+ resolved = (0, oas_utils.dereferenceRef)(propSchema, api);
113
+ } else resolved = propSchema;
114
+ if (resolved && !(0, oas_types.isRef)(resolved)) subschemas.push({
115
+ key: baseKey ? [baseKey, propName].join(".") : propName,
116
+ schema: resolved
117
+ });
118
+ }
119
+ }
120
+ if (!("properties" in resolvedSchema) && typeof resolvedSchema === "object" && !("type" in resolvedSchema && resolvedSchema.type !== "object")) {
121
+ for (const [propName, propSchema] of Object.entries(resolvedSchema)) if (propSchema && (Array.isArray(propSchema) || typeof propSchema === "object" && propSchema !== null)) {
122
+ const raw = unwrapFirstPolymorphicBranch(propSchema);
123
+ const resolved = (0, oas_types.isRef)(raw) ? (0, oas_utils.dereferenceRef)(raw, api) : raw;
124
+ const toPush = resolved && !(0, oas_types.isRef)(resolved) ? resolved : raw;
125
+ if (toPush && typeof toPush === "object") subschemas.push({
126
+ key: baseKey ? [baseKey, propName].join(".") : propName,
127
+ schema: toPush
128
+ });
129
+ }
130
+ }
131
+ if ("items" in resolvedSchema && resolvedSchema.items !== void 0 && resolvedSchema.items !== true) {
132
+ const itemsSchema = resolvedSchema.items;
133
+ let resolved;
134
+ if ((0, oas_types.isRef)(itemsSchema)) {
135
+ if (!seenRefs.has(itemsSchema.$ref)) {
136
+ seenRefs.add(itemsSchema.$ref);
137
+ resolved = (0, oas_utils.dereferenceRef)(itemsSchema, api);
138
+ }
139
+ } else resolved = itemsSchema;
140
+ if (resolved && !(0, oas_types.isRef)(resolved)) subschemas.push({
141
+ key: baseKey,
142
+ schema: resolved,
143
+ parentIsArray: true
144
+ });
145
+ }
146
+ }
147
+ return subschemas;
152
148
  }
149
+ /**
150
+ * With a supplied JSON Schema object, spider through it for any schemas that may contain specific
151
+ * kind of `format` that also happen to be within the current `requestBody` payload that we're
152
+ * creating a HAR representation for.
153
+ *
154
+ */
153
155
  function getTypedFormatsInSchema(format, schema, api, opts, seenRefs = /* @__PURE__ */ new Set()) {
154
- try {
155
- if (_optionalChain([schema, 'optionalAccess', _6 => _6.format]) === format) {
156
- if (opts.parentIsArray) {
157
- const parentData = get(opts.payload, opts.parentKey || "");
158
- if (parentData !== void 0 && Array.isArray(parentData)) {
159
- return Object.keys(parentData).map((pdk) => {
160
- const currentKey = [opts.parentKey, pdk].join(".");
161
- if (get(opts.payload, currentKey) !== void 0) {
162
- return currentKey;
163
- }
164
- return false;
165
- }).filter(Boolean);
166
- }
167
- } else if (opts.parentKey && get(opts.payload, opts.parentKey) !== void 0) {
168
- return opts.parentKey;
169
- } else if (!opts.parentKey && opts.payload !== void 0) {
170
- return true;
171
- }
172
- return false;
173
- }
174
- const subschemas = getSubschemas(schema, api, opts, seenRefs);
175
- if (!subschemas) {
176
- return false;
177
- }
178
- return subschemas.flatMap(({ key, schema: subschema, parentIsArray: entryIsArray }) => {
179
- if (_types.isRef.call(void 0, subschema)) {
180
- const resolved = _utils.dereferenceRef.call(void 0, subschema, api);
181
- if (resolved && !_types.isRef.call(void 0, resolved)) {
182
- return resolved;
183
- }
184
- return false;
185
- }
186
- return getTypedFormatsInSchema(
187
- format,
188
- subschema,
189
- api,
190
- {
191
- payload: opts.payload,
192
- parentKey: key,
193
- parentIsArray: entryIsArray
194
- },
195
- seenRefs
196
- );
197
- }).filter(Boolean);
198
- } catch (e) {
199
- return [];
200
- }
156
+ try {
157
+ if (schema?.format === format) {
158
+ if (opts.parentIsArray) {
159
+ const parentData = get(opts.payload, opts.parentKey || "");
160
+ if (parentData !== void 0 && Array.isArray(parentData)) return Object.keys(parentData).map((pdk) => {
161
+ const currentKey = [opts.parentKey, pdk].join(".");
162
+ if (get(opts.payload, currentKey) !== void 0) return currentKey;
163
+ return false;
164
+ }).filter(Boolean);
165
+ } else if (opts.parentKey && get(opts.payload, opts.parentKey) !== void 0) return opts.parentKey;
166
+ else if (!opts.parentKey && opts.payload !== void 0) return true;
167
+ return false;
168
+ }
169
+ const subschemas = getSubschemas(schema, api, opts, seenRefs);
170
+ if (!subschemas) return false;
171
+ return subschemas.flatMap(({ key, schema: subschema, parentIsArray: entryIsArray }) => {
172
+ if ((0, oas_types.isRef)(subschema)) {
173
+ const resolved = (0, oas_utils.dereferenceRef)(subschema, api);
174
+ if (resolved && !(0, oas_types.isRef)(resolved)) return resolved;
175
+ return false;
176
+ }
177
+ return getTypedFormatsInSchema(format, subschema, api, {
178
+ payload: opts.payload,
179
+ parentKey: key,
180
+ parentIsArray: entryIsArray
181
+ }, seenRefs);
182
+ }).filter(Boolean);
183
+ } catch {
184
+ return [];
185
+ }
201
186
  }
187
+ /**
188
+ * Extract content type from a parameter's `content` field.
189
+ * According to OAS spec, when `content` is present, `style` and `explode` are ignored.
190
+ * We prioritize `application/json` and other JSON-like content types over other content types.
191
+ * Note: this is just a safe guard. In OAS parser, we enforce that there is exactly one content type.
192
+ *
193
+ * @param param - The parameter object
194
+ * @returns The content type, or `null` if no content is present
195
+ */
202
196
  function getParameterContentType(param) {
203
- if (!("content" in param) || typeof param.content !== "object" || !param.content) {
204
- return null;
205
- }
206
- const contentKeys = Object.keys(param.content);
207
- if (contentKeys.length < 1) {
208
- return null;
209
- }
210
- return _utils.getParameterContentType.call(void 0, contentKeys) || null;
197
+ if (!param.content) return null;
198
+ const contentKeys = Object.keys(param.content);
199
+ if (contentKeys.length < 1) return null;
200
+ return (0, oas_utils.getParameterContentType)(contentKeys) || null;
211
201
  }
202
+ /**
203
+ * Extract schema from a parameter's `content` field.
204
+ *
205
+ * @param param - The parameter object
206
+ * @param contentType - The content type
207
+ * @returns The schema, or `null` if no schema is present
208
+ */
212
209
  function getParameterContentSchema(param, contentType, api) {
213
- if (!("content" in param) || typeof param.content !== "object" || !param.content) {
214
- return null;
215
- }
216
- const mediaTypeObject = param.content[contentType];
217
- if (typeof mediaTypeObject === "object" && mediaTypeObject && "schema" in mediaTypeObject && mediaTypeObject.schema) {
218
- const schema = _types.isRef.call(void 0, mediaTypeObject.schema) ? _utils.dereferenceRef.call(void 0, mediaTypeObject.schema, api) : mediaTypeObject.schema;
219
- if (!schema || _types.isRef.call(void 0, schema)) {
220
- return null;
221
- }
222
- return schema;
223
- }
224
- return null;
210
+ if (!param.content) return null;
211
+ const mediaTypeObject = param.content[contentType];
212
+ if (typeof mediaTypeObject === "object" && mediaTypeObject && "schema" in mediaTypeObject && mediaTypeObject.schema) {
213
+ const schema = (0, oas_types.isRef)(mediaTypeObject.schema) ? (0, oas_utils.dereferenceRef)(mediaTypeObject.schema, api) : mediaTypeObject.schema;
214
+ if (!schema || (0, oas_types.isRef)(schema)) return null;
215
+ return schema;
216
+ }
217
+ return null;
225
218
  }
219
+ /**
220
+ * Recursively parse string values that are valid JSON.
221
+ *
222
+ * This is used when we're dealing with objects that have nested `format: json` descriptors.
223
+ */
226
224
  function parseJSONStrings(obj) {
227
- if (typeof obj === "string") {
228
- try {
229
- const p = JSON.parse(obj);
230
- return typeof p === "object" && p !== null ? parseJSONStrings(p) : p;
231
- } catch (e2) {
232
- return obj;
233
- }
234
- }
235
- if (Array.isArray(obj)) {
236
- return obj.map(parseJSONStrings);
237
- }
238
- if (obj !== null && typeof obj === "object") {
239
- const out = {};
240
- for (const [k, v] of Object.entries(obj)) {
241
- out[k] = parseJSONStrings(v);
242
- }
243
- return out;
244
- }
245
- return obj;
225
+ if (typeof obj === "string") try {
226
+ const p = JSON.parse(obj);
227
+ return typeof p === "object" && p !== null ? parseJSONStrings(p) : p;
228
+ } catch {
229
+ return obj;
230
+ }
231
+ if (Array.isArray(obj)) return obj.map(parseJSONStrings);
232
+ if (obj !== null && typeof obj === "object") {
233
+ const out = {};
234
+ for (const [k, v] of Object.entries(obj)) out[k] = parseJSONStrings(v);
235
+ return out;
236
+ }
237
+ return obj;
246
238
  }
239
+ /**
240
+ * Like {@link parseJSONStrings} but only parses string values that are clearly JSON objects or
241
+ * arrays (after trim, starts with `{` or `[`). Used for payload keys that are not declared on the
242
+ * schema's `properties` map so numerical strings are not coerced into numbers.
243
+ */
247
244
  function parseJSONStringsObjectContainersOnly(obj) {
248
- if (typeof obj === "string") {
249
- const trimmed = obj.trim();
250
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
251
- try {
252
- const parsed = JSON.parse(obj);
253
- return parseJSONStringsObjectContainersOnly(parsed);
254
- } catch (e3) {
255
- return obj;
256
- }
257
- }
258
- return obj;
259
- }
260
- if (Array.isArray(obj)) {
261
- return obj.map(parseJSONStringsObjectContainersOnly);
262
- }
263
- if (obj !== null && typeof obj === "object") {
264
- const out = {};
265
- for (const [k, v] of Object.entries(obj)) {
266
- out[k] = parseJSONStringsObjectContainersOnly(v);
267
- }
268
- return out;
269
- }
270
- return obj;
245
+ if (typeof obj === "string") {
246
+ const trimmed = obj.trim();
247
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
248
+ return parseJSONStringsObjectContainersOnly(JSON.parse(obj));
249
+ } catch {
250
+ return obj;
251
+ }
252
+ return obj;
253
+ }
254
+ if (Array.isArray(obj)) return obj.map(parseJSONStringsObjectContainersOnly);
255
+ if (obj !== null && typeof obj === "object") {
256
+ const out = {};
257
+ for (const [k, v] of Object.entries(obj)) out[k] = parseJSONStringsObjectContainersOnly(v);
258
+ return out;
259
+ }
260
+ return obj;
271
261
  }
272
262
  function getAdditionalPropertiesSchema(schema) {
273
- return schema.additionalProperties && typeof schema.additionalProperties === "object" ? schema.additionalProperties : void 0;
263
+ return schema.additionalProperties && typeof schema.additionalProperties === "object" ? schema.additionalProperties : void 0;
274
264
  }
275
265
  function mergePropertiesFromAllOf(allOf, api, seenRefs) {
276
- const merged = {};
277
- let found = false;
278
- for (const branch of allOf) {
279
- const collected = collectSchemaObjectProperties(branch, api, new Set(seenRefs));
280
- if (collected) {
281
- found = true;
282
- Object.assign(merged, collected);
283
- }
284
- }
285
- return found ? merged : void 0;
266
+ const merged = {};
267
+ let found = false;
268
+ for (const branch of allOf) {
269
+ const collected = collectSchemaObjectProperties(branch, api, new Set(seenRefs));
270
+ if (collected) {
271
+ found = true;
272
+ Object.assign(merged, collected);
273
+ }
274
+ }
275
+ return found ? merged : void 0;
286
276
  }
287
277
  function collectSchemaObjectProperties(schema, api, seenRefs) {
288
- let node = schema;
289
- if (_types.isRef.call(void 0, node)) {
290
- if (seenRefs.has(node.$ref)) {
291
- return void 0;
292
- }
293
- seenRefs.add(node.$ref);
294
- const deref = _utils.dereferenceRef.call(void 0, node, api);
295
- if (!deref || _types.isRef.call(void 0, deref)) {
296
- return void 0;
297
- }
298
- node = deref;
299
- }
300
- const safe = unwrapFirstPolymorphicBranch(node);
301
- if (_types.isRef.call(void 0, safe)) {
302
- return collectSchemaObjectProperties(safe, api, seenRefs);
303
- }
304
- node = safe;
305
- if (node) {
306
- if ("allOf" in node && Array.isArray(node.allOf) && node.allOf.length) {
307
- return mergePropertiesFromAllOf(node.allOf, api, seenRefs);
308
- }
309
- if (node.properties && typeof node.properties === "object") {
310
- return node.properties;
311
- }
312
- }
313
- return void 0;
278
+ let node = schema;
279
+ if ((0, oas_types.isRef)(node)) {
280
+ if (seenRefs.has(node.$ref)) return;
281
+ seenRefs.add(node.$ref);
282
+ const deref = (0, oas_utils.dereferenceRef)(node, api);
283
+ if (!deref || (0, oas_types.isRef)(deref)) return;
284
+ node = deref;
285
+ }
286
+ const safe = unwrapFirstPolymorphicBranch(node);
287
+ if ((0, oas_types.isRef)(safe)) return collectSchemaObjectProperties(safe, api, seenRefs);
288
+ node = safe;
289
+ if (node) {
290
+ if ("allOf" in node && Array.isArray(node.allOf) && node.allOf.length) return mergePropertiesFromAllOf(node.allOf, api, seenRefs);
291
+ if (node.properties && typeof node.properties === "object") return node.properties;
292
+ }
314
293
  }
315
294
  function getPayloadPropertyKeys(payload) {
316
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
317
- return [];
318
- }
319
- return Object.keys(payload).filter(
320
- (k) => typeof payload[k] !== "undefined"
321
- );
295
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return [];
296
+ return Object.keys(payload).filter((k) => typeof payload[k] !== "undefined");
322
297
  }
323
298
  function getPolymorphicSchema(node) {
324
- return node.oneOf && Array.isArray(node.oneOf) && node.oneOf.length ? node.oneOf : node.anyOf && Array.isArray(node.anyOf) && node.anyOf.length ? node.anyOf : null;
299
+ return node.oneOf && Array.isArray(node.oneOf) && node.oneOf.length ? node.oneOf : node.anyOf && Array.isArray(node.anyOf) && node.anyOf.length ? node.anyOf : null;
325
300
  }
301
+ /**
302
+ * Choose a single branch from a polymorphic schema that best matches the payload we have.
303
+ *
304
+ * A branch matches when every non-`undefined` payload key exists on that branch's merged object
305
+ * properties. If we have no payload, or no branches match, we use the first branch.
306
+ *
307
+ * When several branches match the one with the fewest declared properties wins, which would get us
308
+ * as close to a best match as possible, however having more data in our payload would give us more
309
+ * insight into which branch is what the user wants.
310
+ */
326
311
  function pickPolymorphicBranch(alternatives, keys, api) {
327
- if (!keys.length) {
328
- return alternatives[0];
329
- }
330
- const scored = alternatives.map((branch, idx) => {
331
- const props = collectSchemaObjectProperties(branch, api, /* @__PURE__ */ new Set());
332
- const allMatch = Boolean(props && keys.every((k) => Object.prototype.hasOwnProperty.call(props, k)));
333
- const propCount = props ? Object.keys(props).length : Number.POSITIVE_INFINITY;
334
- return { idx, branch, allMatch, propCount };
335
- });
336
- const matches = scored.filter((entry) => entry.allMatch);
337
- if (matches.length === 1) return matches[0].branch;
338
- if (matches.length > 1) {
339
- matches.sort((a, b) => a.propCount - b.propCount || a.idx - b.idx);
340
- return matches[0].branch;
341
- }
342
- return scored[0].branch;
312
+ if (!keys.length) return alternatives[0];
313
+ const scored = alternatives.map((branch, idx) => {
314
+ const props = collectSchemaObjectProperties(branch, api, /* @__PURE__ */ new Set());
315
+ return {
316
+ idx,
317
+ branch,
318
+ allMatch: Boolean(props && keys.every((k) => Object.prototype.hasOwnProperty.call(props, k))),
319
+ propCount: props ? Object.keys(props).length : Number.POSITIVE_INFINITY
320
+ };
321
+ });
322
+ const matches = scored.filter((entry) => entry.allMatch);
323
+ if (matches.length === 1) return matches[0].branch;
324
+ if (matches.length > 1) {
325
+ matches.sort((a, b) => a.propCount - b.propCount || a.idx - b.idx);
326
+ return matches[0].branch;
327
+ }
328
+ return scored[0].branch;
343
329
  }
330
+ /**
331
+ * Resolve a request-body JSON Schema against a concrete payload.
332
+ *
333
+ */
344
334
  function getSafeRequestBody(schema, payload, api) {
345
- let resolved = _utils.dereferenceRefDeep.call(void 0, schema, api);
346
- const keys = getPayloadPropertyKeys(payload);
347
- for (let alternatives = getPolymorphicSchema(resolved); alternatives != null; alternatives = getPolymorphicSchema(resolved)) {
348
- resolved = pickPolymorphicBranch(alternatives, keys, api);
349
- }
350
- if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
351
- const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, /* @__PURE__ */ new Set());
352
- if (fromAllOf && Object.keys(fromAllOf).length) {
353
- const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
354
- resolved = {
355
- ...resolved,
356
- type: "object",
357
- properties: { ...fromAllOf, ...existing }
358
- };
359
- }
360
- }
361
- return resolved;
335
+ let resolved = (0, oas_utils.dereferenceRefDeep)(schema, api);
336
+ const keys = getPayloadPropertyKeys(payload);
337
+ for (let alternatives = getPolymorphicSchema(resolved); alternatives != null; alternatives = getPolymorphicSchema(resolved)) resolved = pickPolymorphicBranch(alternatives, keys, api);
338
+ if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
339
+ const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, /* @__PURE__ */ new Set());
340
+ if (fromAllOf && Object.keys(fromAllOf).length) {
341
+ const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
342
+ resolved = {
343
+ ...resolved,
344
+ type: "object",
345
+ properties: {
346
+ ...fromAllOf,
347
+ ...existing
348
+ }
349
+ };
350
+ }
351
+ }
352
+ return resolved;
362
353
  }
354
+ /**
355
+ * Recursively runs through a schema, parsing any values that have `format: json` attached and
356
+ * deserializing them into their JSON representations.
357
+ *
358
+ * @see {@link parseJSONStrings}
359
+ */
363
360
  function parseJSONStringsInBodyWithSchema(obj, schema, api, seenRefs = /* @__PURE__ */ new Set()) {
364
- if (schema === void 0) return parseJSONStrings(obj);
365
- let resolved = schema;
366
- if (_types.isRef.call(void 0, schema)) {
367
- if (seenRefs.has(schema.$ref)) {
368
- return parseJSONStrings(obj);
369
- }
370
- seenRefs.add(schema.$ref);
371
- const deref = _utils.dereferenceRef.call(void 0, schema, api);
372
- if (!deref || _types.isRef.call(void 0, deref)) {
373
- return parseJSONStrings(obj);
374
- }
375
- resolved = deref;
376
- }
377
- const safe = getSafeRequestBody(resolved, obj, api);
378
- if (_types.isRef.call(void 0, safe)) {
379
- return parseJSONStringsInBodyWithSchema(obj, safe, api, seenRefs);
380
- }
381
- resolved = safe;
382
- if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
383
- const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, new Set(seenRefs));
384
- if (fromAllOf && Object.keys(fromAllOf).length) {
385
- const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
386
- resolved = {
387
- ...resolved,
388
- type: "object",
389
- properties: { ...fromAllOf, ...existing }
390
- };
391
- }
392
- }
393
- if (typeof obj === "string") {
394
- if (hasSchemaType(resolved, "string") && resolved.format !== "json") {
395
- return obj;
396
- }
397
- return parseJSONStrings(obj);
398
- }
399
- if (Array.isArray(obj)) {
400
- let items = resolved.items;
401
- if (items && typeof items === "object" && _types.isRef.call(void 0, items)) {
402
- if (seenRefs.has(items.$ref)) {
403
- return obj.map((item) => parseJSONStrings(item));
404
- }
405
- seenRefs.add(items.$ref);
406
- const derefItems = _utils.dereferenceRef.call(void 0, items, api);
407
- items = derefItems && !_types.isRef.call(void 0, derefItems) ? derefItems : void 0;
408
- }
409
- return obj.map((item) => parseJSONStringsInBodyWithSchema(item, items, api, new Set(seenRefs)));
410
- }
411
- if (obj !== null && typeof obj === "object") {
412
- const additionalPropertiesSchema = getAdditionalPropertiesSchema(resolved);
413
- if (!resolved.properties || typeof resolved.properties !== "object") {
414
- if (additionalPropertiesSchema) {
415
- const out2 = {};
416
- for (const [k, v] of Object.entries(obj)) {
417
- out2[k] = parseJSONStringsInBodyWithSchema(v, additionalPropertiesSchema, api, new Set(seenRefs));
418
- }
419
- return out2;
420
- }
421
- return parseJSONStrings(obj);
422
- }
423
- const out = {};
424
- for (const [k, v] of Object.entries(obj)) {
425
- const propSchema = resolved.properties[k];
426
- const schemaForValue = _nullishCoalesce(propSchema, () => ( additionalPropertiesSchema));
427
- out[k] = schemaForValue !== void 0 ? parseJSONStringsInBodyWithSchema(v, schemaForValue, api, new Set(seenRefs)) : parseJSONStringsObjectContainersOnly(v);
428
- }
429
- return out;
430
- }
431
- return obj;
361
+ if (schema === void 0) return parseJSONStrings(obj);
362
+ let resolved = schema;
363
+ if ((0, oas_types.isRef)(schema)) {
364
+ if (seenRefs.has(schema.$ref)) return parseJSONStrings(obj);
365
+ seenRefs.add(schema.$ref);
366
+ const deref = (0, oas_utils.dereferenceRef)(schema, api);
367
+ if (!deref || (0, oas_types.isRef)(deref)) return parseJSONStrings(obj);
368
+ resolved = deref;
369
+ }
370
+ const safe = getSafeRequestBody(resolved, obj, api);
371
+ if ((0, oas_types.isRef)(safe)) return parseJSONStringsInBodyWithSchema(obj, safe, api, seenRefs);
372
+ resolved = safe;
373
+ if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
374
+ const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, new Set(seenRefs));
375
+ if (fromAllOf && Object.keys(fromAllOf).length) {
376
+ const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
377
+ resolved = {
378
+ ...resolved,
379
+ type: "object",
380
+ properties: {
381
+ ...fromAllOf,
382
+ ...existing
383
+ }
384
+ };
385
+ }
386
+ }
387
+ if (typeof obj === "string") {
388
+ if (hasSchemaType(resolved, "string") && resolved.format !== "json") return obj;
389
+ return parseJSONStrings(obj);
390
+ }
391
+ if (Array.isArray(obj)) {
392
+ let items = resolved.items;
393
+ if (items && typeof items === "object" && (0, oas_types.isRef)(items)) {
394
+ if (seenRefs.has(items.$ref)) return obj.map((item) => parseJSONStrings(item));
395
+ seenRefs.add(items.$ref);
396
+ const derefItems = (0, oas_utils.dereferenceRef)(items, api);
397
+ items = derefItems && !(0, oas_types.isRef)(derefItems) ? derefItems : void 0;
398
+ }
399
+ return obj.map((item) => parseJSONStringsInBodyWithSchema(item, items, api, new Set(seenRefs)));
400
+ }
401
+ if (obj !== null && typeof obj === "object") {
402
+ const additionalPropertiesSchema = getAdditionalPropertiesSchema(resolved);
403
+ if (!resolved.properties || typeof resolved.properties !== "object") {
404
+ if (additionalPropertiesSchema) {
405
+ const out = {};
406
+ for (const [k, v] of Object.entries(obj)) out[k] = parseJSONStringsInBodyWithSchema(v, additionalPropertiesSchema, api, new Set(seenRefs));
407
+ return out;
408
+ }
409
+ return parseJSONStrings(obj);
410
+ }
411
+ const out = {};
412
+ for (const [k, v] of Object.entries(obj)) {
413
+ const schemaForValue = resolved.properties[k] ?? additionalPropertiesSchema;
414
+ out[k] = schemaForValue !== void 0 ? parseJSONStringsInBodyWithSchema(v, schemaForValue, api, new Set(seenRefs)) : parseJSONStringsObjectContainersOnly(v);
415
+ }
416
+ return out;
417
+ }
418
+ return obj;
432
419
  }
433
420
 
434
421
  // src/lib/style-formatting/style-serializer.ts
435
- var isRfc3986Reserved = (char) => ":/?#[]@!$&'()*+,;=".indexOf(char) > -1;
436
- var isRfc3986Unreserved = (char) => /^[a-z0-9\-._~]+$/i.test(char);
422
+ /**
423
+ * This file has been extracted and modified from `swagger-client`.
424
+ *
425
+ * @license Apache 2.0
426
+ * @link https://npm.im/swagger-client
427
+ * @link https://github.com/swagger-api/swagger-js/blob/master/src/execute/oas3/style-serializer.js
428
+ */
429
+ const isRfc3986Reserved = (char) => ":/?#[]@!$&'()*+,;=".indexOf(char) > -1;
430
+ const isRfc3986Unreserved = (char) => /^[a-z0-9\-._~]+$/i.test(char);
437
431
  function isURIEncoded(value) {
438
- try {
439
- return decodeURIComponent(value) !== value;
440
- } catch (e4) {
441
- return false;
442
- }
432
+ try {
433
+ return decodeURIComponent(value) !== value;
434
+ } catch {
435
+ return false;
436
+ }
443
437
  }
444
438
  function isObject(value) {
445
- return typeof value === "object" && value !== null;
439
+ return typeof value === "object" && value !== null;
446
440
  }
447
- function encodeDisallowedCharacters(str, {
448
- escape,
449
- returnIfEncoded = false,
450
- isAllowedReserved
451
- } = {}, parse) {
452
- if (typeof str === "number") {
453
- str = str.toString();
454
- }
455
- if (returnIfEncoded) {
456
- if (isURIEncoded(str)) {
457
- return str;
458
- }
459
- }
460
- if (typeof str !== "string" || !str.length) {
461
- return str;
462
- }
463
- if (!escape) {
464
- return str;
465
- }
466
- if (parse) {
467
- return JSON.parse(str);
468
- }
469
- return [...str].map((char) => {
470
- if (isRfc3986Unreserved(char)) {
471
- return char;
472
- }
473
- if (isRfc3986Reserved(char) && (escape === "unsafe" || isAllowedReserved)) {
474
- return char;
475
- }
476
- const encoder = new TextEncoder();
477
- const encoded = Array.from(encoder.encode(char)).map((byte) => `0${byte.toString(16).toUpperCase()}`.slice(-2)).map((encodedByte) => `%${encodedByte}`).join("");
478
- return encoded;
479
- }).join("");
441
+ function encodeDisallowedCharacters(str, { escape, returnIfEncoded = false, isAllowedReserved } = {}, parse) {
442
+ if (typeof str === "number") str = str.toString();
443
+ if (returnIfEncoded) {
444
+ if (isURIEncoded(str)) return str;
445
+ }
446
+ if (typeof str !== "string" || !str.length) return str;
447
+ if (!escape) return str;
448
+ if (parse) return JSON.parse(str);
449
+ return [...str].map((char) => {
450
+ if (isRfc3986Unreserved(char)) return char;
451
+ if (isRfc3986Reserved(char) && (escape === "unsafe" || isAllowedReserved)) return char;
452
+ const encoder = new TextEncoder();
453
+ return Array.from(encoder.encode(char)).map((byte) => `0${byte.toString(16).toUpperCase()}`.slice(-2)).map((encodedByte) => `%${encodedByte}`).join("");
454
+ }).join("");
480
455
  }
481
456
  function stylize(config) {
482
- const { value } = config;
483
- if (Array.isArray(value)) {
484
- return encodeArray(config);
485
- }
486
- if (isObject(value)) {
487
- return encodeObject(config);
488
- }
489
- return encodePrimitive(config);
457
+ const { value } = config;
458
+ if (Array.isArray(value)) return encodeArray(config);
459
+ if (isObject(value)) return encodeObject(config);
460
+ return encodePrimitive(config);
490
461
  }
491
- function encodeArray({
492
- location,
493
- key,
494
- value,
495
- style,
496
- explode,
497
- escape,
498
- isAllowedReserved = false
499
- }) {
500
- const valueEncoder = (str) => {
501
- if (str === null) {
502
- return "null";
503
- }
504
- const result = encodeDisallowedCharacters(str, {
505
- escape,
506
- returnIfEncoded: location === "query",
507
- isAllowedReserved
508
- });
509
- return result;
510
- };
511
- switch (style) {
512
- /**
513
- * @example <caption>`style: simple`</caption>
514
- * `["blue","black","brown"]` → `blue,black,brown`
515
- */
516
- case "simple":
517
- return value.map((val) => valueEncoder(val)).join(",");
518
- /**
519
- * @example <caption>`style: label`</caption>
520
- * `["blue","black","brown"]` → `.blue.black.brown`
521
- */
522
- case "label":
523
- return `.${value.map((val) => valueEncoder(val)).join(".")}`;
524
- /**
525
- * @example <caption>`style: matrix` + `explode: true`</caption>
526
- * `["blue","black","brown"]` → `;color=blue;color=black;color=brown`
527
- *
528
- * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
529
- * `["blue","black","brown"]` → `;color=blue,black,brown `
530
- */
531
- case "matrix":
532
- return value.map((val) => valueEncoder(val)).reduce((prev, curr) => {
533
- if (!prev || explode) {
534
- return `${prev || ""};${key}=${curr}`;
535
- }
536
- return `${prev},${curr}`;
537
- }, "");
538
- /**
539
- * @example <caption>`style: form` + `explode: true`</caption>
540
- * `["blue","black","brown"]` → `color=blue&color=black&color=brown`
541
- *
542
- * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
543
- * `["blue","black","brown"]` → `color=blue,black,brown`
544
- */
545
- case "form":
546
- return value.map((val) => valueEncoder(val)).join(explode ? `&${key}=` : ",");
547
- /**
548
- * @example <caption>`style: spaceDelimited`</caption>
549
- * `["blue","black","brown"]` → `blue%20black%20brown`
550
- */
551
- case "spaceDelimited":
552
- return value.map((val) => valueEncoder(val)).join(` ${explode ? `${key}=` : ""}`);
553
- /**
554
- * @example <caption>`style: pipeDelimited`</caption>
555
- * `["blue","black","brown"]` → `blue|black|brown`
556
- */
557
- case "pipeDelimited":
558
- return value.map((val) => valueEncoder(val)).join(`|${explode ? `${key}=` : ""}`);
559
- default:
560
- }
462
+ /**
463
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#style-examples}
464
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#style-examples}
465
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#style-examples}
466
+ */
467
+ function encodeArray({ location, key, value, style, explode, escape, isAllowedReserved = false }) {
468
+ const valueEncoder = (str) => {
469
+ if (str === null) return "null";
470
+ return encodeDisallowedCharacters(str, {
471
+ escape,
472
+ returnIfEncoded: location === "query",
473
+ isAllowedReserved
474
+ });
475
+ };
476
+ switch (style) {
477
+ /**
478
+ * @example <caption>`style: simple`</caption>
479
+ * `["blue","black","brown"]` → `blue,black,brown`
480
+ */
481
+ case "simple": return value.map((val) => valueEncoder(val)).join(",");
482
+ /**
483
+ * @example <caption>`style: label`</caption>
484
+ * `["blue","black","brown"]` → `.blue.black.brown`
485
+ */
486
+ case "label": return `.${value.map((val) => valueEncoder(val)).join(".")}`;
487
+ /**
488
+ * @example <caption>`style: matrix` + `explode: true`</caption>
489
+ * `["blue","black","brown"]` → `;color=blue;color=black;color=brown`
490
+ *
491
+ * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
492
+ * `["blue","black","brown"]` → `;color=blue,black,brown `
493
+ */
494
+ case "matrix": return value.map((val) => valueEncoder(val)).reduce((prev, curr) => {
495
+ if (!prev || explode) return `${prev || ""};${key}=${curr}`;
496
+ return `${prev},${curr}`;
497
+ }, "");
498
+ /**
499
+ * @example <caption>`style: form` + `explode: true`</caption>
500
+ * `["blue","black","brown"]` → `color=blue&color=black&color=brown`
501
+ *
502
+ * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
503
+ * `["blue","black","brown"]` → `color=blue,black,brown`
504
+ */
505
+ case "form": return value.map((val) => valueEncoder(val)).join(explode ? `&${key}=` : ",");
506
+ /**
507
+ * @example <caption>`style: spaceDelimited`</caption>
508
+ * `["blue","black","brown"]` → `blue%20black%20brown`
509
+ */
510
+ case "spaceDelimited": return value.map((val) => valueEncoder(val)).join(` ${explode ? `${key}=` : ""}`);
511
+ /**
512
+ * @example <caption>`style: pipeDelimited`</caption>
513
+ * `["blue","black","brown"]` → `blue|black|brown`
514
+ */
515
+ case "pipeDelimited": return value.map((val) => valueEncoder(val)).join(`|${explode ? `${key}=` : ""}`);
516
+ }
561
517
  }
518
+ /**
519
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#style-examples}
520
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#style-examples}
521
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#style-examples}
522
+ */
562
523
  function encodeObject({ location, key, value, style, explode, escape, isAllowedReserved = false }) {
563
- const valueEncoder = (str) => encodeDisallowedCharacters(str, {
564
- escape,
565
- returnIfEncoded: location === "query",
566
- isAllowedReserved
567
- });
568
- const valueKeys = Object.keys(value);
569
- switch (style) {
570
- /**
571
- * @example <caption>`style: simple` + `explode: true`</caption>
572
- * `{ "R": 100, "G": 200, "B": 150 }` → `R=100,G=200,B=150`
573
- *
574
- * @example <caption>`style: simple` + `explode: false` (the default behavior)</caption>
575
- * `{ "R": 100, "G": 200, "B": 150 }` → `R,100,G,200,B,150`
576
- */
577
- case "simple":
578
- return valueKeys.reduce((prev, curr) => {
579
- const val = valueEncoder(value[curr]);
580
- const middleChar = explode ? "=" : ",";
581
- const prefix = prev ? `${prev},` : "";
582
- return `${prefix}${curr}${middleChar}${val}`;
583
- }, "");
584
- /**
585
- * @example <caption>`style: label` + `explode: true`</caption>
586
- * `{ "R": 100, "G": 200, "B": 150 }` → `.R=100.G=200.B=150`
587
- *
588
- * @example <caption>`style: label` + `explode: false` (the default behavior)</caption>
589
- * `{ "R": 100, "G": 200, "B": 150 }` → `.R.100.G.200.B.150`
590
- */
591
- case "label":
592
- return valueKeys.reduce((prev, curr) => {
593
- const val = valueEncoder(value[curr]);
594
- const middleChar = explode ? "=" : ".";
595
- const prefix = prev ? `${prev}.` : ".";
596
- return `${prefix}${curr}${middleChar}${val}`;
597
- }, "");
598
- /**
599
- * @example <caption>`style: matrix` + `explode: true`</caption>
600
- * `{ "R": 100, "G": 200, "B": 150 }` → `;R=100;G=200;B=150`
601
- *
602
- * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
603
- * `{ "R": 100, "G": 200, "B": 150 }` → `;color=R,100,G,200,B,150`
604
- */
605
- case "matrix":
606
- if (explode) {
607
- return valueKeys.reduce((prev, curr) => {
608
- const val = valueEncoder(value[curr]);
609
- const prefix = prev ? `${prev};` : ";";
610
- return `${prefix}${curr}=${val}`;
611
- }, "");
612
- }
613
- return valueKeys.reduce((prev, curr) => {
614
- const val = valueEncoder(value[curr]);
615
- const prefix = prev ? `${prev},` : `;${key}=`;
616
- return `${prefix}${curr},${val}`;
617
- }, "");
618
- /**
619
- * @example <caption>`style: form` + `explode: true`</caption>
620
- * `{ "R": 100, "G": 200, "B": 150 }` → `R=100&G=200&B=150`
621
- *
622
- * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
623
- * `{ "R": 100, "G": 200, "B": 150 }` → `color=R,100,G,200,B,150`
624
- */
625
- case "form":
626
- return valueKeys.reduce((prev, curr) => {
627
- const val = valueEncoder(value[curr]);
628
- const prefix = prev ? `${prev}${explode ? "&" : ","}` : "";
629
- const separator = explode ? "=" : ",";
630
- return `${prefix}${curr}${separator}${val}`;
631
- }, "");
632
- /**
633
- * @example <caption>`style: spaceDelimited`</caption>
634
- * `{ "R": 100, "G": 200, "B": 150 }` → `R%20100%20G%20200%20B%20150`
635
- */
636
- case "spaceDelimited":
637
- return valueKeys.reduce((prev, curr) => {
638
- const val = valueEncoder(value[curr]);
639
- const prefix = prev ? `${prev} ` : "";
640
- return `${prefix}${curr} ${val}`;
641
- }, "");
642
- /**
643
- * @example <caption>`style: pipeDelimited`</caption>
644
- * `{ "R": 100, "G": 200, "B": 150 }` → `R|100|G|200|B|150`
645
- */
646
- case "pipeDelimited":
647
- return valueKeys.reduce((prev, curr) => {
648
- const val = valueEncoder(value[curr]);
649
- const prefix = prev ? `${prev}|` : "";
650
- return `${prefix}${curr}|${val}`;
651
- }, "");
652
- /**
653
- * @example <caption>`style: deepObject`</caption>
654
- * `{ "R": 100, "G": 200, "B": 150 }` → `color[R]=100&color[G]=200&color[B]=150`
655
- */
656
- case "deepObject":
657
- return valueKeys.reduce((curr) => {
658
- const val = valueEncoder(value[curr]);
659
- return `${val}`;
660
- }, "");
661
- default:
662
- }
524
+ const valueEncoder = (str) => encodeDisallowedCharacters(str, {
525
+ escape,
526
+ returnIfEncoded: location === "query",
527
+ isAllowedReserved
528
+ });
529
+ const valueKeys = Object.keys(value);
530
+ switch (style) {
531
+ /**
532
+ * @example <caption>`style: simple` + `explode: true`</caption>
533
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R=100,G=200,B=150`
534
+ *
535
+ * @example <caption>`style: simple` + `explode: false` (the default behavior)</caption>
536
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R,100,G,200,B,150`
537
+ */
538
+ case "simple": return valueKeys.reduce((prev, curr) => {
539
+ const val = valueEncoder(value[curr]);
540
+ const middleChar = explode ? "=" : ",";
541
+ return `${prev ? `${prev},` : ""}${curr}${middleChar}${val}`;
542
+ }, "");
543
+ /**
544
+ * @example <caption>`style: label` + `explode: true`</caption>
545
+ * `{ "R": 100, "G": 200, "B": 150 }` → `.R=100.G=200.B=150`
546
+ *
547
+ * @example <caption>`style: label` + `explode: false` (the default behavior)</caption>
548
+ * `{ "R": 100, "G": 200, "B": 150 }` → `.R.100.G.200.B.150`
549
+ */
550
+ case "label": return valueKeys.reduce((prev, curr) => {
551
+ const val = valueEncoder(value[curr]);
552
+ const middleChar = explode ? "=" : ".";
553
+ return `${prev ? `${prev}.` : "."}${curr}${middleChar}${val}`;
554
+ }, "");
555
+ /**
556
+ * @example <caption>`style: matrix` + `explode: true`</caption>
557
+ * `{ "R": 100, "G": 200, "B": 150 }` → `;R=100;G=200;B=150`
558
+ *
559
+ * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
560
+ * `{ "R": 100, "G": 200, "B": 150 }` → `;color=R,100,G,200,B,150`
561
+ */
562
+ case "matrix":
563
+ if (explode) return valueKeys.reduce((prev, curr) => {
564
+ const val = valueEncoder(value[curr]);
565
+ return `${prev ? `${prev};` : ";"}${curr}=${val}`;
566
+ }, "");
567
+ return valueKeys.reduce((prev, curr) => {
568
+ const val = valueEncoder(value[curr]);
569
+ return `${prev ? `${prev},` : `;${key}=`}${curr},${val}`;
570
+ }, "");
571
+ /**
572
+ * @example <caption>`style: form` + `explode: true`</caption>
573
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R=100&G=200&B=150`
574
+ *
575
+ * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
576
+ * `{ "R": 100, "G": 200, "B": 150 }` → `color=R,100,G,200,B,150`
577
+ */
578
+ case "form": return valueKeys.reduce((prev, curr) => {
579
+ const val = valueEncoder(value[curr]);
580
+ return `${prev ? `${prev}${explode ? "&" : ","}` : ""}${curr}${explode ? "=" : ","}${val}`;
581
+ }, "");
582
+ /**
583
+ * @example <caption>`style: spaceDelimited`</caption>
584
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R%20100%20G%20200%20B%20150`
585
+ */
586
+ case "spaceDelimited": return valueKeys.reduce((prev, curr) => {
587
+ const val = valueEncoder(value[curr]);
588
+ return `${prev ? `${prev} ` : ""}${curr} ${val}`;
589
+ }, "");
590
+ /**
591
+ * @example <caption>`style: pipeDelimited`</caption>
592
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R|100|G|200|B|150`
593
+ */
594
+ case "pipeDelimited": return valueKeys.reduce((prev, curr) => {
595
+ const val = valueEncoder(value[curr]);
596
+ return `${prev ? `${prev}|` : ""}${curr}|${val}`;
597
+ }, "");
598
+ /**
599
+ * @example <caption>`style: deepObject`</caption>
600
+ * `{ "R": 100, "G": 200, "B": 150 }` → `color[R]=100&color[G]=200&color[B]=150`
601
+ */
602
+ case "deepObject": return valueKeys.reduce((curr) => {
603
+ return `${valueEncoder(value[curr])}`;
604
+ }, "");
605
+ }
663
606
  }
607
+ /**
608
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#style-examples}
609
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#style-examples}
610
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#style-examples}
611
+ */
664
612
  function encodePrimitive({ location, key, value, style, escape, isAllowedReserved = false }) {
665
- const valueEncoder = (str) => encodeDisallowedCharacters(str, {
666
- escape,
667
- returnIfEncoded: location === "query" || location === "body",
668
- isAllowedReserved
669
- });
670
- switch (style) {
671
- /**
672
- * @example <caption>`style: simple`</caption>
673
- * `blue` → `blue`
674
- */
675
- case "simple":
676
- return valueEncoder(value);
677
- /**
678
- * @example <caption>`style: label`</caption>
679
- * `blue` → `.blue`
680
- */
681
- case "label":
682
- return `.${valueEncoder(value)}`;
683
- /**
684
- * @example <caption>`style: matrix`</caption>
685
- * `blue` → `;color=blue`
686
- */
687
- case "matrix":
688
- if (value === "") {
689
- return `;${key}`;
690
- }
691
- return `;${key}=${valueEncoder(value)}`;
692
- /**
693
- * @example <caption>`style: form`</caption>
694
- * `blue` → `color=blue`
695
- */
696
- case "form":
697
- return valueEncoder(value);
698
- /**
699
- * @example <caption>`style: deepObject`</caption>
700
- * `blue` → n/a
701
- */
702
- case "deepObject":
703
- return valueEncoder(value);
704
- default:
705
- }
613
+ const valueEncoder = (str) => encodeDisallowedCharacters(str, {
614
+ escape,
615
+ returnIfEncoded: location === "query" || location === "body",
616
+ isAllowedReserved
617
+ });
618
+ switch (style) {
619
+ /**
620
+ * @example <caption>`style: simple`</caption>
621
+ * `blue` → `blue`
622
+ */
623
+ case "simple": return valueEncoder(value);
624
+ /**
625
+ * @example <caption>`style: label`</caption>
626
+ * `blue` → `.blue`
627
+ */
628
+ case "label": return `.${valueEncoder(value)}`;
629
+ /**
630
+ * @example <caption>`style: matrix`</caption>
631
+ * `blue` → `;color=blue`
632
+ */
633
+ case "matrix":
634
+ if (value === "") return `;${key}`;
635
+ return `;${key}=${valueEncoder(value)}`;
636
+ /**
637
+ * @example <caption>`style: form`</caption>
638
+ * `blue` → `color=blue`
639
+ */
640
+ case "form": return valueEncoder(value);
641
+ /**
642
+ * @example <caption>`style: deepObject`</caption>
643
+ * `blue` → n/a
644
+ */
645
+ case "deepObject": return valueEncoder(value);
646
+ }
706
647
  }
707
648
 
708
649
  // src/lib/style-formatting/index.ts
709
650
  function shouldNotStyleEmptyValues(parameter) {
710
- return ["simple", "spaceDelimited", "pipeDelimited", "deepObject"].includes(parameter.style || "");
651
+ return [
652
+ "simple",
653
+ "spaceDelimited",
654
+ "pipeDelimited",
655
+ "deepObject"
656
+ ].includes(parameter.style || "");
711
657
  }
712
658
  function shouldNotStyleReservedHeader(parameter) {
713
- return ["accept", "authorization", "content-type"].includes(parameter.name.toLowerCase());
659
+ return [
660
+ "accept",
661
+ "authorization",
662
+ "content-type"
663
+ ].includes(parameter.name.toLowerCase());
714
664
  }
665
+ /**
666
+ * Note: This isn't necessarily part of the spec. Behavior for the value 'undefined' is, well,
667
+ * undefined. This code makes our system look better. If we wanted to be more accurate, we might
668
+ * want to remove this, restore the un-fixed behavior for undefined and have our UI pass in empty
669
+ * string instead of undefined.
670
+ */
715
671
  function removeUndefinedForPath(value) {
716
- let finalValue = value;
717
- if (typeof finalValue === "undefined") {
718
- return "";
719
- }
720
- if (Array.isArray(finalValue)) {
721
- finalValue = finalValue.filter((val) => val === void 0 ? "" : val);
722
- if (finalValue.length === 0) {
723
- finalValue = "";
724
- }
725
- }
726
- if (typeof finalValue === "object") {
727
- Object.keys(finalValue).forEach((key) => {
728
- finalValue[key] = finalValue[key] === void 0 ? "" : finalValue[key];
729
- });
730
- }
731
- return finalValue;
672
+ let finalValue = value;
673
+ if (typeof finalValue === "undefined") return "";
674
+ if (Array.isArray(finalValue)) {
675
+ finalValue = finalValue.filter((val) => val === void 0 ? "" : val);
676
+ if (finalValue.length === 0) finalValue = "";
677
+ }
678
+ if (typeof finalValue === "object") Object.keys(finalValue).forEach((key) => {
679
+ finalValue[key] = finalValue[key] === void 0 ? "" : finalValue[key];
680
+ });
681
+ return finalValue;
732
682
  }
733
683
  function stylizeValue(value, parameter) {
734
- let finalValue = value;
735
- if (shouldNotStyleEmptyValues(parameter) && (typeof finalValue === "undefined" || finalValue === "")) {
736
- if (parameter.in === "path") {
737
- return "";
738
- }
739
- return;
740
- }
741
- if (parameter.in === "path") {
742
- finalValue = removeUndefinedForPath(finalValue);
743
- }
744
- if (parameter.in === "header" && shouldNotStyleReservedHeader(parameter)) {
745
- return value;
746
- }
747
- if (parameter.content && (parameter.in === "query" || parameter.in === "header")) {
748
- const contentType = getParameterContentType(parameter);
749
- if (!contentType) {
750
- return;
751
- }
752
- let serialized;
753
- if (_utils.matchesMimeType.json(contentType)) {
754
- serialized = JSON.stringify(value);
755
- } else {
756
- serialized = String(value);
757
- }
758
- return parameter.in === "query" ? encodeURIComponent(serialized) : serialized;
759
- }
760
- let style = parameter.style;
761
- if (!style) {
762
- if (parameter.in === "query") {
763
- style = "form";
764
- } else if (parameter.in === "path") {
765
- style = "simple";
766
- } else if (parameter.in === "header") {
767
- style = "simple";
768
- } else if (parameter.in === "cookie") {
769
- style = "form";
770
- }
771
- }
772
- let explode = parameter.explode;
773
- if (explode === void 0 && style === "form") {
774
- explode = true;
775
- }
776
- return stylize({
777
- location: parameter.in,
778
- value: finalValue,
779
- key: parameter.name,
780
- style,
781
- explode,
782
- /**
783
- * @todo this parameter is optional to stylize. It defaults to false, and can accept falsy, truthy, or "unsafe".
784
- * I do not know if it is correct for query to use this. See style-serializer for more info
785
- */
786
- escape: true,
787
- ...parameter.in === "query" ? { isAllowedReserved: parameter.allowReserved || false } : {}
788
- });
684
+ let finalValue = value;
685
+ if (shouldNotStyleEmptyValues(parameter) && (typeof finalValue === "undefined" || finalValue === "")) {
686
+ if (parameter.in === "path") return "";
687
+ return;
688
+ }
689
+ if (parameter.in === "path") finalValue = removeUndefinedForPath(finalValue);
690
+ /**
691
+ * Eventhough `accept`, `authorization`, and `content-type` headers can be defined as parameters,
692
+ * they should be completely ignored when it comes to serialization.
693
+ *
694
+ * > If `in` is "header" and the `name` field is "Accept", "Content-Type" or "Authorization", the
695
+ * > parameter definition SHALL be ignored.
696
+ *
697
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#fixed-fields-10}
698
+ */
699
+ if (parameter.in === "header" && shouldNotStyleReservedHeader(parameter)) return value;
700
+ /**
701
+ * If content is present, we should use the content type to format the value. We also ignore the style and explode settings.
702
+ *
703
+ * @see {@link https://swagger.io/docs/specification/v3_0/describing-parameters/#schema-vs-content}
704
+ */
705
+ if (parameter.content && (parameter.in === "query" || parameter.in === "header")) {
706
+ const contentType = getParameterContentType(parameter);
707
+ if (!contentType) return;
708
+ /**
709
+ * @todo Handle other content types
710
+ */
711
+ let serialized;
712
+ if (oas_utils.matchesMimeType.json(contentType)) serialized = JSON.stringify(value);
713
+ else serialized = String(value);
714
+ return parameter.in === "query" ? encodeURIComponent(serialized) : serialized;
715
+ }
716
+ /**
717
+ * All parameter types have a default `style` format so if they don't have one prescribed we
718
+ * should still conform to what the spec defines.
719
+ *
720
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#parameterStyle}
721
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#parameterStyle}
722
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#parameter-style}
723
+ */
724
+ let style = parameter.style;
725
+ if (!style) {
726
+ if (parameter.in === "query") style = "form";
727
+ else if (parameter.in === "path") style = "simple";
728
+ else if (parameter.in === "header") style = "simple";
729
+ else if (parameter.in === "cookie") style = "form";
730
+ }
731
+ let explode = parameter.explode;
732
+ if (explode === void 0 && style === "form")
733
+ /**
734
+ * Per the spec if no `explode` is present but `style` is `form` then `explode` should default to `true`.
735
+ *
736
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#parameterExplode}
737
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#parameterExplode}
738
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#parameter-explode}
739
+ */
740
+ explode = true;
741
+ return stylize({
742
+ location: parameter.in,
743
+ value: finalValue,
744
+ key: parameter.name,
745
+ style,
746
+ explode,
747
+ /**
748
+ * @todo this parameter is optional to stylize. It defaults to false, and can accept falsy, truthy, or "unsafe".
749
+ * I do not know if it is correct for query to use this. See style-serializer for more info
750
+ */
751
+ escape: true,
752
+ ...parameter.in === "query" ? { isAllowedReserved: parameter.allowReserved || false } : {}
753
+ });
789
754
  }
790
755
  function handleDeepObject(value, parameter) {
791
- return _qs2.default.stringify(value, {
792
- encoder(str, defaultEncoder, charset, type) {
793
- if (type === "key") {
794
- const prefixedKey = str.split(/[[\]]/g).filter(Boolean).map((k) => `[${k}]`).join("");
795
- return `${parameter.name}${prefixedKey}`;
796
- } else if (type === "value") {
797
- return stylizeValue(str, parameter);
798
- }
799
- }
800
- }).split("&").map((item) => {
801
- const split = item.split("=");
802
- return {
803
- label: split[0],
804
- // `qs` will coerce null values into being `undefined` string but we want to preserve them.
805
- value: split[1] === "undefined" ? null : split[1]
806
- };
807
- });
756
+ return qs.default.stringify(value, { encoder(str, defaultEncoder, charset, type) {
757
+ if (type === "key") {
758
+ const prefixedKey = str.split(/[[\]]/g).filter(Boolean).map((k) => `[${k}]`).join("");
759
+ return `${parameter.name}${prefixedKey}`;
760
+ } else if (type === "value") return stylizeValue(str, parameter);
761
+ } }).split("&").map((item) => {
762
+ const split = item.split("=");
763
+ return {
764
+ label: split[0],
765
+ value: split[1] === "undefined" ? null : split[1]
766
+ };
767
+ });
808
768
  }
809
769
  function handleExplode(value, parameter) {
810
- if (Array.isArray(value) && _optionalChain([parameter, 'access', _7 => _7.schema, 'optionalAccess', _8 => _8.type]) === "array" && parameter.style === "deepObject") {
811
- const newObj = {};
812
- const deepObjs = handleDeepObject(value, parameter);
813
- deepObjs.forEach((obj) => {
814
- newObj[obj.label] = obj.value;
815
- });
816
- return newObj;
817
- }
818
- if (Array.isArray(value)) {
819
- return value.map((val) => {
820
- return stylizeValue(val, parameter);
821
- });
822
- }
823
- if (typeof value === "object" && value !== null) {
824
- const newObj = {};
825
- Object.keys(value).forEach((key) => {
826
- if (parameter.style === "deepObject") {
827
- const deepObjs = handleDeepObject(value, parameter);
828
- deepObjs.forEach((obj) => {
829
- newObj[obj.label] = obj.value;
830
- });
831
- } else {
832
- newObj[key] = stylizeValue(value[key], parameter);
833
- }
834
- });
835
- return newObj;
836
- }
837
- return stylizeValue(value, parameter);
770
+ if (Array.isArray(value) && parameter.schema && typeof parameter.schema === "object" && !(0, oas_types.isRef)(parameter.schema) && parameter.schema.type === "array" && parameter.style === "deepObject") {
771
+ const newObj = {};
772
+ handleDeepObject(value, parameter).forEach((obj) => {
773
+ newObj[obj.label] = obj.value;
774
+ });
775
+ return newObj;
776
+ }
777
+ if (Array.isArray(value)) return value.map((val) => {
778
+ return stylizeValue(val, parameter);
779
+ });
780
+ if (typeof value === "object" && value !== null) {
781
+ const newObj = {};
782
+ Object.keys(value).forEach((key) => {
783
+ if (parameter.style === "deepObject") handleDeepObject(value, parameter).forEach((obj) => {
784
+ newObj[obj.label] = obj.value;
785
+ });
786
+ else newObj[key] = stylizeValue(value[key], parameter);
787
+ });
788
+ return newObj;
789
+ }
790
+ return stylizeValue(value, parameter);
838
791
  }
839
792
  function shouldExplode(parameter) {
840
- return (parameter.explode || parameter.explode !== false && parameter.style === "form" || // style: deepObject && explode: false doesn't exist so explode it always
841
- // https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples
842
- parameter.style === "deepObject") && // header and path doesn't explode into separate parameters like query and cookie do
843
- parameter.in !== "header" && parameter.in !== "path" && !parameter.content;
793
+ return (parameter.explode || parameter.explode !== false && parameter.style === "form" || parameter.style === "deepObject") && parameter.in !== "header" && parameter.in !== "path" && !parameter.content;
844
794
  }
845
795
  function formatStyle(value, parameter) {
846
- if (!parameter.content && parameter.style === "deepObject" && (!value || typeof value !== "object" || parameter.explode === false)) {
847
- return void 0;
848
- }
849
- if (shouldExplode(parameter)) {
850
- return handleExplode(value, parameter);
851
- }
852
- return stylizeValue(value, parameter);
796
+ if (!parameter.content && parameter.style === "deepObject" && (!value || typeof value !== "object" || parameter.explode === false)) return;
797
+ if (shouldExplode(parameter)) return handleExplode(value, parameter);
798
+ return stylizeValue(value, parameter);
853
799
  }
854
800
 
855
801
  // src/index.ts
802
+ /**
803
+ * Retrieves the value for a given parameter out of the bucket of values for its `in` type (e.g.
804
+ * `values.header`).
805
+ *
806
+ * HTTP header names are case-insensitive, but incoming header values (e.g. as normalized by
807
+ * `api/core`) are often lowercased while the OAS document defining the header parameter may use
808
+ * any casing (e.g. `X-Customer-Code`). So for headers we fall back to a case-insensitive lookup
809
+ * if there wasn't an exact match on the parameter name.
810
+ */
856
811
  function getParamValue(values, param, type) {
857
- const bucket = values[type];
858
- if (bucket && typeof bucket === "object" && !(param.name in bucket) && type === "header") {
859
- const matchedKey = Object.keys(bucket).find((key) => key.toLowerCase() === param.name.toLowerCase());
860
- if (matchedKey !== void 0) {
861
- return bucket[matchedKey];
862
- }
863
- }
864
- return _optionalChain([bucket, 'optionalAccess', _9 => _9[param.name]]);
812
+ const bucket = values[type];
813
+ if (bucket && typeof bucket === "object" && !(param.name in bucket) && type === "header") {
814
+ const matchedKey = Object.keys(bucket).find((key) => key.toLowerCase() === param.name.toLowerCase());
815
+ if (matchedKey !== void 0) return bucket[matchedKey];
816
+ }
817
+ return bucket?.[param.name];
865
818
  }
866
819
  function formatter(values, param, type, onlyIfExists = false, api) {
867
- if (param.style) {
868
- const value2 = getParamValue(values, param, type);
869
- return formatStyle(value2, param);
870
- }
871
- let value;
872
- if (typeof getParamValue(values, param, type) !== "undefined") {
873
- value = getParamValue(values, param, type);
874
- } else if (onlyIfExists && !param.required) {
875
- value = void 0;
876
- } else if (param.required && param.schema) {
877
- const schema = _types.isRef.call(void 0, param.schema) ? _utils.dereferenceRef.call(void 0, param.schema, api) : param.schema;
878
- if (schema && !_types.isRef.call(void 0, schema) && schema.default) {
879
- value = schema.default;
880
- } else if (param.content) {
881
- const contentType = getParameterContentType(param);
882
- const contentSchema = contentType ? getParameterContentSchema(param, contentType, api) : null;
883
- value = _optionalChain([contentSchema, 'optionalAccess', _10 => _10.default]);
884
- }
885
- } else if (param.required && param.content) {
886
- const contentType = getParameterContentType(param);
887
- const schema = contentType ? getParameterContentSchema(param, contentType, api) : null;
888
- value = _optionalChain([schema, 'optionalAccess', _11 => _11.default]);
889
- }
890
- if (value === void 0 && type === "path") {
891
- return param.name;
892
- }
893
- if (param.schema && !_types.isRef.call(void 0, param.schema) && param.schema.type === "array" && param.schema.items && !_types.isRef.call(void 0, param.schema.items) && param.schema.items.format === "binary") {
894
- if (Array.isArray(value)) {
895
- return value;
896
- }
897
- return JSON.stringify(value);
898
- }
899
- if (value !== void 0) {
900
- if (type === "query" || type === "header" && param.content) {
901
- return formatStyle(value, param);
902
- }
903
- return value;
904
- }
820
+ if (param.style) {
821
+ const value = getParamValue(values, param, type);
822
+ return formatStyle(value, param);
823
+ }
824
+ let value;
825
+ if (typeof getParamValue(values, param, type) !== "undefined") value = getParamValue(values, param, type);
826
+ else if (onlyIfExists && !param.required) value = void 0;
827
+ else if (param.required && param.schema && typeof param.schema === "object") {
828
+ const schema = (0, oas_types.isRef)(param.schema) ? (0, oas_utils.dereferenceRef)(param.schema, api) : param.schema;
829
+ if (schema && typeof schema === "object" && !(0, oas_types.isRef)(schema) && schema.default) value = schema.default;
830
+ else if (param.content) {
831
+ const contentType = getParameterContentType(param);
832
+ value = (contentType ? getParameterContentSchema(param, contentType, api) : null)?.default;
833
+ }
834
+ } else if (param.required && param.content) {
835
+ const contentType = getParameterContentType(param);
836
+ value = (contentType ? getParameterContentSchema(param, contentType, api) : null)?.default;
837
+ }
838
+ if (value === void 0 && type === "path") return param.name;
839
+ if (param.schema && typeof param.schema === "object" && !(0, oas_types.isRef)(param.schema) && param.schema.type === "array" && param.schema.items && typeof param.schema.items === "object" && !Array.isArray(param.schema.items) && !(0, oas_types.isRef)(param.schema.items) && param.schema.items.format === "binary") {
840
+ if (Array.isArray(value)) return value;
841
+ return JSON.stringify(value);
842
+ }
843
+ if (value !== void 0) {
844
+ if (type === "query" || type === "header" && (param.content || typeof value === "object" && value !== null)) return formatStyle(value, param);
845
+ return value;
846
+ }
905
847
  }
906
848
  function multipartBodyToFormatterParams(payload, oasMediaTypeObject, schema) {
907
- const encoding = oasMediaTypeObject.encoding;
908
- if (typeof payload === "object" && payload !== null) {
909
- return Object.keys(payload).map((key) => {
910
- if (!_optionalChain([schema, 'access', _12 => _12.properties, 'optionalAccess', _13 => _13[key]])) {
911
- return false;
912
- }
913
- const paramEncoding = encoding ? encoding[key] : void 0;
914
- const propertySchema = schema.properties[key];
915
- const isObjectSchema = typeof propertySchema === "object" && propertySchema !== null && !_types.isRef.call(void 0, propertySchema);
916
- const hasObjectType = isObjectSchema && // OAS 3.1 uses JSON Schema union types, so object schemas can appear as
917
- // `type: ['object', 'null']` or another union that includes `object`.
918
- (Array.isArray(propertySchema.type) ? propertySchema.type.includes("object") : propertySchema.type === "object");
919
- const hasObjectProperties = isObjectSchema && typeof propertySchema.properties === "object" && propertySchema.properties !== null;
920
- const shouldDefaultNestedMultipartObject = !paramEncoding && (hasObjectType || hasObjectProperties);
921
- return {
922
- name: key,
923
- // Preserve nested multipart object paths as form fields unless the spec supplies explicit
924
- // encoding for this property.
925
- style: paramEncoding ? paramEncoding.style : shouldDefaultNestedMultipartObject ? "deepObject" : void 0,
926
- explode: paramEncoding ? paramEncoding.explode : shouldDefaultNestedMultipartObject ? true : void 0,
927
- required: schema.required && typeof schema.required === "boolean" && Boolean(schema.required) || Array.isArray(schema.required) && schema.required.includes(key),
928
- schema: schema.properties[key],
929
- in: "body"
930
- };
931
- }).filter(Boolean);
932
- }
933
- return [];
849
+ const encoding = oasMediaTypeObject.encoding;
850
+ if (typeof payload === "object" && payload !== null) return Object.keys(payload).map((key) => {
851
+ if (!schema.properties?.[key]) return false;
852
+ const paramEncoding = encoding ? encoding[key] : void 0;
853
+ const propertySchema = schema.properties[key];
854
+ const isObjectSchema = typeof propertySchema === "object" && propertySchema !== null && !(0, oas_types.isRef)(propertySchema);
855
+ const hasObjectType = isObjectSchema && (Array.isArray(propertySchema.type) ? propertySchema.type.includes("object") : propertySchema.type === "object");
856
+ const hasObjectProperties = isObjectSchema && typeof propertySchema.properties === "object" && propertySchema.properties !== null;
857
+ const shouldDefaultNestedMultipartObject = !paramEncoding && (hasObjectType || hasObjectProperties);
858
+ return {
859
+ name: key,
860
+ style: paramEncoding ? paramEncoding.style : shouldDefaultNestedMultipartObject ? "deepObject" : void 0,
861
+ explode: paramEncoding ? paramEncoding.explode : shouldDefaultNestedMultipartObject ? true : void 0,
862
+ required: schema.required && typeof schema.required === "boolean" && Boolean(schema.required) || Array.isArray(schema.required) && schema.required.includes(key),
863
+ schema: schema.properties[key],
864
+ in: "body"
865
+ };
866
+ }).filter(Boolean);
867
+ return [];
934
868
  }
935
- var defaultFormDataTypes = Object.keys(_utils.jsonSchemaTypes).reduce((prev, curr) => {
936
- return Object.assign(prev, { [curr]: {} });
869
+ const defaultFormDataTypes = Object.keys(oas_utils.jsonSchemaTypes).reduce((prev, curr) => {
870
+ return Object.assign(prev, { [curr]: {} });
937
871
  }, {});
938
872
  function getResponseContentType(content) {
939
- const types = Object.keys(content) || [];
940
- if (_optionalChain([types, 'optionalAccess', _14 => _14.length])) {
941
- const jsonType = types.find((t) => _utils.matchesMimeType.json(t));
942
- if (jsonType) {
943
- return jsonType;
944
- }
945
- return types[0];
946
- }
947
- return "application/json";
873
+ const types = Object.keys(content) || [];
874
+ if (types?.length) {
875
+ const jsonType = types.find((t) => oas_utils.matchesMimeType.json(t));
876
+ if (jsonType) return jsonType;
877
+ return types[0];
878
+ }
879
+ return "application/json";
948
880
  }
949
881
  function isPrimitive(val) {
950
- return typeof val === "string" || typeof val === "number" || typeof val === "boolean";
882
+ return typeof val === "string" || typeof val === "number" || typeof val === "boolean";
951
883
  }
952
884
  function stringify(json) {
953
- return JSON.stringify(
954
- _removeundefinedobjects2.default.call(void 0, typeof json.RAW_BODY !== "undefined" ? json.RAW_BODY : json, {
955
- preserveNullishArrays: true,
956
- preserveEmptyArray: true,
957
- preserveEmptyObject: {
958
- arrayItem: false,
959
- objectProperty: true,
960
- root: true
961
- }
962
- })
963
- );
885
+ return JSON.stringify((0, remove_undefined_objects.default)(typeof json.RAW_BODY !== "undefined" ? json.RAW_BODY : json, {
886
+ preserveNullishArrays: true,
887
+ preserveEmptyArray: true,
888
+ preserveEmptyObject: {
889
+ arrayItem: false,
890
+ objectProperty: true,
891
+ root: true
892
+ }
893
+ }));
964
894
  }
965
895
  function stringifyParameter(param) {
966
- if (param === null || isPrimitive(param)) {
967
- return String(param);
968
- } else if (Array.isArray(param) && param.every(isPrimitive)) {
969
- return String(param);
970
- }
971
- return JSON.stringify(param);
896
+ if (param === null || isPrimitive(param)) return String(param);
897
+ else if (Array.isArray(param) && param.every(isPrimitive)) return String(param);
898
+ return JSON.stringify(param);
972
899
  }
973
900
  function appendHarValue(harParam, name, value, addtlData = {}) {
974
- if (typeof value === "undefined") return;
975
- if (Array.isArray(value)) {
976
- value.forEach((singleValue) => {
977
- appendHarValue(harParam, name, singleValue);
978
- });
979
- } else if (typeof value === "object" && value !== null) {
980
- Object.keys(value).forEach((key) => {
981
- appendHarValue(harParam, key, value[key]);
982
- });
983
- } else {
984
- harParam.push({
985
- ...addtlData,
986
- name,
987
- value: String(value)
988
- });
989
- }
901
+ if (typeof value === "undefined") return;
902
+ if (Array.isArray(value)) value.forEach((singleValue) => {
903
+ appendHarValue(harParam, name, singleValue);
904
+ });
905
+ else if (typeof value === "object" && value !== null) Object.keys(value).forEach((key) => {
906
+ appendHarValue(harParam, key, value[key]);
907
+ });
908
+ else harParam.push({
909
+ ...addtlData,
910
+ name,
911
+ value: String(value)
912
+ });
990
913
  }
991
914
  function encodeBodyForHAR(body) {
992
- if (isPrimitive(body)) {
993
- return body;
994
- } else if (typeof body === "object" && body !== null && !Array.isArray(body) && typeof body.RAW_BODY !== "undefined") {
995
- if (isPrimitive(body.RAW_BODY)) {
996
- return body.RAW_BODY;
997
- }
998
- return stringify(body.RAW_BODY);
999
- }
1000
- return stringify(body);
915
+ if (isPrimitive(body)) return body;
916
+ else if (typeof body === "object" && body !== null && !Array.isArray(body) && typeof body.RAW_BODY !== "undefined") {
917
+ if (isPrimitive(body.RAW_BODY)) return body.RAW_BODY;
918
+ return stringify(body.RAW_BODY);
919
+ }
920
+ return stringify(body);
1001
921
  }
1002
922
  function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = { proxyUrl: "" }) {
1003
- let operation;
1004
- if (!operationSchema || typeof operationSchema.getParameters !== "function") {
1005
- operation = new (0, _operation.Operation)(
1006
- oas,
1007
- _optionalChain([operationSchema, 'optionalAccess', _15 => _15.path]) || "",
1008
- _optionalChain([operationSchema, 'optionalAccess', _16 => _16.method]) || "",
1009
- operationSchema || { path: "", method: "" }
1010
- );
1011
- } else {
1012
- operation = operationSchema;
1013
- }
1014
- const apiDefinition = oas.getDefinition();
1015
- const formData = {
1016
- ...defaultFormDataTypes,
1017
- ...values
1018
- };
1019
- const shouldSerializeBody = Object.prototype.hasOwnProperty.call(values, "body") && values.body !== void 0;
1020
- if (!formData.server) {
1021
- formData.server = {
1022
- selected: 0,
1023
- variables: operation.defaultVariables(0)
1024
- };
1025
- }
1026
- formData.server.variables = {
1027
- ...operation.defaultVariables(formData.server.selected),
1028
- ...formData.server.variables ? formData.server.variables : {}
1029
- };
1030
- const har = {
1031
- cookies: [],
1032
- headers: [],
1033
- headersSize: 0,
1034
- queryString: [],
1035
- // @ts-expect-error This is fine because we're fleshing `postData` out further down.
1036
- postData: {},
1037
- bodySize: 0,
1038
- method: operation.method.toUpperCase(),
1039
- url: `${operation.url(formData.server.selected, formData.server.variables)}${operation.path}`.replace(
1040
- /\s/g,
1041
- "%20"
1042
- ),
1043
- httpVersion: "HTTP/1.1"
1044
- };
1045
- if (opts.proxyUrl) {
1046
- if (oas.getExtension(_extensions.PROXY_ENABLED, operation)) {
1047
- har.url = `${opts.proxyUrl}/${har.url}`;
1048
- }
1049
- }
1050
- const parameters = operation.getParameters();
1051
- har.url = har.url.replace(/{([-_a-zA-Z0-9[\]]+)}/g, (full, key) => {
1052
- if (!operation || !parameters) return key;
1053
- const parameter = parameters.find((param) => param.name === key) || { name: key };
1054
- if (!("style" in parameter) || !parameter.style) {
1055
- return encodeURIComponent(formatter(formData, parameter, "path", false, oas.api));
1056
- }
1057
- return formatter(formData, parameter, "path", false, oas.api);
1058
- });
1059
- const queryStrings = _optionalChain([parameters, 'optionalAccess', _17 => _17.filter, 'call', _18 => _18((param) => param.in === "query")]);
1060
- if (_optionalChain([queryStrings, 'optionalAccess', _19 => _19.length])) {
1061
- queryStrings.forEach((queryString) => {
1062
- const value = formatter(formData, queryString, "query", true, oas.api);
1063
- appendHarValue(har.queryString, queryString.name, value);
1064
- });
1065
- }
1066
- const cookies = _optionalChain([parameters, 'optionalAccess', _20 => _20.filter, 'call', _21 => _21((param) => param.in === "cookie")]);
1067
- if (_optionalChain([cookies, 'optionalAccess', _22 => _22.length])) {
1068
- cookies.forEach((cookie) => {
1069
- const value = formatter(formData, cookie, "cookie", true, oas.api);
1070
- appendHarValue(har.cookies, cookie.name, value);
1071
- });
1072
- }
1073
- if (operation.schema.responses) {
1074
- Object.keys(operation.schema.responses).some((statusCode) => {
1075
- const response = operation.getResponseByStatusCode(statusCode);
1076
- if (!response) return false;
1077
- const content = response.content;
1078
- if (!content) return false;
1079
- if (Object.keys(formData.header || {}).find((h) => h.toLowerCase() === "accept")) return true;
1080
- har.headers.push({
1081
- name: "accept",
1082
- value: getResponseContentType(content)
1083
- });
1084
- return true;
1085
- });
1086
- }
1087
- let hasContentType = false;
1088
- let contentType = operation.getContentType();
1089
- const headers = _optionalChain([parameters, 'optionalAccess', _23 => _23.filter, 'call', _24 => _24((param) => param.in === "header")]);
1090
- if (_optionalChain([headers, 'optionalAccess', _25 => _25.length])) {
1091
- headers.forEach((header) => {
1092
- const value = formatter(formData, header, "header", true, oas.api);
1093
- if (typeof value === "undefined") return;
1094
- if (header.name.toLowerCase() === "content-type") {
1095
- hasContentType = true;
1096
- contentType = String(value);
1097
- }
1098
- appendHarValue(har.headers, header.name, value);
1099
- });
1100
- }
1101
- const userDefinedHeaders = oas.getExtension(_extensions.HEADERS, operation);
1102
- if (userDefinedHeaders) {
1103
- userDefinedHeaders.forEach((header) => {
1104
- if (typeof header.key === "string" && header.key.toLowerCase() === "content-type") {
1105
- hasContentType = true;
1106
- contentType = String(header.value);
1107
- }
1108
- har.headers.push({
1109
- name: String(header.key),
1110
- value: String(header.value)
1111
- });
1112
- });
1113
- }
1114
- if (formData.header) {
1115
- const contentTypeFormHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "content-type");
1116
- if (contentTypeFormHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "content-type")) {
1117
- hasContentType = true;
1118
- contentType = String(formData.header[contentTypeFormHeader]);
1119
- har.headers.push({
1120
- name: "content-type",
1121
- value: contentType
1122
- });
1123
- }
1124
- const acceptHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "accept");
1125
- if (acceptHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "accept")) {
1126
- har.headers.push({
1127
- name: "accept",
1128
- value: String(formData.header[acceptHeader])
1129
- });
1130
- }
1131
- const authorizationHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "authorization");
1132
- if (authorizationHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "authorization")) {
1133
- har.headers.push({
1134
- name: "authorization",
1135
- value: String(formData.header[authorizationHeader])
1136
- });
1137
- }
1138
- }
1139
- let requestBody;
1140
- if (operation.hasRequestBody()) {
1141
- const isFormUrlEncoded = _utils.matchesMimeType.formUrlEncoded(contentType);
1142
- const matchesRequestBodyType = (payload) => {
1143
- return payload.type === (isFormUrlEncoded ? "formData" : "body");
1144
- };
1145
- requestBody = _optionalChain([operation, 'access', _26 => _26.getParametersAsJSONSchema, 'call', _27 => _27({ contentType }), 'optionalAccess', _28 => _28.find, 'call', _29 => _29(matchesRequestBodyType)]);
1146
- }
1147
- if (_optionalChain([requestBody, 'optionalAccess', _30 => _30.schema]) && Object.keys(requestBody.schema).length) {
1148
- const requestBodySchema = requestBody.schema;
1149
- const isFormUrlEncoded = _utils.matchesMimeType.formUrlEncoded(contentType);
1150
- if (isFormUrlEncoded) {
1151
- if (Object.keys(formData.formData || {}).length) {
1152
- const cleanFormData = _removeundefinedobjects2.default.call(void 0, formData.formData, { preserveNullishArrays: true });
1153
- if (cleanFormData !== void 0) {
1154
- const postData = { params: [], mimeType: "application/x-www-form-urlencoded" };
1155
- Object.keys(cleanFormData).forEach((name) => {
1156
- postData.params.push({
1157
- name,
1158
- value: stringifyParameter(cleanFormData[name])
1159
- });
1160
- });
1161
- har.postData = postData;
1162
- }
1163
- }
1164
- } else if (shouldSerializeBody) {
1165
- const isMultipart = _utils.matchesMimeType.multipart(contentType);
1166
- const isJSON = _utils.matchesMimeType.json(contentType);
1167
- if (isMultipart || isJSON) {
1168
- try {
1169
- let cleanBody = _removeundefinedobjects2.default.call(void 0, formData.body, {
1170
- preserveNullishArrays: true,
1171
- preserveEmptyArray: true,
1172
- preserveEmptyObject: {
1173
- arrayItem: false,
1174
- objectProperty: true,
1175
- root: true
1176
- }
1177
- });
1178
- if (isMultipart) {
1179
- har.postData = { params: [], mimeType: "multipart/form-data" };
1180
- const safeBodySchema = getSafeRequestBody(requestBodySchema, formData.body, operation.api);
1181
- const binaryTypes = Object.keys(_nullishCoalesce(safeBodySchema.properties, () => ( {}))).filter((key) => {
1182
- if (!_optionalChain([safeBodySchema, 'access', _31 => _31.properties, 'optionalAccess', _32 => _32[key]]) || typeof safeBodySchema.properties[key] !== "object" || safeBodySchema.properties[key] === null) {
1183
- return false;
1184
- }
1185
- const propData = safeBodySchema.properties[key];
1186
- if (propData.format === "binary") {
1187
- return true;
1188
- } else if (propData.type === "array" && propData.items && typeof propData.items === "object" && propData.items !== null && propData.items.format === "binary") {
1189
- return true;
1190
- }
1191
- return false;
1192
- });
1193
- if (cleanBody !== void 0) {
1194
- let multipartParams = [];
1195
- const multipartContent = operation.getRequestBody(contentType);
1196
- if (multipartContent) {
1197
- multipartParams = multipartBodyToFormatterParams(
1198
- formData.body,
1199
- multipartContent.mediaTypeObject,
1200
- safeBodySchema
1201
- );
1202
- }
1203
- if (multipartParams.length) {
1204
- Object.keys(cleanBody).forEach((name) => {
1205
- const param = multipartParams.find((multipartParam) => multipartParam.name === name);
1206
- if (param) {
1207
- const addtlData = {};
1208
- let value = formatter(formData, param, "body", true, oas.api);
1209
- if (!Array.isArray(value)) {
1210
- value = [value];
1211
- }
1212
- value.forEach((val) => {
1213
- if (binaryTypes.includes(name)) {
1214
- const parsed = _dataurls.parse.call(void 0, val);
1215
- if (parsed) {
1216
- addtlData.fileName = "name" in parsed ? parsed.name : "unknown";
1217
- if ("contentType" in parsed) {
1218
- addtlData.contentType = parsed.contentType;
1219
- }
1220
- }
1221
- }
1222
- appendHarValue(_optionalChain([har, 'access', _33 => _33.postData, 'optionalAccess', _34 => _34.params]) || [], name, val, addtlData);
1223
- });
1224
- }
1225
- });
1226
- }
1227
- }
1228
- } else {
1229
- har.postData = { mimeType: contentType, text: "" };
1230
- if (hasSchemaType(requestBody.schema, "string") || hasSchemaType(requestBody.schema, "integer") || hasSchemaType(requestBody.schema, "number") || hasSchemaType(requestBody.schema, "boolean")) {
1231
- har.postData.text = JSON.stringify(JSON.parse(cleanBody));
1232
- } else {
1233
- const jsonTypes = getTypedFormatsInSchema("json", requestBodySchema, operation.api, {
1234
- payload: cleanBody
1235
- });
1236
- if (Array.isArray(jsonTypes) && jsonTypes.length) {
1237
- try {
1238
- jsonTypes.forEach((prop) => {
1239
- try {
1240
- set(cleanBody, String(prop), JSON.parse(get(cleanBody, String(prop))));
1241
- } catch (e5) {
1242
- }
1243
- });
1244
- if (typeof cleanBody.RAW_BODY !== "undefined") {
1245
- cleanBody = cleanBody.RAW_BODY;
1246
- }
1247
- har.postData.text = JSON.stringify(cleanBody);
1248
- } catch (e6) {
1249
- har.postData.text = stringify(formData.body);
1250
- }
1251
- } else {
1252
- try {
1253
- const parsed = parseJSONStringsInBodyWithSchema(cleanBody, requestBodySchema, operation.api);
1254
- if (typeof _optionalChain([parsed, 'optionalAccess', _35 => _35.RAW_BODY]) !== "undefined") {
1255
- har.postData.text = isPrimitive(parsed.RAW_BODY) ? String(parsed.RAW_BODY) : stringify(parsed.RAW_BODY);
1256
- } else {
1257
- har.postData.text = JSON.stringify(parsed);
1258
- }
1259
- } catch (e7) {
1260
- har.postData.text = encodeBodyForHAR(formData.body);
1261
- }
1262
- }
1263
- }
1264
- }
1265
- } catch (e8) {
1266
- har.postData = { mimeType: contentType, text: stringify(formData.body) };
1267
- }
1268
- } else {
1269
- har.postData = { mimeType: contentType, text: encodeBodyForHAR(formData.body) };
1270
- }
1271
- }
1272
- }
1273
- if ((_optionalChain([har, 'access', _36 => _36.postData, 'optionalAccess', _37 => _37.text]) || _optionalChain([requestBody, 'optionalAccess', _38 => _38.schema]) && Object.keys(requestBody.schema).length) && !hasContentType) {
1274
- har.headers.push({
1275
- name: "content-type",
1276
- value: contentType
1277
- });
1278
- }
1279
- const securityRequirements = operation.getSecurity();
1280
- if (_optionalChain([securityRequirements, 'optionalAccess', _39 => _39.length])) {
1281
- securityRequirements.forEach((schemes) => {
1282
- Object.keys(schemes).forEach((security) => {
1283
- const securityValue = _chunk6CVT7KVTcjs.configureSecurity.call(void 0, apiDefinition, auth, security);
1284
- if (!securityValue) {
1285
- return;
1286
- }
1287
- if (securityValue.value.name === "authorization") {
1288
- if (har[securityValue.type].find((v) => v.name === securityValue.value.name)) {
1289
- return;
1290
- }
1291
- }
1292
- if (har[securityValue.type].find(
1293
- (v) => v.name === securityValue.value.name && v.value === securityValue.value.value
1294
- )) {
1295
- return;
1296
- }
1297
- har[securityValue.type].push(securityValue.value);
1298
- });
1299
- });
1300
- }
1301
- if (Object.keys(har.postData || {}).length === 0) {
1302
- delete har.postData;
1303
- }
1304
- return {
1305
- log: {
1306
- entries: [
1307
- {
1308
- request: har
1309
- }
1310
- ]
1311
- }
1312
- };
923
+ let operation;
924
+ if (!operationSchema || typeof operationSchema.getParameters !== "function")
925
+ /**
926
+ * If `operationSchema` was supplied as a plain object instead of an instance of `Operation`
927
+ * then we should create a new instance of it. We're doing it with a check on `getParameters`
928
+ * instead of checking `instanceof Operation` because JS is very weird when it comes to
929
+ * checking `instanceof` against classes. One instance of `Operation` may not always match up
930
+ * with another if they're being loaded between two different libraries.
931
+ *
932
+ * It's weird. This is easier.
933
+ */
934
+ operation = new oas_operation.Operation(oas, operationSchema?.path || "", operationSchema?.method || "", operationSchema || {
935
+ path: "",
936
+ method: ""
937
+ });
938
+ else operation = operationSchema;
939
+ const apiDefinition = oas.getDefinition();
940
+ const formData = {
941
+ ...defaultFormDataTypes,
942
+ ...values
943
+ };
944
+ const shouldSerializeBody = Object.prototype.hasOwnProperty.call(values, "body") && values.body !== void 0;
945
+ if (!formData.server) formData.server = {
946
+ selected: 0,
947
+ variables: operation.defaultVariables(0)
948
+ };
949
+ formData.server.variables = {
950
+ ...operation.defaultVariables(formData.server.selected),
951
+ ...formData.server.variables ? formData.server.variables : {}
952
+ };
953
+ const har = {
954
+ cookies: [],
955
+ headers: [],
956
+ headersSize: 0,
957
+ queryString: [],
958
+ postData: {},
959
+ bodySize: 0,
960
+ method: operation.method.toUpperCase(),
961
+ url: `${operation.url(formData.server.selected, formData.server.variables)}${operation.path}`.replace(/\s/g, "%20"),
962
+ httpVersion: "HTTP/1.1"
963
+ };
964
+ if (opts.proxyUrl) {
965
+ if (oas.getExtension(oas_extensions.PROXY_ENABLED, operation)) har.url = `${opts.proxyUrl}/${har.url}`;
966
+ }
967
+ const parameters = operation.getParameters();
968
+ har.url = har.url.replace(/{([-_a-zA-Z0-9[\]]+)}/g, (full, key) => {
969
+ if (!operation || !parameters) return key;
970
+ const parameter = parameters.find((param) => param.name === key) || { name: key };
971
+ if (!parameter.style) return encodeURIComponent(formatter(formData, parameter, "path", false, oas.api));
972
+ return formatter(formData, parameter, "path", false, oas.api);
973
+ });
974
+ const queryStrings = parameters?.filter((param) => param.in === "query");
975
+ if (queryStrings?.length) queryStrings.forEach((queryString) => {
976
+ const value = formatter(formData, queryString, "query", true, oas.api);
977
+ appendHarValue(har.queryString, queryString.name, value);
978
+ });
979
+ const cookies = parameters?.filter((param) => param.in === "cookie");
980
+ if (cookies?.length) cookies.forEach((cookie) => {
981
+ const value = formatter(formData, cookie, "cookie", true, oas.api);
982
+ appendHarValue(har.cookies, cookie.name, value);
983
+ });
984
+ if (operation.schema.responses) Object.keys(operation.schema.responses).some((statusCode) => {
985
+ const response = operation.getResponseByStatusCode(statusCode);
986
+ if (!response) return false;
987
+ const content = response.content;
988
+ if (!content) return false;
989
+ if (Object.keys(formData.header || {}).find((h) => h.toLowerCase() === "accept")) return true;
990
+ har.headers.push({
991
+ name: "accept",
992
+ value: getResponseContentType(content)
993
+ });
994
+ return true;
995
+ });
996
+ let hasContentType = false;
997
+ let contentType = operation.getContentType();
998
+ const headers = parameters?.filter((param) => param.in === "header");
999
+ if (headers?.length) headers.forEach((header) => {
1000
+ const value = formatter(formData, header, "header", true, oas.api);
1001
+ if (typeof value === "undefined") return;
1002
+ if (header.name.toLowerCase() === "content-type") {
1003
+ hasContentType = true;
1004
+ contentType = String(value);
1005
+ }
1006
+ appendHarValue(har.headers, header.name, value);
1007
+ });
1008
+ const userDefinedHeaders = oas.getExtension(oas_extensions.HEADERS, operation);
1009
+ if (userDefinedHeaders) userDefinedHeaders.forEach((header) => {
1010
+ if (typeof header.key === "string" && header.key.toLowerCase() === "content-type") {
1011
+ hasContentType = true;
1012
+ contentType = String(header.value);
1013
+ }
1014
+ har.headers.push({
1015
+ name: String(header.key),
1016
+ value: String(header.value)
1017
+ });
1018
+ });
1019
+ if (formData.header) {
1020
+ const contentTypeFormHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "content-type");
1021
+ if (contentTypeFormHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "content-type")) {
1022
+ hasContentType = true;
1023
+ contentType = String(formData.header[contentTypeFormHeader]);
1024
+ har.headers.push({
1025
+ name: "content-type",
1026
+ value: contentType
1027
+ });
1028
+ }
1029
+ const acceptHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "accept");
1030
+ if (acceptHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "accept")) har.headers.push({
1031
+ name: "accept",
1032
+ value: String(formData.header[acceptHeader])
1033
+ });
1034
+ const authorizationHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "authorization");
1035
+ if (authorizationHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "authorization")) har.headers.push({
1036
+ name: "authorization",
1037
+ value: String(formData.header[authorizationHeader])
1038
+ });
1039
+ }
1040
+ let requestBody;
1041
+ if (operation.hasRequestBody()) {
1042
+ const isFormUrlEncoded = oas_utils.matchesMimeType.formUrlEncoded(contentType);
1043
+ const matchesRequestBodyType = (payload) => {
1044
+ return payload.type === (isFormUrlEncoded ? "formData" : "body");
1045
+ };
1046
+ requestBody = operation.getParametersAsJSONSchema({ contentType })?.find(matchesRequestBodyType);
1047
+ }
1048
+ if (requestBody?.schema && Object.keys(requestBody.schema).length) {
1049
+ const requestBodySchema = requestBody.schema;
1050
+ if (oas_utils.matchesMimeType.formUrlEncoded(contentType)) {
1051
+ if (Object.keys(formData.formData || {}).length) {
1052
+ const cleanFormData = (0, remove_undefined_objects.default)(formData.formData, { preserveNullishArrays: true });
1053
+ if (cleanFormData !== void 0) {
1054
+ const postData = {
1055
+ params: [],
1056
+ mimeType: "application/x-www-form-urlencoded"
1057
+ };
1058
+ Object.keys(cleanFormData).forEach((name) => {
1059
+ postData.params.push({
1060
+ name,
1061
+ value: stringifyParameter(cleanFormData[name])
1062
+ });
1063
+ });
1064
+ har.postData = postData;
1065
+ }
1066
+ }
1067
+ } else if (shouldSerializeBody) {
1068
+ const isMultipart = oas_utils.matchesMimeType.multipart(contentType);
1069
+ const isJSON = oas_utils.matchesMimeType.json(contentType);
1070
+ if (isMultipart || isJSON) try {
1071
+ let cleanBody = (0, remove_undefined_objects.default)(formData.body, {
1072
+ preserveNullishArrays: true,
1073
+ preserveEmptyArray: true,
1074
+ preserveEmptyObject: {
1075
+ arrayItem: false,
1076
+ objectProperty: true,
1077
+ root: true
1078
+ }
1079
+ });
1080
+ if (isMultipart) {
1081
+ har.postData = {
1082
+ params: [],
1083
+ mimeType: "multipart/form-data"
1084
+ };
1085
+ const safeBodySchema = getSafeRequestBody(requestBodySchema, formData.body, operation.api);
1086
+ /**
1087
+ * Discover all `{ type: string, format: binary }` properties, or arrays containing the
1088
+ * same, within the request body. If there are any, then that means that we're dealing
1089
+ * with a `multipart/form-data` request and need to treat the payload as
1090
+ * `postData.params` and supply filenames and content types for the files (if they're
1091
+ * available).
1092
+ *
1093
+ * @todo It'd be nice to replace this with `getTypedFormatsInSchema` instead.
1094
+ * @example `{ type: string, format: binary }`
1095
+ * @example `{ type: array, items: { type: string, format: binary } }`
1096
+ */
1097
+ const binaryTypes = Object.keys(safeBodySchema.properties ?? {}).filter((key) => {
1098
+ if (!safeBodySchema.properties?.[key] || typeof safeBodySchema.properties[key] !== "object" || safeBodySchema.properties[key] === null) return false;
1099
+ const propData = safeBodySchema.properties[key];
1100
+ if (propData.format === "binary") return true;
1101
+ else if (propData.type === "array" && propData.items && typeof propData.items === "object" && propData.items !== null && propData.items.format === "binary") return true;
1102
+ return false;
1103
+ });
1104
+ if (cleanBody !== void 0) {
1105
+ let multipartParams = [];
1106
+ const multipartContent = operation.getRequestBody(contentType);
1107
+ if (multipartContent) multipartParams = multipartBodyToFormatterParams(formData.body, multipartContent.mediaTypeObject, safeBodySchema);
1108
+ if (multipartParams.length) Object.keys(cleanBody).forEach((name) => {
1109
+ const param = multipartParams.find((multipartParam) => multipartParam.name === name);
1110
+ if (param) {
1111
+ const addtlData = {};
1112
+ let value = formatter(formData, param, "body", true, oas.api);
1113
+ if (!Array.isArray(value)) value = [value];
1114
+ value.forEach((val) => {
1115
+ if (binaryTypes.includes(name)) {
1116
+ const parsed = (0, _readme_data_urls.parse)(val);
1117
+ if (parsed) {
1118
+ addtlData.fileName = "name" in parsed ? parsed.name : "unknown";
1119
+ if ("contentType" in parsed) addtlData.contentType = parsed.contentType;
1120
+ }
1121
+ }
1122
+ appendHarValue(har.postData?.params || [], name, val, addtlData);
1123
+ });
1124
+ }
1125
+ });
1126
+ }
1127
+ } else {
1128
+ har.postData = {
1129
+ mimeType: contentType,
1130
+ text: ""
1131
+ };
1132
+ if (hasSchemaType(requestBody.schema, "string") || hasSchemaType(requestBody.schema, "integer") || hasSchemaType(requestBody.schema, "number") || hasSchemaType(requestBody.schema, "boolean")) har.postData.text = JSON.stringify(JSON.parse(cleanBody));
1133
+ else {
1134
+ /**
1135
+ * Handle formatted JSON objects that have properties that accept arbitrary JSON.
1136
+ *
1137
+ * Find all `{ type: string, format: json }` properties in the schema because we need
1138
+ * to manually `JSON.parse` them before submit, otherwise they'll be escaped instead
1139
+ * of actual objects. We also only want values that the user has entered, so we drop
1140
+ * any `undefined` `cleanBody` keys.
1141
+ */
1142
+ const jsonTypes = getTypedFormatsInSchema("json", requestBodySchema, operation.api, { payload: cleanBody });
1143
+ if (Array.isArray(jsonTypes) && jsonTypes.length) try {
1144
+ jsonTypes.forEach((prop) => {
1145
+ try {
1146
+ set(cleanBody, String(prop), JSON.parse(get(cleanBody, String(prop))));
1147
+ } catch {}
1148
+ });
1149
+ if (typeof cleanBody.RAW_BODY !== "undefined") cleanBody = cleanBody.RAW_BODY;
1150
+ har.postData.text = JSON.stringify(cleanBody);
1151
+ } catch {
1152
+ har.postData.text = stringify(formData.body);
1153
+ }
1154
+ else try {
1155
+ const parsed = parseJSONStringsInBodyWithSchema(cleanBody, requestBodySchema, operation.api);
1156
+ if (typeof parsed?.RAW_BODY !== "undefined") har.postData.text = isPrimitive(parsed.RAW_BODY) ? String(parsed.RAW_BODY) : stringify(parsed.RAW_BODY);
1157
+ else har.postData.text = JSON.stringify(parsed);
1158
+ } catch {
1159
+ har.postData.text = encodeBodyForHAR(formData.body);
1160
+ }
1161
+ }
1162
+ }
1163
+ } catch {
1164
+ har.postData = {
1165
+ mimeType: contentType,
1166
+ text: stringify(formData.body)
1167
+ };
1168
+ }
1169
+ else har.postData = {
1170
+ mimeType: contentType,
1171
+ text: encodeBodyForHAR(formData.body)
1172
+ };
1173
+ }
1174
+ }
1175
+ if ((har.postData?.text || requestBody?.schema && Object.keys(requestBody.schema).length) && !hasContentType) har.headers.push({
1176
+ name: "content-type",
1177
+ value: contentType
1178
+ });
1179
+ const securityRequirements = operation.getSecurity();
1180
+ if (securityRequirements?.length) securityRequirements.forEach((schemes) => {
1181
+ Object.keys(schemes).forEach((security) => {
1182
+ const securityValue = require_lib_configure_security(apiDefinition, auth, security);
1183
+ if (!securityValue) return;
1184
+ if (securityValue.value.name === "authorization") {
1185
+ if (har[securityValue.type].find((v) => v.name === securityValue.value.name)) return;
1186
+ }
1187
+ if (har[securityValue.type].find((v) => v.name === securityValue.value.name && v.value === securityValue.value.value)) return;
1188
+ har[securityValue.type].push(securityValue.value);
1189
+ });
1190
+ });
1191
+ if (Object.keys(har.postData || {}).length === 0) delete har.postData;
1192
+ return { log: { entries: [{ request: har }] } };
1313
1193
  }
1314
1194
 
1315
-
1316
- exports.default = oasToHar;
1317
- /**
1318
- * This file has been extracted and modified from `swagger-client`.
1319
- *
1320
- * @license Apache 2.0
1321
- * @link https://npm.im/swagger-client
1322
- * @link https://github.com/swagger-api/swagger-js/blob/master/src/execute/oas3/style-serializer.js
1323
- */
1324
-
1325
- module.exports = exports.default;
1195
+ module.exports = oasToHar;
1326
1196
  //# sourceMappingURL=index.cjs.map