@redocly/cli 2.60.0 → 2.62.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.
Files changed (141) hide show
  1. package/THIRD_PARTY_NOTICES +24 -3
  2. package/lib/chunks/{AP2GA7RS.js → 22EANOP2.js} +87 -87
  3. package/lib/chunks/{B5GZ7KU2.js → 2EP764NP.js} +1 -1
  4. package/lib/chunks/2OVI7BIW.js +105 -0
  5. package/lib/chunks/{GYKYFMW3.js → 2XK7ML3U.js} +1 -1
  6. package/lib/chunks/{DAAOXDSB.js → 37WWN4MA.js} +1 -1
  7. package/lib/chunks/{IAN3UOJT.js → 3C6UUCEW.js} +1 -1
  8. package/lib/chunks/{S27TE7KZ.js → 3DEJQSYG.js} +1 -1
  9. package/lib/chunks/{SDNESV5E.js → 3JYY42DL.js} +1 -1
  10. package/lib/chunks/{SNR3DAVL.js → 4WO6ZSKT.js} +1 -1
  11. package/lib/chunks/53INGMTO.js +20 -0
  12. package/lib/chunks/5NOJ76EP.js +9 -0
  13. package/lib/chunks/{SXOXAG7R.js → 5PG3ST2N.js} +2 -2
  14. package/lib/chunks/{BHUCIWQF.js → 66GKT2TZ.js} +1 -1
  15. package/lib/chunks/{V46KUEYR.js → 6DO6IN4A.js} +1 -1
  16. package/lib/chunks/{2F2YM4RD.js → 6EGJEFXO.js} +1 -1
  17. package/lib/chunks/{MJYI42E6.js → 6NB3FKVN.js} +8 -8
  18. package/lib/chunks/{GHPOEF7A.js → 75SLMDAN.js} +1 -1
  19. package/lib/chunks/{CAJM6OL3.js → AB2EMYEK.js} +1 -1
  20. package/lib/chunks/{PKYNMOKV.js → AZO6SCNH.js} +1 -1
  21. package/lib/chunks/{LF35KJ5M.js → B2J7WNDG.js} +1 -1
  22. package/lib/chunks/C67OKMFJ.js +11 -0
  23. package/lib/chunks/{ZJAFKITR.js → DC2HDHGE.js} +1 -1
  24. package/lib/chunks/{XZKUPNLZ.js → DFWXX7E2.js} +1 -1
  25. package/lib/chunks/{HFGKPU2P.js → FDMXHRDK.js} +1 -1
  26. package/lib/chunks/{SL6UQOKE.js → G5N3UXMR.js} +1 -1
  27. package/lib/chunks/{HVO5F4MP.js → GVQMC2WB.js} +1 -1
  28. package/lib/chunks/{RDMFHSDB.js → HBENVUR4.js} +1 -1
  29. package/lib/chunks/HN2ZK7LZ.js +20 -0
  30. package/lib/chunks/I6AAWNTY.js +20 -0
  31. package/lib/chunks/{HSHAARAO.js → KPPPJNVL.js} +1 -1
  32. package/lib/chunks/{52MW7SRF.js → KRCCY64H.js} +1 -1
  33. package/lib/chunks/LNYTDBAU.js +12 -0
  34. package/lib/chunks/{4XDEFJCF.js → LRLGVYCG.js} +1 -1
  35. package/lib/chunks/{3MPID4OC.js → LVGVWPDB.js} +1 -1
  36. package/lib/chunks/{XHDOW23C.js → MNH2K4WM.js} +1 -1
  37. package/lib/chunks/{J4NCFMOR.js → N3GO4LRW.js} +1 -1
  38. package/lib/chunks/{GD6WKI2C.js → NBI4EQPC.js} +1 -1
  39. package/lib/chunks/{G4ZIYGF5.js → NENSYJQB.js} +1 -1
  40. package/lib/chunks/NFRA6IE2.js +7 -0
  41. package/lib/chunks/{O5WCU6SC.js → OMIM3KH6.js} +10 -10
  42. package/lib/chunks/{YNPWONFN.js → OP7NIAI7.js} +1 -1
  43. package/lib/chunks/{CKZ35ARL.js → OT7Y7FIM.js} +1 -1
  44. package/lib/chunks/{ACVFQG4D.js → PTNNX4IU.js} +1 -1
  45. package/lib/chunks/{UPHYYNN3.js → PXCT44HL.js} +5 -5
  46. package/lib/chunks/{HQUG6XPO.js → QAUXTHD6.js} +2 -2
  47. package/lib/chunks/{N4AA4DRD.js → R2TPTKNR.js} +1 -1
  48. package/lib/chunks/{UXSV2J6V.js → REIGI2Y7.js} +1 -1
  49. package/lib/chunks/{S5G22GL5.js → RGU6OZYB.js} +1 -1
  50. package/lib/chunks/{W3K4YAMS.js → RPHIT72T.js} +1 -1
  51. package/lib/chunks/{7C244K4X.js → RUIEI3YV.js} +1 -1
  52. package/lib/chunks/{NADFEIIN.js → S3STDXJN.js} +1 -1
  53. package/lib/chunks/{DJWI7SF7.js → S6NFOZ34.js} +1 -1
  54. package/lib/chunks/{VCV3FKMW.js → SLQPKXO2.js} +1 -1
  55. package/lib/chunks/{4WAQNM63.js → SS6PCAMM.js} +58 -12
  56. package/lib/chunks/{CEPC3LL4.js → SXBAAS4M.js} +1 -1
  57. package/lib/chunks/{7ED6ZTTH.js → SYWAPWW7.js} +1 -1
  58. package/lib/chunks/{S46ENZHC.js → T4Y6M5MJ.js} +1 -1
  59. package/lib/chunks/{O4RAFGZA.js → TBZEEKTV.js} +1 -1
  60. package/lib/chunks/{HNKSHJLU.js → TF4PPK4N.js} +1 -1
  61. package/lib/chunks/TWWNWQRB.js +7 -0
  62. package/lib/chunks/{EXCIOEBN.js → US7X4XPD.js} +1 -1
  63. package/lib/chunks/VGM6NIVC.js +8 -0
  64. package/lib/chunks/{QGUZ4KFX.js → VX2VONNO.js} +1 -1
  65. package/lib/chunks/{DTMC35L3.js → VXLODB3S.js} +1 -1
  66. package/lib/chunks/{4HEJ6GQB.js → WEOCCL26.js} +2 -2
  67. package/lib/chunks/{Q526MFO3.js → WQ3XMPU7.js} +1 -1
  68. package/lib/chunks/{2U6O26CV.js → XJE2OFDN.js} +116 -16
  69. package/lib/chunks/{WFIIXHF3.js → XJTGJYVS.js} +1 -1
  70. package/lib/chunks/YDVWNFMS.js +24 -0
  71. package/lib/chunks/{HZZP3BZQ.js → YPYZCXVX.js} +1 -1
  72. package/lib/chunks/{72ZX5WSN.js → ZYQDPQVA.js} +1 -1
  73. package/lib/eject-assets/AGENTS.md +24 -23
  74. package/lib/eject-assets/generators/cli/docs.ts +1 -1
  75. package/lib/eject-assets/generators/cli/engine-source.ts +1 -1
  76. package/lib/eject-assets/generators/cli/index.ts +2 -2
  77. package/lib/eject-assets/generators/cli/render.ts +1 -1
  78. package/lib/eject-assets/generators/go/client.ts +1 -1
  79. package/lib/eject-assets/generators/go/descriptor.ts +1 -1
  80. package/lib/eject-assets/generators/go/index.ts +2 -2
  81. package/lib/eject-assets/generators/go/models.ts +1 -1
  82. package/lib/eject-assets/generators/go/naming.ts +1 -1
  83. package/lib/eject-assets/generators/go/operations.ts +35 -3
  84. package/lib/eject-assets/generators/go/pagination.ts +1 -1
  85. package/lib/eject-assets/generators/go/types.ts +1 -1
  86. package/lib/eject-assets/generators/mock/faker.ts +1 -1
  87. package/lib/eject-assets/generators/mock/index.ts +2 -2
  88. package/lib/eject-assets/generators/mock/render.ts +1 -1
  89. package/lib/eject-assets/generators/mock/sample.ts +1 -1
  90. package/lib/eject-assets/generators/mock/values.ts +1 -1
  91. package/lib/eject-assets/generators/php/client.ts +1 -1
  92. package/lib/eject-assets/generators/php/descriptor.ts +1 -1
  93. package/lib/eject-assets/generators/php/index.ts +2 -2
  94. package/lib/eject-assets/generators/php/models.ts +1 -1
  95. package/lib/eject-assets/generators/php/naming.ts +1 -1
  96. package/lib/eject-assets/generators/php/operations.ts +21 -3
  97. package/lib/eject-assets/generators/php/pagination.ts +1 -1
  98. package/lib/eject-assets/generators/php/types.ts +1 -1
  99. package/lib/eject-assets/generators/python/client.ts +1 -1
  100. package/lib/eject-assets/generators/python/descriptor.ts +1 -1
  101. package/lib/eject-assets/generators/python/index.ts +2 -2
  102. package/lib/eject-assets/generators/python/models.ts +1 -1
  103. package/lib/eject-assets/generators/python/naming.ts +1 -1
  104. package/lib/eject-assets/generators/python/operations.ts +19 -6
  105. package/lib/eject-assets/generators/python/pagination.ts +1 -1
  106. package/lib/eject-assets/generators/python/types.ts +1 -1
  107. package/lib/eject-assets/generators/swr/index.ts +2 -2
  108. package/lib/eject-assets/generators/swr/render.ts +1 -1
  109. package/lib/eject-assets/generators/tanstack-query/index.ts +2 -2
  110. package/lib/eject-assets/generators/tanstack-query/render.ts +1 -1
  111. package/lib/eject-assets/generators/transformers/index.ts +2 -2
  112. package/lib/eject-assets/generators/transformers/render.ts +1 -1
  113. package/lib/eject-assets/generators/typescript/banner.ts +1 -1
  114. package/lib/eject-assets/generators/typescript/client.ts +1 -1
  115. package/lib/eject-assets/generators/typescript/descriptor.ts +1 -1
  116. package/lib/eject-assets/generators/typescript/index.ts +2 -2
  117. package/lib/eject-assets/generators/typescript/inline-runtime.ts +1 -1
  118. package/lib/eject-assets/generators/typescript/operation-signature.ts +1 -1
  119. package/lib/eject-assets/generators/typescript/operation-types.ts +1 -1
  120. package/lib/eject-assets/generators/typescript/operations.ts +3 -4
  121. package/lib/eject-assets/generators/typescript/response-headers.ts +1 -1
  122. package/lib/eject-assets/generators/typescript/type-guards.ts +1 -1
  123. package/lib/eject-assets/generators/typescript/types.ts +1 -1
  124. package/lib/eject-assets/generators/zod/index.ts +2 -2
  125. package/lib/eject-assets/generators/zod/schemas.ts +1 -1
  126. package/lib/eject-assets/skills/client-generators/SKILL.md +24 -23
  127. package/lib/eject-assets/skills/go-generator/SKILL.md +11 -0
  128. package/lib/eject-assets/skills/php-generator/SKILL.md +16 -0
  129. package/lib/eject-assets/skills/python-generator/SKILL.md +13 -0
  130. package/lib/eject-assets/skills/typescript-generator/SKILL.md +16 -0
  131. package/lib/index.js +55 -55
  132. package/package.json +1 -1
  133. package/lib/chunks/BZBFESBB.js +0 -11
  134. package/lib/chunks/DJXBNZCO.js +0 -7
  135. package/lib/chunks/GC26XZYZ.js +0 -20
  136. package/lib/chunks/IJ43XWPG.js +0 -20
  137. package/lib/chunks/MCJLOALK.js +0 -22
  138. package/lib/chunks/OKTLNLO3.js +0 -7
  139. package/lib/chunks/PGZIUA7J.js +0 -105
  140. package/lib/chunks/W7VT3BOM.js +0 -9
  141. package/lib/chunks/XQA4EEZA.js +0 -20
@@ -259,12 +259,14 @@ func retryDelay(retry RetryConfig, attempt int, retryAfter string) time.Duration
259
259
  }
260
260
 
261
261
  type requestSpec struct {
262
- OperationID string
263
- Method string
264
- URL string
265
- Headers map[string]string
266
- Query url.Values
267
- Body io.Reader
262
+ OperationID string
263
+ Method string
264
+ URL string
265
+ Headers map[string]string
266
+ Query url.Values
267
+ Body io.Reader
268
+ // Stream sends Body as is: no buffering, one attempt, the caller's Content-Type.
269
+ Stream bool
268
270
  ContentType string
269
271
  Timeout time.Duration
270
272
  Retry *RetryConfig
@@ -303,7 +305,7 @@ func send(ctx context.Context, config *Config, spec requestSpec) (*http.Response
303
305
  if httpClient == nil {
304
306
  httpClient = http.DefaultClient
305
307
  }
306
- if spec.Body != nil {
308
+ if spec.Body != nil && !spec.Stream {
307
309
  payload, err := io.ReadAll(spec.Body)
308
310
  if err != nil {
309
311
  return nil, err
@@ -319,6 +321,10 @@ func send(ctx context.Context, config *Config, spec requestSpec) (*http.Response
319
321
  fullURL += separator + spec.Query.Encode()
320
322
  }
321
323
  maxAttempts := 1 + retry.Retries
324
+ if spec.Stream {
325
+ // The first attempt consumes the reader, so there is nothing to replay.
326
+ maxAttempts = 1
327
+ }
322
328
  for attempt := 1; ; attempt++ {
323
329
  attemptCtx := ctx
324
330
  var cancel context.CancelFunc
@@ -326,7 +332,10 @@ func send(ctx context.Context, config *Config, spec requestSpec) (*http.Response
326
332
  attemptCtx, cancel = context.WithTimeout(ctx, timeout)
327
333
  }
328
334
  var bodyReader io.Reader
329
- if spec.bodyBytes != nil {
335
+ switch {
336
+ case spec.Stream:
337
+ bodyReader = spec.Body
338
+ case spec.bodyBytes != nil:
330
339
  bodyReader = bytes.NewReader(spec.bodyBytes)
331
340
  }
332
341
  req, err := http.NewRequestWithContext(attemptCtx, method, fullURL, bodyReader)
@@ -339,7 +348,7 @@ func send(ctx context.Context, config *Config, spec requestSpec) (*http.Response
339
348
  for key, value := range headers {
340
349
  req.Header.Set(key, value)
341
350
  }
342
- if spec.ContentType != "" && spec.bodyBytes != nil {
351
+ if spec.ContentType != "" && bodyReader != nil && req.Header.Get("Content-Type") == "" {
343
352
  req.Header.Set("Content-Type", spec.ContentType)
344
353
  }
345
354
  for _, mw := range config.Middleware {
@@ -863,6 +872,41 @@ func toMultipart(body any) (string, io.Reader, error) {
863
872
  }
864
873
  return writer.FormDataContentType(), buffer, nil
865
874
  }
875
+
876
+ // multipartBody prepares the body of an untyped multipart operation: an io.Reader is
877
+ // streamed and a []byte or string sent as is, all under the caller's Content-Type (the
878
+ // boundary is theirs to set); any other value goes through toMultipart.
879
+ func multipartBody(body any) (string, io.Reader, bool, error) {
880
+ if reader, stream, raw := rawBody(body); raw {
881
+ return "", reader, stream, nil
882
+ }
883
+ contentType, reader, err := toMultipart(body)
884
+ return contentType, reader, false, err
885
+ }
886
+
887
+ // binaryBody prepares the body of a binary operation: an io.Reader is streamed, a
888
+ // []byte or string sent as is, and any other value JSON-marshalled.
889
+ func binaryBody(body any) (io.Reader, bool, error) {
890
+ if reader, stream, raw := rawBody(body); raw {
891
+ return reader, stream, nil
892
+ }
893
+ payload, err := json.Marshal(body)
894
+ return bytes.NewReader(payload), false, err
895
+ }
896
+
897
+ // rawBody recognizes a body that needs no encoding: an io.Reader streams through in one
898
+ // attempt, a []byte or a string is replayable bytes.
899
+ func rawBody(body any) (io.Reader, bool, bool) {
900
+ switch typed := body.(type) {
901
+ case io.Reader:
902
+ return typed, true, true
903
+ case []byte:
904
+ return bytes.NewReader(typed), false, true
905
+ case string:
906
+ return strings.NewReader(typed), false, true
907
+ }
908
+ return nil, false, false
909
+ }
866
910
  `;var t=`<?php
867
911
 
868
912
  // @redocly/client-generator PHP runtime \u2014 embedded into generated clients.
@@ -1080,8 +1124,17 @@ function rawSend(Config $config, array $request): array
1080
1124
  return strlen($line);
1081
1125
  },
1082
1126
  ]);
1083
- if (($request['body'] ?? null) !== null) {
1084
- curl_setopt($handle, CURLOPT_POSTFIELDS, $request['body']);
1127
+ $body = $request['body'] ?? null;
1128
+ if (is_resource($body)) {
1129
+ curl_setopt_array($handle, [CURLOPT_UPLOAD => true, CURLOPT_INFILE => $body]);
1130
+ // php://input and wrappers without stream_stat report seekable but fstat() fails (with a
1131
+ // warning for the wrappers): those go chunked.
1132
+ $stat = @fstat($body);
1133
+ if (stream_get_meta_data($body)['seekable'] && $stat !== false) {
1134
+ curl_setopt($handle, CURLOPT_INFILESIZE, $stat['size'] - ftell($body));
1135
+ }
1136
+ } elseif ($body !== null) {
1137
+ curl_setopt($handle, CURLOPT_POSTFIELDS, $body);
1085
1138
  }
1086
1139
  if ($config->timeout !== null) {
1087
1140
  curl_setopt($handle, CURLOPT_TIMEOUT_MS, (int) round($config->timeout * 1000));
@@ -1120,7 +1173,8 @@ function send(Config $config, array $request): array
1120
1173
  {
1121
1174
  $headers = $request['headers'] ?? [];
1122
1175
  $headers['X-Redocly-Client'] = $config->clientHeader;
1123
- if (($request['contentType'] ?? null) !== null) {
1176
+ $callerContentType = in_array('content-type', array_map('strtolower', array_keys($headers)), true);
1177
+ if (($request['contentType'] ?? null) !== null && !$callerContentType) {
1124
1178
  $headers['Content-Type'] = $request['contentType'];
1125
1179
  }
1126
1180
  if (($request['idempotencyKey'] ?? null) !== null) {
@@ -1134,7 +1188,8 @@ function send(Config $config, array $request): array
1134
1188
  $handler = fn (array $req): array => $middleware($req, $next);
1135
1189
  }
1136
1190
 
1137
- $attempts = max(1, (int) ($config->retry['attempts'] ?? 3));
1191
+ // The first attempt consumes a stream resource, so there is nothing to replay.
1192
+ $attempts = is_resource($request['body'] ?? null) ? 1 : max(1, (int) ($config->retry['attempts'] ?? 3));
1138
1193
  $retryOn = $config->retry['retryOn'] ?? __NAMESPACE__ . '\\\\defaultRetryOn';
1139
1194
  $response = null;
1140
1195
  for ($attempt = 1; $attempt <= $attempts; $attempt++) {
@@ -1367,6 +1422,22 @@ function toMultipart(array $body): array
1367
1422
  $parts .= "--{$boundary}--\\r\\n";
1368
1423
  return ['multipart/form-data; boundary=' . $boundary, $parts];
1369
1424
  }
1425
+
1426
+ /**
1427
+ * The body of an untyped multipart operation: a stream resource or a string passes through
1428
+ * under the caller's Content-Type (the boundary is theirs to set); an array is encoded.
1429
+ * Returns \`[contentType, body]\`.
1430
+ */
1431
+ function multipartBody(mixed $body): array
1432
+ {
1433
+ return is_array($body) ? toMultipart($body) : [null, $body];
1434
+ }
1435
+
1436
+ /** The body of an octet-stream operation: a stream resource or a string passes through; anything else is JSON. */
1437
+ function binaryBody(mixed $body): mixed
1438
+ {
1439
+ return is_resource($body) || is_string($body) ? $body : json_encode($body);
1440
+ }
1370
1441
  `;var n={"_errors.py":`# Runtime errors and the result-mode envelope for generated Python clients.
1371
1442
  # Hand-authored once, embedded into every generated client (see
1372
1443
  # scripts/generate-runtime-sources.mjs) \u2014 mirror of the TypeScript runtime's
@@ -1706,6 +1777,7 @@ def send(
1706
1777
  params: Optional[Dict[str, Any]] = None,
1707
1778
  json_body: Any = None,
1708
1779
  content: Any = None,
1780
+ content_type: Optional[str] = None,
1709
1781
  data: Any = None,
1710
1782
  files: Any = None,
1711
1783
  timeout: Optional[float] = None,
@@ -1727,6 +1799,9 @@ def send(
1727
1799
  merged_headers["Idempotency-Key"] = (
1728
1800
  key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())
1729
1801
  )
1802
+ # The declared content type fills the gap; a caller-provided header always wins.
1803
+ if content_type is not None and not any(name.lower() == "content-type" for name in merged_headers):
1804
+ merged_headers["Content-Type"] = content_type
1730
1805
 
1731
1806
  context = {
1732
1807
  "url": url,
@@ -1741,7 +1816,9 @@ def send(
1741
1816
  if on_request:
1742
1817
  on_request(context)
1743
1818
 
1744
- max_attempts = 1 + int(merged_retry.get("retries", 0))
1819
+ # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.
1820
+ replayable = content is None or isinstance(content, (bytes, bytearray, str))
1821
+ max_attempts = 1 + int(merged_retry.get("retries", 0)) if replayable else 1
1745
1822
  retry_on = merged_retry.get("retry_on") or (
1746
1823
  lambda ctx: _default_retry_on(context["method"], context["headers"], ctx.get("response"))
1747
1824
  )
@@ -1800,6 +1877,7 @@ async def send_async(
1800
1877
  params: Optional[Dict[str, Any]] = None,
1801
1878
  json_body: Any = None,
1802
1879
  content: Any = None,
1880
+ content_type: Optional[str] = None,
1803
1881
  data: Any = None,
1804
1882
  files: Any = None,
1805
1883
  timeout: Optional[float] = None,
@@ -1819,6 +1897,8 @@ async def send_async(
1819
1897
  merged_headers["Idempotency-Key"] = (
1820
1898
  key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())
1821
1899
  )
1900
+ if content_type is not None and not any(name.lower() == "content-type" for name in merged_headers):
1901
+ merged_headers["Content-Type"] = content_type
1822
1902
  context = {
1823
1903
  "url": url,
1824
1904
  "method": method.upper(),
@@ -1831,7 +1911,9 @@ async def send_async(
1831
1911
  on_request = getattr(mw, "on_request", None) or (mw.get("on_request") if isinstance(mw, dict) else None)
1832
1912
  if on_request:
1833
1913
  on_request(context)
1834
- max_attempts = 1 + int(merged_retry.get("retries", 0))
1914
+ # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.
1915
+ replayable = content is None or isinstance(content, (bytes, bytearray, str))
1916
+ max_attempts = 1 + int(merged_retry.get("retries", 0)) if replayable else 1
1835
1917
  retry_on = merged_retry.get("retry_on") or (
1836
1918
  lambda ctx: _default_retry_on(context["method"], context["headers"], ctx.get("response"))
1837
1919
  )
@@ -2244,7 +2326,9 @@ async def aiter_sse(
2244
2326
  `,"_multipart.py":`# Multipart bodies for generated Python clients \u2014 a typed dict/dataclass body is
2245
2327
  # split into httpx's (data, files): bytes and file-like values upload as parts,
2246
2328
  # everything else is form data (nested values JSON-encoded, mirroring the
2247
- # TypeScript runtime's FormData serialization).
2329
+ # TypeScript runtime's FormData serialization). A body that is already bytes, a
2330
+ # \`str\`, a file-like object, or an (async) iterator of bytes passes through as httpx
2331
+ # \`content=\` untouched; the caller sets its Content-Type.
2248
2332
  from __future__ import annotations
2249
2333
 
2250
2334
  import json
@@ -2265,4 +2349,20 @@ def to_multipart(body: Any) -> Tuple[Dict[str, Any], Dict[str, Any]]:
2265
2349
  else:
2266
2350
  data[key] = value
2267
2351
  return data, files
2352
+
2353
+
2354
+ def is_stream_body(body: Any) -> bool:
2355
+ return (
2356
+ isinstance(body, (bytes, bytearray, str))
2357
+ or callable(getattr(body, "read", None))
2358
+ or hasattr(body, "__next__")
2359
+ or hasattr(body, "__aiter__")
2360
+ )
2361
+
2362
+
2363
+ def multipart_arguments(body: Any) -> Dict[str, Any]:
2364
+ if is_stream_body(body):
2365
+ return {"content": body}
2366
+ data, files = to_multipart(body)
2367
+ return {"data": data, "files": files}
2268
2368
  `};export{e as a,t as b,n as c};
@@ -4,6 +4,6 @@ import { dirname as __pathDirname } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  var __filename = __fileURLToPath(import.meta.url);
6
6
  var __dirname = __pathDirname(__filename);
7
- import{b as xe,f as Pe}from"./MJYI42E6.js";import{$ as fe,V as le,W as he,Z as b,aa as de,ba as j,c as L,da as ye,ea as U,f as ie,fa as A,ia as k,ja as Se,ka as ge,la as Q,ma as K,oa as Ce,q as ae,r as pe,ra as be,s as ce,v as me,w as ue}from"./AP2GA7RS.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{performance as mt}from"perf_hooks";var D={thresholds:{maxParamsGood:5,maxDepthGood:4,maxPolymorphismGood:2,maxDependencyDepthGood:3,maxAmbiguousGood:0,maxOperationsForDiscoverability:1e3},weights:{parameterSimplicity:.1,schemaSimplicity:.1,documentationQuality:.18,constraintClarity:.12,exampleCoverage:.18,errorClarity:.12,dependencyClarity:.1,identifierClarity:.05,polymorphismClarity:.05,anyOfPenaltyMultiplier:2,discoverabilityWeight:.1},hotspotLimit:10},Oe=new Set(["id","name","type","value","data","key","status","state","code","result","item","object","resource","entity","input","output","payload","body","content","info"]);function B(e){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),t=Math.floor(r.length/2);return r.length%2!==0?r[t]:(r[t-1]+r[t])/2}function He(e,r,t=D){let{thresholds:o,weights:n}=t,s=x(1-e.parameterCount/(o.maxParamsGood*2)),a=Math.max(e.maxRequestSchemaDepth,e.maxResponseSchemaDepth)/(o.maxDepthGood*2),c=De(e,n.anyOfPenaltyMultiplier)/(o.maxPolymorphismGood*3),h=x(1-a-c),u=(e.operationDescriptionPresent?1:0)+e.paramsWithDescription+e.schemaPropertiesWithDescription,f=1+e.parameterCount+e.totalSchemaProperties,$=f>0?x(u/f):1,O=e.totalSchemaProperties>0?x(e.constraintCount/e.totalSchemaProperties):1,y=(e.requestExamplePresent?1:0)+(e.responseExamplePresent?1:0),g=(e.requestBodyPresent?1:0)+1,M=x(y/g),T=e.totalErrorResponses>0?x(e.structuredErrorResponseCount/e.totalErrorResponses):1,I=x(1-r/(o.maxDependencyDepthGood*2)),l=x(1-e.ambiguousIdentifierCount/Math.max(o.maxAmbiguousGood+3,1)),m=De(e,n.anyOfPenaltyMultiplier),d=m===0?1:e.hasDiscriminator?x(1-m/(o.maxPolymorphismGood*4)):x(1-m/(o.maxPolymorphismGood*2));return{parameterSimplicity:s,schemaSimplicity:h,documentationQuality:$,constraintClarity:O,exampleCoverage:M,errorClarity:T,dependencyClarity:I,identifierClarity:l,polymorphismClarity:d}}function ze(e,r=D){let t=r.weights,o=e.parameterSimplicity*t.parameterSimplicity+e.schemaSimplicity*t.schemaSimplicity+e.documentationQuality*t.documentationQuality+e.constraintClarity*t.constraintClarity+e.exampleCoverage*t.exampleCoverage+e.errorClarity*t.errorClarity+e.dependencyClarity*t.dependencyClarity+e.identifierClarity*t.identifierClarity+e.polymorphismClarity*t.polymorphismClarity;return $e(x(o)*100)}function Re(e,r,t=D){let o=new Map;for(let[n,s]of e.operations){let i=r.get(n)??0,a=He(s,i,t);o.set(n,{agentReadiness:ze(a,t),subscores:a})}return o}function Me(e,r=D){return x(1-e/r.thresholds.maxOperationsForDiscoverability)}function ve(e,r,t=D){if(e.size===0)return{agentReadiness:100};let o=[];for(let i of e.values())o.push(i.agentReadiness);let n=t.weights.discoverabilityWeight,s=r*100;return{agentReadiness:$e(B(o)*(1-n)+s*n)}}function J(e,r,t){return e-r+r*t}function De(e,r){return J(e.polymorphismCount,e.anyOfCount,r)}function x(e){return Math.max(0,Math.min(1,e))}function Ee(e){let r=e.size||1,t={parameterSimplicity:0,schemaSimplicity:0,documentationQuality:0,constraintClarity:0,exampleCoverage:0,errorClarity:0,dependencyClarity:0,identifierClarity:0,polymorphismClarity:0};for(let o of e.values())t.parameterSimplicity+=o.subscores.parameterSimplicity,t.schemaSimplicity+=o.subscores.schemaSimplicity,t.documentationQuality+=o.subscores.documentationQuality,t.constraintClarity+=o.subscores.constraintClarity,t.exampleCoverage+=o.subscores.exampleCoverage,t.errorClarity+=o.subscores.errorClarity,t.dependencyClarity+=o.subscores.dependencyClarity,t.identifierClarity+=o.subscores.identifierClarity,t.polymorphismClarity+=o.subscores.polymorphismClarity;return t.parameterSimplicity/=r,t.schemaSimplicity/=r,t.documentationQuality/=r,t.constraintClarity/=r,t.exampleCoverage/=r,t.errorClarity/=r,t.dependencyClarity/=r,t.identifierClarity/=r,t.polymorphismClarity/=r,t}function $e(e){return Math.round(e*10)/10}function we(e,r,t){let o=Math.max(1,e);return r/o+t/o}function Qe(e,r){return r.totalSchemaProperties>e.totalSchemaProperties?!0:r.totalSchemaProperties<e.totalSchemaProperties?!1:we(r.totalSchemaProperties,r.schemaPropertiesWithDescription,r.constraintCount)>we(e.totalSchemaProperties,e.schemaPropertiesWithDescription,e.constraintCount)}var Ke=["enum","const","format","pattern","minimum","maximum","minLength","maxLength","minItems","maxItems","minProperties","maxProperties","multipleOf","exclusiveMinimum","exclusiveMaximum","uniqueItems"];function Y(){return{depth:-1,maxDepth:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,hasPropertyExamples:!1,writableTopLevelFields:0,refsUsed:[],debugEntries:null,pendingRef:null}}function Ie(e){Object.assign(e,Y())}function Le(e){return{ref:{enter(r){typeof r?.$ref=="string"&&(e.refsUsed.push(r.$ref),e.pendingRef=r.$ref)}},Schema:{enter(r,t){e.depth++,e.maxDepth=Math.max(e.maxDepth,e.depth);let o=0;for(let i of Ke)r[i]!==void 0&&(e.constraintCount++,o++);r.discriminator?.propertyName&&(e.hasDiscriminator=!0);let n={};for(let i of["oneOf","anyOf","allOf"]){let a=r[i];Array.isArray(a)&&(e.polymorphismCount+=a.length,i==="anyOf"&&(e.anyOfCount+=a.length),n[i]=a.length)}let s=[];if(L(r.properties)){let i=Object.entries(r.properties);e.totalSchemaProperties+=i.length;for(let[a,c]of i){s.push(a);let h=c&&"$ref"in c&&c.$ref?t.resolve(c)?.node??c:c;h?.description&&e.schemaPropertiesWithDescription++,(h?.example!==void 0||h?.examples)&&(e.hasPropertyExamples=!0),h?.readOnly||e.writableTopLevelFields++}}e.debugEntries!==null&&e.debugEntries.push({ref:e.pendingRef,depth:e.depth,propertyNames:s,polymorphism:Object.keys(n).length>0?n:{},constraintCount:o}),e.pendingRef=null},leave(){e.depth--}}}}function qe(e,r,t){return{operations:new Map,currentPath:"",pathLevelParams:[],current:null,walkSchema:e,anyOfPenaltyMultiplier:r,debugOperationId:t,debugLogs:[]}}function Je(e,r,t){return{path:e,method:r,operationId:t.operationId,operationDescriptionPresent:!!t.description,parameterCount:0,requiredParameterCount:0,paramsWithDescription:0,ambiguousIdentifierCount:0,maxRequestSchemaDepth:0,maxResponseSchemaDepth:0,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,topLevelWritableFieldCount:0,requestBodyPresent:!1,requestExamplePresent:!1,responseExamplePresent:!1,structuredErrorResponseCount:0,totalErrorResponses:0,inRequestBody:!1,inResponse:!1,currentResponseCode:"",errorStructuredCounted:!1,maxEffectivePolymorphism:-1,refsUsed:new Set}}function Ye(e){let{inRequestBody:r,inResponse:t,currentResponseCode:o,errorStructuredCounted:n,maxEffectivePolymorphism:s,...i}=e;return i}function We(e){return{RequestBody:{enter(){e.current&&(e.current.requestBodyPresent=!0,e.current.inRequestBody=!0)},leave(){e.current&&(e.current.inRequestBody=!1)}},Response:{enter(r,t){let o=e.current;if(!o)return;let n=String(t.key);o.inResponse=!0,o.currentResponseCode=n,o.errorStructuredCounted=!1,Te(n)&&(o.totalErrorResponses++,!r.content&&r.description&&(o.structuredErrorResponseCount++,o.errorStructuredCounted=!0))},leave(){e.current&&(e.current.inResponse=!1)}},MediaType:{enter(r){let t=e.current;if(t&&(Ze(r)&&(t.inRequestBody&&(t.requestExamplePresent=!0),t.inResponse&&(t.responseExamplePresent=!0)),t.inResponse&&Te(t.currentResponseCode)&&!t.errorStructuredCounted&&(t.structuredErrorResponseCount++,t.errorStructuredCounted=!0),r.schema)){let o=!!e.debugOperationId&&(t.operationId===e.debugOperationId||`${t.method.toUpperCase()} ${t.path}`===e.debugOperationId),n=e.walkSchema(r.schema,o);Qe(t,n)&&(t.totalSchemaProperties=n.totalSchemaProperties,t.schemaPropertiesWithDescription=n.schemaPropertiesWithDescription,t.constraintCount=n.constraintCount);let s=J(n.polymorphismCount,n.anyOfCount,e.anyOfPenaltyMultiplier);s>t.maxEffectivePolymorphism&&(t.maxEffectivePolymorphism=s,t.polymorphismCount=n.polymorphismCount,t.anyOfCount=n.anyOfCount),n.hasDiscriminator&&(t.hasDiscriminator=!0);for(let i of n.refsUsed)t.refsUsed.add(i);if(n.hasPropertyExamples&&(t.inRequestBody&&(t.requestExamplePresent=!0),t.inResponse&&(t.responseExamplePresent=!0)),t.inRequestBody&&(t.maxRequestSchemaDepth=Math.max(t.maxRequestSchemaDepth,n.maxDepth),t.topLevelWritableFieldCount=Math.max(t.topLevelWritableFieldCount,n.writableTopLevelFields)),t.inResponse&&(t.maxResponseSchemaDepth=Math.max(t.maxResponseSchemaDepth,n.maxDepth)),o&&n.debugEntries){let i=t.inRequestBody?"REQUEST BODY":`RESPONSE ${t.currentResponseCode}`;e.debugLogs.push({context:i,entries:n.debugEntries,totalProperties:n.totalSchemaProperties,totalPolymorphism:n.polymorphismCount,totalConstraints:n.constraintCount,maxDepth:n.maxDepth})}}}},Paths:{PathItem:{enter(r,t){e.currentPath=String(t.key),e.pathLevelParams=r.parameters??[]},Operation:{enter(r,t){let o=String(t.key),n=Je(e.currentPath,o,r);e.current=n;let s=Xe(e.pathLevelParams,r.parameters??[],t.resolve);for(let i of s.values())n.parameterCount++,i.required&&n.requiredParameterCount++,i.description&&n.paramsWithDescription++,et(i)&&n.ambiguousIdentifierCount++},leave(r){let t=e.current;if(!t)return;let o=r.operationId??`${t.method.toUpperCase()} ${t.path}`;e.operations.set(o,Ye(t)),e.current=null}}}}}}function Ue(e){return{operationCount:e.operations.size,operations:e.operations}}function Ae(e,r){return r(e).node}function Xe(e,r,t){let o=new Map;for(let n of e){let s=Ae(n,t);s?.name&&s.in&&o.set(`${s.in}:${s.name}`,s)}for(let n of r){let s=Ae(n,t);s?.name&&s.in&&o.set(`${s.in}:${s.name}`,s)}return o}function Ze(e){return e.example!==void 0||ie(e.examples)}function et(e){if(e.description)return!1;let r=(e.name??"").toLowerCase();return Oe.has(r)}function Te(e){if(e==="default"||/^4xx$/i.test(e)||/^5xx$/i.test(e))return!0;let r=parseInt(e,10);return r>=400&&r<600}function tt(e,r){if(!r.startsWith("#/"))return;let t=e;for(let o of r.slice(2).split("/"))t=t?.[ce(o)];return t}function ke({document:e,types:r,resolvedRefMap:t,ctx:o,debugOperationId:n,scoringConstants:s}){let i=s?.weights.anyOfPenaltyMultiplier??D.weights.anyOfPenaltyMultiplier,a=Y(),c=Le(a),h=Q([{severity:"warn",ruleId:"score-schema",visitor:c}],r),u=(l,m)=>{Ie(a),m&&(a.debugEntries=[]),K({document:{...e,parsed:l},rootType:r.Schema,normalizedVisitors:h,resolvedRefMap:t,ctx:o});let{depth:d,pendingRef:w,debugEntries:_,...N}=a;return{...N,refsUsed:[...a.refsUsed],debugEntries:m?a.debugEntries??void 0:void 0}},f=new Map,$=new WeakSet,O={maxDepth:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,hasPropertyExamples:!1,writableTopLevelFields:0,refsUsed:[]};function y(l,m){return{maxDepth:Math.max(l.maxDepth,m.maxDepth),polymorphismCount:l.polymorphismCount+m.polymorphismCount,anyOfCount:l.anyOfCount+m.anyOfCount,hasDiscriminator:l.hasDiscriminator||m.hasDiscriminator,totalSchemaProperties:l.totalSchemaProperties+m.totalSchemaProperties,schemaPropertiesWithDescription:l.schemaPropertiesWithDescription+m.schemaPropertiesWithDescription,constraintCount:l.constraintCount+m.constraintCount,hasPropertyExamples:l.hasPropertyExamples||m.hasPropertyExamples,writableTopLevelFields:l.writableTopLevelFields+m.writableTopLevelFields,refsUsed:[...l.refsUsed,...m.refsUsed],debugEntries:l.debugEntries||m.debugEntries?[...l.debugEntries??[],...m.debugEntries??[]]:void 0}}let g=(l,m=!1)=>{let d=l,w=pe(l)?l.$ref:void 0;if(w){if(!m){let S=f.get(w);if(S)return S}d=tt(e.parsed,w)??l}if(L(d)&&$.has(d))return{...O};L(d)&&$.add(d);let _=d?.oneOf,N=d?.anyOf,Z=Array.isArray(_)&&_.length>1,ee=Array.isArray(N)&&N.length>1,G=Z||ee,te=Array.isArray(d?.allOf)&&d.allOf.length>0,V=d?.discriminator,q=!G&&L(V?.mapping)?Object.values(V.mapping).filter(S=>typeof S=="string"&&me(S)).map(S=>({$ref:S})):null,re=Array.isArray(q)&&q.length>0,C;if(G||te||re){let S={...d},F=null,oe=P=>{F=F?y(F,P):P},ne=(P,v)=>{let E=g(v[0],m);for(let z=1;z<v.length;z++){let se=g(v[z],m);se.totalSchemaProperties>E.totalSchemaProperties&&(E=se)}return{...E,polymorphismCount:E.polymorphismCount+v.length,anyOfCount:E.anyOfCount+(P==="anyOf"?v.length:0),hasDiscriminator:E.hasDiscriminator||!!V}};G&&delete S.discriminator,Z&&(delete S.oneOf,oe(ne("oneOf",_))),ee&&(delete S.anyOf,oe(ne("anyOf",N)));let H=null;if(re){delete S.discriminator;let P=g(q[0],m);for(let v=1;v<q.length;v++){let E=g(q[v],m);E.totalSchemaProperties>P.totalSchemaProperties&&(P=E)}H={...P,polymorphismCount:P.polymorphismCount+q.length,hasDiscriminator:!0}}let W=null;if(te){delete S.allOf,W={...O};for(let P of d.allOf)W=y(W,g(P,m));W.polymorphismCount+=d.allOf.length}C=u(S,m),W&&(C=y(C,W)),F&&(C=y(C,F)),H&&(C=y(C,H)),w&&(C={...C,refsUsed:[w,...C.refsUsed]})}else C=u(l,m);return L(d)&&$.delete(d),w&&!m&&f.set(w,C),C},M=qe(g,i,n),T=We(M),I=Q([{severity:"warn",ruleId:"score",visitor:T}],r);return K({document:e,rootType:r.Root,normalizedVisitors:I,resolvedRefMap:t,ctx:o}),{metrics:Ue(M),debugLogs:M.debugLogs}}function Ne(e){let r=new Map;for(let[n,s]of e)for(let i of s.refsUsed){let a=r.get(i);a||(a=new Set,r.set(i,a)),a.add(n)}let t=new Map;for(let n of e.keys())t.set(n,new Set);for(let n of r.values()){if(n.size<2)continue;let s=Array.from(n);for(let i=0;i<s.length;i++)for(let a=i+1;a<s.length;a++)t.get(s[i]).add(s[a]),t.get(s[a]).add(s[i])}let o=new Map;for(let n of e.keys()){let s=rt(n,t);o.set(n,s)}return o}function rt(e,r){let t=new Set([e]),o=[e],n=0;for(;o.length>0;){let s=[];for(let i of o)for(let a of r.get(i)??[])t.has(a)||(t.add(a),s.push(a));s.length>0&&n++,o=s}return n}function Fe(e){let r={agentReadiness:e.agentReadiness,discoverability:Math.round(e.discoverability*100),subscores:e.subscores,rawMetrics:{operationCount:e.rawMetrics.operationCount,operations:Object.fromEntries(Array.from(e.rawMetrics.operations.entries()).map(([t,o])=>{let{refsUsed:n,...s}=o;return[t,s]}))},operationScores:Object.fromEntries(e.operationScores),dependencyDepths:Object.fromEntries(e.dependencyDepths),hotspots:e.hotspots};k.output(JSON.stringify(r,null,2))}function je(e,r=!1){ot(e),nt(e),it(e),r&&at(e),pt(e)}function _e(e){return e>=80?de:e>=50?j:fe}function Be(e){return _e(e)(b(e.toFixed(1)))}function p(e){k.output(e+`
7
+ import{b as xe,f as Pe}from"./6NB3FKVN.js";import{$ as fe,V as le,W as he,Z as b,aa as de,ba as j,c as L,da as ye,ea as U,f as ie,fa as A,ia as k,ja as Se,ka as ge,la as Q,ma as K,oa as Ce,q as ae,r as pe,ra as be,s as ce,v as me,w as ue}from"./22EANOP2.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{performance as mt}from"perf_hooks";var D={thresholds:{maxParamsGood:5,maxDepthGood:4,maxPolymorphismGood:2,maxDependencyDepthGood:3,maxAmbiguousGood:0,maxOperationsForDiscoverability:1e3},weights:{parameterSimplicity:.1,schemaSimplicity:.1,documentationQuality:.18,constraintClarity:.12,exampleCoverage:.18,errorClarity:.12,dependencyClarity:.1,identifierClarity:.05,polymorphismClarity:.05,anyOfPenaltyMultiplier:2,discoverabilityWeight:.1},hotspotLimit:10},Oe=new Set(["id","name","type","value","data","key","status","state","code","result","item","object","resource","entity","input","output","payload","body","content","info"]);function B(e){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),t=Math.floor(r.length/2);return r.length%2!==0?r[t]:(r[t-1]+r[t])/2}function He(e,r,t=D){let{thresholds:o,weights:n}=t,s=x(1-e.parameterCount/(o.maxParamsGood*2)),a=Math.max(e.maxRequestSchemaDepth,e.maxResponseSchemaDepth)/(o.maxDepthGood*2),c=De(e,n.anyOfPenaltyMultiplier)/(o.maxPolymorphismGood*3),h=x(1-a-c),u=(e.operationDescriptionPresent?1:0)+e.paramsWithDescription+e.schemaPropertiesWithDescription,f=1+e.parameterCount+e.totalSchemaProperties,$=f>0?x(u/f):1,O=e.totalSchemaProperties>0?x(e.constraintCount/e.totalSchemaProperties):1,y=(e.requestExamplePresent?1:0)+(e.responseExamplePresent?1:0),g=(e.requestBodyPresent?1:0)+1,M=x(y/g),T=e.totalErrorResponses>0?x(e.structuredErrorResponseCount/e.totalErrorResponses):1,I=x(1-r/(o.maxDependencyDepthGood*2)),l=x(1-e.ambiguousIdentifierCount/Math.max(o.maxAmbiguousGood+3,1)),m=De(e,n.anyOfPenaltyMultiplier),d=m===0?1:e.hasDiscriminator?x(1-m/(o.maxPolymorphismGood*4)):x(1-m/(o.maxPolymorphismGood*2));return{parameterSimplicity:s,schemaSimplicity:h,documentationQuality:$,constraintClarity:O,exampleCoverage:M,errorClarity:T,dependencyClarity:I,identifierClarity:l,polymorphismClarity:d}}function ze(e,r=D){let t=r.weights,o=e.parameterSimplicity*t.parameterSimplicity+e.schemaSimplicity*t.schemaSimplicity+e.documentationQuality*t.documentationQuality+e.constraintClarity*t.constraintClarity+e.exampleCoverage*t.exampleCoverage+e.errorClarity*t.errorClarity+e.dependencyClarity*t.dependencyClarity+e.identifierClarity*t.identifierClarity+e.polymorphismClarity*t.polymorphismClarity;return $e(x(o)*100)}function Re(e,r,t=D){let o=new Map;for(let[n,s]of e.operations){let i=r.get(n)??0,a=He(s,i,t);o.set(n,{agentReadiness:ze(a,t),subscores:a})}return o}function Me(e,r=D){return x(1-e/r.thresholds.maxOperationsForDiscoverability)}function ve(e,r,t=D){if(e.size===0)return{agentReadiness:100};let o=[];for(let i of e.values())o.push(i.agentReadiness);let n=t.weights.discoverabilityWeight,s=r*100;return{agentReadiness:$e(B(o)*(1-n)+s*n)}}function J(e,r,t){return e-r+r*t}function De(e,r){return J(e.polymorphismCount,e.anyOfCount,r)}function x(e){return Math.max(0,Math.min(1,e))}function Ee(e){let r=e.size||1,t={parameterSimplicity:0,schemaSimplicity:0,documentationQuality:0,constraintClarity:0,exampleCoverage:0,errorClarity:0,dependencyClarity:0,identifierClarity:0,polymorphismClarity:0};for(let o of e.values())t.parameterSimplicity+=o.subscores.parameterSimplicity,t.schemaSimplicity+=o.subscores.schemaSimplicity,t.documentationQuality+=o.subscores.documentationQuality,t.constraintClarity+=o.subscores.constraintClarity,t.exampleCoverage+=o.subscores.exampleCoverage,t.errorClarity+=o.subscores.errorClarity,t.dependencyClarity+=o.subscores.dependencyClarity,t.identifierClarity+=o.subscores.identifierClarity,t.polymorphismClarity+=o.subscores.polymorphismClarity;return t.parameterSimplicity/=r,t.schemaSimplicity/=r,t.documentationQuality/=r,t.constraintClarity/=r,t.exampleCoverage/=r,t.errorClarity/=r,t.dependencyClarity/=r,t.identifierClarity/=r,t.polymorphismClarity/=r,t}function $e(e){return Math.round(e*10)/10}function we(e,r,t){let o=Math.max(1,e);return r/o+t/o}function Qe(e,r){return r.totalSchemaProperties>e.totalSchemaProperties?!0:r.totalSchemaProperties<e.totalSchemaProperties?!1:we(r.totalSchemaProperties,r.schemaPropertiesWithDescription,r.constraintCount)>we(e.totalSchemaProperties,e.schemaPropertiesWithDescription,e.constraintCount)}var Ke=["enum","const","format","pattern","minimum","maximum","minLength","maxLength","minItems","maxItems","minProperties","maxProperties","multipleOf","exclusiveMinimum","exclusiveMaximum","uniqueItems"];function Y(){return{depth:-1,maxDepth:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,hasPropertyExamples:!1,writableTopLevelFields:0,refsUsed:[],debugEntries:null,pendingRef:null}}function Ie(e){Object.assign(e,Y())}function Le(e){return{ref:{enter(r){typeof r?.$ref=="string"&&(e.refsUsed.push(r.$ref),e.pendingRef=r.$ref)}},Schema:{enter(r,t){e.depth++,e.maxDepth=Math.max(e.maxDepth,e.depth);let o=0;for(let i of Ke)r[i]!==void 0&&(e.constraintCount++,o++);r.discriminator?.propertyName&&(e.hasDiscriminator=!0);let n={};for(let i of["oneOf","anyOf","allOf"]){let a=r[i];Array.isArray(a)&&(e.polymorphismCount+=a.length,i==="anyOf"&&(e.anyOfCount+=a.length),n[i]=a.length)}let s=[];if(L(r.properties)){let i=Object.entries(r.properties);e.totalSchemaProperties+=i.length;for(let[a,c]of i){s.push(a);let h=c&&"$ref"in c&&c.$ref?t.resolve(c)?.node??c:c;h?.description&&e.schemaPropertiesWithDescription++,(h?.example!==void 0||h?.examples)&&(e.hasPropertyExamples=!0),h?.readOnly||e.writableTopLevelFields++}}e.debugEntries!==null&&e.debugEntries.push({ref:e.pendingRef,depth:e.depth,propertyNames:s,polymorphism:Object.keys(n).length>0?n:{},constraintCount:o}),e.pendingRef=null},leave(){e.depth--}}}}function qe(e,r,t){return{operations:new Map,currentPath:"",pathLevelParams:[],current:null,walkSchema:e,anyOfPenaltyMultiplier:r,debugOperationId:t,debugLogs:[]}}function Je(e,r,t){return{path:e,method:r,operationId:t.operationId,operationDescriptionPresent:!!t.description,parameterCount:0,requiredParameterCount:0,paramsWithDescription:0,ambiguousIdentifierCount:0,maxRequestSchemaDepth:0,maxResponseSchemaDepth:0,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,topLevelWritableFieldCount:0,requestBodyPresent:!1,requestExamplePresent:!1,responseExamplePresent:!1,structuredErrorResponseCount:0,totalErrorResponses:0,inRequestBody:!1,inResponse:!1,currentResponseCode:"",errorStructuredCounted:!1,maxEffectivePolymorphism:-1,refsUsed:new Set}}function Ye(e){let{inRequestBody:r,inResponse:t,currentResponseCode:o,errorStructuredCounted:n,maxEffectivePolymorphism:s,...i}=e;return i}function We(e){return{RequestBody:{enter(){e.current&&(e.current.requestBodyPresent=!0,e.current.inRequestBody=!0)},leave(){e.current&&(e.current.inRequestBody=!1)}},Response:{enter(r,t){let o=e.current;if(!o)return;let n=String(t.key);o.inResponse=!0,o.currentResponseCode=n,o.errorStructuredCounted=!1,Te(n)&&(o.totalErrorResponses++,!r.content&&r.description&&(o.structuredErrorResponseCount++,o.errorStructuredCounted=!0))},leave(){e.current&&(e.current.inResponse=!1)}},MediaType:{enter(r){let t=e.current;if(t&&(Ze(r)&&(t.inRequestBody&&(t.requestExamplePresent=!0),t.inResponse&&(t.responseExamplePresent=!0)),t.inResponse&&Te(t.currentResponseCode)&&!t.errorStructuredCounted&&(t.structuredErrorResponseCount++,t.errorStructuredCounted=!0),r.schema)){let o=!!e.debugOperationId&&(t.operationId===e.debugOperationId||`${t.method.toUpperCase()} ${t.path}`===e.debugOperationId),n=e.walkSchema(r.schema,o);Qe(t,n)&&(t.totalSchemaProperties=n.totalSchemaProperties,t.schemaPropertiesWithDescription=n.schemaPropertiesWithDescription,t.constraintCount=n.constraintCount);let s=J(n.polymorphismCount,n.anyOfCount,e.anyOfPenaltyMultiplier);s>t.maxEffectivePolymorphism&&(t.maxEffectivePolymorphism=s,t.polymorphismCount=n.polymorphismCount,t.anyOfCount=n.anyOfCount),n.hasDiscriminator&&(t.hasDiscriminator=!0);for(let i of n.refsUsed)t.refsUsed.add(i);if(n.hasPropertyExamples&&(t.inRequestBody&&(t.requestExamplePresent=!0),t.inResponse&&(t.responseExamplePresent=!0)),t.inRequestBody&&(t.maxRequestSchemaDepth=Math.max(t.maxRequestSchemaDepth,n.maxDepth),t.topLevelWritableFieldCount=Math.max(t.topLevelWritableFieldCount,n.writableTopLevelFields)),t.inResponse&&(t.maxResponseSchemaDepth=Math.max(t.maxResponseSchemaDepth,n.maxDepth)),o&&n.debugEntries){let i=t.inRequestBody?"REQUEST BODY":`RESPONSE ${t.currentResponseCode}`;e.debugLogs.push({context:i,entries:n.debugEntries,totalProperties:n.totalSchemaProperties,totalPolymorphism:n.polymorphismCount,totalConstraints:n.constraintCount,maxDepth:n.maxDepth})}}}},Paths:{PathItem:{enter(r,t){e.currentPath=String(t.key),e.pathLevelParams=r.parameters??[]},Operation:{enter(r,t){let o=String(t.key),n=Je(e.currentPath,o,r);e.current=n;let s=Xe(e.pathLevelParams,r.parameters??[],t.resolve);for(let i of s.values())n.parameterCount++,i.required&&n.requiredParameterCount++,i.description&&n.paramsWithDescription++,et(i)&&n.ambiguousIdentifierCount++},leave(r){let t=e.current;if(!t)return;let o=r.operationId??`${t.method.toUpperCase()} ${t.path}`;e.operations.set(o,Ye(t)),e.current=null}}}}}}function Ue(e){return{operationCount:e.operations.size,operations:e.operations}}function Ae(e,r){return r(e).node}function Xe(e,r,t){let o=new Map;for(let n of e){let s=Ae(n,t);s?.name&&s.in&&o.set(`${s.in}:${s.name}`,s)}for(let n of r){let s=Ae(n,t);s?.name&&s.in&&o.set(`${s.in}:${s.name}`,s)}return o}function Ze(e){return e.example!==void 0||ie(e.examples)}function et(e){if(e.description)return!1;let r=(e.name??"").toLowerCase();return Oe.has(r)}function Te(e){if(e==="default"||/^4xx$/i.test(e)||/^5xx$/i.test(e))return!0;let r=parseInt(e,10);return r>=400&&r<600}function tt(e,r){if(!r.startsWith("#/"))return;let t=e;for(let o of r.slice(2).split("/"))t=t?.[ce(o)];return t}function ke({document:e,types:r,resolvedRefMap:t,ctx:o,debugOperationId:n,scoringConstants:s}){let i=s?.weights.anyOfPenaltyMultiplier??D.weights.anyOfPenaltyMultiplier,a=Y(),c=Le(a),h=Q([{severity:"warn",ruleId:"score-schema",visitor:c}],r),u=(l,m)=>{Ie(a),m&&(a.debugEntries=[]),K({document:{...e,parsed:l},rootType:r.Schema,normalizedVisitors:h,resolvedRefMap:t,ctx:o});let{depth:d,pendingRef:w,debugEntries:_,...N}=a;return{...N,refsUsed:[...a.refsUsed],debugEntries:m?a.debugEntries??void 0:void 0}},f=new Map,$=new WeakSet,O={maxDepth:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,hasPropertyExamples:!1,writableTopLevelFields:0,refsUsed:[]};function y(l,m){return{maxDepth:Math.max(l.maxDepth,m.maxDepth),polymorphismCount:l.polymorphismCount+m.polymorphismCount,anyOfCount:l.anyOfCount+m.anyOfCount,hasDiscriminator:l.hasDiscriminator||m.hasDiscriminator,totalSchemaProperties:l.totalSchemaProperties+m.totalSchemaProperties,schemaPropertiesWithDescription:l.schemaPropertiesWithDescription+m.schemaPropertiesWithDescription,constraintCount:l.constraintCount+m.constraintCount,hasPropertyExamples:l.hasPropertyExamples||m.hasPropertyExamples,writableTopLevelFields:l.writableTopLevelFields+m.writableTopLevelFields,refsUsed:[...l.refsUsed,...m.refsUsed],debugEntries:l.debugEntries||m.debugEntries?[...l.debugEntries??[],...m.debugEntries??[]]:void 0}}let g=(l,m=!1)=>{let d=l,w=pe(l)?l.$ref:void 0;if(w){if(!m){let S=f.get(w);if(S)return S}d=tt(e.parsed,w)??l}if(L(d)&&$.has(d))return{...O};L(d)&&$.add(d);let _=d?.oneOf,N=d?.anyOf,Z=Array.isArray(_)&&_.length>1,ee=Array.isArray(N)&&N.length>1,G=Z||ee,te=Array.isArray(d?.allOf)&&d.allOf.length>0,V=d?.discriminator,q=!G&&L(V?.mapping)?Object.values(V.mapping).filter(S=>typeof S=="string"&&me(S)).map(S=>({$ref:S})):null,re=Array.isArray(q)&&q.length>0,C;if(G||te||re){let S={...d},F=null,oe=P=>{F=F?y(F,P):P},ne=(P,v)=>{let E=g(v[0],m);for(let z=1;z<v.length;z++){let se=g(v[z],m);se.totalSchemaProperties>E.totalSchemaProperties&&(E=se)}return{...E,polymorphismCount:E.polymorphismCount+v.length,anyOfCount:E.anyOfCount+(P==="anyOf"?v.length:0),hasDiscriminator:E.hasDiscriminator||!!V}};G&&delete S.discriminator,Z&&(delete S.oneOf,oe(ne("oneOf",_))),ee&&(delete S.anyOf,oe(ne("anyOf",N)));let H=null;if(re){delete S.discriminator;let P=g(q[0],m);for(let v=1;v<q.length;v++){let E=g(q[v],m);E.totalSchemaProperties>P.totalSchemaProperties&&(P=E)}H={...P,polymorphismCount:P.polymorphismCount+q.length,hasDiscriminator:!0}}let W=null;if(te){delete S.allOf,W={...O};for(let P of d.allOf)W=y(W,g(P,m));W.polymorphismCount+=d.allOf.length}C=u(S,m),W&&(C=y(C,W)),F&&(C=y(C,F)),H&&(C=y(C,H)),w&&(C={...C,refsUsed:[w,...C.refsUsed]})}else C=u(l,m);return L(d)&&$.delete(d),w&&!m&&f.set(w,C),C},M=qe(g,i,n),T=We(M),I=Q([{severity:"warn",ruleId:"score",visitor:T}],r);return K({document:e,rootType:r.Root,normalizedVisitors:I,resolvedRefMap:t,ctx:o}),{metrics:Ue(M),debugLogs:M.debugLogs}}function Ne(e){let r=new Map;for(let[n,s]of e)for(let i of s.refsUsed){let a=r.get(i);a||(a=new Set,r.set(i,a)),a.add(n)}let t=new Map;for(let n of e.keys())t.set(n,new Set);for(let n of r.values()){if(n.size<2)continue;let s=Array.from(n);for(let i=0;i<s.length;i++)for(let a=i+1;a<s.length;a++)t.get(s[i]).add(s[a]),t.get(s[a]).add(s[i])}let o=new Map;for(let n of e.keys()){let s=rt(n,t);o.set(n,s)}return o}function rt(e,r){let t=new Set([e]),o=[e],n=0;for(;o.length>0;){let s=[];for(let i of o)for(let a of r.get(i)??[])t.has(a)||(t.add(a),s.push(a));s.length>0&&n++,o=s}return n}function Fe(e){let r={agentReadiness:e.agentReadiness,discoverability:Math.round(e.discoverability*100),subscores:e.subscores,rawMetrics:{operationCount:e.rawMetrics.operationCount,operations:Object.fromEntries(Array.from(e.rawMetrics.operations.entries()).map(([t,o])=>{let{refsUsed:n,...s}=o;return[t,s]}))},operationScores:Object.fromEntries(e.operationScores),dependencyDepths:Object.fromEntries(e.dependencyDepths),hotspots:e.hotspots};k.output(JSON.stringify(r,null,2))}function je(e,r=!1){ot(e),nt(e),it(e),r&&at(e),pt(e)}function _e(e){return e>=80?de:e>=50?j:fe}function Be(e){return _e(e)(b(e.toFixed(1)))}function p(e){k.output(e+`
8
8
  `)}function ot(e){p(""),p(b(A(" Scores"))),p(""),p(` Agent Readiness: ${Be(e.agentReadiness)}/100`),p("")}function nt(e){p(b(A(" Subscores"))),p("");let r=e.subscores;R("Parameter Simplicity",r.parameterSimplicity),R("Schema Simplicity",r.schemaSimplicity),R("Documentation Quality",r.documentationQuality),R("Constraint Clarity",r.constraintClarity),R("Example Coverage",r.exampleCoverage),R("Error Clarity",r.errorClarity),R("Dependency Clarity",r.dependencyClarity),R("Identifier Clarity",r.identifierClarity),R("Polymorphism Clarity",r.polymorphismClarity),R("Discoverability",e.discoverability),p("")}function R(e,r){let t=Math.round(r*100),o=st(r);p(` ${e.padEnd(24)} ${o} ${_e(t)(t+"%")}`)}function st(e){let t=Math.round(e*20);return U("["+"\u2588".repeat(t)+"\u2591".repeat(20-t)+"]")}function it(e){if(p(b(A(" Raw Metrics Summary"))),p(""),p(` Total operations: ${e.rawMetrics.operationCount}`),e.rawMetrics.operationCount===0){p("");return}let r=[],t=[],o=[],n=[],s=0,i=0,a=0;for(let u of e.rawMetrics.operations.values())r.push(u.parameterCount),t.push(Math.max(u.maxRequestSchemaDepth,u.maxResponseSchemaDepth)),o.push(u.polymorphismCount),n.push(u.totalSchemaProperties),u.requestExamplePresent&&s++,u.responseExamplePresent&&i++,u.operationDescriptionPresent&&a++;let c=e.rawMetrics.operationCount;function h(u,f){let O=(f.reduce((T,I)=>T+I,0)/c).toFixed(1),y=B(f).toFixed(1),g=Math.min(...f),M=Math.max(...f);p(` ${u.padEnd(26)} avg ${O.padStart(6)} median ${y.padStart(6)} min ${String(g).padStart(5)} max ${String(M).padStart(5)}`)}h("Parameters/operation:",r),h("Schema depth:",t),h("Polymorphism/operation:",o),h("Properties/operation:",n),p(` Operations with request examples: ${s}/${c} (${X(s,c)})`),p(` Operations with response examples: ${i}/${c} (${X(i,c)})`),p(` Operations with description: ${a}/${c} (${X(a,c)})`),p("")}function X(e,r){return r>0?`${Math.round(e/r*100)}%`:"N/A"}function at(e){p(b(A(" Per-Operation Metrics"))),p("");let r=" "+"Operation".padEnd(50)+"Props".padStart(7)+"Poly".padStart(7)+"Depth".padStart(7)+"Params".padStart(8)+"Constr".padStart(8);p(U(r)),p(U(" "+"\u2500".repeat(r.length-2)));let t=[...e.rawMetrics.operations.entries()].sort(([,o],[,n])=>n.totalSchemaProperties-o.totalSchemaProperties);for(let[,o]of t){let n=(o.operationId??`${o.method.toUpperCase()} ${o.path}`).slice(0,48),s=Math.max(o.maxRequestSchemaDepth,o.maxResponseSchemaDepth),i=" "+n.padEnd(50)+String(o.totalSchemaProperties).padStart(7)+String(o.polymorphismCount).padStart(7)+String(s).padStart(7)+String(o.parameterCount).padStart(8)+String(o.constraintCount).padStart(8);p(i)}p("")}function Ge(e,r){if(p(""),p(b(A(` Debug: ${e} schema breakdown`))),p(""),r.length===0){p(j(` No schemas found for operation "${e}".`)),p(j(' Make sure the value matches an operationId or "METHOD /path" exactly.')),p("");return}for(let t of r){p(b(U(` ${t.context}`))),p(U(" "+"\u2500".repeat(70)));let o=new Map;for(let s of t.entries){let i=s.ref??`(inline depth ${s.depth})`,a=o.get(i);if(a){a.count++,a.totalProps+=s.propertyNames.length;for(let c of s.propertyNames)a.propNames.includes(c)||a.propNames.push(c)}else o.set(i,{count:1,totalProps:s.propertyNames.length,propNames:[...s.propertyNames]})}for(let s of t.entries){let i=s.ref??"(inline)",a=" ".repeat(Math.min(s.depth,6)),c=s.propertyNames.length,h=` ${a}${i}`;c>0&&(h+=` (${c} properties)`);let u=[];if(s.polymorphism.oneOf&&u.push(`oneOf:${s.polymorphism.oneOf}`),s.polymorphism.anyOf&&u.push(`anyOf:${s.polymorphism.anyOf}`),s.polymorphism.allOf&&u.push(`allOf:${s.polymorphism.allOf}`),u.length>0&&(h+=` [${u.join(", ")}]`),s.constraintCount>0&&(h+=` {${s.constraintCount} constraints}`),p(h),c>0&&c<=20)p(` ${a} properties: ${s.propertyNames.join(", ")}`);else if(c>20){let f=s.propertyNames.slice(0,15).join(", ");p(` ${a} properties: ${f}, ... +${c-15} more`)}}p(""),p(` Totals: ${t.totalProperties} properties, ${t.totalPolymorphism} polymorphism items, ${t.totalConstraints} constraints, max depth ${t.maxDepth}`);let n=[...o.entries()].filter(([,s])=>s.totalProps>0).sort(([,s],[,i])=>i.totalProps-s.totalProps).slice(0,10);if(n.length>0){p(""),p(b(" Top schemas by property count:"));for(let[s,i]of n)p(` ${s}: ${i.totalProps} properties`)}p("")}}function pt(e){if(e.hotspots.length===0){p(b(A(" No hotspot operations found."))),p("");return}p(b(A(` Top ${e.hotspots.length} Hotspot Operations`))),p("");for(let r of e.hotspots){let t=r.operationId?`${r.method.toUpperCase()} ${r.path} (${r.operationId})`:`${r.method.toUpperCase()} ${r.path}`;p(b(` ${t}`)),p(` Agent Readiness: ${Be(r.agentReadinessScore)}`);for(let o of r.reasons)p(j(` - ${o}`));p("")}}function Ve(e,r,t,o=D){let n=[];for(let[s,i]of r){let a=e.operations.get(s);if(!a)continue;let c=ct(a,t.get(s)??0,o);c.length!==0&&n.push({path:a.path,method:a.method,operationId:a.operationId,agentReadinessScore:i.agentReadiness,reasons:c})}return n.sort((s,i)=>s.reasons.length!==i.reasons.length?i.reasons.length-s.reasons.length:s.agentReadinessScore-i.agentReadinessScore),n.slice(0,o.hotspotLimit)}function ct(e,r,t){let{thresholds:o}=t,n=[];e.parameterCount>o.maxParamsGood&&n.push(`High parameter count (${e.parameterCount})`);let s=Math.max(e.maxRequestSchemaDepth,e.maxResponseSchemaDepth);s>o.maxDepthGood&&n.push(`Deep schema nesting (depth ${s})`),e.anyOfCount>0&&!e.hasDiscriminator?n.push(`Polymorphism (anyOf) without discriminator (${e.anyOfCount} anyOf)`):e.polymorphismCount>o.maxPolymorphismGood&&n.push(`High polymorphism count (${e.polymorphismCount})`);let i=e.requestBodyPresent&&!e.requestExamplePresent,a=!e.responseExamplePresent;return i&&a?n.push("Missing request and response examples"):i?n.push("Missing request body examples"):a&&n.push("Missing response examples"),e.totalErrorResponses>0&&e.structuredErrorResponseCount===0&&n.push("No structured error responses (4xx/5xx)"),e.operationDescriptionPresent||n.push("Missing operation description"),e.parameterCount>0&&e.paramsWithDescription===0&&n.push("No parameter descriptions"),r>o.maxDependencyDepthGood&&n.push(`High dependency depth (${r})`),e.ambiguousIdentifierCount>o.maxAmbiguousGood&&n.push(`Ambiguous identifiers (${e.ambiguousIdentifierCount})`),n}async function Vt({argv:e,config:r,collectSpecData:t}){let[{path:o}]=await xe(e.api?[e.api]:[],r),n=new le(r.resolve),{bundle:s}=await be({config:r,ref:o});t?.(s);let i=ge(s.parsed);if(Se(i)!=="oas3")throw new Ce(`The score command currently supports only OpenAPI 3.x. Detected: ${i}`);let a=mt.now(),c=ae(r.extendTypes(ue(i),i),r),h=await he({rootDocument:s,rootType:c.Root,externalRefResolver:n}),u=e["debug-operation-id"],{metrics:f,debugLogs:$}=ke({document:s,types:c,resolvedRefMap:h,ctx:{problems:[],specVersion:i,config:r,visitorsData:{}},debugOperationId:u}),O=Ne(f.operations),y=Re(f,O),g=Me(f.operationCount),{agentReadiness:M}=ve(y,g),T=Ve(f,y,O),I={agentReadiness:M,discoverability:g,subscores:Ee(y),rawMetrics:f,hotspots:T,operationScores:y,dependencyDepths:O};ut(I,o,a,e.format,!!e["operation-details"],u?{operationId:u,logs:$}:void 0)}function ut(e,r,t,o,n,s){k.info(`Document: ${ye(r)} score:
9
9
  `),o==="json"?Fe(e):je(e,n),s&&Ge(s.operationId,s.logs),Pe("score",t,r)}export{Vt as handleScore};
@@ -0,0 +1,24 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{a as we,e as Re,f as be,g as k,h as A,i as Oe,j as Ie,k as S,l as x,m as Pe,n as ke,v as Ae,w as xe}from"./KRCCY64H.js";import{$ as E,K as lt,V as le,Y as ft,Z as fe,_ as g,aa as me,ba as q,c as p,ca as T,ea as b,ga as w,ia as R,ja as he,ka as ge,la as ye,ma as Se,q as de,ra as ve,w as pe}from"./22EANOP2.js";import{e as ce}from"./RFWIIJFG.js";import Ce from"node:path";function O(t){return t?t.trim():""}function L(t){let e=O(t.operationId)||O(t.path);return[O(t.ruleId),O(t.severity),O(t.message),e,O(t.target),O(t.schemaPath)].join("")}var N=t=>fe(b(t));function mt(t){return t==="error"?"error":t==="warning"?"warning":"note"}function ht(t){if(t==null)return"";let e=String(t);return!e.includes(",")&&!e.includes('"')&&!e.includes(`
8
+ `)?e:`"${e.replace(/"/g,'""')}"`}function gt(t){return Ce.isAbsolute(t)?Ce.relative(process.cwd(),t)||".":t}function yt(t){if(!t)return null;let e=t.operationPathTemplate;return typeof e=="string"&&e.length>0?e:null}function St(t){return Object.entries(t).sort((e,n)=>{let r=n[1]-e[1];return r!==0?r:e[0].localeCompare(n[0])})}function vt(t){let e=[],n=new Map;for(let r of t){let s=L({ruleId:r.ruleId,severity:r.severity,message:r.message,operationId:r.operationId,path:r.path,target:r.target,schemaPath:r.schemaPath}),i=n.get(s);if(i!==void 0){e[i].occurrences+=1;continue}n.set(s,e.length),e.push({finding:r,occurrences:1})}return e}function wt(t){let e=vt(t.findings).map(r=>({occurrences:r.occurrences,exchangeIndex:r.finding.exchangeIndex,ruleId:r.finding.ruleId,severity:r.finding.severity,category:r.finding.category,message:r.finding.message,operationId:r.finding.operationId,specSource:r.finding.specSource,target:r.finding.target,schemaPath:r.finding.schemaPath,dataPath:r.finding.dataPath,details:r.finding.details,method:r.finding.method,url:r.finding.url,path:r.finding.path,status:r.finding.status})),n={run:{id:t.runId,specSource:t.meta.specSource,trafficPath:t.meta.trafficPath,format:t.meta.format,matchMode:t.meta.matchMode,server:t.meta.server,totalExchanges:t.summary.totalExchanges,documentedExchanges:t.summary.documentedExchanges,undocumentedExchanges:t.summary.undocumentedExchanges,skippedExchanges:t.summary.skippedExchanges,findingsBySeverity:t.summary.findingsBySeverity,findingsByRule:t.summary.findingsByRule,totalProblems:t.summary.totalProblemGroups,durationMs:t.summary.durationMs},problems:e};return`${JSON.stringify(n,null,2)}
9
+ `}function Rt(t){let e=["run_id","finding_id","exchange_index","severity","category","rule_id","message","method","path","url","status","operation_id","spec_source","target","schema_path","data_path"],n=t.findings.map(s=>[t.runId,s.id,s.exchangeIndex,s.severity,s.category,s.ruleId,s.message,s.method,s.path,s.url,s.status,s.operationId,s.specSource,s.target,s.schemaPath,s.dataPath]);return`${[e,...n].map(s=>s.map(ht).join(",")).join(`
10
+ `)}
11
+ `}function bt(t){let e=new Map;for(let s of t.findings)e.has(s.ruleId)||e.set(s.ruleId,{id:s.ruleId,name:s.ruleId,shortDescription:{text:`${s.category} detection`}});let n=t.findings.map(s=>{let i=s.specSource??s.url??void 0;return{ruleId:s.ruleId,level:mt(s.severity),message:{text:s.message},locations:i?[{physicalLocation:{artifactLocation:{uri:i}}}]:void 0,properties:{runId:t.runId,exchangeIndex:s.exchangeIndex,method:s.method,path:s.path,status:s.status,operationId:s.operationId,target:s.target,schemaPath:s.schemaPath,dataPath:s.dataPath}}}),r={$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"drift",rules:Array.from(e.values())}},results:n}]};return`${JSON.stringify(r,null,2)}
12
+ `}function Ot(t){return t.findingsBySeverity.error+t.findingsBySeverity.warning+t.findingsBySeverity.info}function It(t){return t>=500?E:t>=400?q:t>=300?T:t>=200?me:w}function Pt(t,e,n){let r=(f,h)=>e?h(f):f,s=f=>f==="error"?r("\u2716",E):f==="warning"?r("\u25B2",q):r("\u25CF",T),i=f=>f==="error"?r("ERROR",E):f==="warning"?r("WARN",q):r("INFO",T),{summary:o,meta:a}=t,u=Ot(o),l=o.previewFindings.slice(0,n),c=[];if(c.push(r("\u250F\u2501 Drift Report",N)),c.push(`\u2503 Run: ${t.runId}`),c.push(`\u2503 Spec: ${a.specSource}`),c.push(`\u2503 Traffic: ${a.trafficPath}`),c.push(a.server?`\u2503 Server: ${a.server} (overrides description servers)`:`\u2503 Match mode: ${a.matchMode}`),c.push(`\u2503 Traffic format: ${a.format}${a.format==="auto"?" (auto-detect)":""}`),c.push(`\u2503 Exchanges: total=${o.totalExchanges} documented=${o.documentedExchanges} undocumented=${o.undocumentedExchanges}${o.skippedExchanges>0?` skipped=${o.skippedExchanges}`:""}`),c.push(`\u2503 Findings: total=${u} ${r(`error=${o.findingsBySeverity.error}`,E)} ${r(`warning=${o.findingsBySeverity.warning}`,q)} ${r(`info=${o.findingsBySeverity.info}`,T)}`),c.push(`\u2503 Problems: total=${o.totalProblemGroups}`),c.push(`\u2517 Duration: ${o.durationMs}ms`),u===0)return c.push(""),c.push(r("\u2714 No findings.",b)),`${c.join(`
13
+ `)}
14
+ `;c.push(""),c.push(r(`Types (${Object.keys(o.problemGroupsByRule).length})`,N));for(let[f,h]of St(o.problemGroupsByRule)){let y=o.findingsByRule[f]??h;c.push(` ${r("\u2022",w)} ${f}: ${h} problems / ${y} findings`)}let m=new Map;for(let f of l)m.has(f.ruleId)||m.set(f.ruleId,[]),m.get(f.ruleId).push(f);let v=Array.from(m.keys()).sort((f,h)=>{let y=(o.problemGroupsByRule[h]??0)-(o.problemGroupsByRule[f]??0);return y!==0?y:f.localeCompare(h)});c.push(""),c.push(r(`Problems by type (showing first ${l.length} of ${o.totalProblemGroups})`,N));let _=0;for(let f of v){let h=m.get(f);if(!h||h.length===0)continue;let y=o.problemGroupsByRule[f]??h.length,X=o.findingsByRule[f]??y;c.push(""),c.push(`${r("\u25C9",b)} ${r(f,N)} ${r(`(${h.length} problems shown / ${y} total, ${X} findings)`,w)}`);for(let d of h){_+=1;let oe=d.occurrences,ut=d.status!==void 0?r(String(d.status),It(d.status)):r("-",w),ct=yt(d.details)??d.path,dt=d.operationId?` ${r(d.operationId,g)}`:"";if(c.push(`${s(d.severity)} ${i(d.severity)} #${_}${oe>1?` ${r(`\xD7${oe}`,w)}`:""} ${r("\u2192",w)} ${d.message}`),c.push(` \u21B3 sample exchange=${d.exchangeIndex} ${r(d.method,b)} ${ct} (${ut})${dt}`),c.push(""),c.push(` ${r(d.url,w)}`),(d.specSource||d.schemaPath||d.dataPath)&&(c.push(""),d.specSource&&c.push(` ${r("spec:",g)} ${r(gt(d.specSource),b)}`),d.schemaPath&&c.push(` ${r("schemaPath=",g)} ${r(d.schemaPath,g)}`),d.dataPath&&c.push(` ${r("dataPath=",g)} ${r(d.dataPath,b)}`)),d.details)if(c.push(""),d.ruleId==="security-baseline"&&typeof d.details.summary=="string")c.push(` ${r("security:",g)} ${d.details.summary}`);else if(d.ruleId==="owasp-api-top10"&&typeof d.details.summary=="string"){let C=typeof d.details.issueId=="string"?d.details.issueId:null,$=typeof d.details.issueTitle=="string"?d.details.issueTitle:null;c.push(` ${r("owasp:",g)} ${d.details.summary}`),(C||$)&&c.push(` ${r("issue:",g)} ${[C,$].filter(Boolean).join(" - ")}`)}else if(d.ruleId==="schema-consistency"&&typeof d.details.summary=="string"){let C=typeof d.details.path=="string"?d.details.path:null,$=typeof d.details.expected=="string"?d.details.expected:null,ae=typeof d.details.actual=="string"?d.details.actual:null,ue=typeof d.details.suggestion=="string"?d.details.suggestion:null;if(c.push(` ${r("schema:",g)} ${d.details.summary}`),C&&c.push(` ${r("path:",g)} ${r(C,b)}`),$&&c.push(` ${r("expected:",g)} ${$}`),ae&&c.push(` ${r("actual:",g)} ${ae}`),ue){c.push(` ${r("hint:",g)}`);for(let pt of ue.split(`
15
+ `))c.push(` ${pt}`)}}else c.push(` ${r("details:",g)} ${JSON.stringify(d.details)}`);c.push("")}}let P=o.totalProblemGroups-l.length;return P>0?(c[c.length-1]!==""&&c.push(""),c.push(r(`\u2026 ${P} problems omitted from terminal output. Use --format json/csv/sarif for the complete export.`,w))):c[c.length-1]===""&&c.pop(),`${c.join(`
16
+ `)}
17
+ `}function an(t,e){let n=e.maxFindings??10;switch(e.format){case"json":return wt(t);case"csv":return Rt(t);case"sarif":return bt(t);case"pretty":return Pt(t,e.color??!1,n);default:throw new Error(`Unsupported report format: ${e.format}`)}}import{randomUUID as st}from"node:crypto";function kt(t,e){let n=A(t||"/")||"/",r=A(e.basePath||"/")||"/";return r==="/"?n:n===r?"/":n.startsWith(`${r}/`)?n.slice(r.length)||"/":null}function At(t,e){return!t.host||!e?!0:t.host===e.toLowerCase()}function xt(t){try{return decodeURIComponent(t)}catch{return t}}function Ct(t,e,n){let r=n==="strict-host"?e.host?20:5:0;return t.pathScore*10+r}function $e(t,e){let n={};for(let r=0;r<t.pathParams.length;r+=1){let s=t.pathParams[r],i=e[r+1];s&&i!==void 0&&(n[s]=xt(i))}return n}function $t(t,e){let n=A(e)||"/";for(let r of t){let s=r.pathRegex.exec(n);if(s)return{operation:r,pathParams:$e(r,s)}}return null}function Ee(t,e,n,r){let s=e.request.method.toLowerCase(),i=t.operationsByMethod.get(s);if(!i||i.length===0)return null;if(r!==void 0)return $t(i,r);let o=null;for(let a of i)for(let u of a.servers){if(n==="strict-host"&&!At(u,e.request.host))continue;let l=kt(e.request.path,u);if(!l)continue;let c=a.pathRegex.exec(l);if(!c)continue;let m={score:Ct(a,u,n),matched:{operation:a,pathParams:$e(a,c)}};(!o||m.score>o.score)&&(o=m)}return o?.matched??null}var qe=6,Et=2e3,qt=50,Tt=5,Ft=1e6,Mt=/(?:token|api[_-]?key|apikey|password|passwd|secret|authorization|jwt)/i,jt=/(?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|private[_-]?key|ssn|credit[_-]?card|card[_-]?number|cvv)/i,Bt=new Set(["page","limit","offset","cursor","per_page","perpage","size","start","after","before"]),Te=4,_t=Te*2;function Lt(t){return t.length<=_t?"***":`${t.slice(0,Te)}\u2026`}function Nt(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function zt(t){return typeof t=="string"||typeof t=="number"}function Vt(t){let e=t.toLowerCase();return e.includes("secret")||e.includes("token")||e.includes("key")?e.startsWith("is")||e.startsWith("has")||e.startsWith("can")||e.startsWith("should")||e.startsWith("enable")||e.startsWith("allow"):!1}function Kt(t){if(typeof t=="number")return t===0||t===1;let e=t.trim().toLowerCase();return e==="true"||e==="false"||e==="0"||e==="1"}function Ht(t){if(!p(t)&&!Array.isArray(t))return[];let e=[],n=[{value:t,path:""}],r=0;for(;n.length>0&&r<Et&&e.length<qe;){let s=n.pop();if(!s)break;if(r+=1,Array.isArray(s.value)){let i=Math.min(s.value.length,qt);for(let o=0;o<i;o+=1){let a=s.value[o];(p(a)||Array.isArray(a))&&n.push({value:a,path:`${s.path}/${o}`})}continue}if(p(s.value))for(let[i,o]of Object.entries(s.value)){let a=`${s.path}/${Nt(i)}`;if(jt.test(i)&&zt(o)){let u=String(o);if(Vt(i)&&Kt(o))continue;if(u.length>0&&(e.push(a||"/"),e.length>=qe))break}(p(o)||Array.isArray(o))&&n.push({value:o,path:a})}}return e}function Dt(t){for(let e of t.keys())if(Bt.has(e.toLowerCase()))return!0;return!1}function I(t,e,n,r,s){return{ruleId:"owasp-api-top10",severity:r,category:"security",message:e,exchangeIndex:t.exchange.index,operationId:t.matchedOperation?.operation.operationId,specSource:t.matchedOperation?.operation.specSource,target:n,details:s}}function Ut(t){let e=[];for(let[n,r]of t.exchange.request.query.entries())if(Mt.test(n)&&(e.push({key:n,valuePreview:Lt(r)}),e.length>=Tt))break;return e.length===0?[]:[I(t,"Sensitive credential-like query parameters detected","request","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:"Authentication data should not be passed via query parameters because it can leak via logs, browser history, and referrers.",sensitiveQueryParams:e})]}function Jt(t){let e=t.exchange.response;if(!e)return[];let n=e.headers["access-control-allow-origin"]?.trim(),r=e.headers["access-control-allow-credentials"]?.trim().toLowerCase();return n!=="*"||r!=="true"?[]:[I(t,"Insecure CORS policy: wildcard origin with credentials enabled","response","error",{issueId:"API8:2023",issueTitle:"Security Misconfiguration",summary:'Access-Control-Allow-Origin is "*" while Access-Control-Allow-Credentials is true. Browsers may expose authenticated API responses to untrusted origins.',headers:{accessControlAllowOrigin:n,accessControlAllowCredentials:r}})]}function Gt(t){let e=t.exchange.response;if(!e)return[];let n=e.headers["set-cookie"];if(!n)return[];let r=[];for(let s of be(n)){let i=new Set(s.split(";").slice(1).map(o=>o.split("=")[0].trim().toLowerCase()));t.exchange.request.protocol==="https:"&&!i.has("secure")&&r.push(I(t,'Set-Cookie header is missing "Secure" attribute',"response","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:'Session cookies over HTTPS should include "Secure" to prevent transmission over plain HTTP.',setCookiePreview:s.slice(0,200)})),i.has("httponly")||r.push(I(t,'Set-Cookie header is missing "HttpOnly" attribute',"response","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:'Session cookies should include "HttpOnly" to reduce risk of token theft via client-side script access.',setCookiePreview:s.slice(0,200)})),i.has("samesite")||r.push(I(t,'Set-Cookie header is missing "SameSite" attribute',"response","info",{issueId:"API8:2023",issueTitle:"Security Misconfiguration",summary:'Set "SameSite" on session cookies to reduce CSRF risk for state-changing requests.',setCookiePreview:s.slice(0,200)}))}return r}function Wt(t){let e=t.exchange.response;if(!e||e.bodyJson===void 0)return[];let n=Ht(e.bodyJson);return n.length===0?[]:[I(t,"Potential sensitive data exposure in response payload","response","warning",{issueId:"API3:2019",issueTitle:"Excessive Data Exposure",summary:`Sensitive-looking fields detected in response payload: ${n.join(", ")}`,exposedPaths:n})]}function Qt(t){let e=t.exchange.response;return!e||e.status>=400||t.exchange.request.method!=="GET"?[]:!e.bodyText||e.bodyText.length<Ft?[]:Dt(t.exchange.request.query)?[]:[I(t,"Large response without pagination parameters (possible resource-consumption risk)","response","info",{issueId:"API4:2023",issueTitle:"Unrestricted Resource Consumption",summary:"A large response was returned without common pagination query parameters. Consider explicit page/limit controls for large collections.",responseBytes:e.bodyText.length})]}var z=class{id="owasp-api-top10";analyze(e){return e.matchedOperation?[...Ut(e),...Jt(e),...Gt(e),...Wt(e),...Qt(e)]:[]}};function V(t,e){let n=t.replace(/\{([^}]+)\}/g,(i,o)=>{let a=e?.[o];return a?.default!==void 0?String(a.default):Array.isArray(a?.enum)&&a.enum.length>0?String(a.enum[0]):""}),r=k(n),s=!!(r.host&&!Re(r.host));return{rawUrl:t,protocol:s?r.protocol:void 0,host:s?r.host.toLowerCase():void 0,basePath:A(r.pathname||"/")}}function Fe(t){return t?t.startsWith("/")?t:`/${t}`:"/"}function K(t,e){let n=`${Math.floor(t/100)}XX`;return[String(t),n,n.toLowerCase(),"default"].find(r=>e.includes(r))}function Me(t){if(!t)return{};let e={};for(let n of t.split(";")){let[r,...s]=n.trim().split("=");if(!r)continue;let i=s.join("=").trim();e[r]=i}return e}var Yt=/^([^[\]]+)\[([^[\]]+)\]$/;function ee(t){let e=t.match(Yt);return e?{parameterName:e[1],property:e[2]}:void 0}function Xt(t,e){let n;for(let[r,s]of e){let i=ee(r);i?.parameterName===t&&(n??={},n[i.property]=s)}return n}var je="application/x-www-form-urlencoded",Zt=["additionalProperties","patternProperties","unevaluatedProperties"];function Be(t){let e={properties:new Map,arrayKeys:new Set,jsonKeys:new Set,checksOtherKeys:!1};Z(t,e,!0,new Set);for(let[n,r]of e.properties){let s=p(r)&&r.type==="array";s&&e.arrayKeys.add(n),_e(s?r.items:r,new Set)&&e.jsonKeys.add(n)}return e}function Z(t,e,n,r){if(!(!p(t)||r.has(t))){if(r.add(t),p(t.properties))for(let[s,i]of Object.entries(t.properties))e.properties.set(s,i);n&&Zt.some(s=>t[s]!==void 0)&&(e.checksOtherKeys=!0);for(let s of Array.isArray(t.allOf)?t.allOf:[])Z(s,e,n,r);for(let s of[t.oneOf,t.anyOf])for(let i of Array.isArray(s)?s:[])Z(i,e,!1,r)}}function _e(t,e){return!p(t)||e.has(t)?!1:(e.add(t),t.type!==void 0?Array.isArray(t.type)?t.type.includes("object"):t.type==="object":p(t.properties)||[t.allOf,t.oneOf,t.anyOf].some(n=>Array.isArray(n)&&n.some(r=>_e(r,e))))}function er(t){try{return JSON.parse(t)}catch{return t}}function tr(t,e){let{formSchema:n}=t;if(n){let i=[...new Set(e.query.keys())];return i.length===0?void 0:Object.fromEntries(i.map(o=>{let a=e.query.getAll(o),u=n.jsonKeys.has(o)?a.map(er):a;return[o,n.arrayKeys.has(o)||u.length>1?u:u[0]]}))}let r=k(e.url).search.slice(1);if(r==="")return;let s;try{s=decodeURIComponent(r)}catch{s=r}if(!S(t.mediaType))return s;try{return JSON.parse(s)}catch{return}}function H(t,e,n,r){switch(t.in){case"path":return n[t.name];case"query":{if(t.style==="deepObject")return Xt(t.name,e.query);let s=e.query.getAll(t.name);return s.length===0?void 0:(p(t.schema)?t.schema.type:void 0)==="array"||s.length>1?s:s[0]}case"querystring":return tr(t,e);case"header":return e.headers[t.name.toLowerCase()];case"cookie":return r[t.name];default:return}}var Le=200;function Ne(t){return t!==void 0&&t!==""}function rr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function nr(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function sr(t){return!t||t==="#"?"":t.startsWith("#")?t.slice(1):t}function te(t){let e=sr(t);return!e||e==="/"?[]:e.split("/").slice(1).map(n=>rr(n))}function ze(t,e){return`/${[...te(t),nr(e)].join("/")}`}function ir(t,e){let n=te(e),r=t;for(let s of n){if(Array.isArray(r)){let i=Number.parseInt(s,10);if(!Number.isInteger(i)||i<0||i>=r.length)return;r=r[i];continue}if(!p(r))return;r=r[s]}return r}function re(t){let e=t.instancePath??"",n=t.params??{};return t.keyword==="required"&&typeof n.missingProperty=="string"?ze(e,n.missingProperty):t.keyword==="additionalProperties"&&typeof n.additionalProperty=="string"?ze(e,n.additionalProperty):e}function or(t){let e=te(t);if(e.length===0)return"root";let n=[];for(let r of e)/^\d+$/.test(r)?n.push(`[${r}]`):n.length===0?n.push(r):n.push(`.${r}`);return n.join("")}function ar(t){if(t===void 0)return"[missing]";let e=JSON.stringify(t);return e?e.length>Le?`${e.slice(0,Le)}\u2026`:e:String(t)}function ur(t){let e=t.params??{};if(t.keyword==="required"&&typeof e.missingProperty=="string")return`required field "${e.missingProperty}"`;if(t.keyword==="type"&&typeof e.type=="string")return`type "${e.type}"`;if(t.keyword==="additionalProperties")return"no additional undocumented properties";if(t.keyword==="format"&&typeof e.format=="string")return`format "${e.format}"`}function cr(t,e,n){let r=t==="request"?"Request":"Response",s=e.params??{},i=or(n);return e.keyword==="required"&&typeof s.missingProperty=="string"?`${r} is missing required field "${i}".`:e.keyword==="additionalProperties"&&typeof s.additionalProperty=="string"?`${r} has undocumented field "${i}".`:e.keyword==="type"&&typeof s.type=="string"?`${r} field "${i}" must be ${s.type}.`:e.keyword==="enum"?`${r} field "${i}" has a value outside allowed enum values.`:e.keyword==="format"&&typeof s.format=="string"?`${r} field "${i}" does not match format "${s.format}".`:`${r} schema mismatch at "${i}": ${e.message??"validation error"}`}function Ke(t,e,n){let r=re(e),s=ir(t,r);return{summary:cr(n,e,r),keyword:e.keyword??null,path:r||"/",expected:ur(e)??null,actual:ar(s),suggestion:null,params:e.params??{},ajvMessage:e.message??"validation error"}}function dr(t,e,n,r){if(e===void 0||!t.schema)return;let s=n.validateSchema(t.schema,e,{coerce:!S(t.mediaType),target:"request"});if(!s.valid)for(let i of s.errors){let o=Ke(e,i,"request");r.push({ruleId:"schema-consistency",severity:"error",category:"schema",message:`Invalid ${t.in} parameter "${t.name}": ${typeof o.summary=="string"?o.summary:i.message??"schema mismatch"}`,exchangeIndex:n.exchange.index,operationId:n.matchedOperation?.operation.operationId,specSource:n.matchedOperation?.operation.specSource,target:"request",schemaPath:i.schemaPath,dataPath:re(i),details:{...o,parameter:{name:t.name,in:t.in}}})}}function pr(t,e){let n=[],r={query:new Set,header:new Set,cookie:new Set},s=new Set,i=!0;for(let a of e.operation.requestParameters)if(a.in==="querystring"){let{formSchema:u}=a;(!u||u.properties.size===0||u.checksOtherKeys&&!He(t))&&(i=!1);for(let l of u?.properties.keys()??[])r.query.add(l)}else a.in==="header"?r.header.add(a.name.toLowerCase()):(a.in==="query"||a.in==="cookie")&&(r[a.in].add(a.name),a.in==="query"&&a.style==="deepObject"&&s.add(a.name));let o=i?t.exchange.request.query.keys():[];for(let a of new Set(o)){if(r.query.has(a))continue;let u=ee(a);u&&s.has(u.parameterName)||n.push({ruleId:"schema-consistency",severity:"warning",category:"documentation",message:`Undocumented query parameter in traffic: "${a}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"})}for(let a of Object.keys(t.exchange.request.headers))ke(a,t.ignoreHeaders)||r.header.has(a.toLowerCase())||n.push({ruleId:"schema-consistency",severity:"info",category:"documentation",message:`Undocumented header in traffic: "${a}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"});return n}function He(t){let e=t.exchange.response;return e!==void 0&&e.status>=400&&e.status<500}function lr(t,e){let n=t.exchange.response;if(!n)return;let{responseStatuses:r,responseBodyContent:s}=e.operation,i=K(n.status,r);if(!(i===void 0||s[i]===void 0))return x(s[i],n.contentType)}function Ve(t,e,n,r){let s=n.validateSchema(t,e,{target:r});return s.valid?[]:s.errors.map(i=>{let o=Ke(e,i,r);return{ruleId:"schema-consistency",severity:"error",category:"schema",message:typeof o.summary=="string"?o.summary:`Schema mismatch (${r}): ${i.message??"validation error"}`,exchangeIndex:n.exchange.index,operationId:n.matchedOperation?.operation.operationId,specSource:n.matchedOperation?.operation.specSource,target:r,schemaPath:i.schemaPath,dataPath:re(i),details:o}})}var D=class{id="schema-consistency";analyze(e){let n=e.matchedOperation;if(!n)return[];let r=[];if(r.push(...pr(e,n)),!He(e)){for(let u of n.operation.requestParameters){if(e.ignoreCookies&&u.in==="cookie")continue;let l=H(u,e.exchange.request,n.pathParams,e.cookies);if(l===void 0&&S(u.mediaType)&&k(e.exchange.request.url).search!==""){r.push({ruleId:this.id,severity:"error",category:"schema",message:`Invalid ${u.in} parameter "${u.name}": the query string is not valid JSON.`,exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"});continue}if(u.required&&l===void 0){r.push({ruleId:this.id,severity:"error",category:"documentation",message:`Missing required ${u.in} parameter: "${u.name}"`,exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"});continue}dr(u,l,e,r)}let i=e.exchange.request.contentType,o=x(n.operation.requestBodyContent,i),a=Ne(e.exchange.request.bodyText);n.operation.requestBodyRequired&&!a&&r.push({ruleId:this.id,severity:"error",category:"documentation",message:"Missing required request body",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"}),o&&a&&S(i)&&(e.exchange.request.bodyJson===void 0?r.push({ruleId:this.id,severity:"error",category:"schema",message:"Request body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"}):r.push(...Ve(o,e.exchange.request.bodyJson,e,"request")))}let s=lr(e,n);if(s&&e.exchange.response&&Ne(e.exchange.response.bodyText)){let i=e.exchange.response.contentType;S(i)&&(e.exchange.response.bodyJson===void 0?r.push({ruleId:this.id,severity:"error",category:"schema",message:"Response body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"response"}):r.push(...Ve(s,e.exchange.response.bodyJson,e,"response")))}return r}};function ne(t){if(!t)return null;let[e]=t.trim().split(/\s+/,1);return e?e.toLowerCase():null}function Ue(t){return!!t.exchange.request.headers.authorization}function fr(t,e){return t?t.split(";").map(n=>n.trim()).some(n=>n.startsWith(`${e}=`)):!1}function mr(t,e){let n=t.matchedOperation?.operation;if(!n)return{schemeName:e,schemeType:"unknown",satisfied:!0,reason:"No matched OpenAPI operation."};let r=n.securitySchemes[e];if(!r)return{schemeName:e,schemeType:"missing",satisfied:!1,reason:"Security scheme is referenced but not defined in components.securitySchemes."};let s=String(r.type??"unknown");if(r.type==="apiKey"){let i=String(r.name??""),o=String(r.in??"header");if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:'apiKey scheme is missing the "name" field in the OpenAPI spec.'};if(o==="header"){let a=!!t.exchange.request.headers[i.toLowerCase()];return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey header "${i}".`:`Missing required apiKey header "${i}".`}}if(o==="query"){let a=t.exchange.request.query.has(i);return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey query parameter "${i}".`:`Missing required apiKey query parameter "${i}".`}}if(o==="cookie"){if(t.ignoreCookies)return{schemeName:e,schemeType:s,satisfied:!0,skipped:!0,reason:`Skipped apiKey cookie "${i}" validation because --ignore-cookies is enabled.`};let a=fr(t.exchange.request.headers.cookie,i);return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey cookie "${i}".`:`Missing required apiKey cookie "${i}".`}}return{schemeName:e,schemeType:s,satisfied:!1,reason:`Unsupported apiKey location "${o}" in OpenAPI security scheme.`}}if(r.type==="http"){let i=t.exchange.request.headers.authorization;if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Missing Authorization header."};let o=String(r.scheme??"").toLowerCase(),a=ne(i);if(!o)return{schemeName:e,schemeType:s,satisfied:!0,reason:"Authorization header is present and no specific HTTP auth scheme is documented."};if(!a)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Authorization header is malformed and does not include an auth scheme."};let u=a===o;return{schemeName:e,schemeType:s,satisfied:u,reason:u?`Authorization uses expected "${o}" scheme.`:`Authorization uses "${a}" but "${o}" is required.`}}if(r.type==="oauth2"||r.type==="openIdConnect"){let i=t.exchange.request.headers.authorization;if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Missing Authorization header for OAuth2/OpenID Connect scheme."};let o=ne(i),a=o==="bearer";return{schemeName:e,schemeType:s,satisfied:a,reason:a?"Authorization uses bearer token as expected for OAuth2/OpenID Connect.":`Authorization scheme "${o??"unknown"}" does not satisfy OAuth2/OpenID Connect (expected bearer).`}}return r.type==="mutualTLS"?{schemeName:e,schemeType:s,satisfied:!0,reason:"mutualTLS cannot be validated from HTTP traffic logs alone."}:{schemeName:e,schemeType:s,satisfied:!1,reason:`Unsupported security scheme type "${s}".`}}function hr(t){let e=t.matchedOperation?.operation.security;if(!e)return{satisfied:!0,requirements:[]};if(e.length===0)return{satisfied:!0,requirements:[]};let n=e.map((r,s)=>{let i=Object.keys(r);if(i.length===0)return{requirementIndex:s,satisfied:!0,schemeResults:[]};let o=i.map(a=>mr(t,a));return{requirementIndex:s,satisfied:o.every(a=>a.satisfied),schemeResults:o}});return{satisfied:n.some(r=>r.satisfied),requirements:n}}function gr(t){let e=[];for(let n of t.requirements)for(let r of n.schemeResults)r.satisfied||e.push({requirement:n.requirementIndex+1,schemeName:r.schemeName,reason:r.reason});return e}function De(t){let e=[];for(let n of t.requirements)for(let r of n.schemeResults)r.skipped&&e.push({requirement:n.requirementIndex+1,schemeName:r.schemeName,reason:r.reason});return e}function yr(t){if(t.length===0)return"All documented security requirements are satisfied.";let e=new Map;for(let r of t){let s=e.get(r.requirement);s?s.push(r):e.set(r.requirement,[r])}let n=Array.from(e.entries()).sort((r,s)=>r[0]-s[0]).map(([r,s])=>{let i=s.map(a=>a.schemeName).join(" + "),o=s.map(a=>a.reason).join(" ");return`Option ${r} (${i}): ${o}`});return n.length===1?`Authentication check failed. ${n[0]}`:`None of the documented authentication options matched. Any one of these options would satisfy the OpenAPI security requirements: ${n.join(" | ")}`}function Sr(t){return Array.from(t.exchange.request.query.keys()).filter(e=>{let n=e.toLowerCase();return n.includes("token")||n.includes("apikey")||n.includes("api_key")||n.includes("access_key")})}var vr=/^(?:(?:.+\.)?localhost|127(?:\.\d{1,3}){3}|::1)$/i;function wr(t){let e;try{e=new URL(t.url).hostname}catch{e=t.host?.replace(/:\d+$/,"")}return e?vr.test(e.replace(/^\[|\]$/g,"")):!1}function Rr(t){if(t.exchange.request.protocol!=="http:"||!t.exchange.request.protocolKnown||wr(t.exchange.request))return{flag:!1,hasAuthHeader:!1,sensitiveQueryKeys:[]};let e=Ue(t),n=Sr(t);return{flag:e||n.length>0,hasAuthHeader:e,sensitiveQueryKeys:n}}var U=class{id="security-baseline";analyze(e){if(!e.matchedOperation)return[];let n=[],r=hr(e);if(r.satisfied){let i=De(r);i.length>0&&n.push({ruleId:this.id,severity:"info",category:"security",message:"Some documented cookie-based security checks were skipped",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{summary:i.map(o=>`Skipped option ${o.requirement} (${o.schemeName}): ${o.reason}`).join(" "),skippedChecks:i}})}else{let i=gr(r);n.push({ruleId:this.id,severity:"error",category:"security",message:"Request does not satisfy documented OpenAPI security requirements",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{summary:yr(i),failedChecks:i,skippedChecks:De(r),authorizationScheme:ne(e.exchange.request.headers.authorization),hasAuthorizationHeader:Ue(e)}})}let s=Rr(e);return s.flag&&n.push({ruleId:this.id,severity:"warning",category:"security",message:"Potential credential exposure over insecure HTTP transport",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{protocol:e.exchange.request.protocol,hasAuthorizationHeader:s.hasAuthHeader,sensitiveQueryKeys:s.sensitiveQueryKeys}}),n}};var J=class{id="undocumented-endpoint";analyze(e){if(e.matchedOperation)return[];let{method:n,path:r,host:s}=e.exchange.request,o=e.matchMode==="strict-host"&&!e.hostCompatibleWithSpecServers?`Undocumented server: ${n} ${r} was sent to "${s}", which does not match any server in the description`:`Undocumented endpoint: ${n} ${r}`;return[{ruleId:this.id,severity:"error",category:"documentation",message:o,exchangeIndex:e.exchange.index,target:"request"}]}};var se={"undocumented-endpoint":()=>new J,"schema-consistency":()=>new D,"security-baseline":()=>new U,"owasp-api-top10":()=>new z},br=Object.keys(se),Or=["undocumented-endpoint","schema-consistency","security-baseline"];function Je(t){return!t||t.length===0?Or.map(e=>se[e]()):[...new Set(t)].map(e=>{let n=se[e];if(!n)throw new Error(`Unknown rule id: "${e}". Available rules: ${br.join(", ")}`);return n()})}var Qe=ce(lt(),1);var Ye=ce(ft(),1),Ge=Qe.default,We=Ye.default;function G(t,e){if(!p(t))return!1;let n=e==="request"?"readOnly":"writeOnly";return t[n]===!0||Array.isArray(t.allOf)&&t.allOf.some(r=>p(r)&&r[n]===!0)}function Xe(t,e,n,r=new WeakSet){if(!p(t)||r.has(t))return!1;r.add(t);let s=t.properties;return p(s)&&G(s[e],n)?!0:[t.allOf,t.oneOf,t.anyOf].some(i=>Array.isArray(i)&&i.some(o=>Xe(o,e,n,r)))}var Ir=new Set(["items","additionalItems","additionalProperties","unevaluatedItems","unevaluatedProperties","contains","propertyNames","not","if","then","else"]),Pr=new Set(["allOf","anyOf","oneOf","prefixItems"]),kr=new Set(["properties","patternProperties","dependentSchemas","$defs","definitions"]);function Ze(t,e,n=new WeakSet){if(!p(t))return t;if(n.has(t))return!0;n.add(t);let r=i=>Ze(i,e,n),s={};for(let[i,o]of Object.entries(t))Ir.has(i)?s[i]=Array.isArray(o)?o.map(r):r(o):Pr.has(i)&&Array.isArray(o)?s[i]=o.map(r):kr.has(i)&&p(o)?s[i]=Object.fromEntries(Object.entries(o).map(([a,u])=>[a,r(u)])):s[i]=o;return Array.isArray(t.required)&&(s.required=t.required.filter(i=>typeof i!="string"||!Xe(t,i,e))),n.delete(t),s}var F=class{ajv;fallbackAjv;objectSchemaCaches={none:new WeakMap,request:new WeakMap,response:new WeakMap};scalarSchemaCache=new Map;constructor(e){let n={strict:!1,allErrors:!0,allowUnionTypes:!0,discriminator:!0,coerceTypes:e?.coerceTypes?"array":!1,validateFormats:!0,verbose:!0,formats:{enum:!0}};this.ajv=new Ge(n),this.fallbackAjv=new Ge({...n,discriminator:!1}),We(this.ajv),We(this.fallbackAjv)}validate(e,n,r){if(e===void 0)return{valid:!0,errors:[]};let s;try{s=this.getOrCompileValidator(e,r)}catch(a){return{valid:!1,errors:[{message:`Schema compilation failed: ${a.message}`}]}}let i=!!s(n),o=s.errors??[];return{valid:i,errors:o}}getOrCompileValidator(e,n){if(p(e)){let o=this.objectSchemaCaches[n??"none"],a=o.get(e);if(a)return a;let u=n?Ze(e,n):e,l=this.compileSchema(u);return o.set(e,l),l}let r=`${n??"none"}:${JSON.stringify(e)}`,s=this.scalarSchemaCache.get(r);if(s)return s;let i=this.compileSchema(e);return this.scalarSchemaCache.set(r,i),i}compileSchema(e){try{return this.ajv.compile(e)}catch{return this.fallbackAjv.compile(e)}}};function et(t){switch(t.kind){case"operation":return"operation";case"parameter":return`parameter:${t.in}:${t.name}`;case"response":return`response:${t.status}`;case"property":return`property:${t.target}:${t.status??""}:${t.path}`}}function Q(t,e){let n=et(e);t.has(n)||t.set(n,{item:e,covered:!1})}function M(t,e){let n=t.get(et(e));n&&(n.covered=!0)}function tt(t,e){return t?`${t}.${e}`:e}function j(t,e,n,r,s){if(!(!p(t)||s.has(t))){s.add(t);for(let i of[t.allOf,t.oneOf,t.anyOf])if(Array.isArray(i))for(let o of i)j(o,e,n,r,s);if(p(t.properties))for(let[i,o]of Object.entries(t.properties)){if(G(o,e.target))continue;let a=tt(n,i);Q(r,{kind:"property",...e,path:a}),j(o,e,a,r,s)}p(t.items)&&j(t.items,e,`${n}[]`,r,s),s.delete(t)}}function B(t,e,n,r,s,i){if(!(!p(e)||i.has(e))){i.add(e);for(let o of[e.allOf,e.oneOf,e.anyOf])if(Array.isArray(o))for(let a of o)B(t,a,n,r,s,i);if(p(e.properties)&&p(t))for(let[o,a]of Object.entries(e.properties)){if(t[o]===void 0)continue;let u=tt(r,o);M(s,{kind:"property",...n,path:u}),B(t[o],a,n,u,s,i)}if(p(e.items)&&Array.isArray(t))for(let o of t)B(o,e.items,n,`${r}[]`,s,i);i.delete(e)}}function Ar(t,e){let n=new Map;Q(n,{kind:"operation"});for(let r of t.requestParameters){if(e&&r.in==="cookie")continue;let s=[...r.formSchema?.properties??[]].filter(([,i])=>!G(i,"request")).map(([i])=>`${r.name}.${i}`);for(let i of s.length>0?s:[r.name])Q(n,{kind:"parameter",name:i,in:r.in})}for(let[r,s]of Object.entries(t.requestBodyContent))S(r)&&j(s,{target:"request"},"",n,new Set);for(let r of t.responseStatuses){Q(n,{kind:"response",status:r});for(let[s,i]of Object.entries(t.responseBodyContent[r]??{}))S(s)&&j(i,{target:"response",status:r},"",n,new Set)}return{operation:t,entries:n}}function xr(t){return t.request.bodyJson!==void 0||t.response?.bodyJson!==void 0}function W(t,e){let n={covered:0,total:0};for(let r of t)for(let s of r.entries.values())s.item.kind===e&&(n.total+=1,s.covered&&(n.covered+=1));return n}function Cr(t){let e={method:t.operation.method.toUpperCase(),path:t.operation.pathTemplate,operationId:t.operation.operationId,missing:[],covered:[]};for(let n of t.entries.values())(n.covered?e.covered:e.missing).push(n.item);return e}var Y=class{states=new Map;exchanges={total:0,matched:0,withBody:0};constructor(e){for(let n of e.openApiIndex.operationsByMethod.values())for(let r of n)this.states.set(r,Ar(r,e.ignoreCookies))}record(e,n,r){if(this.exchanges.total+=1,!n)return;let s=this.states.get(n.operation);if(!s)return;this.exchanges.matched+=1,xr(e)&&(this.exchanges.withBody+=1);let{operation:i,pathParams:o}=n,{entries:a}=s;M(a,{kind:"operation"});for(let c of i.requestParameters){let m=H(c,e.request,o,r);if(m!==void 0&&(M(a,{kind:"parameter",name:c.name,in:c.in}),c.formSchema&&p(m)))for(let v of Object.keys(m))M(a,{kind:"parameter",name:`${c.name}.${v}`,in:c.in})}if(e.request.bodyJson!==void 0){let c=x(i.requestBodyContent,e.request.contentType);B(e.request.bodyJson,c,{target:"request"},"",a,new Set)}let u=e.response;if(!u)return;let l=K(u.status,i.responseStatuses);if(l!==void 0&&(M(a,{kind:"response",status:l}),u.bodyJson!==void 0)){let c=x(i.responseBodyContent[l]??{},u.contentType);B(u.bodyJson,c,{target:"response",status:l},"",a,new Set)}}finalize(){let e=Array.from(this.states.values()).sort((n,r)=>n.operation.pathTemplate.localeCompare(r.operation.pathTemplate)||n.operation.method.localeCompare(r.operation.method));return{exchanges:this.exchanges,totals:{operations:W(e,"operation"),parameters:W(e,"parameter"),properties:W(e,"property"),responses:W(e,"response")},operations:e.map(Cr)}}};var $r=10,rt={info:0,warning:1,error:2};function Er(){return{totalExchanges:0,documentedExchanges:0,undocumentedExchanges:0,skippedExchanges:0,hostCompatibleExchanges:0,findingsBySeverity:{info:0,warning:0,error:0},findingsByRule:{}}}function qr(t,e){t.findingsBySeverity[e.severity]+=1,t.findingsByRule[e.ruleId]=(t.findingsByRule[e.ruleId]??0)+1}function Tr(t,e){return{...t,id:st(),method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function Fr(t,e){return{exchangeIndex:t.exchangeIndex,ruleId:t.ruleId,severity:t.severity,category:t.category,message:t.message,occurrences:1,operationId:t.operationId,specSource:t.specSource,target:t.target,schemaPath:t.schemaPath,dataPath:t.dataPath,details:t.details,method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function Mr(t,e){if(!e)return;t.operationId||(t.operationId=e.operation.operationId),t.specSource||(t.specSource=e.operation.specSource);let n=t.details??{};if(!p(n)){t.details={operationPathTemplate:e.operation.pathTemplate};return}typeof n.operationPathTemplate!="string"&&(n.operationPathTemplate=e.operation.pathTemplate),t.details=n}function jr(t){let e=new Set,n=!1;for(let r of t.operationsByMethod.values())for(let s of r)for(let i of s.servers)i.host?e.add(i.host):n=!0;return{specServerHosts:e,hasHostlessSpecServer:n}}async function Br(t,e){let n=[];for(let r of t)try{let s=await r.analyze(e);s.length>0&&n.push(...s)}catch(s){R.warn(`Rule "${r.id}" failed to execute: ${s.message}
18
+ `)}return n}var nt=class t{startedAt=Date.now();runId=st();previewLimit;rules;schemaValidator=new F;coercingSchemaValidator=new F({coerceTypes:!0});options;coverage;counters=Er();findings=[];previewFindings=[];problemGroupsByRule={};problemKeyStats=new Map;totalProblemGroups=0;server;ignoreHeaders;minSeverityRank;specServerHosts;hasHostlessSpecServer;constructor(e,n){this.options=e,this.rules=n,this.server=Ae(e.server),this.ignoreHeaders=e.ignoreHeaders?Pe(e.ignoreHeaders):void 0;let{specServerHosts:r,hasHostlessSpecServer:s}=jr(e.openApiIndex);this.specServerHosts=r,this.hasHostlessSpecServer=s,this.minSeverityRank=rt[e.minSeverity??"info"],this.previewLimit=e.previewFindingsLimit&&e.previewFindingsLimit>0?e.previewFindingsLimit:$r,this.coverage=e.coverage?new Y({openApiIndex:e.openApiIndex,ignoreCookies:e.ignoreCookies??!1}):void 0}static create(e){if(e.openApiIndex.loadedOperations===0)throw new Error("No OpenAPI operations available to validate traffic against.");return new t(e,Je(e.activeRules))}async process(e){this.counters.totalExchanges+=1;let n=Me(e.request.headers.cookie),r;if(this.server!==void 0&&(r=xe(e.request,this.server),r===void 0))return this.counters.skippedExchanges+=1,this.coverage?.record(e,null,n),[];let s=this.isHostCompatible(e.request.host);s&&(this.counters.hostCompatibleExchanges+=1);let i=Ee(this.options.openApiIndex,e,this.options.matchMode,r);i?this.counters.documentedExchanges+=1:this.counters.undocumentedExchanges+=1,this.coverage?.record(e,i,n);let o=await Br(this.rules,{exchange:e,matchedOperation:i,matchMode:this.options.matchMode,hostCompatibleWithSpecServers:r!==void 0||s,ignoreCookies:this.options.ignoreCookies??!1,ignoreHeaders:this.ignoreHeaders,cookies:n,validateSchema:(u,l,c)=>c?.coerce?this.coercingSchemaValidator.validate(u,l,c?.target):this.schemaValidator.validate(u,l,c?.target)}),a=[];for(let u of o){if(rt[u.severity]<this.minSeverityRank)continue;Mr(u,i);let l=Tr(u,e);this.findings.push(l),a.push(l),qr(this.counters,u);let c=L({ruleId:u.ruleId,severity:u.severity,message:u.message,operationId:u.operationId,path:e.request.path,target:u.target,schemaPath:u.schemaPath}),m=this.problemKeyStats.get(c);if(m){m.occurrences+=1,m.previewIndex!==null&&(this.previewFindings[m.previewIndex].occurrences=m.occurrences);continue}if(this.totalProblemGroups+=1,this.problemGroupsByRule[u.ruleId]=(this.problemGroupsByRule[u.ruleId]??0)+1,this.previewFindings.length<this.previewLimit){let v=this.previewFindings.length;this.previewFindings.push(Fr(u,e)),this.problemKeyStats.set(c,{occurrences:1,previewIndex:v});continue}this.problemKeyStats.set(c,{occurrences:1,previewIndex:null})}return a}isHostCompatible(e){return!e||this.hasHostlessSpecServer||this.specServerHosts.has(e.toLowerCase())}finalize(){let e={runId:this.runId,totalExchanges:this.counters.totalExchanges,documentedExchanges:this.counters.documentedExchanges,undocumentedExchanges:this.counters.undocumentedExchanges,skippedExchanges:this.counters.skippedExchanges,hostCompatibleExchanges:this.counters.hostCompatibleExchanges,findingsBySeverity:this.counters.findingsBySeverity,findingsByRule:this.counters.findingsByRule,problemGroupsByRule:this.problemGroupsByRule,totalProblemGroups:this.totalProblemGroups,durationMs:Date.now()-this.startedAt,previewFindings:this.previewFindings,previewLimit:this.previewLimit,previewTruncated:this.totalProblemGroups>this.previewFindings.length};return{runId:this.runId,summary:e,findings:this.findings,coverage:this.coverage?.finalize()}}};import{stat as _r}from"node:fs/promises";var Lr=["get","put","post","delete","patch","head","options","trace"],Nr=new Set(["query","querystring","header","path","cookie"]),zr=/^(default|[1-5](\d{2}|xx))$/i;function Vr(t){return Lr.includes(t)}function Kr(t){return Nr.has(t)}function it(t,e){if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!p(r))continue;let s=r.in;if(typeof s!="string"||!Kr(s))continue;let i=String(r.name??""),o=s==="querystring"?Object.entries(ie(r.content)):[],[a]=o,u=a?Ie(a[0]):void 0,l=s==="querystring"?a?.[1]:r.schema;s==="querystring"&&!a?R.warn(`Parameter "${i}" (querystring) of "${e}" has no content schema, so its value is not validated. Run \`redocly lint\` to check the description.
19
+ `):o.length>1&&R.warn(`Parameter "${i}" (querystring) of "${e}" has more than one media type, so only "${u}" is used. Run \`redocly lint\` to check the description.
20
+ `),n.push({name:i,in:s,required:!!r.required||s==="path",style:typeof r.style=="string"?r.style:void 0,schema:l,mediaType:u,formSchema:u===je?Be(l):void 0})}return n}function ot(t){let e=t.in==="header";return`${t.in}:${e?t.name.toLowerCase():t.name}`}function Hr(t,e){let n=new Map;for(let r of t)n.set(ot(r),r);for(let r of e)n.set(ot(r),r);return Array.from(n.values())}function ie(t){let e={};if(!p(t))return e;for(let[n,r]of Object.entries(t))p(r)&&"schema"in r&&(e[n.toLowerCase()]=r.schema);return e}function Dr(t){return p(t)?ie(t.content):{}}function Ur(t){let e={};for(let[n,r]of Object.entries(t))!p(r)||!("content"in r)||(e[n]=ie(r.content));return e}function Jr(t,e,n){let r=t??e??n;return!Array.isArray(r)||r.length===0?[V("/")]:r.map(s=>{if(!p(s))return V("/");let i=typeof s.url=="string"?s.url:"/",o=p(s.variables)?s.variables:void 0;return V(i,o)})}function Gr(t,e,n){return n||`${t.toUpperCase()} ${e}`}function Wr(t){try{let e=ge(t.parsed);return he(e)==="oas3"?e:null}catch{return null}}function at(t){return Array.isArray(t)?t:void 0}function Qr(t,e){let n,r,s={},i="/",o=[],a;return{Root:{enter(u){n=u.servers,r=u.security;let l=p(u.components)?u.components.securitySchemes:void 0;s=p(l)?l:{}}},Paths:{PathItem:{enter(u,l){i=Fe(String(l.key)),o=it(u.parameters,i),a=u.servers},Operation:{enter(u,l){let c=String(l.key);if(!Vr(c))return;let m=Hr(o,it(u.parameters,`${c.toUpperCase()} ${i}`)),v=Oe(i),_=Jr(u.servers,a,n),P=u.requestBody,f=p(u.responses)?Object.fromEntries(Object.entries(u.responses).filter(([X])=>zr.test(X))):{},h={operationId:Gr(c,i,typeof u.operationId=="string"?u.operationId:void 0),method:c,pathTemplate:i,pathRegex:v.regex,pathParams:v.params,pathScore:v.score,servers:_,requestParameters:m,requestBodyContent:Dr(P),requestBodyRequired:p(P)&&!!P.required,responseStatuses:Object.keys(f),responseBodyContent:Ur(f),security:at(u.security)??at(r),securitySchemes:s,specSource:t},y=e.get(c)??[];y.push(h),e.set(c,y)}}}}}}function Yr(t,e,n,r,s){let i=de(n.extendTypes(pe(e),e),n),o=new Map,a={problems:[],specVersion:e,config:n,visitorsData:{}},u=ye([{severity:"warn",ruleId:"drift-index",visitor:Qr(r,s)}],i);Se({document:t,rootType:i.Root,normalizedVisitors:u,resolvedRefMap:o,ctx:a})}function Xr(t){return`${t.host??""}|${t.basePath}`}function Zr(t){for(let e of t.values()){let n=new Map;for(let r of e){let s=n.get(r.pathRegex.source)??[];s.push(r),n.set(r.pathRegex.source,s)}for(let r of n.values()){let s=new Map;for(let i of r)for(let o of i.servers){let a=Xr(o),u=s.get(a)??new Set;u.add(i.specSource),s.set(a,u)}for(let i of s.values())if(i.size>1){let[o]=r;R.warn(`"${o.method.toUpperCase()} ${o.pathTemplate}" is documented for the same server in multiple descriptions (${Array.from(i).join(", ")}). Matching traffic is validated against only one of them.
21
+ `);break}}}}function en(t,e){for(let r of t.values())r.sort((s,i)=>i.pathScore-s.pathScore);let n=Array.from(t.values()).reduce((r,s)=>r+s.length,0);return{operationsByMethod:t,loadedSpecs:e,loadedOperations:n}}async function tn(t){return(await _r(t)).isDirectory()?{specFiles:await we(t),fromDirectory:!0}:{specFiles:[t],fromDirectory:!1}}async function rs(t,e){let{specFiles:n,fromDirectory:r}=await tn(t),s=new Map,i=new le(e.resolve),o=0;for(let a of n){let u=await i.resolveDocument(null,a,!0);if(u instanceof Error){R.warn(`Failed to load OpenAPI description ${a}: ${u.message}
22
+ `);continue}let l=Wr(u);if(!l){r||R.warn(`Skipping ${a}: not an OpenAPI 3.x description.
23
+ `);continue}let c;try{let{bundle:m}=await ve({config:e,doc:u,externalRefResolver:i,dereference:!0});c=m}catch(m){R.warn(`Failed to bundle OpenAPI description ${a}: ${m.message}
24
+ `);continue}o+=1,Yr(c,l,e,a,s)}return o>1&&Zr(s),en(s,o)}function ss(t){return t.split(",").map(e=>e.trim()).filter(Boolean)}export{an as a,nt as b,rs as c,ss as d};
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  var __filename = __fileURLToPath(import.meta.url);
6
6
  var __dirname = __pathDirname(__filename);
7
- import{b as A,c as F,d as S,e as l}from"./UXSV2J6V.js";import"./EXCIOEBN.js";import{e as $,g as x,n as I,o as P}from"./W7VT3BOM.js";import{f as p}from"./MJYI42E6.js";import"./LRUXN6H5.js";import{aa as w,ia as n,l as u}from"./AP2GA7RS.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";async function O({argv:t,config:o,version:c}){let h=performance.now(),j=Date.now(),{organization:g,project:d,"mount-path":z,verbose:D}=t,f=t.domain||x(),e,r,y,b,s=[];try{let i=$();if(e=P(t.files,(a,T)=>{n.warn(`File ${a} is overwritten by ${T}
7
+ import{b as A,c as F,d as S,e as l}from"./REIGI2Y7.js";import"./US7X4XPD.js";import{e as $,g as x,n as I,o as P}from"./5NOJ76EP.js";import{f as p}from"./6NB3FKVN.js";import"./LRUXN6H5.js";import{aa as w,ia as n,l as u}from"./22EANOP2.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";async function O({argv:t,config:o,version:c}){let h=performance.now(),j=Date.now(),{organization:g,project:d,"mount-path":z,verbose:D}=t,f=t.domain||x(),e,r,y,b,s=[];try{let i=$();if(e=P(t.files,(a,T)=>{n.warn(`File ${a} is overwritten by ${T}
8
8
  `)}),!e.length)return p("push",h,"No files to upload");let m=await I({domain:f,apiKey:i,organization:g,project:d,mountPath:z,files:e,defaultBranch:t["default-branch"],commit:{message:t.message,branchName:t.branch,sha:t["commit-sha"],url:t["commit-url"],createdAt:t["created-at"],namespace:t.namespace,repository:t.repository,author:U(t.author)},version:c,replace:t.replace,onUploadStart:a=>{n.info(`Uploading to ${a.mountPath} ${e.length} ${u("file",e.length)}:
9
9
  `)},onSunsetWarning:a=>s.push(a),onSlugDeprecated:S});r=m.pushId,y=m.organizationId,b=m.projectId}catch(i){l("push",s),F("\u2717 File upload failed.",i)}for(let i of e)n.info(w(`\u2713 ${i.name}
10
10
  `));return n.info(`
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  var __filename = __fileURLToPath(import.meta.url);
6
6
  var __dirname = __pathDirname(__filename);
7
- import{a,b,c,d,e}from"./GC26XZYZ.js";import"./2U6O26CV.js";import"./BZBFESBB.js";import"./4WAQNM63.js";import"./WZXA5XPB.js";import"./AP2GA7RS.js";import"./NEWT5A6S.js";import"./UW4UC7ZI.js";import"./RFWIIJFG.js";export{e as phpDocs,c as phpGenerator,d as phpSample,a as phpType,b as renderPhpModels};
7
+ import{a,b,c,d,e}from"./I6AAWNTY.js";import"./XJE2OFDN.js";import"./C67OKMFJ.js";import"./SS6PCAMM.js";import"./WZXA5XPB.js";import"./22EANOP2.js";import"./NEWT5A6S.js";import"./UW4UC7ZI.js";import"./RFWIIJFG.js";export{e as phpDocs,c as phpGenerator,d as phpSample,a as phpType,b as renderPhpModels};
@@ -91,29 +91,30 @@ discriminated union on `kind`: `scalar`, `array`, `object`, `record`, `ref`,
91
91
 
92
92
  ## Helpers (import from '@redocly/client-generator')
93
93
 
94
- | Helper | Use |
95
- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
96
- | `flattenAllOf(schema, model)` | The merged property view of allOf compositions — languages without intersection types render this. |
97
- | `deref(schema, model)` | Follow a `ref` chain to the schema it names (cycle-guarded). |
98
- | `jsonSuccessSchema(op)` / `sseResponse(op)` | The primary JSON success schema; the `text/event-stream` response when the operation streams. |
99
- | `isMultipartBody(op)` | Whether the request body is multipart. |
100
- | `isBinaryContentType(contentType)` | Whether a body of this content type is bytes (archives, PDF, images, media) — decode it as a Blob, not JSON or text. |
101
- | `serverUrlParts(server)` | A server-URL template as literal/variable parts, ready for any concatenation syntax. |
102
- | `securityRequirements(op, model)` | The operation's security as OR-alternatives of AND-sets, denormalized against the declared schemes. |
103
- | `paginationItemSchema(pageSchema, itemsPointer, model)` | The raw element schema behind a pagination rule's `items` pointer — a `ref` element keeps its name. |
104
- | `discriminatorCases(schema, model)` | `{ property, cases }` dispatch table for discriminated unions. |
105
- | `isNullable(schema)` / `unwrapNullable(schema)` | Detect and strip `null` union members (`Optional[T]`, pointers, `Option<T>`). |
106
- | `enumValues(schema)` | Values plus SCREAMING_SNAKE member-name suggestions. |
107
- | `headerCoerceType(schema, model)` | Response-header coerce hint (`integer`/`number`/`boolean`/`string`) through refs, nullables, and allOf wrappers. |
108
- | `casing` / `identifierFor(name, { style, reserved })` | camel/pascal/snake/screaming; keyword-safe identifiers (`RESERVED_WORDS.python/go/typescript` shipped). |
109
- | `uniqueIdentifiers(names, { style, reserved, taken })` | The same, made unique among themselves and among names you already took — for a signature that takes one argument per parameter. |
110
- | `Printer` | Indentation-aware text builder — no manual whitespace bookkeeping. |
111
- | `docText(description)` | Description as trimmed lines for any comment syntax. |
112
- | `schemaAtPointer(schema, pointer, model)` | Resolve an RFC 6901 JSON pointer over a schema (through refs and allOf) — e.g. a pagination `items` pointer to its element type. |
113
- | `paginationRuleFor(op, config)` | The pagination rule that applies to an operation (per-op config > extension > fitting convention), normalized. |
114
- | `renderReferencePage(model, options)` | The Markdown reference page a generator's `docs` hook returns — your `sample` hook supplies its call snippets. |
115
- | `NotSupportedError` | Throw it to reject an option the generator can't honor — the CLI prints the message as a user error, not a crash. |
116
- | `AUTHORING_HELPER_NAMES` | The list of the above (introspection). |
94
+ | Helper | Use |
95
+ | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
96
+ | `flattenAllOf(schema, model)` | The merged property view of allOf compositions — languages without intersection types render this. |
97
+ | `deref(schema, model)` | Follow a `ref` chain to the schema it names (cycle-guarded). |
98
+ | `jsonSuccessSchema(op)` / `sseResponse(op)` | The primary JSON success schema; the `text/event-stream` response when the operation streams. |
99
+ | `isMultipartBody(op)` | Whether the request body is multipart. |
100
+ | `isUntypedMultipartBody(op)` | Whether the request body is multipart with a schema that is neither an object nor a `$ref`, so the caller supplies the encoded body. |
101
+ | `isBinaryContentType(contentType)` | Whether a body of this content type is bytes (archives, PDF, images, media) — decode it as a Blob, not JSON or text. |
102
+ | `serverUrlParts(server)` | A server-URL template as literal/variable parts, ready for any concatenation syntax. |
103
+ | `securityRequirements(op, model)` | The operation's security as OR-alternatives of AND-sets, denormalized against the declared schemes. |
104
+ | `paginationItemSchema(pageSchema, itemsPointer, model)` | The raw element schema behind a pagination rule's `items` pointer — a `ref` element keeps its name. |
105
+ | `discriminatorCases(schema, model)` | `{ property, cases }` dispatch table for discriminated unions. |
106
+ | `isNullable(schema)` / `unwrapNullable(schema)` | Detect and strip `null` union members (`Optional[T]`, pointers, `Option<T>`). |
107
+ | `enumValues(schema)` | Values plus SCREAMING_SNAKE member-name suggestions. |
108
+ | `headerCoerceType(schema, model)` | Response-header coerce hint (`integer`/`number`/`boolean`/`string`) through refs, nullables, and allOf wrappers. |
109
+ | `casing` / `identifierFor(name, { style, reserved })` | camel/pascal/snake/screaming; keyword-safe identifiers (`RESERVED_WORDS.python/go/typescript` shipped). |
110
+ | `uniqueIdentifiers(names, { style, reserved, taken })` | The same, made unique among themselves and among names you already took — for a signature that takes one argument per parameter. |
111
+ | `Printer` | Indentation-aware text builder — no manual whitespace bookkeeping. |
112
+ | `docText(description)` | Description as trimmed lines for any comment syntax. |
113
+ | `schemaAtPointer(schema, pointer, model)` | Resolve an RFC 6901 JSON pointer over a schema (through refs and allOf) — e.g. a pagination `items` pointer to its element type. |
114
+ | `paginationRuleFor(op, config)` | The pagination rule that applies to an operation (per-op config > extension > fitting convention), normalized. |
115
+ | `renderReferencePage(model, options)` | The Markdown reference page a generator's `docs` hook returns — your `sample` hook supplies its call snippets. |
116
+ | `NotSupportedError` | Throw it to reject an option the generator can't honor — the CLI prints the message as a user error, not a crash. |
117
+ | `AUTHORING_HELPER_NAMES` | The list of the above (introspection). |
117
118
 
118
119
  Worked example: the built-in `python` generator
119
120
  (`packages/client-generator/src/generators/python/index.ts` in the Redocly CLI repo) is
@@ -1,4 +1,4 @@
1
- // Ejected from @redocly/client-generator@0.4.25 — the built-in "cli" generator.
1
+ // Ejected from @redocly/client-generator@0.5.1 — the built-in "cli" generator.
2
2
  // This file is yours: edit freely; the generated client stays machine-owned and is
3
3
  // rebuilt by `redocly generate-client`. Newer generator versions merge in with
4
4
  // `redocly eject-generator cli --update`.
@@ -1,4 +1,4 @@
1
- // Ejected from @redocly/client-generator@0.4.25 — the built-in "cli" generator.
1
+ // Ejected from @redocly/client-generator@0.5.1 — the built-in "cli" generator.
2
2
  // This file is yours: edit freely; the generated client stays machine-owned and is
3
3
  // rebuilt by `redocly generate-client`. Newer generator versions merge in with
4
4
  // `redocly eject-generator cli --update`.
@@ -1,4 +1,4 @@
1
- // Ejected from @redocly/client-generator@0.4.25 — the built-in "cli" generator.
1
+ // Ejected from @redocly/client-generator@0.5.1 — the built-in "cli" generator.
2
2
  // This file is yours: edit freely; the generated client stays machine-owned and is
3
3
  // rebuilt by `redocly generate-client`. Newer generator versions merge in with
4
4
  // `redocly eject-generator cli --update`.
@@ -86,5 +86,5 @@ export default {
86
86
  docs: cliDocs,
87
87
  requires: ["typescript","zod"],
88
88
  errorModes: ["throw"],
89
- requiresGenerator: '^0.4.25',
89
+ requiresGenerator: '^0.5.1',
90
90
  };