@readme/oas-to-har 22.0.1 → 23.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.
@@ -80,4 +80,4 @@ function configureSecurity(apiDefinition, values, scheme) {
80
80
 
81
81
  export { configureSecurity };
82
82
  //# sourceMappingURL=out.js.map
83
- //# sourceMappingURL=chunk-RHTGXJGI.mjs.map
83
+ //# sourceMappingURL=chunk-67WTTRX2.js.map
@@ -1,11 +1,95 @@
1
- import { configureSecurity } from './chunk-RHTGXJGI.mjs';
2
- import { parse } from '@readme/data-urls';
3
- import { getExtension, PROXY_ENABLED, HEADERS } from '@readme/oas-extensions';
4
- import { set, get } from 'lodash';
5
- import { utils, Operation } from 'oas';
6
- import { isRef } from 'oas/rmoas.types';
7
- import removeUndefinedObjects from 'remove-undefined-objects';
8
- import qs from 'qs';
1
+ 'use strict';
2
+
3
+ var dataUrls = require('@readme/data-urls');
4
+ var oasExtensions = require('@readme/oas-extensions');
5
+ var lodash = require('lodash');
6
+ var oas = require('oas');
7
+ var rmoas_types = require('oas/rmoas.types');
8
+ var removeUndefinedObjects = require('remove-undefined-objects');
9
+ var qs = require('qs');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var removeUndefinedObjects__default = /*#__PURE__*/_interopDefault(removeUndefinedObjects);
14
+ var qs__default = /*#__PURE__*/_interopDefault(qs);
15
+
16
+ // src/index.ts
17
+ function harValue(type, value) {
18
+ if (!value.value)
19
+ return void 0;
20
+ return { type, value };
21
+ }
22
+ function configureSecurity(apiDefinition, values, scheme) {
23
+ if (!scheme)
24
+ return void 0;
25
+ if (Object.keys(values || {}).length === 0)
26
+ return void 0;
27
+ if (!apiDefinition.components.securitySchemes[scheme])
28
+ return void 0;
29
+ const security = apiDefinition.components.securitySchemes[scheme];
30
+ if (rmoas_types.isRef(security)) {
31
+ return void 0;
32
+ } else if (!values[scheme]) {
33
+ return false;
34
+ }
35
+ if (security.type === "http") {
36
+ if (security.scheme === "basic") {
37
+ const auth = values[scheme];
38
+ if (typeof auth !== "object")
39
+ return false;
40
+ if (!auth.user && !auth.pass)
41
+ return false;
42
+ let user = auth.user ?? null;
43
+ if (user === null || user.length === 0) {
44
+ user = "";
45
+ }
46
+ let pass = auth.pass ?? null;
47
+ if (pass === null || pass.length === 0) {
48
+ pass = "";
49
+ }
50
+ return harValue("headers", {
51
+ name: "authorization",
52
+ value: `Basic ${Buffer.from(`${user}:${pass}`).toString("base64")}`
53
+ });
54
+ } else if (security.scheme === "bearer") {
55
+ return harValue("headers", {
56
+ name: "authorization",
57
+ value: `Bearer ${values[scheme]}`
58
+ });
59
+ }
60
+ }
61
+ if (security.type === "apiKey") {
62
+ if (security.in === "query") {
63
+ return harValue("queryString", {
64
+ name: security.name,
65
+ value: String(values[scheme])
66
+ });
67
+ } else if (security.in === "header") {
68
+ const header = {
69
+ name: security.name,
70
+ value: String(values[scheme])
71
+ };
72
+ if (security["x-bearer-format"]) {
73
+ const bearerFormat = security["x-bearer-format"].charAt(0).toUpperCase() + security["x-bearer-format"].slice(1);
74
+ header.name = security.name;
75
+ header.value = `${bearerFormat} ${header.value}`;
76
+ }
77
+ return harValue("headers", header);
78
+ } else if (security.in === "cookie") {
79
+ return harValue("cookies", {
80
+ name: security.name,
81
+ value: String(values[scheme])
82
+ });
83
+ }
84
+ }
85
+ if (security.type === "oauth2") {
86
+ return harValue("headers", {
87
+ name: "authorization",
88
+ value: `Bearer ${values[scheme]}`
89
+ });
90
+ }
91
+ return void 0;
92
+ }
9
93
 
10
94
  // src/lib/style-formatting/style-serializer.ts
11
95
  function isObject(value) {
@@ -215,7 +299,7 @@ function stylizeValue(value, parameter) {
215
299
  });
216
300
  }
217
301
  function handleDeepObject(value, parameter) {
218
- return qs.stringify(value, {
302
+ return qs__default.default.stringify(value, {
219
303
  // eslint-disable-next-line consistent-return
220
304
  encoder(str, defaultEncoder, charset, type) {
221
305
  if (type === "key") {
@@ -296,7 +380,7 @@ function getSafeRequestBody(obj) {
296
380
  function getSubschemas(schema, opts) {
297
381
  let subSchemaDataSize = 0;
298
382
  if (opts.parentIsArray) {
299
- const parentData = get(opts.payload, opts.parentKey);
383
+ const parentData = lodash.get(opts.payload, opts.parentKey);
300
384
  if (parentData === void 0 || !Array.isArray(parentData)) {
301
385
  return false;
302
386
  }
@@ -324,17 +408,17 @@ function getTypedFormatsInSchema(format, schema, opts) {
324
408
  try {
325
409
  if (schema?.format === format) {
326
410
  if (opts.parentIsArray) {
327
- const parentData = get(opts.payload, opts.parentKey);
411
+ const parentData = lodash.get(opts.payload, opts.parentKey);
328
412
  if (parentData !== void 0 && Array.isArray(parentData)) {
329
413
  return Object.keys(parentData).map((pdk) => {
330
414
  const currentKey = [opts.parentKey, pdk].join(".");
331
- if (get(opts.payload, currentKey) !== void 0) {
415
+ if (lodash.get(opts.payload, currentKey) !== void 0) {
332
416
  return currentKey;
333
417
  }
334
418
  return false;
335
419
  }).filter(Boolean);
336
420
  }
337
- } else if (opts.parentKey && get(opts.payload, opts.parentKey) !== void 0) {
421
+ } else if (opts.parentKey && lodash.get(opts.payload, opts.parentKey) !== void 0) {
338
422
  return opts.parentKey;
339
423
  } else if (opts.payload !== void 0) {
340
424
  return true;
@@ -370,7 +454,7 @@ function getTypedFormatsInSchema(format, schema, opts) {
370
454
  }
371
455
 
372
456
  // src/index.ts
373
- var { jsonSchemaTypes, matchesMimeType } = utils;
457
+ var { jsonSchemaTypes, matchesMimeType } = oas.utils;
374
458
  function formatter(values, param, type, onlyIfExists = false) {
375
459
  if (param.style) {
376
460
  const value2 = values[type][param.name];
@@ -381,12 +465,12 @@ function formatter(values, param, type, onlyIfExists = false) {
381
465
  value = values[type][param.name];
382
466
  } else if (onlyIfExists && !param.required) {
383
467
  value = void 0;
384
- } else if (param.required && param.schema && !isRef(param.schema) && param.schema.default) {
468
+ } else if (param.required && param.schema && !rmoas_types.isRef(param.schema) && param.schema.default) {
385
469
  value = param.schema.default;
386
470
  } else if (type === "path") {
387
471
  return param.name;
388
472
  }
389
- if (param.schema && !isRef(param.schema) && param.schema.type === "array" && param.schema.items && !isRef(param.schema.items) && param.schema.items.format === "binary") {
473
+ if (param.schema && !rmoas_types.isRef(param.schema) && param.schema.type === "array" && param.schema.items && !rmoas_types.isRef(param.schema.items) && param.schema.items.format === "binary") {
390
474
  if (Array.isArray(value)) {
391
475
  return value;
392
476
  }
@@ -440,7 +524,7 @@ function isPrimitive(val) {
440
524
  return typeof val === "string" || typeof val === "number" || typeof val === "boolean";
441
525
  }
442
526
  function stringify(json) {
443
- return JSON.stringify(removeUndefinedObjects(typeof json.RAW_BODY !== "undefined" ? json.RAW_BODY : json));
527
+ return JSON.stringify(removeUndefinedObjects__default.default(typeof json.RAW_BODY !== "undefined" ? json.RAW_BODY : json));
444
528
  }
445
529
  function stringifyParameter(param) {
446
530
  if (param === null || isPrimitive(param)) {
@@ -480,15 +564,15 @@ function encodeBodyForHAR(body) {
480
564
  }
481
565
  return stringify(body);
482
566
  }
483
- function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
567
+ function oasToHar(oas$1, operationSchema, values = {}, auth = {}, opts = {
484
568
  // If true, the operation URL will be rewritten and prefixed with https://try.readme.io/ in
485
569
  // order to funnel requests through our CORS-friendly proxy.
486
570
  proxyUrl: false
487
571
  }) {
488
572
  let operation;
489
573
  if (!operationSchema || typeof operationSchema.getParameters !== "function") {
490
- operation = new Operation(
491
- oas,
574
+ operation = new oas.Operation(
575
+ oas$1,
492
576
  operationSchema?.path || "",
493
577
  operationSchema?.method || "",
494
578
  operationSchema || { path: "", method: "" }
@@ -496,17 +580,17 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
496
580
  } else {
497
581
  operation = operationSchema;
498
582
  }
499
- const apiDefinition = oas.getDefinition();
583
+ const apiDefinition = oas$1.getDefinition();
500
584
  const formData = {
501
585
  ...defaultFormDataTypes,
502
586
  server: {
503
587
  selected: 0,
504
- variables: oas.defaultVariables(0)
588
+ variables: oas$1.defaultVariables(0)
505
589
  },
506
590
  ...values
507
591
  };
508
592
  formData.server.variables = {
509
- ...oas.defaultVariables(formData.server.selected),
593
+ ...oas$1.defaultVariables(formData.server.selected),
510
594
  ...formData.server.variables ? formData.server.variables : {}
511
595
  };
512
596
  const har = {
@@ -518,11 +602,11 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
518
602
  postData: {},
519
603
  bodySize: 0,
520
604
  method: operation.method.toUpperCase(),
521
- url: `${oas.url(formData.server.selected, formData.server.variables)}${operation.path}`.replace(/\s/g, "%20"),
605
+ url: `${oas$1.url(formData.server.selected, formData.server.variables)}${operation.path}`.replace(/\s/g, "%20"),
522
606
  httpVersion: "HTTP/1.1"
523
607
  };
524
608
  if (opts.proxyUrl) {
525
- if (getExtension(PROXY_ENABLED, oas, operation)) {
609
+ if (oasExtensions.getExtension(oasExtensions.PROXY_ENABLED, oas$1, operation)) {
526
610
  har.url = `https://try.readme.io/${har.url}`;
527
611
  }
528
612
  }
@@ -552,7 +636,7 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
552
636
  }
553
637
  if (operation.schema.responses) {
554
638
  Object.keys(operation.schema.responses).some((response) => {
555
- if (isRef(operation.schema.responses[response]))
639
+ if (rmoas_types.isRef(operation.schema.responses[response]))
556
640
  return false;
557
641
  const content = operation.schema.responses[response].content;
558
642
  if (!content)
@@ -581,7 +665,7 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
581
665
  appendHarValue(har.headers, header.name, value);
582
666
  });
583
667
  }
584
- const userDefinedHeaders = getExtension(HEADERS, oas, operation);
668
+ const userDefinedHeaders = oasExtensions.getExtension(oasExtensions.HEADERS, oas$1, operation);
585
669
  if (userDefinedHeaders) {
586
670
  userDefinedHeaders.forEach((header) => {
587
671
  if (typeof header.key === "string" && header.key.toLowerCase() === "content-type") {
@@ -620,7 +704,7 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
620
704
  const requestBodySchema = requestBody.schema;
621
705
  if (operation.isFormUrlEncoded()) {
622
706
  if (Object.keys(formData.formData).length) {
623
- const cleanFormData = removeUndefinedObjects(JSON.parse(JSON.stringify(formData.formData)));
707
+ const cleanFormData = removeUndefinedObjects__default.default(JSON.parse(JSON.stringify(formData.formData)));
624
708
  if (cleanFormData !== void 0) {
625
709
  har.postData.params = [];
626
710
  har.postData.mimeType = "application/x-www-form-urlencoded";
@@ -637,7 +721,7 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
637
721
  const isJSON = operation.isJson();
638
722
  if (isMultipart || isJSON) {
639
723
  try {
640
- let cleanBody = removeUndefinedObjects(JSON.parse(JSON.stringify(formData.body)));
724
+ let cleanBody = removeUndefinedObjects__default.default(JSON.parse(JSON.stringify(formData.body)));
641
725
  if (isMultipart) {
642
726
  har.postData.mimeType = "multipart/form-data";
643
727
  har.postData.params = [];
@@ -667,7 +751,7 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
667
751
  }
668
752
  value.forEach((val) => {
669
753
  if (binaryTypes.includes(name)) {
670
- const parsed = parse(val);
754
+ const parsed = dataUrls.parse(val);
671
755
  if (parsed) {
672
756
  addtlData.fileName = "name" in parsed ? parsed.name : "unknown";
673
757
  if ("contentType" in parsed) {
@@ -690,7 +774,7 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
690
774
  try {
691
775
  jsonTypes.forEach((prop) => {
692
776
  try {
693
- set(cleanBody, prop, JSON.parse(get(cleanBody, prop)));
777
+ lodash.set(cleanBody, prop, JSON.parse(lodash.get(cleanBody, prop)));
694
778
  } catch (e) {
695
779
  }
696
780
  });
@@ -764,6 +848,7 @@ function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = {
764
848
  * @link https://github.com/swagger-api/swagger-js/blob/master/src/execute/oas3/style-serializer.js
765
849
  */
766
850
 
767
- export { oasToHar as default };
851
+ module.exports = oasToHar;
768
852
  //# sourceMappingURL=out.js.map
769
- //# sourceMappingURL=index.mjs.map
853
+
854
+ module.exports = exports.default//# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/lib/configure-security.ts","../src/lib/style-formatting/index.ts","../src/lib/style-formatting/style-serializer.ts","../src/lib/utils.ts"],"names":["lodashGet","isRef","value"],"mappings":";AAiBA,SAAS,SAAS,oBAAoB;AACtC,SAAS,cAAc,eAAe,eAAe;AACrD,SAAS,OAAOA,YAAW,OAAO,iBAAiB;AACnD,SAAS,WAAW,aAAa;AACjC,SAAS,SAAAC,cAAa;AACtB,OAAO,4BAA4B;;;ACpBnC,SAAS,aAAa;AAItB,SAAS,SAAS,MAA6C,OAAwC;AACrG,MAAI,CAAC,MAAM;AAAO,WAAO;AACzB,SAAO,EAAE,MAAM,MAAM;AACvB;AAEe,SAAR,kBAAmC,eAA4B,QAAoB,QAAgB;AACxG,MAAI,CAAC;AAAQ,WAAO;AAEpB,MAAI,OAAO,KAAK,UAAU,CAAC,CAAC,EAAE,WAAW;AAAG,WAAO;AAEnD,MAAI,CAAC,cAAc,WAAW,gBAAgB,MAAM;AAAG,WAAO;AAC9D,QAAM,WAAW,cAAc,WAAW,gBAAgB,MAAM;AAIhE,MAAI,MAAM,QAAQ,GAAG;AACnB,WAAO;AAAA,EACT,WAAW,CAAC,OAAO,MAAM,GAAG;AAE1B,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,SAAS,QAAQ;AAC5B,QAAI,SAAS,WAAW,SAAS;AAC/B,YAAM,OAAO,OAAO,MAAM;AAC1B,UAAI,OAAO,SAAS;AAAU,eAAO;AACrC,UAAI,CAAC,KAAK,QAAQ,CAAC,KAAK;AAAM,eAAO;AAErC,UAAI,OAAO,KAAK,QAAQ;AACxB,UAAI,SAAS,QAAQ,KAAK,WAAW,GAAG;AACtC,eAAO;AAAA,MACT;AAEA,UAAI,OAAO,KAAK,QAAQ;AACxB,UAAI,SAAS,QAAQ,KAAK,WAAW,GAAG;AACtC,eAAO;AAAA,MACT;AAEA,a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eAAe,MAAM,QAAQ;AACrE,YAAI,CAAC,eAAe;AAClB;AAAA,QACF;AAIA,YAAI,cAAc,MAAM,SAAS,iBAAiB;AAChD,cAAI,IAAI,cAAc,IAAI,EAAE,KAAK,OAAK,EAAE,SAAS,cAAc,MAAM,IAAI,GAAG;AAC1E;AAAA,UACF;AAAA,QACF;AAGA,YACE,IAAI,cAAc,IAAI,EAAE;AAAA,UACtB,OAAK,EAAE,SAAS,cAAc,MAAM,QAAQ,EAAE,UAAU,cAAc,MAAM;AAAA,QAC9E,GACA;AACA;AAAA,QACF;AAEA,YAAI,cAAc,IAAI,EAAE,KAAK,cAAc,KAAK;AAAA,MAClD,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAGA,MAAI,OAAO,KAAK,IAAI,QAAQ,EAAE,WAAW,GAAG;AAC1C,WAAO,IAAI;AAAA,EACb;AAEA,SAAO;AAAA,IACL,KAAK;AAAA,MACH,SAAS;AAAA,QACP;AAAA,UACE,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["import type { AuthForHAR } from './lib/configure-security';\nimport type { Extensions } from '@readme/oas-extensions';\nimport type { PostDataParams, Request } from 'har-format';\nimport type Oas from 'oas';\nimport type { SchemaWrapper } from 'oas/operation/get-parameters-as-json-schema';\nimport type {\n HttpMethods,\n JSONSchema,\n MediaTypeObject,\n OASDocument,\n OperationObject,\n ParameterObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n} from 'oas/rmoas.types';\n\nimport { parse as parseDataUrl } from '@readme/data-urls';\nimport { getExtension, PROXY_ENABLED, HEADERS } from '@readme/oas-extensions';\nimport { get as lodashGet, set as lodashSet } from 'lodash'; // eslint-disable-line no-restricted-imports\nimport { Operation, utils } from 'oas';\nimport { isRef } from 'oas/rmoas.types';\nimport removeUndefinedObjects from 'remove-undefined-objects';\n\nimport configureSecurity from './lib/configure-security';\nimport formatStyle from './lib/style-formatting';\nimport { getSafeRequestBody, getTypedFormatsInSchema, hasSchemaType } from './lib/utils';\n\nconst { jsonSchemaTypes, matchesMimeType } = utils;\n\nexport type { AuthForHAR } from './lib/configure-security';\nexport interface DataForHAR {\n body?: any;\n cookie?: Record<string, any>;\n formData?: Record<string, any>; // `application/x-www-form-urlencoded` requests payloads.\n header?: Record<string, any>;\n path?: Record<string, any>;\n query?: Record<string, any>;\n server?: {\n selected: number;\n variables?: Record<string, unknown>;\n };\n}\n\nfunction formatter(\n values: DataForHAR,\n param: ParameterObject,\n type: 'body' | 'cookie' | 'header' | 'path' | 'query',\n onlyIfExists = false,\n) {\n if (param.style) {\n const value = values[type][param.name];\n // Note: Technically we could send everything through the format style and choose the proper\n // default for each `in` type (e.g. query defaults to form).\n return formatStyle(value, param);\n }\n\n let value;\n\n // Handle missing values\n if (typeof values[type][param.name] !== 'undefined') {\n value = values[type][param.name];\n } else if (onlyIfExists && !param.required) {\n value = undefined;\n } else if (param.required && param.schema && !isRef(param.schema) && param.schema.default) {\n value = param.schema.default;\n } else if (type === 'path') {\n // If we don't have any values for the path parameter, just use the name of the parameter as the\n // value so we don't try try to build a URL to something like `https://example.com/undefined`.\n return param.name;\n }\n\n // Handle file uploads. Specifically arrays of file uploads which need to be formatted very\n // specifically.\n if (\n param.schema &&\n !isRef(param.schema) &&\n param.schema.type === 'array' &&\n param.schema.items &&\n !isRef(param.schema.items) &&\n param.schema.items.format === 'binary'\n ) {\n if (Array.isArray(value)) {\n // If this is array of binary data then we shouldn't do anything because we'll prepare them\n // separately in the HAR in order to preserve `fileName` and `contentType` data within\n // `postData.params`. If we don't then the HAR we generate for this data will be invalid.\n return value;\n }\n\n return JSON.stringify(value);\n }\n\n if (value !== undefined) {\n // Query params should always be formatted, even if they don't have a `style` serialization\n // configured.\n if (type === 'query') {\n return formatStyle(value, param);\n }\n\n return value;\n }\n\n return undefined;\n}\n\nfunction multipartBodyToFormatterParams(payload: unknown, oasMediaTypeObject: MediaTypeObject, schema: SchemaObject) {\n const encoding = oasMediaTypeObject.encoding;\n\n if (typeof payload === 'object' && payload !== null) {\n return Object.keys(payload)\n .map(key => {\n // If we have an incoming parameter, but it's not in the schema ignore it.\n if (!schema.properties[key]) {\n return false;\n }\n\n const paramEncoding = encoding ? encoding[key] : undefined;\n\n return {\n name: key,\n // If the style isn't defined, use the default\n style: paramEncoding ? paramEncoding.style : undefined,\n // If explode isn't defined, use the default\n explode: paramEncoding ? paramEncoding.explode : undefined,\n required:\n (schema.required && typeof schema.required === 'boolean' && Boolean(schema.required)) ||\n (Array.isArray(schema.required) && schema.required.includes(key)),\n schema: schema.properties[key],\n in: 'body',\n };\n })\n .filter(Boolean) as ParameterObject[];\n }\n\n // Pretty sure that we'll never have anything but an object for multipart bodies, so returning\n // empty array if we get anything else.\n return [];\n}\n\nconst defaultFormDataTypes = Object.keys(jsonSchemaTypes).reduce((prev, curr) => {\n return Object.assign(prev, { [curr]: {} });\n}, {});\n\nfunction getResponseContentType(content: MediaTypeObject) {\n const types = Object.keys(content) || [];\n\n // If this response content has multiple types available we should always prefer the one that's\n // JSON-compatible. If they don't have one that is we'll return the first available, otherwise\n // if they don't have **any** repsonse content types present we'll assume it's JSON.\n if (types && types.length) {\n const jsonType = types.find(t => matchesMimeType.json(t));\n if (jsonType) {\n return jsonType;\n }\n\n return types[0];\n }\n\n return 'application/json';\n}\n\nfunction isPrimitive(val: unknown) {\n return typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean';\n}\n\nfunction stringify(json: Record<string | 'RAW_BODY', unknown>) {\n return JSON.stringify(removeUndefinedObjects(typeof json.RAW_BODY !== 'undefined' ? json.RAW_BODY : json));\n}\n\nfunction stringifyParameter(param: any): string {\n if (param === null || isPrimitive(param)) {\n return param;\n } else if (Array.isArray(param) && param.every(isPrimitive)) {\n return String(param);\n }\n\n return JSON.stringify(param);\n}\n\nfunction appendHarValue(\n harParam: Request['cookies'] | Request['headers'] | Request['queryString'] | PostDataParams['params'],\n name: string,\n value: any,\n addtlData: {\n contentType?: string;\n fileName?: string;\n } = {},\n) {\n if (typeof value === 'undefined') return;\n\n if (Array.isArray(value)) {\n // If the formatter gives us an array, we're expected to add each array value as a new\n // parameter item with the same parameter name\n value.forEach(singleValue => {\n appendHarValue(harParam, name, singleValue);\n });\n } else if (typeof value === 'object' && value !== null) {\n // If the formatter gives us an object, we're expected to add each property value as a new\n // parameter item, each with the name of the property\n Object.keys(value).forEach(key => {\n appendHarValue(harParam, key, value[key]);\n });\n } else {\n // If the formatter gives us a non-array, non-object, we add it as is\n harParam.push({\n ...addtlData,\n name,\n value: String(value),\n });\n }\n}\n\nfunction encodeBodyForHAR(body: any) {\n if (isPrimitive(body)) {\n return body;\n } else if (\n typeof body === 'object' &&\n body !== null &&\n !Array.isArray(body) &&\n typeof body.RAW_BODY !== 'undefined'\n ) {\n // `RAW_BODY` is a ReadMe-specific thing where we'll interpret the entire payload as a\n // raw string. https://docs.readme.com/docs/raw-body-content\n if (isPrimitive(body.RAW_BODY)) {\n return body.RAW_BODY;\n }\n\n return stringify(body.RAW_BODY);\n }\n\n return stringify(body);\n}\n\nexport interface oasToHarOptions {\n // If true, the operation URL will be rewritten and prefixed with https://try.readme.io/ in\n // order to funnel requests through our CORS-friendly proxy.\n proxyUrl: boolean;\n}\n\nexport default function oasToHar(\n oas: Oas,\n operationSchema?: Operation,\n values: DataForHAR = {},\n auth: AuthForHAR = {},\n opts: oasToHarOptions = {\n // If true, the operation URL will be rewritten and prefixed with https://try.readme.io/ in\n // order to funnel requests through our CORS-friendly proxy.\n proxyUrl: false,\n },\n) {\n let operation: Operation;\n if (!operationSchema || typeof operationSchema.getParameters !== 'function') {\n /**\n * If `operationSchema` was supplied as a plain object instead of an instance of `Operation`\n * then we should create a new instance of it. We're doing it with a check on `getParameters`\n * instead of checking `instanceof Operation` because JS is very weird when it comes to\n * checking `instanceof` against classes. One instance of `Operation` may not always match up\n * with another if they're being loaded between two different libraries.\n *\n * It's weird. This is easier.\n */\n operation = new Operation(\n oas as unknown as OASDocument,\n operationSchema?.path || '',\n operationSchema?.method || ('' as HttpMethods),\n (operationSchema as unknown as OperationObject) || { path: '', method: '' },\n );\n } else {\n operation = operationSchema;\n }\n\n const apiDefinition = oas.getDefinition();\n\n const formData: DataForHAR = {\n ...defaultFormDataTypes,\n server: {\n selected: 0,\n variables: oas.defaultVariables(0),\n },\n ...values,\n };\n\n // If the incoming `server.variables` is missing variables let's pad it out with defaults.\n formData.server.variables = {\n ...oas.defaultVariables(formData.server.selected),\n ...(formData.server.variables ? formData.server.variables : {}),\n };\n\n const har: Request = {\n cookies: [],\n headers: [],\n headersSize: 0,\n queryString: [],\n // @ts-expect-error This is fine because we're fleshing `postData` out further down.\n postData: {},\n bodySize: 0,\n method: operation.method.toUpperCase(),\n url: `${oas.url(formData.server.selected, formData.server.variables)}${operation.path}`.replace(/\\s/g, '%20'),\n httpVersion: 'HTTP/1.1',\n };\n\n if (opts.proxyUrl) {\n if (getExtension(PROXY_ENABLED, oas, operation)) {\n har.url = `https://try.readme.io/${har.url}`;\n }\n }\n\n const parameters = operation.getParameters();\n\n har.url = har.url.replace(/{([-_a-zA-Z0-9[\\]]+)}/g, (full, key) => {\n if (!operation || !parameters) return key; // No path params at all\n\n // Find the path parameter or set a default value if it does not exist\n const parameter = parameters.find(param => param.name === key) || ({ name: key } as ParameterObject);\n\n // The library that handles our style processing already encodes uri elements. For everything\n // else we need to handle it here.\n if (!('style' in parameter) || !parameter.style) {\n return encodeURIComponent(formatter(formData, parameter, 'path'));\n }\n\n return formatter(formData, parameter, 'path');\n });\n\n const queryStrings = parameters && parameters.filter(param => param.in === 'query');\n if (queryStrings && queryStrings.length) {\n queryStrings.forEach(queryString => {\n const value = formatter(formData, queryString, 'query', true);\n appendHarValue(har.queryString, queryString.name, value);\n });\n }\n\n // Do we have any `cookie` parameters on the operation?\n const cookies = parameters && parameters.filter(param => param.in === 'cookie');\n if (cookies && cookies.length) {\n cookies.forEach(cookie => {\n const value = formatter(formData, cookie, 'cookie', true);\n appendHarValue(har.cookies, cookie.name, value);\n });\n }\n\n // Does this response have any documented content types?\n if (operation.schema.responses) {\n Object.keys(operation.schema.responses).some(response => {\n if (isRef(operation.schema.responses[response])) return false;\n\n const content = (operation.schema.responses[response] as ResponseObject).content;\n if (!content) return false;\n\n // If there's no `accept` header present we should add one so their eventual code snippet\n // follows best practices.\n if (Object.keys(formData.header).find(h => h.toLowerCase() === 'accept')) return true;\n\n har.headers.push({\n name: 'accept',\n value: getResponseContentType(content),\n });\n\n return true;\n });\n }\n\n // Do we have any `header` parameters on the operation?\n let hasContentType = false;\n let contentType = operation.getContentType();\n const headers = parameters && parameters.filter(param => param.in === 'header');\n if (headers && headers.length) {\n headers.forEach(header => {\n const value = formatter(formData, header, 'header', true);\n if (typeof value === 'undefined') return;\n\n if (header.name.toLowerCase() === 'content-type') {\n hasContentType = true;\n contentType = String(value);\n }\n\n appendHarValue(har.headers, header.name, value);\n });\n }\n\n // Are there `x-headers` static headers configured for this OAS?\n const userDefinedHeaders = getExtension(HEADERS, oas, operation) as Extensions['headers'];\n if (userDefinedHeaders) {\n userDefinedHeaders.forEach(header => {\n if (typeof header.key === 'string' && header.key.toLowerCase() === 'content-type') {\n hasContentType = true;\n contentType = String(header.value);\n }\n\n har.headers.push({\n name: String(header.key),\n value: String(header.value),\n });\n });\n }\n\n if (formData.header) {\n // Do we have an `accept` header set up in the form data, but it hasn't been added yet?\n const acceptHeader = Object.keys(formData.header).find(h => h.toLowerCase() === 'accept');\n if (acceptHeader && !har.headers.find(hdr => hdr.name.toLowerCase() === 'accept')) {\n har.headers.push({\n name: 'accept',\n value: String(formData.header[acceptHeader]),\n });\n }\n\n // Do we have a manually-defined `authorization` header set up in the form data?\n const authorizationHeader = Object.keys(formData.header).find(h => h.toLowerCase() === 'authorization');\n if (authorizationHeader && !har.headers.find(hdr => hdr.name.toLowerCase() === 'authorization')) {\n har.headers.push({\n name: 'authorization',\n value: String(formData.header[authorizationHeader]),\n });\n }\n }\n\n let requestBody: SchemaWrapper;\n if (operation.hasRequestBody()) {\n requestBody = operation.getParametersAsJSONSchema().find(payload => {\n // `formData` is used in our API Explorer for `application/x-www-form-urlencoded` endpoints\n // and if you have an operation with that, it will only ever have a `formData`. `body` is\n // used for all other payload shapes.\n return payload.type === (operation.isFormUrlEncoded() ? 'formData' : 'body');\n });\n }\n\n if (requestBody && requestBody.schema && Object.keys(requestBody.schema).length) {\n const requestBodySchema = requestBody.schema as SchemaObject;\n\n if (operation.isFormUrlEncoded()) {\n if (Object.keys(formData.formData).length) {\n const cleanFormData = removeUndefinedObjects(JSON.parse(JSON.stringify(formData.formData)));\n if (cleanFormData !== undefined) {\n har.postData.params = [];\n har.postData.mimeType = 'application/x-www-form-urlencoded';\n\n Object.keys(cleanFormData).forEach(name => {\n har.postData.params.push({\n name,\n value: stringifyParameter(cleanFormData[name]),\n });\n });\n }\n }\n } else if (\n 'body' in formData &&\n formData.body !== undefined &&\n (isPrimitive(formData.body) || Object.keys(formData.body).length)\n ) {\n const isMultipart = operation.isMultipart();\n const isJSON = operation.isJson();\n\n if (isMultipart || isJSON) {\n try {\n let cleanBody = removeUndefinedObjects(JSON.parse(JSON.stringify(formData.body)));\n\n if (isMultipart) {\n har.postData.mimeType = 'multipart/form-data';\n har.postData.params = [];\n\n // Because some request body schema shapes might not always be a top-level `properties`,\n // instead nesting it in an `oneOf` or `anyOf` we need to extract the first usable\n // schema that we have in order to process this multipart payload.\n const safeBodySchema = getSafeRequestBody(requestBodySchema);\n\n /**\n * Discover all `{ type: string, format: binary }` properties, or arrays containing the\n * same, within the request body. If there are any, then that means that we're dealing\n * with a `multipart/form-data` request and need to treat the payload as\n * `postData.params` and supply filenames and content types for the files (if they're\n * available).\n *\n * @todo It'd be nice to replace this with `getTypedFormatsInSchema` instead.\n * @example `{ type: string, format: binary }`\n * @example `{ type: array, items: { type: string, format: binary } }`\n */\n const binaryTypes = Object.keys(safeBodySchema.properties).filter(key => {\n const propData = safeBodySchema.properties[key] as JSONSchema;\n if (propData.format === 'binary') {\n return true;\n } else if (\n propData.type === 'array' &&\n propData.items &&\n typeof propData.items === 'object' &&\n propData.items !== null &&\n (propData.items as JSONSchema).format === 'binary'\n ) {\n return true;\n }\n\n return false;\n });\n\n if (cleanBody !== undefined) {\n const multipartParams = multipartBodyToFormatterParams(\n formData.body,\n (operation.schema.requestBody as RequestBodyObject).content['multipart/form-data'],\n safeBodySchema,\n );\n\n if (multipartParams.length) {\n Object.keys(cleanBody).forEach(name => {\n const param = multipartParams.find(multipartParam => multipartParam.name === name);\n\n // If we're dealing with a binary type, and the value is a valid data URL we should\n // parse out any available filename and content type to send along with the\n // parameter to interpreters like `fetch-har` can make sense of it and send a usable\n // payload.\n const addtlData: { contentType?: string; fileName?: string } = {};\n\n let value = formatter(formData, param, 'body', true);\n if (!Array.isArray(value)) {\n value = [value];\n }\n\n value.forEach((val: string) => {\n if (binaryTypes.includes(name)) {\n const parsed = parseDataUrl(val);\n if (parsed) {\n addtlData.fileName = 'name' in parsed ? parsed.name : 'unknown';\n if ('contentType' in parsed) {\n addtlData.contentType = parsed.contentType;\n }\n }\n }\n\n appendHarValue(har.postData.params, name, val, addtlData);\n });\n });\n }\n }\n } else {\n har.postData.mimeType = contentType;\n\n if (\n hasSchemaType(requestBody.schema, 'string') ||\n hasSchemaType(requestBody.schema, 'integer') ||\n hasSchemaType(requestBody.schema, 'number') ||\n hasSchemaType(requestBody.schema, 'boolean')\n ) {\n har.postData.text = JSON.stringify(JSON.parse(cleanBody));\n } else {\n /**\n * Handle formatted JSON objects that have properties that accept arbitrary JSON.\n *\n * Find all `{ type: string, format: json }` properties in the schema because we need\n * to manually `JSON.parse` them before submit, otherwise they'll be escaped instead\n * of actual objects. We also only want values that the user has entered, so we drop\n * any `undefined` `cleanBody` keys.\n */\n const jsonTypes = getTypedFormatsInSchema('json', requestBodySchema.properties, { payload: cleanBody });\n\n if (Array.isArray(jsonTypes) && jsonTypes.length) {\n try {\n jsonTypes.forEach((prop: string) => {\n try {\n lodashSet(cleanBody, prop, JSON.parse(lodashGet(cleanBody, prop)));\n } catch (e) {\n // leave the prop as a string value\n }\n });\n\n // `RAW_BODY` is a ReadMe-specific thing where we'll interpret the entire payload\n // as a raw string. https://docs.readme.com/docs/raw-body-content\n if (typeof cleanBody.RAW_BODY !== 'undefined') {\n cleanBody = cleanBody.RAW_BODY;\n }\n\n har.postData.text = JSON.stringify(cleanBody);\n } catch (e) {\n har.postData.text = stringify(formData.body);\n }\n } else {\n har.postData.text = encodeBodyForHAR(formData.body);\n }\n }\n }\n } catch (e) {\n // If anything above fails for whatever reason, assume that whatever we had is invalid\n // JSON and just treat it as raw text.\n har.postData.text = stringify(formData.body);\n }\n } else {\n har.postData.mimeType = contentType;\n har.postData.text = encodeBodyForHAR(formData.body);\n }\n }\n }\n\n // Add a `content-type` header if there are any body values setup above or if there is a schema\n // defined, but only do so if we don't already have a `content-type` present as it's impossible\n // for a request to have multiple.\n if (\n (har.postData.text || (requestBody && requestBody.schema && Object.keys(requestBody.schema).length)) &&\n !hasContentType\n ) {\n har.headers.push({\n name: 'content-type',\n value: contentType,\n });\n }\n\n const securityRequirements = operation.getSecurity();\n\n if (securityRequirements && securityRequirements.length) {\n // TODO pass these values through the formatter?\n securityRequirements.forEach(schemes => {\n Object.keys(schemes).forEach(security => {\n const securityValue = configureSecurity(apiDefinition, auth, security);\n if (!securityValue) {\n return;\n }\n\n // If this is an `authorization` header and we've already added one (maybe one was manually\n // specified), then we shouldn't add another.\n if (securityValue.value.name === 'authorization') {\n if (har[securityValue.type].find(v => v.name === securityValue.value.name)) {\n return;\n }\n }\n\n // If we've already added this **specific** security value then don't add it again.\n if (\n har[securityValue.type].find(\n v => v.name === securityValue.value.name && v.value === securityValue.value.value,\n )\n ) {\n return;\n }\n\n har[securityValue.type].push(securityValue.value);\n });\n });\n }\n\n // If we didn't end up filling the `postData` object then we don't need it.\n if (Object.keys(har.postData).length === 0) {\n delete har.postData;\n }\n\n return {\n log: {\n entries: [\n {\n request: har,\n },\n ],\n },\n };\n}\n","import type { OASDocument, SecuritySchemeObject } from 'oas/rmoas.types';\n\nimport { isRef } from 'oas/rmoas.types';\n\nexport type AuthForHAR = Record<string, string | number | { pass?: string; user?: string }>;\n\nfunction harValue(type: 'cookies' | 'headers' | 'queryString', value: { name: string; value: string }) {\n if (!value.value) return undefined;\n return { type, value };\n}\n\nexport default function configureSecurity(apiDefinition: OASDocument, values: AuthForHAR, scheme: string) {\n if (!scheme) return undefined;\n\n if (Object.keys(values || {}).length === 0) return undefined;\n\n if (!apiDefinition.components.securitySchemes[scheme]) return undefined;\n const security = apiDefinition.components.securitySchemes[scheme] as SecuritySchemeObject & {\n 'x-bearer-format'?: string;\n };\n\n if (isRef(security)) {\n return undefined;\n } else if (!values[scheme]) {\n // If we don't have any data for this auth scheme then we shouldn't add it.\n return false;\n }\n\n if (security.type === 'http') {\n if (security.scheme === 'basic') {\n const auth = values[scheme];\n if (typeof auth !== 'object') return false;\n if (!auth.user && !auth.pass) return false;\n\n let user = auth.user ?? null;\n if (user === null || user.length === 0) {\n user = '';\n }\n\n let pass = auth.pass ?? null;\n if (pass === null || pass.length === 0) {\n pass = '';\n }\n\n return harValue('headers', {\n name: 'authorization',\n value: `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`,\n });\n } else if (security.scheme === 'bearer') {\n return harValue('headers', {\n name: 'authorization',\n value: `Bearer ${values[scheme]}`,\n });\n }\n }\n\n if (security.type === 'apiKey') {\n if (security.in === 'query') {\n return harValue('queryString', {\n name: security.name,\n value: String(values[scheme]),\n });\n } else if (security.in === 'header') {\n const header = {\n name: security.name,\n value: String(values[scheme]),\n };\n\n if (security['x-bearer-format']) {\n // Uppercase: token -> Token\n const bearerFormat = security['x-bearer-format'].charAt(0).toUpperCase() + security['x-bearer-format'].slice(1);\n header.name = security.name;\n header.value = `${bearerFormat} ${header.value}`;\n }\n\n return harValue('headers', header);\n } else if (security.in === 'cookie') {\n return harValue('cookies', {\n name: security.name,\n value: String(values[scheme]),\n });\n }\n }\n\n if (security.type === 'oauth2') {\n return harValue('headers', {\n name: 'authorization',\n value: `Bearer ${values[scheme]}`,\n });\n }\n\n return undefined;\n}\n","import type { StylizerConfig } from './style-serializer';\nimport type { ParameterObject, SchemaObject } from 'oas/rmoas.types';\n\nimport qs from 'qs';\n\nimport stylize from './style-serializer';\n\n// Certain styles don't support empty values.\nfunction shouldNotStyleEmptyValues(parameter: ParameterObject) {\n return ['simple', 'spaceDelimited', 'pipeDelimited', 'deepObject'].includes(parameter.style);\n}\n\nfunction shouldNotStyleReservedHeader(parameter: ParameterObject) {\n return ['accept', 'authorization', 'content-type'].includes(parameter.name.toLowerCase());\n}\n\n/**\n * Note: This isn't necessarily part of the spec. Behavior for the value 'undefined' is, well,\n * undefined. This code makes our system look better. If we wanted to be more accurate, we might\n * want to remove this, restore the un-fixed behavior for undefined and have our UI pass in empty\n * string instead of undefined.\n */\nfunction removeUndefinedForPath(value: any) {\n let finalValue = value;\n\n if (typeof finalValue === 'undefined') {\n return '';\n }\n\n if (Array.isArray(finalValue)) {\n finalValue = finalValue.filter(val => (val === undefined ? '' : val));\n\n if (finalValue.length === 0) {\n finalValue = '';\n }\n }\n\n if (typeof finalValue === 'object') {\n Object.keys(finalValue).forEach(key => {\n finalValue[key] = finalValue[key] === undefined ? '' : finalValue[key];\n });\n }\n\n return finalValue;\n}\n\nfunction stylizeValue(value: unknown, parameter: ParameterObject) {\n let finalValue = value;\n\n // Some styles don't work with empty values. We catch those there\n if (shouldNotStyleEmptyValues(parameter) && (typeof finalValue === 'undefined' || finalValue === '')) {\n // Paths need return an unstyled empty string instead of undefined so it's ignored in the final\n // path string.\n if (parameter.in === 'path') {\n return '';\n }\n\n // Everything but path should return undefined when unstyled so it's ignored in the final\n // parameter array.\n return undefined;\n }\n\n // Every style that adds their style to empty values should use emptystring for path parameters\n // instead of undefined to avoid the string `undefined`.\n if (parameter.in === 'path') {\n finalValue = removeUndefinedForPath(finalValue);\n }\n\n /**\n * Eventhough `accept`, `authorization`, and `content-type` headers can be defined as parameters,\n * they should be completely ignored when it comes to serialization.\n *\n * > If `in` is \"header\" and the `name` field is \"Accept\", \"Content-Type\" or \"Authorization\", the\n * > parameter definition SHALL be ignored.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#fixed-fields-10}\n */\n if (parameter.in === 'header' && shouldNotStyleReservedHeader(parameter)) {\n return value;\n }\n\n /**\n * All parameter types have a default `style` format so if they don't have one prescribed we\n * should still conform to what the spec defines.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#user-content-parameterstyle}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#user-content-parameterstyle}\n */\n let style = parameter.style;\n if (!style) {\n if (parameter.in === 'query') {\n style = 'form';\n } else if (parameter.in === 'path') {\n style = 'simple';\n } else if (parameter.in === 'header') {\n style = 'simple';\n } else if (parameter.in === 'cookie') {\n style = 'form';\n }\n }\n\n let explode = parameter.explode;\n if (explode === undefined && style === 'form') {\n /**\n * Per the spec if no `explode` is present but `style` is `form` then `explode` should default to `true`.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#user-content-parameterexplode}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#user-content-parameterexplode}\n */\n explode = true;\n }\n\n return stylize({\n location: parameter.in as StylizerConfig['location'],\n value: finalValue,\n key: parameter.name,\n style: style as StylizerConfig['style'],\n explode,\n /**\n * @todo this parameter is optional to stylize. It defaults to false, and can accept falsy, truthy, or \"unsafe\".\n * I do not know if it is correct for query to use this. See style-serializer for more info\n */\n escape: true,\n ...(parameter.in === 'query' ? { isAllowedReserved: parameter.allowReserved || false } : {}),\n });\n}\n\nfunction handleDeepObject(value: any, parameter: ParameterObject) {\n return qs\n .stringify(value, {\n // eslint-disable-next-line consistent-return\n encoder(str, defaultEncoder, charset, type) {\n if (type === 'key') {\n // `str` will be here as `dog[treats][0]` but because the `qs` library doesn't have any\n // awareness of our OpenAPI parameters we need to rewrite it to slap the `parameter.name`\n // to the top, like `pets[dog][treats][0]`.\n const prefixedKey = str\n .split(/[[\\]]/g)\n .filter(Boolean)\n .map((k: string) => `[${k}]`)\n .join('');\n\n return `${parameter.name}${prefixedKey}`;\n } else if (type === 'value') {\n return stylizeValue(str, parameter);\n }\n },\n })\n .split('&')\n .map(item => {\n const split = item.split('=');\n return {\n label: split[0],\n // `qs` will coerce null values into being `undefined` string but we want to preserve them.\n value: split[1] === 'undefined' ? null : split[1],\n };\n });\n}\n\n// Explode is handled on its own, because style-serializer doesn't return what we expect for proper\n// HAR output.\nfunction handleExplode(value: any, parameter: ParameterObject) {\n // This is to handle the case of arrays of objects in the querystring\n // which is something that's not technically in the spec but since we're\n // using the `qs` module already, it's fairly easy for us to add support\n // for this use case.\n //\n // An example URL would be something like this:\n // https://example.com/?line_items[0][a_string]=abc&line_items[0][quantity]=1&line_items[1][a_string]=def&line_items[1][quantity]=2\n //\n // Some open issues discussing this here:\n // https://github.com/OAI/OpenAPI-Specification/issues/1706\n // https://github.com/OAI/OpenAPI-Specification/issues/1006\n //\n // Link to the spec for this:\n // https://github.com/OAI/OpenAPI-Specification/blob/36a3a67264cc1c4f1eff110cea3ebfe679435108/versions/3.1.0.md#style-examples\n if (\n Array.isArray(value) &&\n (parameter.schema as SchemaObject)?.type === 'array' &&\n parameter.style === 'deepObject'\n ) {\n const newObj: Record<string, unknown> = {};\n const deepObjs = handleDeepObject(value, parameter);\n deepObjs.forEach(obj => {\n newObj[obj.label] = obj.value;\n });\n return newObj;\n }\n\n if (Array.isArray(value)) {\n return value.map(val => {\n return stylizeValue(val, parameter);\n });\n }\n\n if (typeof value === 'object' && value !== null) {\n const newObj: Record<string, unknown> = {};\n\n Object.keys(value).forEach(key => {\n if (parameter.style === 'deepObject') {\n const deepObjs = handleDeepObject(value, parameter);\n deepObjs.forEach(obj => {\n newObj[obj.label] = obj.value;\n });\n } else {\n newObj[key] = stylizeValue(value[key], parameter);\n }\n });\n\n return newObj;\n }\n\n return stylizeValue(value, parameter);\n}\n\nfunction shouldExplode(parameter: ParameterObject) {\n return (\n (parameter.explode ||\n (parameter.explode !== false && parameter.style === 'form') ||\n // style: deepObject && explode: false doesn't exist so explode it always\n // https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples\n parameter.style === 'deepObject') &&\n // header and path doesn't explode into separate parameters like query and cookie do\n parameter.in !== 'header' &&\n parameter.in !== 'path'\n );\n}\n\nexport default function formatStyle(value: unknown, parameter: ParameterObject) {\n // Deep object style only works on objects and arrays, and only works with explode=true.\n if (parameter.style === 'deepObject' && (!value || typeof value !== 'object' || parameter.explode === false)) {\n return undefined;\n }\n\n // This custom explode logic allows us to bubble up arrays and objects to be handled differently\n // by our HAR transformer. We need this because the `stylizeValue` function assumes we're building\n // strings, not richer data types.\n //\n // The first part of this conditional checks if `explode` is enabled. Explode is disabled for\n // everything by default except for forms.\n //\n // The second part of this conditional bypasses the custom explode logic for headers, because they\n // work differently, and `stylizeValue` is accurate.\n if (shouldExplode(parameter)) {\n return handleExplode(value, parameter);\n }\n\n return stylizeValue(value, parameter);\n}\n","/* eslint-disable @typescript-eslint/no-use-before-define */\n/* eslint-disable import/no-import-module-exports */\n/* eslint-disable no-param-reassign */\nimport type { Merge } from 'type-fest';\n\n/**\n * This file has been extracted and modified from `swagger-client`.\n *\n * @license Apache 2.0\n * @link https://npm.im/swagger-client\n * @link https://github.com/swagger-api/swagger-js/blob/master/src/execute/oas3/style-serializer.js\n */\n\nconst isRfc3986Reserved = (char: string) => \":/?#[]@!$&'()*+,;=\".indexOf(char) > -1;\nconst isRfc3986Unreserved = (char: string) => /^[a-z0-9\\-._~]+$/i.test(char);\n\nfunction isURIEncoded(value: string) {\n try {\n return decodeURIComponent(value) !== value;\n } catch (err) {\n // `decodeURIComponent` will throw an exception if a string that has an un-encoded percent sign\n // in it (like 20%), o if it's throwing we can just assume that the value hasn't been encoded.\n return false;\n }\n}\n\nfunction isObject(value: unknown) {\n return typeof value === 'object' && value !== null;\n}\n\nexport interface StylizerConfig {\n escape: boolean | 'unsafe';\n explode: boolean;\n isAllowedReserved?: boolean;\n key: string;\n location: 'body' | 'query';\n style: 'deepObject' | 'form' | 'label' | 'matrix' | 'pipeDelimited' | 'simple' | 'spaceDelimited';\n value: any;\n}\n\nexport default function stylize(config: StylizerConfig) {\n const { value } = config;\n\n if (Array.isArray(value)) {\n return encodeArray(config);\n }\n\n if (isObject(value)) {\n return encodeObject(config);\n }\n\n return encodePrimitive(config);\n}\n\nexport function encodeDisallowedCharacters(\n str: string,\n // eslint-disable-next-line @typescript-eslint/default-param-last\n {\n escape,\n returnIfEncoded = false,\n isAllowedReserved,\n }: {\n escape?: boolean | 'unsafe';\n isAllowedReserved?: boolean;\n returnIfEncoded?: boolean;\n } = {},\n parse: boolean,\n) {\n if (typeof str === 'number') {\n str = (str as number).toString();\n }\n\n if (returnIfEncoded) {\n if (isURIEncoded(str)) {\n return str;\n }\n }\n\n if (typeof str !== 'string' || !str.length) {\n return str;\n }\n\n if (!escape) {\n return str;\n }\n\n if (parse) {\n return JSON.parse(str);\n }\n\n // In ES6 you can do this quite easily by using the new ... spread operator. This causes the\n // string iterator (another new ES6 feature) to be used internally, and because that iterator is\n // designed to deal with code points rather than UCS-2/UTF-16 code units.\n return [...str]\n .map(char => {\n if (isRfc3986Unreserved(char)) {\n return char;\n }\n\n if (isRfc3986Reserved(char) && (escape === 'unsafe' || isAllowedReserved)) {\n return char;\n }\n\n const encoder = new TextEncoder();\n const encoded = Array.from(encoder.encode(char))\n .map(byte => `0${byte.toString(16).toUpperCase()}`.slice(-2))\n .map(encodedByte => `%${encodedByte}`)\n .join('');\n\n return encoded;\n })\n .join('');\n}\n\n/**\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples}\n */\nfunction encodeArray({\n location,\n key,\n value,\n style,\n explode,\n escape,\n isAllowedReserved = false,\n}: Merge<StylizerConfig, { value: string[] }>) {\n const valueEncoder = (str: string) =>\n module.exports.encodeDisallowedCharacters(str, {\n escape,\n returnIfEncoded: location === 'query',\n isAllowedReserved,\n });\n\n switch (style) {\n /**\n * @example <caption>`style: simple`</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `blue,black,brown`\n */\n case 'simple':\n return value.map(val => valueEncoder(val)).join(',');\n\n /**\n * @example <caption>`style: label`</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `.blue.black.brown`\n */\n case 'label':\n return `.${value.map(val => valueEncoder(val)).join('.')}`;\n\n /**\n * @example <caption>`style: matrix` + `explode: true`</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `;color=blue;color=black;color=brown`\n *\n * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `;color=blue,black,brown\t`\n */\n case 'matrix':\n return value\n .map(val => valueEncoder(val))\n .reduce((prev, curr) => {\n if (!prev || explode) {\n return `${prev || ''};${key}=${curr}`;\n }\n return `${prev},${curr}`;\n }, '');\n\n /**\n * @example <caption>`style: form` + `explode: true`</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `color=blue&color=black&color=brown`\n *\n * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `color=blue,black,brown`\n */\n case 'form':\n return value.map(val => valueEncoder(val)).join(explode ? `&${key}=` : ',');\n\n /**\n * @example <caption>`style: spaceDelimited`</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `blue%20black%20brown`\n */\n case 'spaceDelimited':\n return value.map(val => valueEncoder(val)).join(` ${explode ? `${key}=` : ''}`);\n\n /**\n * @example <caption>`style: pipeDelimited`</caption>\n * `[\"blue\",\"black\",\"brown\"]` → `blue|black|brown`\n */\n case 'pipeDelimited':\n return value.map(val => valueEncoder(val)).join(`|${explode ? `${key}=` : ''}`);\n\n default:\n return undefined;\n }\n}\n\n/**\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples}\n */\nfunction encodeObject({ location, key, value, style, explode, escape, isAllowedReserved = false }: StylizerConfig) {\n const valueEncoder = (str: string) =>\n module.exports.encodeDisallowedCharacters(str, {\n escape,\n returnIfEncoded: location === 'query',\n isAllowedReserved,\n });\n\n const valueKeys = Object.keys(value);\n\n switch (style) {\n /**\n * @example <caption>`style: simple` + `explode: true`</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `R=100,G=200,B=150`\n *\n * @example <caption>`style: simple` + `explode: false` (the default behavior)</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `R,100,G,200,B,150`\n */\n case 'simple':\n return valueKeys.reduce((prev, curr) => {\n const val = valueEncoder(value[curr]);\n const middleChar = explode ? '=' : ',';\n const prefix = prev ? `${prev},` : '';\n\n return `${prefix}${curr}${middleChar}${val}`;\n }, '');\n\n /**\n * @example <caption>`style: label` + `explode: true`</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `.R=100.G=200.B=150`\n *\n * @example <caption>`style: label` + `explode: false` (the default behavior)</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `.R.100.G.200.B.150`\n */\n case 'label':\n return valueKeys.reduce((prev, curr) => {\n const val = valueEncoder(value[curr]);\n const middleChar = explode ? '=' : '.';\n const prefix = prev ? `${prev}.` : '.';\n\n return `${prefix}${curr}${middleChar}${val}`;\n }, '');\n\n /**\n * @example <caption>`style: matrix` + `explode: true`</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `;R=100;G=200;B=150`\n *\n * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `;color=R,100,G,200,B,150`\n */\n case 'matrix':\n if (explode) {\n return valueKeys.reduce((prev, curr) => {\n const val = valueEncoder(value[curr]);\n const prefix = prev ? `${prev};` : ';';\n\n return `${prefix}${curr}=${val}`;\n }, '');\n }\n\n return valueKeys.reduce((prev, curr) => {\n const val = valueEncoder(value[curr]);\n const prefix = prev ? `${prev},` : `;${key}=`;\n\n return `${prefix}${curr},${val}`;\n }, '');\n\n /**\n * @example <caption>`style: form` + `explode: true`</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `R=100&G=200&B=150`\n *\n * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `color=R,100,G,200,B,150`\n */\n case 'form':\n return valueKeys.reduce((prev, curr) => {\n const val = valueEncoder(value[curr]);\n const prefix = prev ? `${prev}${explode ? '&' : ','}` : '';\n const separator = explode ? '=' : ',';\n\n return `${prefix}${curr}${separator}${val}`;\n }, '');\n\n /**\n * @example <caption>`style: spaceDelimited`</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `R%20100%20G%20200%20B%20150`\n */\n case 'spaceDelimited':\n return valueKeys.reduce((prev, curr) => {\n const val = valueEncoder(value[curr]);\n const prefix = prev ? `${prev} ` : '';\n\n return `${prefix}${curr} ${val}`;\n }, '');\n\n /**\n * @example <caption>`style: pipeDelimited`</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `R|100|G|200|B|150`\n */\n case 'pipeDelimited':\n return valueKeys.reduce((prev, curr) => {\n const val = valueEncoder(value[curr]);\n const prefix = prev ? `${prev}|` : '';\n\n return `${prefix}${curr}|${val}`;\n }, '');\n\n /**\n * @example <caption>`style: deepObject`</caption>\n * `{ \"R\": 100, \"G\": 200, \"B\": 150 }` → `color[R]=100&color[G]=200&color[B]=150`\n */\n case 'deepObject':\n return valueKeys.reduce(curr => {\n const val = valueEncoder(value[curr]);\n return `${val}`;\n }, '');\n\n default:\n return undefined;\n }\n}\n\n/**\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples}\n */\nfunction encodePrimitive({ location, key, value, style, escape, isAllowedReserved = false }: StylizerConfig) {\n const valueEncoder = (str: string) =>\n module.exports.encodeDisallowedCharacters(str, {\n escape,\n returnIfEncoded: location === 'query' || location === 'body',\n isAllowedReserved,\n });\n\n switch (style) {\n /**\n * @example <caption>`style: simple`</caption>\n * `blue` → `blue`\n */\n case 'simple':\n return valueEncoder(value);\n\n /**\n * @example <caption>`style: label`</caption>\n * `blue` → `.blue`\n */\n case 'label':\n return `.${valueEncoder(value)}`;\n\n /**\n * @example <caption>`style: matrix`</caption>\n * `blue` → `;color=blue`\n */\n case 'matrix':\n if (value === '') {\n return `;${key}`;\n }\n\n return `;${key}=${valueEncoder(value)}`;\n\n /**\n * @example <caption>`style: form`</caption>\n * `blue` → `color=blue`\n */\n case 'form':\n return valueEncoder(value);\n\n /**\n * @example <caption>`style: deepObject`</caption>\n * `blue` → n/a\n */\n case 'deepObject':\n return valueEncoder(value);\n\n default:\n return undefined;\n }\n}\n","import type { JSONSchema, SchemaObject } from 'oas/rmoas.types';\n\nimport { get as lodashGet } from 'lodash'; // eslint-disable-line no-restricted-imports\n\n/**\n * Determine if a schema `type` is, or contains, a specific discriminator.\n *\n */\nexport function hasSchemaType(\n schema: SchemaObject,\n discriminator: 'array' | 'object' | 'string' | 'number' | 'boolean' | 'integer' | 'null',\n) {\n if (Array.isArray(schema.type)) {\n return schema.type.includes(discriminator);\n }\n\n return schema.type === discriminator;\n}\n\n/**\n * Because some request body schema shapes might not always be a top-level `properties`, instead\n * nesting it in an `oneOf` or `anyOf` we need to extract the first usable schema that we have. If\n * we don't do this then these non-conventional request body schema payloads may not be properly\n * represented in the HAR that we generate.\n *\n */\nexport function getSafeRequestBody(obj: any) {\n if ('oneOf' in obj) {\n return getSafeRequestBody(obj.oneOf[0]);\n } else if ('anyOf' in obj) {\n return getSafeRequestBody(obj.anyOf[0]);\n }\n\n return obj;\n}\n\ninterface Options {\n parentIsArray?: boolean;\n parentKey?: string;\n payload: unknown;\n}\n\nfunction getSubschemas(schema: any, opts: Options) {\n let subSchemaDataSize = 0;\n if (opts.parentIsArray) {\n // If we don't have data for this parent schema in our body payload then we\n // shouldn't bother spidering further into the schema looking for more `format`s\n // for data that definitely doesn't exist.\n const parentData = lodashGet(opts.payload, opts.parentKey);\n if (parentData === undefined || !Array.isArray(parentData)) {\n return false;\n }\n\n subSchemaDataSize = parentData.length;\n }\n\n let subschemas: any[] = [];\n if (subSchemaDataSize > 0) {\n for (let idx = 0; idx < subSchemaDataSize; idx += 1) {\n subschemas = subschemas.concat(\n Object.entries(schema).map(([key, subschema]: [string, JSONSchema]) => ({\n key: opts.parentKey ? [opts.parentKey, idx, key].join('.') : key,\n schema: getSafeRequestBody(subschema),\n })),\n );\n }\n } else {\n subschemas = Object.entries(schema).map(([key, subschema]: [string, JSONSchema]) => ({\n key: opts.parentKey ? [opts.parentKey, key].join('.') : key,\n schema: getSafeRequestBody(subschema),\n }));\n }\n\n return subschemas;\n}\n\n/**\n * With a supplied JSON Schema object, spider through it for any schemas that may contain specific\n * kind of `format` that also happen to be within the current `requestBody` payload that we're\n * creating a HAR representation for.\n *\n */\nexport function getTypedFormatsInSchema(\n format: 'json' | 'binary',\n schema: any,\n opts: Options,\n): boolean | string | (string | boolean)[] {\n try {\n if (schema?.format === format) {\n if (opts.parentIsArray) {\n const parentData = lodashGet(opts.payload, opts.parentKey);\n if (parentData !== undefined && Array.isArray(parentData)) {\n return Object.keys(parentData)\n .map(pdk => {\n const currentKey = [opts.parentKey, pdk].join('.');\n if (lodashGet(opts.payload, currentKey) !== undefined) {\n return currentKey;\n }\n\n return false;\n })\n .filter(Boolean);\n }\n } else if (opts.parentKey && lodashGet(opts.payload, opts.parentKey) !== undefined) {\n return opts.parentKey;\n } else if (opts.payload !== undefined) {\n // If this payload is present and we're looking for a specific format then we should assume\n // that the **root** schema of the request body is that format, and we aren't trafficking in\n // a nested object or array schema.\n return true;\n }\n\n return false;\n }\n\n const subschemas = getSubschemas(schema, opts);\n if (!subschemas) {\n return false;\n }\n\n return subschemas\n .map(({ key, schema: subschema }) => {\n if ('properties' in subschema) {\n return getTypedFormatsInSchema(format, subschema.properties, { payload: opts.payload, parentKey: key });\n } else if ('items' in subschema) {\n if ((subschema.items as JSONSchema)?.properties) {\n return getTypedFormatsInSchema(format, (subschema.items as JSONSchema).properties, {\n payload: opts.payload,\n parentKey: key,\n parentIsArray: true,\n });\n }\n\n return getTypedFormatsInSchema(format, subschema.items, {\n payload: opts.payload,\n parentKey: key,\n parentIsArray: true,\n });\n }\n\n // If this schema has neither `properties` or `items` then it's a regular schema\n // we can re-run.\n return getTypedFormatsInSchema(format, subschema, { payload: opts.payload, parentKey: key });\n })\n .flat()\n .filter(Boolean);\n } catch (err) {\n // If this fails for whatever reason then we should act as if we didn't find any `format`'d\n // schemas.\n return [];\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AuthForHAR } from './lib/configure-security.mjs';
1
+ import { AuthForHAR } from './lib/configure-security.cjs';
2
2
  import { Request } from 'har-format';
3
3
  import Oas, { Operation } from 'oas';
4
4
  import 'oas/rmoas.types';