@redocly/client-generator 0.7.12 → 0.8.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 (132) hide show
  1. package/README.md +1 -1
  2. package/eject-assets/AGENTS.md +1 -1
  3. package/eject-assets/generators/cli/docs.ts +1 -1
  4. package/eject-assets/generators/cli/engine-source.ts +1 -1
  5. package/eject-assets/generators/cli/index.ts +2 -2
  6. package/eject-assets/generators/cli/render.ts +1 -1
  7. package/eject-assets/generators/go/client.ts +1 -1
  8. package/eject-assets/generators/go/descriptor.ts +1 -1
  9. package/eject-assets/generators/go/index.ts +2 -2
  10. package/eject-assets/generators/go/models.ts +1 -1
  11. package/eject-assets/generators/go/naming.ts +1 -1
  12. package/eject-assets/generators/go/operations.ts +1 -1
  13. package/eject-assets/generators/go/pagination.ts +1 -1
  14. package/eject-assets/generators/go/types.ts +1 -1
  15. package/eject-assets/generators/java/client.ts +66 -0
  16. package/eject-assets/generators/java/descriptor.ts +72 -0
  17. package/eject-assets/generators/java/index.ts +245 -0
  18. package/eject-assets/generators/java/models.ts +362 -0
  19. package/eject-assets/generators/java/naming.ts +135 -0
  20. package/eject-assets/generators/java/operations.ts +300 -0
  21. package/eject-assets/generators/java/pagination.ts +94 -0
  22. package/eject-assets/generators/java/types.ts +103 -0
  23. package/eject-assets/generators/mock/faker.ts +1 -1
  24. package/eject-assets/generators/mock/index.ts +2 -2
  25. package/eject-assets/generators/mock/render.ts +1 -1
  26. package/eject-assets/generators/mock/sample.ts +1 -1
  27. package/eject-assets/generators/mock/values.ts +1 -1
  28. package/eject-assets/generators/php/client.ts +1 -1
  29. package/eject-assets/generators/php/descriptor.ts +1 -1
  30. package/eject-assets/generators/php/index.ts +2 -2
  31. package/eject-assets/generators/php/models.ts +1 -1
  32. package/eject-assets/generators/php/naming.ts +1 -1
  33. package/eject-assets/generators/php/operations.ts +1 -1
  34. package/eject-assets/generators/php/pagination.ts +1 -1
  35. package/eject-assets/generators/php/types.ts +1 -1
  36. package/eject-assets/generators/python/client.ts +1 -1
  37. package/eject-assets/generators/python/descriptor.ts +1 -1
  38. package/eject-assets/generators/python/index.ts +2 -2
  39. package/eject-assets/generators/python/models.ts +1 -1
  40. package/eject-assets/generators/python/naming.ts +1 -1
  41. package/eject-assets/generators/python/operations.ts +1 -1
  42. package/eject-assets/generators/python/pagination.ts +1 -1
  43. package/eject-assets/generators/python/types.ts +1 -1
  44. package/eject-assets/generators/swr/index.ts +2 -2
  45. package/eject-assets/generators/swr/render.ts +1 -1
  46. package/eject-assets/generators/tanstack-query/index.ts +2 -2
  47. package/eject-assets/generators/tanstack-query/render.ts +1 -1
  48. package/eject-assets/generators/transformers/index.ts +2 -2
  49. package/eject-assets/generators/transformers/render.ts +1 -1
  50. package/eject-assets/generators/typescript/banner.ts +1 -1
  51. package/eject-assets/generators/typescript/client.ts +1 -1
  52. package/eject-assets/generators/typescript/descriptor.ts +1 -1
  53. package/eject-assets/generators/typescript/index.ts +2 -2
  54. package/eject-assets/generators/typescript/inline-runtime.ts +1 -1
  55. package/eject-assets/generators/typescript/operation-signature.ts +1 -1
  56. package/eject-assets/generators/typescript/operation-types.ts +1 -1
  57. package/eject-assets/generators/typescript/operations.ts +1 -1
  58. package/eject-assets/generators/typescript/response-headers.ts +1 -1
  59. package/eject-assets/generators/typescript/type-guards.ts +1 -1
  60. package/eject-assets/generators/typescript/types.ts +1 -1
  61. package/eject-assets/generators/zod/index.ts +2 -2
  62. package/eject-assets/generators/zod/schemas.ts +1 -1
  63. package/eject-assets/skills/client-generators/SKILL.md +1 -1
  64. package/eject-assets/skills/java-generator/SKILL.md +161 -0
  65. package/lib/authoring/naming.d.ts +1 -1
  66. package/lib/authoring/naming.d.ts.map +1 -1
  67. package/lib/authoring/naming.js +11 -0
  68. package/lib/authoring/naming.js.map +1 -1
  69. package/lib/generators/index.d.ts.map +1 -1
  70. package/lib/generators/index.js +2 -0
  71. package/lib/generators/index.js.map +1 -1
  72. package/lib/generators/java/client.d.ts +5 -0
  73. package/lib/generators/java/client.d.ts.map +1 -0
  74. package/lib/generators/java/client.js +41 -0
  75. package/lib/generators/java/client.js.map +1 -0
  76. package/lib/generators/java/descriptor.d.ts +14 -0
  77. package/lib/generators/java/descriptor.d.ts.map +1 -0
  78. package/lib/generators/java/descriptor.js +48 -0
  79. package/lib/generators/java/descriptor.js.map +1 -0
  80. package/lib/generators/java/index.d.ts +14 -0
  81. package/lib/generators/java/index.d.ts.map +1 -0
  82. package/lib/generators/java/index.js +173 -0
  83. package/lib/generators/java/index.js.map +1 -0
  84. package/lib/generators/java/models.d.ts +13 -0
  85. package/lib/generators/java/models.d.ts.map +1 -0
  86. package/lib/generators/java/models.js +231 -0
  87. package/lib/generators/java/models.js.map +1 -0
  88. package/lib/generators/java/naming.d.ts +36 -0
  89. package/lib/generators/java/naming.d.ts.map +1 -0
  90. package/lib/generators/java/naming.js +110 -0
  91. package/lib/generators/java/naming.js.map +1 -0
  92. package/lib/generators/java/operations.d.ts +33 -0
  93. package/lib/generators/java/operations.d.ts.map +1 -0
  94. package/lib/generators/java/operations.js +192 -0
  95. package/lib/generators/java/operations.js.map +1 -0
  96. package/lib/generators/java/pagination.d.ts +5 -0
  97. package/lib/generators/java/pagination.d.ts.map +1 -0
  98. package/lib/generators/java/pagination.js +46 -0
  99. package/lib/generators/java/pagination.js.map +1 -0
  100. package/lib/generators/java/types.d.ts +14 -0
  101. package/lib/generators/java/types.d.ts.map +1 -0
  102. package/lib/generators/java/types.js +81 -0
  103. package/lib/generators/java/types.js.map +1 -0
  104. package/lib/generators/meta.d.ts.map +1 -1
  105. package/lib/generators/meta.js +11 -0
  106. package/lib/generators/meta.js.map +1 -1
  107. package/lib/generators/types.d.ts +1 -1
  108. package/lib/generators/types.d.ts.map +1 -1
  109. package/lib/generators/typescript/telemetry/telemetry.d.ts.map +1 -1
  110. package/lib/generators/typescript/telemetry/telemetry.js +72 -11
  111. package/lib/generators/typescript/telemetry/telemetry.js.map +1 -1
  112. package/lib/printers/index.d.ts +1 -0
  113. package/lib/printers/index.d.ts.map +1 -1
  114. package/lib/printers/index.js +2 -1
  115. package/lib/printers/index.js.map +1 -1
  116. package/lib/printers/java.d.ts +25 -0
  117. package/lib/printers/java.d.ts.map +1 -0
  118. package/lib/printers/java.js +104 -0
  119. package/lib/printers/java.js.map +1 -0
  120. package/lib/runtime-sources/java.d.ts +2 -0
  121. package/lib/runtime-sources/java.d.ts.map +1 -0
  122. package/lib/runtime-sources/java.js +3 -0
  123. package/lib/runtime-sources/java.js.map +1 -0
  124. package/lib/runtime-sources/telemetry.d.ts +1 -1
  125. package/lib/runtime-sources/telemetry.d.ts.map +1 -1
  126. package/lib/runtime-sources/telemetry.js +1 -1
  127. package/lib/runtime-sources/telemetry.js.map +1 -1
  128. package/lib/runtime-sources.d.ts +1 -0
  129. package/lib/runtime-sources.d.ts.map +1 -1
  130. package/lib/runtime-sources.js +1 -0
  131. package/lib/runtime-sources.js.map +1 -1
  132. package/package.json +7 -2
@@ -0,0 +1,3 @@
1
+ // GENERATED by scripts/generate-runtime-sources.mjs — do not edit. Regenerated on install (`prepare`); manually: `npm run prepare -w @redocly/client-generator`.
2
+ export const JAVA_RUNTIME_SOURCE = '// @redocly/client-generator Java runtime — embedded into generated clients.\n// Java >= 17, zero dependencies; HTTP over java.net.http.HttpClient, JSON over the\n// small reader/writer below. Hand-authored once and stitched into every generated\n// client (see scripts/generate-runtime-sources.mjs): the generated class inlines this\n// class body, or extends this class under `--runtime module`, so every name below is\n// reachable unqualified either way. Semantically in lockstep with the TypeScript\n// runtime: auth OR-alternatives, a retry loop with Retry-After and full-jitter backoff,\n// per-attempt timeouts, idempotency keys, middleware hooks, pagination, and SSE.\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UncheckedIOException;\nimport java.net.URI;\nimport java.net.URLEncoder;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.net.http.HttpTimeoutException;\nimport java.nio.charset.StandardCharsets;\nimport java.time.Duration;\nimport java.time.LocalDate;\nimport java.time.OffsetDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Objects;\nimport java.util.concurrent.ThreadLocalRandom;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\n\nabstract class Runtime {\n // ─── Errors ───\n\n /** A response with status >= 400, with the decoded body attached. */\n public static class ApiException extends RuntimeException {\n private static final long serialVersionUID = 1L;\n public final String url;\n public final int status;\n public final transient Object body;\n\n public ApiException(String url, int status, Object body) {\n super("Request failed with status " + status + " for " + url);\n this.url = url;\n this.status = status;\n this.body = body;\n }\n }\n\n /** A request attempt exceeded the configured timeout. */\n public static class ApiTimeoutException extends RuntimeException {\n private static final long serialVersionUID = 1L;\n public final String operationId;\n public final Duration timeout;\n public final int attempt;\n\n public ApiTimeoutException(String operationId, Duration timeout, int attempt) {\n super("Request \\"" + operationId + "\\" timed out after " + timeout + " (attempt " + attempt + ")");\n this.operationId = operationId;\n this.timeout = timeout;\n this.attempt = attempt;\n }\n }\n\n // ─── Configuration ───\n\n public record BasicAuth(String username, String password) {}\n\n /** The client credentials; an empty Auth is anonymous. Providers are called per request. */\n public static final class Auth {\n Supplier<String> bearer;\n BasicAuth basic;\n final Map<String, Supplier<String>> apiKey = new LinkedHashMap<>();\n\n public Auth bearer(String token) {\n return bearer(() -> token);\n }\n\n public Auth bearer(Supplier<String> provider) {\n this.bearer = provider;\n return this;\n }\n\n public Auth basic(String username, String password) {\n this.basic = new BasicAuth(username, password);\n return this;\n }\n\n public Auth apiKey(String scheme, String value) {\n return apiKey(scheme, () -> value);\n }\n\n public Auth apiKey(String scheme, Supplier<String> provider) {\n this.apiKey.put(scheme, provider);\n return this;\n }\n }\n\n /** Decides whether an attempt is retried: the response, or the error when there is none. */\n @FunctionalInterface\n public interface RetryOn {\n boolean test(int attempt, HttpResponse<?> response, Exception error);\n }\n\n /** The retry policy: `retries` extra attempts, with fixed or exponential (default) backoff. */\n public static final class Retry {\n int retries;\n Duration delay = Duration.ofSeconds(1);\n String strategy = "exponential";\n boolean noJitter;\n RetryOn retryOn;\n\n public Retry retries(int retries) {\n this.retries = retries;\n return this;\n }\n\n public Retry delay(Duration delay) {\n this.delay = delay;\n return this;\n }\n\n /** `"exponential"` (default) or `"fixed"`. */\n public Retry strategy(String strategy) {\n this.strategy = strategy;\n return this;\n }\n\n public Retry noJitter(boolean noJitter) {\n this.noJitter = noJitter;\n return this;\n }\n\n /** Replaces the default predicate (idempotent methods on 408/429/5xx or a transport error). */\n public Retry retryOn(RetryOn retryOn) {\n this.retryOn = retryOn;\n return this;\n }\n }\n\n /** Hooks around every attempt: `onRequest` before it is sent, `onResponse` in reverse order. */\n public interface Middleware {\n default void onRequest(HttpRequest.Builder request) {}\n\n default void onResponse(HttpResponse<InputStream> response) {}\n }\n\n /** Per-client configuration shared by every operation method. */\n public static final class Config {\n String serverUrl = "";\n HttpClient httpClient;\n final Map<String, String> headers = new LinkedHashMap<>();\n Duration timeout;\n Retry retry = new Retry();\n final List<Middleware> middleware = new ArrayList<>();\n Supplier<String> idempotencyKey;\n Auth auth = new Auth();\n String clientHeader = "redocly-client-generator";\n\n public Config serverUrl(String serverUrl) {\n this.serverUrl = serverUrl;\n return this;\n }\n\n public Config httpClient(HttpClient httpClient) {\n this.httpClient = httpClient;\n return this;\n }\n\n /** A header sent with every request; a `Content-Type` here wins over the description\'s. */\n public Config header(String name, String value) {\n this.headers.put(name, value);\n return this;\n }\n\n /** The budget of one attempt; a later attempt gets a fresh one. */\n public Config timeout(Duration timeout) {\n this.timeout = timeout;\n return this;\n }\n\n public Config retry(Retry retry) {\n this.retry = retry;\n return this;\n }\n\n public Config middleware(Middleware middleware) {\n this.middleware.add(middleware);\n return this;\n }\n\n /** Supplies the `Idempotency-Key` of every POST and PATCH that does not carry one. */\n public Config idempotencyKey(Supplier<String> idempotencyKey) {\n this.idempotencyKey = idempotencyKey;\n return this;\n }\n\n public Config auth(Auth auth) {\n this.auth = auth;\n return this;\n }\n }\n\n /** A `<op>WithHeaders` result: the decoded body plus the coerced declared headers. */\n public record Envelope<T>(T data, Map<String, Object> headers, int status) {}\n\n /** One decoded `text/event-stream` frame; `data` is parsed JSON for JSON event streams. */\n public record ServerSentEvent(String event, Object data, String id, Integer retry) {}\n\n /** One entry of the operations table\'s security requirements. */\n public record SecuritySpec(String scheme, String kind, String name, String in) {\n static SecuritySpec of(String scheme, String kind) {\n return new SecuritySpec(scheme, kind, null, null);\n }\n }\n\n /** One entry of the operations table\'s pagination rules. */\n public record PaginationSpec(\n String style,\n String param,\n String nextCursor,\n String hasMore,\n String nextLink,\n String limitParam,\n String items\n ) {}\n\n record Operation(\n String id,\n String method,\n String path,\n List<List<SecuritySpec>> security,\n PaginationSpec pagination\n ) {}\n\n // ─── JSON ───\n\n /**\n * A minimal JSON reader and writer over plain values: `Map<String, Object>` (insertion\n * ordered), `List<Object>`, `String`, `Long` for integral numbers, `Double` for the rest,\n * `Boolean`, and `null`. No streaming: a response body is read whole, then parsed.\n */\n public static final class Json {\n private final String text;\n private int position;\n\n private Json(String text) {\n this.text = text;\n }\n\n public static Object parse(String text) {\n Json json = new Json(text);\n json.skipWhitespace();\n Object value = json.readValue();\n json.skipWhitespace();\n if (json.position != text.length()) {\n throw json.error("unexpected trailing characters");\n }\n return value;\n }\n\n public static String write(Object value) {\n StringBuilder out = new StringBuilder();\n writeValue(out, value);\n return out.toString();\n }\n\n private IllegalArgumentException error(String message) {\n return new IllegalArgumentException("Invalid JSON at offset " + position + ": " + message);\n }\n\n private void skipWhitespace() {\n while (position < text.length()) {\n char current = text.charAt(position);\n if (current != \' \' && current != \'\\n\' && current != \'\\r\' && current != \'\\t\') {\n break;\n }\n position++;\n }\n }\n\n private Object readValue() {\n if (position >= text.length()) {\n throw error("unexpected end of input");\n }\n char current = text.charAt(position);\n switch (current) {\n case \'{\':\n return readObject();\n case \'[\':\n return readArray();\n case \'"\':\n return readString();\n case \'t\':\n expectWord("true");\n return Boolean.TRUE;\n case \'f\':\n expectWord("false");\n return Boolean.FALSE;\n case \'n\':\n expectWord("null");\n return null;\n default:\n if (current == \'-\' || (current >= \'0\' && current <= \'9\')) {\n return readNumber();\n }\n throw error("unexpected character \'" + current + "\'");\n }\n }\n\n private void expectWord(String word) {\n if (!text.startsWith(word, position)) {\n throw error("expected " + word);\n }\n position += word.length();\n }\n\n private Map<String, Object> readObject() {\n Map<String, Object> object = new LinkedHashMap<>();\n position++;\n skipWhitespace();\n if (peek() == \'}\') {\n position++;\n return object;\n }\n while (true) {\n skipWhitespace();\n if (peek() != \'"\') {\n throw error("expected a string key");\n }\n String key = readString();\n skipWhitespace();\n if (peek() != \':\') {\n throw error("expected \':\'");\n }\n position++;\n skipWhitespace();\n object.put(key, readValue());\n skipWhitespace();\n char next = peek();\n position++;\n if (next == \'}\') {\n return object;\n }\n if (next != \',\') {\n throw error("expected \',\' or \'}\'");\n }\n }\n }\n\n private List<Object> readArray() {\n List<Object> array = new ArrayList<>();\n position++;\n skipWhitespace();\n if (peek() == \']\') {\n position++;\n return array;\n }\n while (true) {\n skipWhitespace();\n array.add(readValue());\n skipWhitespace();\n char next = peek();\n position++;\n if (next == \']\') {\n return array;\n }\n if (next != \',\') {\n throw error("expected \',\' or \']\'");\n }\n }\n }\n\n private char peek() {\n if (position >= text.length()) {\n throw error("unexpected end of input");\n }\n return text.charAt(position);\n }\n\n private String readString() {\n position++;\n StringBuilder out = new StringBuilder();\n while (true) {\n char current = peek();\n position++;\n if (current == \'"\') {\n return out.toString();\n }\n if (current != \'\\\\\') {\n out.append(current);\n continue;\n }\n char escaped = peek();\n position++;\n switch (escaped) {\n case \'"\':\n case \'\\\\\':\n case \'/\':\n out.append(escaped);\n break;\n case \'b\':\n out.append(\'\\b\');\n break;\n case \'f\':\n out.append(\'\\f\');\n break;\n case \'n\':\n out.append(\'\\n\');\n break;\n case \'r\':\n out.append(\'\\r\');\n break;\n case \'t\':\n out.append(\'\\t\');\n break;\n case \'u\':\n if (position + 4 > text.length()) {\n throw error("truncated unicode escape");\n }\n out.append((char) Integer.parseInt(text.substring(position, position + 4), 16));\n position += 4;\n break;\n default:\n throw error("invalid escape \'\\\\" + escaped + "\'");\n }\n }\n }\n\n private Object readNumber() {\n int start = position;\n boolean integral = true;\n if (peek() == \'-\') {\n position++;\n }\n while (position < text.length()) {\n char current = text.charAt(position);\n if (current >= \'0\' && current <= \'9\') {\n position++;\n } else if (current == \'.\' || current == \'e\' || current == \'E\' || current == \'+\' || current == \'-\') {\n integral = false;\n position++;\n } else {\n break;\n }\n }\n String raw = text.substring(start, position);\n try {\n if (integral) {\n return Long.parseLong(raw);\n }\n return Double.parseDouble(raw);\n } catch (NumberFormatException exception) {\n // Beyond a long: keep the value rather than fail the whole document.\n return Double.parseDouble(raw);\n }\n }\n\n private static void writeValue(StringBuilder out, Object value) {\n if (value == null) {\n out.append("null");\n } else if (value instanceof String string) {\n writeString(out, string);\n } else if (value instanceof Boolean || value instanceof Integer || value instanceof Long) {\n out.append(value);\n } else if (value instanceof Number number) {\n double asDouble = number.doubleValue();\n if (Double.isNaN(asDouble) || Double.isInfinite(asDouble)) {\n out.append("null");\n } else if (asDouble == Math.rint(asDouble) && Math.abs(asDouble) < 1e15) {\n out.append((long) asDouble);\n } else {\n out.append(asDouble);\n }\n } else if (value instanceof Map<?, ?> map) {\n out.append(\'{\');\n boolean first = true;\n for (Map.Entry<?, ?> entry : map.entrySet()) {\n if (!first) {\n out.append(\',\');\n }\n first = false;\n writeString(out, String.valueOf(entry.getKey()));\n out.append(\':\');\n writeValue(out, entry.getValue());\n }\n out.append(\'}\');\n } else if (value instanceof Iterable<?> items) {\n out.append(\'[\');\n boolean first = true;\n for (Object item : items) {\n if (!first) {\n out.append(\',\');\n }\n first = false;\n writeValue(out, item);\n }\n out.append(\']\');\n } else if (value instanceof JsonValue typed) {\n writeValue(out, typed.toJson());\n } else if (value instanceof WireValue wire) {\n writeValue(out, wire.wire());\n } else {\n // Dates and anything else print their ISO-8601 / text form.\n writeString(out, textValue(value));\n }\n }\n\n private static void writeString(StringBuilder out, String value) {\n out.append(\'"\');\n for (int index = 0; index < value.length(); index++) {\n char current = value.charAt(index);\n switch (current) {\n case \'"\':\n out.append("\\\\\\"");\n break;\n case \'\\\\\':\n out.append("\\\\\\\\");\n break;\n case \'\\n\':\n out.append("\\\\n");\n break;\n case \'\\r\':\n out.append("\\\\r");\n break;\n case \'\\t\':\n out.append("\\\\t");\n break;\n default:\n if (current < 0x20) {\n out.append(String.format("\\\\u%04x", (int) current));\n } else {\n out.append(current);\n }\n }\n }\n out.append(\'"\');\n }\n }\n\n /** A generated model: serializes itself to the plain JSON graph. */\n public interface JsonValue {\n Object toJson();\n }\n\n /** A generated enum: carries the wire literal (a String or a Long) of each member. */\n public interface WireValue {\n Object wire();\n }\n\n // ─── Hydration helpers (wire value → typed value, null-tolerant) ───\n\n static String asString(Object value) {\n return value == null ? null : value instanceof String string ? string : String.valueOf(value);\n }\n\n static Long asLong(Object value) {\n if (value instanceof Number number) {\n return number.longValue();\n }\n return value instanceof String string && !string.isEmpty() ? Long.parseLong(string) : null;\n }\n\n static Double asDouble(Object value) {\n if (value instanceof Number number) {\n return number.doubleValue();\n }\n return value instanceof String string && !string.isEmpty() ? Double.parseDouble(string) : null;\n }\n\n static Boolean asBoolean(Object value) {\n if (value instanceof Boolean bool) {\n return bool;\n }\n return value instanceof String string ? Boolean.parseBoolean(string) : null;\n }\n\n static OffsetDateTime asOffsetDateTime(Object value) {\n return value == null ? null : OffsetDateTime.parse(asString(value));\n }\n\n static LocalDate asLocalDate(Object value) {\n return value == null ? null : LocalDate.parse(asString(value));\n }\n\n static <T> List<T> asList(Object value, Function<Object, T> item) {\n if (!(value instanceof List<?> raw)) {\n return null;\n }\n List<T> out = new ArrayList<>(raw.size());\n for (Object entry : raw) {\n out.add(item.apply(entry));\n }\n return out;\n }\n\n static <T> Map<String, T> asMap(Object value, Function<Object, T> item) {\n if (!(value instanceof Map<?, ?> raw)) {\n return null;\n }\n Map<String, T> out = new LinkedHashMap<>();\n for (Map.Entry<?, ?> entry : raw.entrySet()) {\n out.put(String.valueOf(entry.getKey()), item.apply(entry.getValue()));\n }\n return out;\n }\n\n static Map<String, Object> asObject(Object value) {\n return asMap(value, item -> item);\n }\n\n static <T> List<Object> mapList(List<T> value, Function<T, Object> item) {\n if (value == null) {\n return null;\n }\n List<Object> out = new ArrayList<>(value.size());\n for (T entry : value) {\n out.add(entry == null ? null : item.apply(entry));\n }\n return out;\n }\n\n static <T> Map<String, Object> mapValues(Map<String, T> value, Function<T, Object> item) {\n if (value == null) {\n return null;\n }\n Map<String, Object> out = new LinkedHashMap<>();\n for (Map.Entry<String, T> entry : value.entrySet()) {\n out.put(entry.getKey(), entry.getValue() == null ? null : item.apply(entry.getValue()));\n }\n return out;\n }\n\n /** The wire text of a typed value: enums by wire literal, date-times with seconds, records as JSON, the rest as text. */\n static String textValue(Object value) {\n if (value instanceof WireValue wire) {\n return String.valueOf(wire.wire());\n }\n if (value instanceof JsonValue || value instanceof Map || value instanceof Iterable) {\n return Json.write(value);\n }\n if (value instanceof OffsetDateTime dateTime) {\n return dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);\n }\n return String.valueOf(value);\n }\n\n static void addQuery(Map<String, List<String>> query, String name, Object value) {\n query.computeIfAbsent(name, key -> new ArrayList<>()).add(textValue(value));\n }\n\n /** The source\'s elements, each mapped — the typed view of a raw page or item sequence. */\n static <T> Iterable<T> mapIterable(Iterable<Object> source, Function<Object, T> map) {\n return () -> {\n Iterator<Object> raw = source.iterator();\n return new Iterator<T>() {\n @Override\n public boolean hasNext() {\n return raw.hasNext();\n }\n\n @Override\n public T next() {\n return map.apply(raw.next());\n }\n };\n };\n }\n\n /** The items of every page, in order, read through the rule\'s `items` pointer. */\n static Iterable<Object> flattenItems(Iterable<Object> pages, String pointer) {\n return () -> {\n Iterator<Object> pageIterator = pages.iterator();\n return new Iterator<Object>() {\n private Iterator<?> items = Collections.emptyIterator();\n\n @Override\n public boolean hasNext() {\n while (!items.hasNext()) {\n if (!pageIterator.hasNext()) {\n return false;\n }\n Object found = resolvePointer(pageIterator.next(), pointer);\n items = found instanceof List<?> list ? list.iterator() : Collections.emptyIterator();\n }\n return true;\n }\n\n @Override\n public Object next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return items.next();\n }\n };\n };\n }\n\n static Map<String, List<String>> cloneQuery(Map<String, List<String>> query) {\n Map<String, List<String>> out = new LinkedHashMap<>();\n for (Map.Entry<String, List<String>> entry : query.entrySet()) {\n out.put(entry.getKey(), new ArrayList<>(entry.getValue()));\n }\n return out;\n }\n\n // ─── Auth and URLs ───\n\n record ResolvedAuth(Map<String, String> headers, Map<String, List<String>> query) {}\n\n private static boolean schemeConfigured(SecuritySpec spec, Auth auth) {\n switch (spec.kind()) {\n case "apiKey":\n return auth.apiKey.containsKey(spec.scheme());\n case "bearer":\n return auth.bearer != null;\n default:\n return auth.basic != null;\n }\n }\n\n /**\n * Apply the first fully-configured OR-alternative; when none is, the first alternative\'s\n * configured schemes are still sent (the server rejects the request — same behavior as\n * the TypeScript runtime).\n */\n static ResolvedAuth resolveAuth(List<List<SecuritySpec>> security, Auth auth) {\n Map<String, String> headers = new LinkedHashMap<>();\n Map<String, List<String>> query = new LinkedHashMap<>();\n if (security == null || security.isEmpty()) {\n return new ResolvedAuth(headers, query);\n }\n List<SecuritySpec> alternative = security.get(0);\n for (List<SecuritySpec> candidate : security) {\n boolean all = true;\n for (SecuritySpec spec : candidate) {\n if (!schemeConfigured(spec, auth)) {\n all = false;\n break;\n }\n }\n if (all) {\n alternative = candidate;\n break;\n }\n }\n List<String> cookies = new ArrayList<>();\n for (SecuritySpec spec : alternative) {\n switch (spec.kind()) {\n case "apiKey": {\n Supplier<String> provider = auth.apiKey.get(spec.scheme());\n if (provider == null) {\n continue;\n }\n String value = provider.get();\n if ("query".equals(spec.in())) {\n addQuery(query, spec.name(), value);\n } else if ("cookie".equals(spec.in())) {\n cookies.add(spec.name() + "=" + encode(value));\n } else {\n headers.put(spec.name(), value);\n }\n break;\n }\n case "bearer":\n if (auth.bearer != null) {\n headers.put("Authorization", "Bearer " + auth.bearer.get());\n }\n break;\n default:\n if (auth.basic != null) {\n String token = auth.basic.username() + ":" + auth.basic.password();\n headers.put(\n "Authorization",\n "Basic " + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8))\n );\n }\n }\n }\n if (!cookies.isEmpty()) {\n headers.put("Cookie", String.join("; ", cookies));\n }\n return new ResolvedAuth(headers, query);\n }\n\n /** Percent-encode one path segment or query component. */\n static String encode(String value) {\n return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");\n }\n\n /** Substitute `{param}` placeholders with encoded values and prefix the server URL. */\n static String buildUrl(String serverUrl, String path, Map<String, String> pathParams) {\n String filled = path;\n for (Map.Entry<String, String> entry : pathParams.entrySet()) {\n filled = filled.replace("{" + entry.getKey() + "}", encode(entry.getValue()));\n }\n String base = serverUrl;\n while (base.endsWith("/")) {\n base = base.substring(0, base.length() - 1);\n }\n return base + filled;\n }\n\n /** Append query params in form style: a list value repeats the key (`tag=a&tag=b`). */\n static String appendQuery(String url, Map<String, List<String>> query) {\n StringBuilder pairs = new StringBuilder();\n for (Map.Entry<String, List<String>> entry : query.entrySet()) {\n for (String value : entry.getValue()) {\n if (pairs.length() > 0) {\n pairs.append(\'&\');\n }\n pairs.append(encode(entry.getKey())).append(\'=\').append(encode(value));\n }\n }\n if (pairs.length() == 0) {\n return url;\n }\n return url + (url.contains("?") ? "&" : "?") + pairs;\n }\n\n // ─── Send ───\n\n /** One request as the generated methods describe it; the runtime adds auth, retries, and middleware. */\n static final class RequestSpec {\n String operationId;\n String method;\n String url;\n Map<String, String> headers = new LinkedHashMap<>();\n Map<String, List<String>> query = new LinkedHashMap<>();\n /** `byte[]` is replayable across attempts; an `InputStream` is sent as is, once. */\n Object body;\n String contentType;\n\n RequestSpec(String operationId, String method, String url) {\n this.operationId = operationId;\n this.method = method;\n this.url = url;\n }\n\n RequestSpec headers(Map<String, String> headers) {\n this.headers = headers;\n return this;\n }\n\n RequestSpec query(Map<String, List<String>> query) {\n this.query = query;\n return this;\n }\n\n RequestSpec body(Object body, String contentType) {\n this.body = body;\n this.contentType = contentType;\n return this;\n }\n }\n\n private static final List<Integer> TRANSIENT_STATUS = List.of(408, 429, 500, 502, 503, 504);\n\n private static boolean defaultRetryOn(String method, Map<String, String> headers, HttpResponse<?> response, Exception error) {\n boolean safe = List.of("GET", "HEAD", "PUT", "DELETE", "OPTIONS").contains(method) || hasHeader(headers, "Idempotency-Key");\n if (!safe) {\n return false;\n }\n if (error != null) {\n return true;\n }\n return response != null && TRANSIENT_STATUS.contains(response.statusCode());\n }\n\n private static boolean hasHeader(Map<String, String> headers, String name) {\n for (String key : headers.keySet()) {\n if (key.equalsIgnoreCase(name)) {\n return true;\n }\n }\n return false;\n }\n\n private static Duration retryDelay(Retry retry, int attempt, String retryAfter) {\n if (retryAfter != null) {\n try {\n return Duration.ofMillis((long) (Double.parseDouble(retryAfter.trim()) * 1000));\n } catch (NumberFormatException ignored) {\n // An HTTP-date Retry-After falls back to the policy\'s own delay.\n }\n }\n Duration raw = "fixed".equals(retry.strategy) ? retry.delay : retry.delay.multipliedBy(1L << (attempt - 1));\n if (retry.noJitter) {\n return raw;\n }\n return Duration.ofMillis(ThreadLocalRandom.current().nextLong(raw.toMillis() + 1));\n }\n\n private static void sleep(Duration delay) {\n try {\n Thread.sleep(Math.max(0, delay.toMillis()));\n } catch (InterruptedException interrupted) {\n Thread.currentThread().interrupt();\n throw new UncheckedIOException(new IOException("Interrupted while waiting to retry", interrupted));\n }\n }\n\n /**\n * The request core: header merge, idempotency keys, the retry loop with a fresh timeout\n * per attempt, and the middleware hooks. Returns the response of the last attempt with\n * its body still unread; callers map status >= 400 to ApiException.\n */\n static HttpResponse<InputStream> send(Config config, RequestSpec spec) {\n Map<String, String> headers = new LinkedHashMap<>(config.headers);\n headers.putAll(spec.headers);\n headers.put("X-Redocly-Client", config.clientHeader);\n String method = spec.method.toUpperCase(Locale.ROOT);\n if ((method.equals("POST") || method.equals("PATCH")) && !hasHeader(headers, "Idempotency-Key") && config.idempotencyKey != null) {\n headers.put("Idempotency-Key", config.idempotencyKey.get());\n }\n if (spec.contentType != null && spec.body != null && !hasHeader(headers, "Content-Type")) {\n headers.put("Content-Type", spec.contentType);\n }\n if (config.httpClient == null) {\n // HTTP/1.1 outright: the default client\'s h2c upgrade attempt confuses servers that\n // do not speak HTTP/2, and a generated SDK cannot know which it will meet.\n config.httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();\n }\n HttpClient httpClient = config.httpClient;\n String fullUrl = appendQuery(spec.url, spec.query);\n boolean stream = spec.body instanceof InputStream;\n // The first attempt consumes a stream, so there is nothing to replay.\n int maxAttempts = stream ? 1 : 1 + Math.max(0, config.retry.retries);\n for (int attempt = 1; ; attempt++) {\n HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(fullUrl));\n if (config.timeout != null) {\n builder.timeout(config.timeout);\n }\n for (Map.Entry<String, String> entry : headers.entrySet()) {\n builder.header(entry.getKey(), entry.getValue());\n }\n HttpRequest.BodyPublisher publisher;\n if (spec.body instanceof InputStream input) {\n publisher = HttpRequest.BodyPublishers.ofInputStream(() -> input);\n } else if (spec.body instanceof byte[] bytes) {\n publisher = HttpRequest.BodyPublishers.ofByteArray(bytes);\n } else {\n publisher = HttpRequest.BodyPublishers.noBody();\n }\n builder.method(method, publisher);\n for (Middleware middleware : config.middleware) {\n middleware.onRequest(builder);\n }\n HttpResponse<InputStream> response = null;\n Exception failure = null;\n try {\n response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream());\n } catch (IOException | InterruptedException exception) {\n if (exception instanceof InterruptedException) {\n Thread.currentThread().interrupt();\n }\n failure = exception;\n }\n boolean retryable = config.retry.retryOn != null\n ? config.retry.retryOn.test(attempt, response, failure)\n : defaultRetryOn(method, headers, response, failure);\n if (failure != null) {\n if (attempt < maxAttempts && retryable) {\n sleep(retryDelay(config.retry, attempt, null));\n continue;\n }\n if (failure instanceof HttpTimeoutException) {\n throw new ApiTimeoutException(spec.operationId, config.timeout, attempt);\n }\n throw new UncheckedIOException("Request to " + fullUrl + " failed: " + failure.getMessage(), new IOException(failure));\n }\n for (int index = config.middleware.size() - 1; index >= 0; index--) {\n config.middleware.get(index).onResponse(response);\n }\n if (response.statusCode() >= 400 && attempt < maxAttempts && retryable) {\n String retryAfter = response.headers().firstValue("Retry-After").orElse(null);\n readBody(response);\n sleep(retryDelay(config.retry, attempt, retryAfter));\n continue;\n }\n return response;\n }\n }\n\n /** The whole response body; the stream is closed afterwards. */\n static byte[] readBody(HttpResponse<InputStream> response) {\n try (InputStream body = response.body()) {\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n byte[] chunk = new byte[8192];\n int read;\n while ((read = body.read(chunk)) != -1) {\n out.write(chunk, 0, read);\n }\n return out.toByteArray();\n } catch (IOException exception) {\n throw new UncheckedIOException(exception);\n }\n }\n\n /** The decoded JSON body, or null for an empty body. */\n static Object decodeJson(HttpResponse<InputStream> response) {\n String text = new String(readBody(response), StandardCharsets.UTF_8);\n return text.isBlank() ? null : Json.parse(text);\n }\n\n /** The structured exception for a non-2xx response; the body is decoded when it is JSON. */\n static ApiException apiErrorFrom(HttpResponse<InputStream> response, String url) {\n String text = new String(readBody(response), StandardCharsets.UTF_8);\n Object body = text;\n if (!text.isBlank()) {\n try {\n body = Json.parse(text);\n } catch (IllegalArgumentException notJson) {\n body = text;\n }\n }\n return new ApiException(url, response.statusCode(), body);\n }\n\n /** Coerce declared response headers per `{name, key, type}` specs; absent or unparsable ones are omitted. */\n static Map<String, Object> readEnvelopeHeaders(HttpResponse<?> response, String[][] specs) {\n Map<String, Object> headers = new LinkedHashMap<>();\n for (String[] spec : specs) {\n String raw = response.headers().firstValue(spec[0]).orElse(null);\n if (raw == null) {\n continue;\n }\n String trimmed = raw.trim();\n try {\n switch (spec[2]) {\n case "integer":\n headers.put(spec[1], Long.parseLong(trimmed));\n break;\n case "number":\n headers.put(spec[1], Double.parseDouble(trimmed));\n break;\n case "boolean": {\n String lower = trimmed.toLowerCase(Locale.ROOT);\n if (lower.equals("true") || lower.equals("false")) {\n headers.put(spec[1], lower.equals("true"));\n }\n break;\n }\n default:\n headers.put(spec[1], raw);\n }\n } catch (NumberFormatException unparsable) {\n // Omitted, like an absent header.\n }\n }\n return headers;\n }\n\n // ─── Pagination ───\n\n /** Walk an RFC 6901 JSON pointer over decoded JSON; null on any miss. */\n static Object resolvePointer(Object data, String pointer) {\n if (pointer == null || pointer.isEmpty()) {\n return data;\n }\n if (!pointer.startsWith("/")) {\n return null;\n }\n Object current = data;\n for (String token : pointer.substring(1).split("/", -1)) {\n String key = token.replace("~1", "/").replace("~0", "~");\n if (current instanceof Map<?, ?> map) {\n current = map.get(key);\n } else if (current instanceof List<?> list) {\n try {\n int index = Integer.parseInt(key);\n current = index >= 0 && index < list.size() ? list.get(index) : null;\n } catch (NumberFormatException notAnIndex) {\n return null;\n }\n } else {\n return null;\n }\n if (current == null) {\n return null;\n }\n }\n return current;\n }\n\n /** The `rel="next"` target of a `Link` header, or null. */\n static String linkNext(String header) {\n if (header == null) {\n return null;\n }\n for (String entry : header.split(",")) {\n String[] parts = entry.split(";");\n if (parts.length < 2) {\n continue;\n }\n String target = parts[0].trim();\n if (!target.startsWith("<") || !target.endsWith(">")) {\n continue;\n }\n for (int index = 1; index < parts.length; index++) {\n String param = parts[index].trim();\n if (param.startsWith("rel=")) {\n String rel = param.substring(4).replace("\\"", "");\n for (String kind : rel.split("\\\\s+")) {\n if (kind.equals("next")) {\n return target.substring(1, target.length() - 1);\n }\n }\n }\n }\n }\n return null;\n }\n\n /** One page fetch: the decoded page and the response it came from. */\n record PageResult(Object page, HttpResponse<InputStream> response) {}\n\n @FunctionalInterface\n interface PageCall {\n PageResult call(Map<String, List<String>> params);\n }\n\n /** An iterator that fetches its next element lazily, once per `hasNext`. */\n abstract static class LazyIterator<T> implements Iterator<T> {\n private T next;\n private boolean ready;\n private boolean done;\n\n /** The next element, or null when the sequence has ended. */\n protected abstract T fetch();\n\n @Override\n public boolean hasNext() {\n if (done) {\n return false;\n }\n if (!ready) {\n next = fetch();\n ready = true;\n if (next == null) {\n done = true;\n }\n }\n return !done;\n }\n\n @Override\n public T next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n ready = false;\n return next;\n }\n }\n\n /**\n * Auto-pagination over raw decoded pages, following the rule in `spec` — the same stop\n * conditions and loop guards as the TypeScript runtime. Generated wrappers hydrate the\n * pages into models.\n */\n static Iterable<Object> iterPages(PageCall call, PaginationSpec spec, Map<String, List<String>> base) {\n return () -> new LazyIterator<>() {\n private boolean started;\n private boolean finished;\n private Object cursor;\n private Map<String, List<String>> params = cloneQuery(base);\n private String previousLink;\n private String previousItems;\n private int position;\n\n @Override\n protected Object fetch() {\n if (finished) {\n return null;\n }\n switch (spec.style()) {\n case "cursor":\n return fetchCursor();\n case "link":\n case "body-link":\n return fetchLink();\n default:\n return fetchOffset();\n }\n }\n\n private Object fetchCursor() {\n if (!started) {\n started = true;\n List<String> seed = base.get(spec.param());\n cursor = seed == null || seed.isEmpty() ? null : seed.get(0);\n }\n Map<String, List<String>> pageParams = cloneQuery(base);\n if (cursor != null) {\n pageParams.put(spec.param(), new ArrayList<>(List.of(String.valueOf(cursor))));\n }\n Object page = call.call(pageParams).page();\n if (spec.hasMore() != null && Boolean.FALSE.equals(resolvePointer(page, spec.hasMore()))) {\n finished = true;\n return page;\n }\n Object next = resolvePointer(page, spec.nextCursor());\n if (next == null || "".equals(next)) {\n finished = true;\n return page;\n }\n if (!(next instanceof String) && !(next instanceof Number)) {\n throw new IllegalStateException("Pagination cursor at " + spec.nextCursor() + " is not a string or number");\n }\n if (cursor != null && String.valueOf(next).equals(String.valueOf(cursor))) {\n throw new IllegalStateException("Pagination did not advance: the operation returned the same cursor twice");\n }\n cursor = next;\n return page;\n }\n\n private Object fetchLink() {\n PageResult result = call.call(params);\n String target;\n if (spec.style().equals("link")) {\n target = linkNext(result.response().headers().firstValue("Link").orElse(null));\n } else {\n Object value = resolvePointer(result.page(), spec.nextLink());\n if (value != null && !(value instanceof String)) {\n throw new IllegalStateException("Pagination link at " + spec.nextLink() + " is not a string");\n }\n target = (String) value;\n }\n if (target == null || target.isEmpty()) {\n finished = true;\n return result.page();\n }\n URI pageUri = result.response().uri();\n URI next = pageUri.resolve(target);\n if (next.toString().equals(previousLink) || next.toString().equals(pageUri.toString())) {\n throw new IllegalStateException("Pagination did not advance: the Link rel=\\"next\\" target repeats");\n }\n previousLink = next.toString();\n params = cloneQuery(base);\n String rawQuery = next.getRawQuery();\n if (rawQuery != null) {\n for (String pair : rawQuery.split("&")) {\n if (pair.isEmpty()) {\n continue;\n }\n int equals = pair.indexOf(\'=\');\n String key = java.net.URLDecoder.decode(equals < 0 ? pair : pair.substring(0, equals), StandardCharsets.UTF_8);\n String value = equals < 0 ? "" : java.net.URLDecoder.decode(pair.substring(equals + 1), StandardCharsets.UTF_8);\n params.put(key, new ArrayList<>(List.of(value)));\n }\n }\n return result.page();\n }\n\n private Object fetchOffset() {\n if (!started) {\n started = true;\n position = spec.style().equals("page") ? 1 : 0;\n List<String> seed = base.get(spec.param());\n if (seed != null && !seed.isEmpty() && !seed.get(0).isEmpty()) {\n try {\n position = Integer.parseInt(seed.get(0));\n } catch (NumberFormatException ignored) {\n // The description\'s default position stands.\n }\n }\n }\n Map<String, List<String>> pageParams = cloneQuery(base);\n pageParams.put(spec.param(), new ArrayList<>(List.of(String.valueOf(position))));\n Object page = call.call(pageParams).page();\n Object items = resolvePointer(page, spec.items());\n List<?> list = items instanceof List<?> found ? found : null;\n if (list != null) {\n String serialized = Json.write(list);\n if (serialized.equals(previousItems)) {\n throw new IllegalStateException("Pagination did not advance: the operation returned the same page twice");\n }\n previousItems = serialized;\n }\n if (list == null || list.isEmpty()) {\n finished = true;\n return page;\n }\n position += spec.style().equals("page") ? 1 : list.size();\n return page;\n }\n };\n }\n\n // ─── Server-Sent Events ───\n\n @FunctionalInterface\n interface SseOpener {\n HttpResponse<InputStream> open(Map<String, String> extraHeaders);\n }\n\n private static ServerSentEvent parseSseFrame(String raw, boolean jsonData) {\n String event = "message";\n List<String> dataLines = new ArrayList<>();\n String id = null;\n Integer retry = null;\n boolean sawField = false;\n for (String line : raw.replace("\\r\\n", "\\n").replace(\'\\r\', \'\\n\').split("\\n")) {\n if (line.isEmpty() || line.startsWith(":")) {\n continue;\n }\n int colon = line.indexOf(\':\');\n String field = colon < 0 ? line : line.substring(0, colon);\n String value = colon < 0 ? "" : line.substring(colon + 1);\n if (value.startsWith(" ")) {\n value = value.substring(1);\n }\n sawField = true;\n switch (field) {\n case "event":\n event = value;\n break;\n case "data":\n dataLines.add(value);\n break;\n case "id":\n id = value;\n break;\n case "retry":\n try {\n retry = Integer.valueOf(value);\n } catch (NumberFormatException ignored) {\n // A non-numeric retry field is ignored, as the spec says.\n }\n break;\n default:\n }\n }\n if (!sawField) {\n return null;\n }\n String text = String.join("\\n", dataLines);\n Object data = jsonData && !text.isEmpty() ? Json.parse(text) : text;\n return new ServerSentEvent(event, data, id, retry);\n }\n\n /**\n * Stream server-sent events, reconnecting with `Last-Event-ID` on a dropped connection\n * (a fresh open = fresh auth); a 4xx/5xx or a bad JSON payload ends the stream with an\n * exception, a clean end of stream ends it quietly.\n */\n static Iterable<ServerSentEvent> iterSse(SseOpener open, boolean jsonData) {\n return () -> new LazyIterator<>() {\n private InputStream body;\n private final StringBuilder buffer = new StringBuilder();\n private final byte[] chunk = new byte[4096];\n private String lastEventId;\n private int serverRetry = -1;\n private int failures;\n private boolean finished;\n\n private void connect() {\n Map<String, String> headers = new LinkedHashMap<>();\n headers.put("Accept", "text/event-stream");\n if (lastEventId != null) {\n headers.put("Last-Event-ID", lastEventId);\n }\n HttpResponse<InputStream> response = open.open(headers);\n if (response.statusCode() >= 400) {\n throw apiErrorFrom(response, response.uri().toString());\n }\n body = response.body();\n failures = 0;\n }\n\n private void backoff() {\n failures++;\n long base = serverRetry >= 0 ? serverRetry : 1000;\n long delay = Math.min(base * (1L << (failures - 1)), 30_000);\n sleep(Duration.ofMillis(ThreadLocalRandom.current().nextLong(delay + 1)));\n }\n\n private ServerSentEvent take(String frame) {\n ServerSentEvent event = parseSseFrame(frame, jsonData);\n if (event == null) {\n return null;\n }\n if (event.id() != null) {\n lastEventId = event.id();\n }\n if (event.retry() != null && event.retry() >= 0) {\n serverRetry = event.retry();\n }\n return event;\n }\n\n @Override\n protected ServerSentEvent fetch() {\n while (!finished) {\n if (body == null) {\n try {\n connect();\n } catch (UncheckedIOException dropped) {\n backoff();\n continue;\n }\n }\n int split = buffer.indexOf("\\n\\n");\n if (split >= 0) {\n String frame = buffer.substring(0, split);\n buffer.delete(0, split + 2);\n ServerSentEvent event = take(frame);\n if (event != null) {\n return event;\n }\n continue;\n }\n int read;\n try {\n read = body.read(chunk);\n } catch (IOException dropped) {\n read = -2;\n }\n if (read >= 0) {\n buffer.append(new String(chunk, 0, read, StandardCharsets.UTF_8).replace("\\r\\n", "\\n").replace(\'\\r\', \'\\n\'));\n continue;\n }\n try {\n body.close();\n } catch (IOException ignored) {\n // The connection is gone either way.\n }\n body = null;\n if (read == -1) {\n finished = true;\n String rest = buffer.toString();\n buffer.setLength(0);\n return rest.isBlank() ? null : take(rest);\n }\n backoff();\n }\n return null;\n }\n };\n }\n\n // ─── Request bodies ───\n\n /** A prepared request body: the bytes or stream to send and the content type to declare, if any. */\n record Body(Object body, String contentType) {}\n\n /** Encode a map as `multipart/form-data`; nested values become JSON parts. */\n static Body toMultipart(Map<String, Object> fields) {\n String boundary = "redocly-" + Long.toHexString(ThreadLocalRandom.current().nextLong()) + Long.toHexString(ThreadLocalRandom.current().nextLong());\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n try {\n for (Map.Entry<String, Object> entry : fields.entrySet()) {\n Object value = entry.getValue();\n if (value == null) {\n continue;\n }\n out.write(("--" + boundary + "\\r\\n").getBytes(StandardCharsets.UTF_8));\n if (value instanceof byte[] bytes) {\n out.write(("Content-Disposition: form-data; name=\\"" + entry.getKey() + "\\"; filename=\\"" + entry.getKey() + "\\"\\r\\nContent-Type: application/octet-stream\\r\\n\\r\\n").getBytes(StandardCharsets.UTF_8));\n out.write(bytes);\n } else if (value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof WireValue) {\n out.write(("Content-Disposition: form-data; name=\\"" + entry.getKey() + "\\"\\r\\n\\r\\n").getBytes(StandardCharsets.UTF_8));\n out.write(textValue(value).getBytes(StandardCharsets.UTF_8));\n } else {\n out.write(("Content-Disposition: form-data; name=\\"" + entry.getKey() + "\\"\\r\\nContent-Type: application/json\\r\\n\\r\\n").getBytes(StandardCharsets.UTF_8));\n out.write(Json.write(value).getBytes(StandardCharsets.UTF_8));\n }\n out.write("\\r\\n".getBytes(StandardCharsets.UTF_8));\n }\n out.write(("--" + boundary + "--\\r\\n").getBytes(StandardCharsets.UTF_8));\n } catch (IOException exception) {\n throw new UncheckedIOException(exception);\n }\n return new Body(out.toByteArray(), "multipart/form-data; boundary=" + boundary);\n }\n\n /**\n * The body of an untyped multipart operation: an InputStream is streamed and a `byte[]`\n * or String sent as is, all under the caller\'s Content-Type (the boundary is theirs to\n * set); a map is encoded with `toMultipart`.\n */\n static Body multipartBody(Object body) {\n if (body instanceof InputStream || body instanceof byte[]) {\n return new Body(body, null);\n }\n if (body instanceof String text) {\n return new Body(text.getBytes(StandardCharsets.UTF_8), null);\n }\n return toMultipart(asObject(body instanceof JsonValue typed ? typed.toJson() : body));\n }\n\n /** The body of a binary operation: an InputStream is streamed, a `byte[]` or String sent as is, anything else JSON-encoded. */\n static Body binaryBody(Object body, String contentType) {\n if (body instanceof InputStream || body instanceof byte[]) {\n return new Body(body, contentType);\n }\n if (body instanceof String text) {\n return new Body(text.getBytes(StandardCharsets.UTF_8), contentType);\n }\n return new Body(Json.write(body).getBytes(StandardCharsets.UTF_8), contentType);\n }\n\n /** A JSON request body from a typed value. */\n static Body jsonBody(Object body, String contentType) {\n Object plain = body instanceof JsonValue typed ? typed.toJson() : body;\n return new Body(Json.write(plain).getBytes(StandardCharsets.UTF_8), contentType);\n }\n\n static Map<String, String> pathParams(String... pairs) {\n Map<String, String> out = new LinkedHashMap<>();\n for (int index = 0; index + 1 < pairs.length; index += 2) {\n out.put(pairs[index], Objects.requireNonNull(pairs[index + 1], "path parameter " + pairs[index]));\n }\n return out;\n }\n}\n';
3
+ //# sourceMappingURL=java.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"java.js","sourceRoot":"","sources":["../../src/runtime-sources/java.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,mBAAmB,GAC9B,0t3DAA0t3D,CAAC"}
@@ -1,2 +1,2 @@
1
- export declare const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageEvent = {\n id: string;\n type: typeof EVENT_TYPE;\n source: string;\n time: string;\n data: {\n usage: Record<string, string | number>;\n sdk: Record<string, string>;\n };\n};\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\nconst activeWindows = new Set<() => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport async function flush(): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow();\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: Record<string, string> = {\n name: options.sdkName,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n async function flushWindow(): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, options.sdkName, sdk);\n counts = new Map();\n if (telemetryDisabled()) return;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch(() => undefined);\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow(), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n nodeProcess()?.on?.('beforeExit', () => void flush());\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n operation.attempts += call.attempts;\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n source: string,\n sdk: Record<string, string>\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const usage: Record<string, string | number> = {\n operation_id: operationId,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n usage[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n usage[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: `evt_${randomHex(16)}`,\n type: EVENT_TYPE,\n source,\n time: new Date(windowStart).toISOString(),\n data: { usage, sdk },\n });\n }\n return events;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', '1.0'),\n attribute('cloudevents.event_data_content_type', 'application/json; charset=utf-8'),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', ''),\n attribute('cloudevents.event_origin', SERVICE_NAME),\n attribute('cloudevents.event_object', 'event'),\n attribute('cloudevents.event_category', 'product'),\n attribute('cloudevents.event_signal', 'metric'),\n ];\n for (const [key, value] of Object.entries(event.data.usage)) {\n attributes.push(attribute(`cloudevents.event_data.usage.${key}`, value));\n }\n for (const [key, value] of Object.entries(event.data.sdk)) {\n attributes.push(attribute(`cloudevents.event_data.sdk.${key}`, value));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
1
+ export declare const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageEvent = {\n id: string;\n type: typeof EVENT_TYPE;\n source: string;\n time: string;\n data: {\n usage: Record<string, string | number>;\n sdk: Record<string, string>;\n };\n};\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\ntype OnFailedSend = 'keep' | 'drop';\n\nconst activeWindows = new Set<(onFailedSend: OnFailedSend) => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport function flush(): Promise<void> {\n return flushWindows('keep');\n}\n\nasync function flushWindows(onFailedSend: OnFailedSend): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow(onFailedSend);\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: Record<string, string> = {\n name: options.sdkName,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n function openWindow(): void {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow('keep'), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n\n async function flushWindow(onFailedSend: OnFailedSend): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, options.sdkName, sdk);\n const sentCounts = counts;\n const sentWindowStart = windowStart;\n counts = new Map();\n if (telemetryDisabled()) return;\n let action: OnFailedSend | undefined;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch((error: unknown) => {\n action = actionForFailedSend(error);\n });\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n if (action !== 'keep' || onFailedSend === 'drop') return;\n\n if (counts.size === 0) openWindow();\n if (sentWindowStart < windowStart) windowStart = sentWindowStart;\n for (const [operationId, sentOperation] of sentCounts) {\n const operation = counts.get(operationId);\n if (operation === undefined) {\n counts.set(operationId, sentOperation);\n } else {\n addCounts(operation, sentOperation);\n }\n }\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) openWindow();\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n // Node emits `beforeExit` again after each send at exit.\n // Kept counts then cause one more send each time, so a failed send here drops its counts.\n nodeProcess()?.on?.('beforeExit', () => void flushWindows('drop'));\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n operation.attempts += call.attempts;\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction addCounts(target: OperationCounts, source: OperationCounts): void {\n target.calls += source.calls;\n target.attempts += source.attempts;\n target.durationSumMs += source.durationSumMs;\n for (const statusClass of STATUS_CLASSES) {\n target.status[statusClass] += source.status[statusClass];\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n target.latency[bucket] += source.latency[bucket];\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n source: string,\n sdk: Record<string, string>\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const usage: Record<string, string | number> = {\n operation_id: operationId,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n usage[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n usage[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: `evt_${randomHex(16)}`,\n type: EVENT_TYPE,\n source,\n time: new Date(windowStart).toISOString(),\n data: { usage, sdk },\n });\n }\n return events;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n if (!response.ok) {\n throw new RejectedSendError(response.status);\n }\n}\n\nclass RejectedSendError extends Error {\n public readonly status: number;\n constructor(status: number) {\n super(`The telemetry endpoint answered ${status}.`);\n this.name = 'RejectedSendError';\n this.status = status;\n }\n}\n\nfunction actionForFailedSend(error: unknown): OnFailedSend {\n // The endpoint can have stored the counts of a send that timed out.\n if (error instanceof Error && error.name === 'TimeoutError') return 'drop';\n if (error instanceof RejectedSendError) {\n if (error.status === 408 || error.status === 429 || error.status >= 500) return 'keep';\n // The endpoint refuses the same counts again.\n return 'drop';\n }\n return 'keep';\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', '1.0'),\n attribute('cloudevents.event_data_content_type', 'application/json; charset=utf-8'),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', ''),\n attribute('cloudevents.event_origin', SERVICE_NAME),\n attribute('cloudevents.event_object', 'event'),\n attribute('cloudevents.event_category', 'product'),\n attribute('cloudevents.event_signal', 'metric'),\n ];\n for (const [key, value] of Object.entries(event.data.usage)) {\n attributes.push(attribute(`cloudevents.event_data.usage.${key}`, value));\n }\n for (const [key, value] of Object.entries(event.data.sdk)) {\n attributes.push(attribute(`cloudevents.event_data.sdk.${key}`, value));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
2
2
  //# sourceMappingURL=telemetry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,wBAAwB,49TACs7T,CAAC"}
1
+ {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,wBAAwB,6pYACunY,CAAC"}
@@ -1,3 +1,3 @@
1
1
  // GENERATED by scripts/generate-runtime-sources.mjs — do not edit. Regenerated on install (`prepare`); manually: `npm run prepare -w @redocly/client-generator`.
2
- export const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageEvent = {\n id: string;\n type: typeof EVENT_TYPE;\n source: string;\n time: string;\n data: {\n usage: Record<string, string | number>;\n sdk: Record<string, string>;\n };\n};\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\nconst activeWindows = new Set<() => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport async function flush(): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow();\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: Record<string, string> = {\n name: options.sdkName,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n async function flushWindow(): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, options.sdkName, sdk);\n counts = new Map();\n if (telemetryDisabled()) return;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch(() => undefined);\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow(), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n nodeProcess()?.on?.('beforeExit', () => void flush());\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n operation.attempts += call.attempts;\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n source: string,\n sdk: Record<string, string>\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const usage: Record<string, string | number> = {\n operation_id: operationId,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n usage[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n usage[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: `evt_${randomHex(16)}`,\n type: EVENT_TYPE,\n source,\n time: new Date(windowStart).toISOString(),\n data: { usage, sdk },\n });\n }\n return events;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', '1.0'),\n attribute('cloudevents.event_data_content_type', 'application/json; charset=utf-8'),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', ''),\n attribute('cloudevents.event_origin', SERVICE_NAME),\n attribute('cloudevents.event_object', 'event'),\n attribute('cloudevents.event_category', 'product'),\n attribute('cloudevents.event_signal', 'metric'),\n ];\n for (const [key, value] of Object.entries(event.data.usage)) {\n attributes.push(attribute(`cloudevents.event_data.usage.${key}`, value));\n }\n for (const [key, value] of Object.entries(event.data.sdk)) {\n attributes.push(attribute(`cloudevents.event_data.sdk.${key}`, value));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
2
+ export const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageEvent = {\n id: string;\n type: typeof EVENT_TYPE;\n source: string;\n time: string;\n data: {\n usage: Record<string, string | number>;\n sdk: Record<string, string>;\n };\n};\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\ntype OnFailedSend = 'keep' | 'drop';\n\nconst activeWindows = new Set<(onFailedSend: OnFailedSend) => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport function flush(): Promise<void> {\n return flushWindows('keep');\n}\n\nasync function flushWindows(onFailedSend: OnFailedSend): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow(onFailedSend);\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: Record<string, string> = {\n name: options.sdkName,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n function openWindow(): void {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow('keep'), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n\n async function flushWindow(onFailedSend: OnFailedSend): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, options.sdkName, sdk);\n const sentCounts = counts;\n const sentWindowStart = windowStart;\n counts = new Map();\n if (telemetryDisabled()) return;\n let action: OnFailedSend | undefined;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch((error: unknown) => {\n action = actionForFailedSend(error);\n });\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n if (action !== 'keep' || onFailedSend === 'drop') return;\n\n if (counts.size === 0) openWindow();\n if (sentWindowStart < windowStart) windowStart = sentWindowStart;\n for (const [operationId, sentOperation] of sentCounts) {\n const operation = counts.get(operationId);\n if (operation === undefined) {\n counts.set(operationId, sentOperation);\n } else {\n addCounts(operation, sentOperation);\n }\n }\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) openWindow();\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n // Node emits `beforeExit` again after each send at exit.\n // Kept counts then cause one more send each time, so a failed send here drops its counts.\n nodeProcess()?.on?.('beforeExit', () => void flushWindows('drop'));\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n operation.attempts += call.attempts;\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction addCounts(target: OperationCounts, source: OperationCounts): void {\n target.calls += source.calls;\n target.attempts += source.attempts;\n target.durationSumMs += source.durationSumMs;\n for (const statusClass of STATUS_CLASSES) {\n target.status[statusClass] += source.status[statusClass];\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n target.latency[bucket] += source.latency[bucket];\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n source: string,\n sdk: Record<string, string>\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const usage: Record<string, string | number> = {\n operation_id: operationId,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n usage[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n usage[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: `evt_${randomHex(16)}`,\n type: EVENT_TYPE,\n source,\n time: new Date(windowStart).toISOString(),\n data: { usage, sdk },\n });\n }\n return events;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n if (!response.ok) {\n throw new RejectedSendError(response.status);\n }\n}\n\nclass RejectedSendError extends Error {\n public readonly status: number;\n constructor(status: number) {\n super(`The telemetry endpoint answered ${status}.`);\n this.name = 'RejectedSendError';\n this.status = status;\n }\n}\n\nfunction actionForFailedSend(error: unknown): OnFailedSend {\n // The endpoint can have stored the counts of a send that timed out.\n if (error instanceof Error && error.name === 'TimeoutError') return 'drop';\n if (error instanceof RejectedSendError) {\n if (error.status === 408 || error.status === 429 || error.status >= 500) return 'keep';\n // The endpoint refuses the same counts again.\n return 'drop';\n }\n return 'keep';\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', '1.0'),\n attribute('cloudevents.event_data_content_type', 'application/json; charset=utf-8'),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', ''),\n attribute('cloudevents.event_origin', SERVICE_NAME),\n attribute('cloudevents.event_object', 'event'),\n attribute('cloudevents.event_category', 'product'),\n attribute('cloudevents.event_signal', 'metric'),\n ];\n for (const [key, value] of Object.entries(event.data.usage)) {\n attributes.push(attribute(`cloudevents.event_data.usage.${key}`, value));\n }\n for (const [key, value] of Object.entries(event.data.sdk)) {\n attributes.push(attribute(`cloudevents.event_data.sdk.${key}`, value));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
3
3
  //# sourceMappingURL=telemetry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,wBAAwB,GACnC,y9TAAy9T,CAAC"}
1
+ {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,wBAAwB,GACnC,0pYAA0pY,CAAC"}
@@ -1,4 +1,5 @@
1
1
  export { GO_RUNTIME_SOURCE } from './runtime-sources/go.js';
2
+ export { JAVA_RUNTIME_SOURCE } from './runtime-sources/java.js';
2
3
  export { PHP_RUNTIME_SOURCE } from './runtime-sources/php.js';
3
4
  export { PYTHON_RUNTIME_SOURCES, type PythonRuntimeModuleName } from './runtime-sources/python.js';
4
5
  export { TELEMETRY_RUNTIME_SOURCE } from './runtime-sources/telemetry.js';
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-sources.d.ts","sourceRoot":"","sources":["../src/runtime-sources.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,KAAK,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACnG,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,KAAK,iBAAiB,GACvB,MAAM,iCAAiC,CAAC"}
1
+ {"version":3,"file":"runtime-sources.d.ts","sourceRoot":"","sources":["../src/runtime-sources.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,KAAK,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACnG,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,KAAK,iBAAiB,GACvB,MAAM,iCAAiC,CAAC"}
@@ -4,6 +4,7 @@
4
4
  // `npm update` and the ejected file stays small and readable. Pure strings — this
5
5
  // entry's import graph must stay dependency-free (guarded like the root entry).
6
6
  export { GO_RUNTIME_SOURCE } from './runtime-sources/go.js';
7
+ export { JAVA_RUNTIME_SOURCE } from './runtime-sources/java.js';
7
8
  export { PHP_RUNTIME_SOURCE } from './runtime-sources/php.js';
8
9
  export { PYTHON_RUNTIME_SOURCES } from './runtime-sources/python.js';
9
10
  export { TELEMETRY_RUNTIME_SOURCE } from './runtime-sources/telemetry.js';
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-sources.js","sourceRoot":"","sources":["../src/runtime-sources.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,2FAA2F;AAC3F,+EAA+E;AAC/E,kFAAkF;AAClF,gFAAgF;AAEhF,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAgC,MAAM,6BAA6B,CAAC;AACnG,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EACL,eAAe,EACf,wBAAwB,GAEzB,MAAM,iCAAiC,CAAC"}
1
+ {"version":3,"file":"runtime-sources.js","sourceRoot":"","sources":["../src/runtime-sources.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,2FAA2F;AAC3F,+EAA+E;AAC/E,kFAAkF;AAClF,gFAAgF;AAEhF,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAgC,MAAM,6BAA6B,CAAC;AACnG,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EACL,eAAe,EACf,wBAAwB,GAEzB,MAAM,iCAAiC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redocly/client-generator",
3
- "version": "0.7.12",
3
+ "version": "0.8.0",
4
4
  "description": "Generate typed, zero-dependency TypeScript clients (fetch, auth, retries, middleware, SSE) from OpenAPI descriptions.",
5
5
  "type": "module",
6
6
  "types": "lib/index.d.ts",
@@ -31,6 +31,11 @@
31
31
  "import": "./lib/printers/php.js",
32
32
  "default": "./lib/printers/php.js"
33
33
  },
34
+ "./printers/java": {
35
+ "types": "./lib/printers/java.d.ts",
36
+ "import": "./lib/printers/java.js",
37
+ "default": "./lib/printers/java.js"
38
+ },
34
39
  "./printers/typescript": {
35
40
  "types": "./lib/printers/typescript.d.ts",
36
41
  "import": "./lib/printers/typescript.js",
@@ -82,7 +87,7 @@
82
87
  "Roman Marshevskyi <roman.marshevskyy@redocly.com> (https://redocly.com/)"
83
88
  ],
84
89
  "dependencies": {
85
- "@redocly/openapi-core": "2.71.1"
90
+ "@redocly/openapi-core": "2.72.0"
86
91
  },
87
92
  "peerDependencies": {
88
93
  "typescript": ">=5.5.0"