@redocly/client-generator 0.7.11 → 0.7.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/eject-assets/generators/cli/docs.ts +1 -1
- package/eject-assets/generators/cli/engine-source.ts +1 -1
- package/eject-assets/generators/cli/index.ts +2 -2
- package/eject-assets/generators/cli/render.ts +1 -1
- package/eject-assets/generators/go/client.ts +1 -1
- package/eject-assets/generators/go/descriptor.ts +1 -1
- package/eject-assets/generators/go/index.ts +2 -2
- package/eject-assets/generators/go/models.ts +7 -2
- package/eject-assets/generators/go/naming.ts +1 -1
- package/eject-assets/generators/go/operations.ts +1 -1
- package/eject-assets/generators/go/pagination.ts +1 -1
- package/eject-assets/generators/go/types.ts +1 -1
- package/eject-assets/generators/mock/faker.ts +17 -9
- package/eject-assets/generators/mock/index.ts +4 -3
- package/eject-assets/generators/mock/render.ts +128 -9
- package/eject-assets/generators/mock/sample.ts +87 -4
- package/eject-assets/generators/mock/values.ts +1 -1
- package/eject-assets/generators/php/client.ts +1 -1
- package/eject-assets/generators/php/descriptor.ts +10 -1
- package/eject-assets/generators/php/index.ts +2 -2
- package/eject-assets/generators/php/models.ts +8 -3
- package/eject-assets/generators/php/naming.ts +1 -1
- package/eject-assets/generators/php/operations.ts +11 -6
- package/eject-assets/generators/php/pagination.ts +3 -2
- package/eject-assets/generators/php/types.ts +12 -2
- package/eject-assets/generators/python/client.ts +1 -1
- package/eject-assets/generators/python/descriptor.ts +1 -1
- package/eject-assets/generators/python/index.ts +3 -3
- package/eject-assets/generators/python/models.ts +9 -3
- package/eject-assets/generators/python/naming.ts +1 -1
- package/eject-assets/generators/python/operations.ts +6 -5
- package/eject-assets/generators/python/pagination.ts +1 -1
- package/eject-assets/generators/python/types.ts +1 -1
- package/eject-assets/generators/swr/index.ts +2 -2
- package/eject-assets/generators/swr/render.ts +1 -1
- package/eject-assets/generators/tanstack-query/index.ts +2 -2
- package/eject-assets/generators/tanstack-query/render.ts +6 -5
- package/eject-assets/generators/transformers/index.ts +2 -2
- package/eject-assets/generators/transformers/render.ts +34 -7
- package/eject-assets/generators/typescript/banner.ts +1 -1
- package/eject-assets/generators/typescript/client.ts +1 -1
- package/eject-assets/generators/typescript/descriptor.ts +1 -1
- package/eject-assets/generators/typescript/index.ts +2 -2
- package/eject-assets/generators/typescript/inline-runtime.ts +1 -1
- package/eject-assets/generators/typescript/operation-signature.ts +1 -1
- package/eject-assets/generators/typescript/operation-types.ts +1 -1
- package/eject-assets/generators/typescript/operations.ts +1 -1
- package/eject-assets/generators/typescript/response-headers.ts +1 -1
- package/eject-assets/generators/typescript/type-guards.ts +1 -1
- package/eject-assets/generators/typescript/types.ts +1 -1
- package/eject-assets/generators/zod/index.ts +2 -2
- package/eject-assets/generators/zod/schemas.ts +1 -1
- package/eject-assets/skills/go-generator/SKILL.md +3 -0
- package/eject-assets/skills/mock-generator/SKILL.md +22 -0
- package/eject-assets/skills/php-generator/SKILL.md +9 -2
- package/eject-assets/skills/python-generator/SKILL.md +6 -0
- package/eject-assets/skills/tanstack-query-generator/SKILL.md +2 -1
- package/eject-assets/skills/transformers-generator/SKILL.md +4 -0
- package/eject-assets/skills/typescript-generator/SKILL.md +5 -0
- package/lib/authoring/schema.d.ts.map +1 -1
- package/lib/authoring/schema.js +4 -1
- package/lib/authoring/schema.js.map +1 -1
- package/lib/generators/go/models.d.ts.map +1 -1
- package/lib/generators/go/models.js +4 -1
- package/lib/generators/go/models.js.map +1 -1
- package/lib/generators/mock/faker.js +18 -8
- package/lib/generators/mock/faker.js.map +1 -1
- package/lib/generators/mock/index.d.ts.map +1 -1
- package/lib/generators/mock/index.js +2 -1
- package/lib/generators/mock/index.js.map +1 -1
- package/lib/generators/mock/render.d.ts +3 -1
- package/lib/generators/mock/render.d.ts.map +1 -1
- package/lib/generators/mock/render.js +119 -9
- package/lib/generators/mock/render.js.map +1 -1
- package/lib/generators/mock/sample.d.ts +18 -1
- package/lib/generators/mock/sample.d.ts.map +1 -1
- package/lib/generators/mock/sample.js +71 -2
- package/lib/generators/mock/sample.js.map +1 -1
- package/lib/generators/php/descriptor.d.ts +6 -0
- package/lib/generators/php/descriptor.d.ts.map +1 -1
- package/lib/generators/php/descriptor.js +8 -0
- package/lib/generators/php/descriptor.js.map +1 -1
- package/lib/generators/php/models.d.ts.map +1 -1
- package/lib/generators/php/models.js +5 -2
- package/lib/generators/php/models.js.map +1 -1
- package/lib/generators/php/operations.d.ts.map +1 -1
- package/lib/generators/php/operations.js +5 -5
- package/lib/generators/php/operations.js.map +1 -1
- package/lib/generators/php/pagination.d.ts.map +1 -1
- package/lib/generators/php/pagination.js +2 -1
- package/lib/generators/php/pagination.js.map +1 -1
- package/lib/generators/php/types.d.ts.map +1 -1
- package/lib/generators/php/types.js +13 -2
- package/lib/generators/php/types.js.map +1 -1
- package/lib/generators/python/index.js +1 -1
- package/lib/generators/python/index.js.map +1 -1
- package/lib/generators/python/models.d.ts.map +1 -1
- package/lib/generators/python/models.js +6 -2
- package/lib/generators/python/models.js.map +1 -1
- package/lib/generators/python/operations.d.ts.map +1 -1
- package/lib/generators/python/operations.js +5 -4
- package/lib/generators/python/operations.js.map +1 -1
- package/lib/generators/tanstack-query/render.js +5 -4
- package/lib/generators/tanstack-query/render.js.map +1 -1
- package/lib/generators/transformers/render.d.ts +1 -1
- package/lib/generators/transformers/render.d.ts.map +1 -1
- package/lib/generators/transformers/render.js +24 -5
- package/lib/generators/transformers/render.js.map +1 -1
- package/lib/generators/typescript/runtime/create-client.js +1 -1
- package/lib/generators/typescript/runtime/create-client.js.map +1 -1
- package/lib/generators/typescript/runtime/paginate.d.ts.map +1 -1
- package/lib/generators/typescript/runtime/paginate.js +5 -4
- package/lib/generators/typescript/runtime/paginate.js.map +1 -1
- package/lib/generators/typescript/runtime/send.d.ts.map +1 -1
- package/lib/generators/typescript/runtime/send.js +10 -4
- package/lib/generators/typescript/runtime/send.js.map +1 -1
- package/lib/generators/typescript/runtime/sse.d.ts.map +1 -1
- package/lib/generators/typescript/runtime/sse.js +6 -1
- package/lib/generators/typescript/runtime/sse.js.map +1 -1
- package/lib/generators/typescript/telemetry/telemetry.d.ts.map +1 -1
- package/lib/generators/typescript/telemetry/telemetry.js +72 -11
- package/lib/generators/typescript/telemetry/telemetry.js.map +1 -1
- package/lib/intermediate-representation/build.d.ts.map +1 -1
- package/lib/intermediate-representation/build.js +51 -26
- package/lib/intermediate-representation/build.js.map +1 -1
- package/lib/intermediate-representation/model.d.ts +6 -2
- package/lib/intermediate-representation/model.d.ts.map +1 -1
- package/lib/intermediate-representation/model.js.map +1 -1
- package/lib/runtime-contract.d.ts +1 -1
- package/lib/runtime-contract.d.ts.map +1 -1
- package/lib/runtime-contract.js.map +1 -1
- package/lib/runtime-sources/python.d.ts +2 -2
- package/lib/runtime-sources/python.js +2 -2
- package/lib/runtime-sources/python.js.map +1 -1
- package/lib/runtime-sources/telemetry.d.ts +1 -1
- package/lib/runtime-sources/telemetry.d.ts.map +1 -1
- package/lib/runtime-sources/telemetry.js +1 -1
- package/lib/runtime-sources/telemetry.js.map +1 -1
- package/lib/runtime-sources/typescript.d.ts +10 -10
- package/lib/runtime-sources/typescript.js +10 -10
- package/lib/runtime-sources/typescript.js.map +1 -1
- package/package.json +2 -2
|
@@ -2,8 +2,8 @@ export declare const PYTHON_RUNTIME_SOURCES: {
|
|
|
2
2
|
readonly '_errors.py': "# Runtime errors and the result-mode envelope for generated Python clients.\n# Hand-authored once, embedded into every generated client (see\n# scripts/generate-runtime-sources.mjs) — mirror of the TypeScript runtime's\n# errors.ts, kept semantically in lockstep.\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, Optional, TypeVar\n\nT = TypeVar(\"T\")\nE = TypeVar(\"E\")\n\n\nclass ApiError(Exception):\n \"\"\"Raised (throw mode) for a non-2xx response, carrying the decoded error body.\"\"\"\n\n def __init__(self, url: str, status: int, status_text: str, body: Any) -> None:\n super().__init__(f\"Request failed with status {status}\")\n self.url = url\n self.status = status\n self.status_text = status_text\n self.body = body\n\n\nclass ApiTimeoutError(Exception):\n \"\"\"Raised when a request attempt exceeds the configured timeout — carries the\n context a log line needs (which operation, what budget, which attempt).\"\"\"\n\n def __init__(self, operation_id: str, timeout: float, attempt: int) -> None:\n super().__init__(\n f'Request \"{operation_id}\" timed out after {timeout} s (attempt {attempt})'\n )\n self.operation_id = operation_id\n self.timeout = timeout\n self.attempt = attempt\n\n\n@dataclass\nclass Result(Generic[T, E]):\n \"\"\"Result-mode return shape: exactly one of `data`/`error` is set.\"\"\"\n\n data: Optional[T]\n error: Optional[E]\n response: Any # httpx.Response\n\n @property\n def ok(self) -> bool:\n return self.error is None\n";
|
|
3
3
|
readonly '_auth.py': "# Auth resolution for generated Python clients — mirror of the TypeScript\n# runtime's auth.ts: the first OR-alternative whose schemes are all configured\n# is applied, so \"bearer OR apiKey\" works with either credential and never\n# sends both. Cookie-borne api keys fold into a single Cookie header.\nfrom __future__ import annotations\n\nimport base64\nfrom typing import Any, Callable, Dict, List, Tuple, Union\nfrom urllib.parse import quote\n\nTokenProvider = Union[str, Callable[[], str]]\n\n\ndef _api_keys(auth: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"The apiKey credentials. `apiKey` is the documented key (it matches the scheme\n kind and the other language SDKs); `api_key` is accepted too, so a snake_case\n config keeps working.\"\"\"\n return {**(auth.get(\"api_key\") or {}), **(auth.get(\"apiKey\") or {})}\n\ndef _resolve_token(provider: TokenProvider) -> str:\n return provider() if callable(provider) else provider\n\n\ndef _is_configured(scheme: Dict[str, Any], auth: Dict[str, Any]) -> bool:\n kind = scheme[\"kind\"]\n if kind == \"apiKey\":\n return scheme[\"scheme\"] in _api_keys(auth)\n if kind == \"bearer\":\n return auth.get(\"bearer\") is not None\n return auth.get(\"basic\") is not None\n\n\ndef resolve_auth(\n security: List[List[Dict[str, Any]]], auth: Dict[str, Any]\n) -> Tuple[Dict[str, str], Dict[str, str]]:\n \"\"\"Build (headers, query) for one operation's security OR-alternatives from\n the client credentials. When no alternative is fully configured, the first\n alternative's configured schemes are still sent (the server rejects the\n request — same behavior as the TypeScript runtime).\"\"\"\n alternative = next(\n (schemes for schemes in security if all(_is_configured(s, auth) for s in schemes)),\n security[0] if security else [],\n )\n headers: Dict[str, str] = {}\n query: Dict[str, str] = {}\n cookies: List[str] = []\n for scheme in alternative:\n kind = scheme[\"kind\"]\n if kind == \"apiKey\":\n provider = _api_keys(auth).get(scheme[\"scheme\"])\n if provider is None:\n continue\n value = _resolve_token(provider)\n location = scheme.get(\"in\", \"header\")\n if location == \"header\":\n headers[scheme[\"name\"]] = value\n elif location == \"query\":\n query[scheme[\"name\"]] = value\n else:\n # Reserved characters (`;`, `=`, space) must not break Cookie syntax.\n cookies.append(f\"{scheme['name']}={quote(value, safe='')}\")\n elif kind == \"bearer\":\n provider = auth.get(\"bearer\")\n if provider is not None:\n headers[\"Authorization\"] = f\"Bearer {_resolve_token(provider)}\"\n else:\n basic = auth.get(\"basic\")\n if basic is not None:\n username, password = basic[\"username\"], basic[\"password\"]\n token = base64.b64encode(f\"{username}:{password}\".encode(\"utf-8\")).decode(\"ascii\")\n headers[\"Authorization\"] = f\"Basic {token}\"\n if cookies:\n headers[\"Cookie\"] = \"; \".join(cookies)\n return headers, query\n";
|
|
4
4
|
readonly '_url.py': "# URL assembly for generated Python clients — path-parameter substitution with\n# percent-encoding, mirroring the TypeScript runtime's url.ts semantics.\nfrom __future__ import annotations\n\nfrom typing import Any, Dict\nfrom urllib.parse import quote\n\n\ndef build_url(server_url: str, path: str, path_params: Dict[str, Any]) -> str:\n filled = path\n for name, value in path_params.items():\n filled = filled.replace(\"{\" + name + \"}\", quote(str(value), safe=\"\"))\n return server_url.rstrip(\"/\") + filled\n";
|
|
5
|
-
readonly '_decode.py': "# Reflective JSON <-> model conversion for generated Python clients. Models are\n# plain dataclasses by default, or pydantic BaseModels under `models: pydantic`;\n# one decoder serves both. For a dataclass it hydrates parsed JSON reflectively,\n# honoring each class's `_field_map` (python name -> wire name) and the typing\n# constructs the generator emits: Optional/Union, List, Dict, Enum, Literal, Any.\n# For a pydantic model it defers to pydantic, which already knows the aliases.\n# encode() mirrors whichever it was given back to wire shape.\nfrom __future__ import annotations\n\nimport dataclasses\nimport typing\nfrom datetime import date, datetime\nfrom enum import Enum\nfrom typing import Any, Dict, Tuple, get_args, get_origin, get_type_hints\n\n# Discriminated unions: resolved Union annotation -> (wire property, {value: class}).\n# The generated module registers its unions here; decode() dispatches through it\n# before falling back to trying members in order.\nDISCRIMINATORS: Dict[Any, Tuple[str, Dict[str, Any]]] = {}\n\n\ndef decode(type_: Any, data: Any):\n \"\"\"Best-effort hydration: wire data -> the annotated Python shape. Unknown or\n mismatched shapes pass through unchanged (the server is the source of truth).\"\"\"\n if data is None or type_ is Any or type_ is None:\n return data\n # `Annotated[Union[...], Field(discriminator=...)]`: pydantic reads that annotation on a\n # model's own field, so here only the union underneath matters.\n if hasattr(type_, \"__metadata__\"):\n type_ = get_args(type_)[0]\n origin = get_origin(type_)\n if origin is typing.Union:\n discriminator = DISCRIMINATORS.get(type_)\n if discriminator is not None and isinstance(data, dict):\n wire_property, mapping = discriminator\n
|
|
6
|
-
readonly '_send.py': "# The request core for generated Python clients — mirror of the TypeScript\n# runtime's send.ts: default + config + per-call headers, on_request middleware\n# BEFORE serialization (mutations are sent), the retry loop (idempotent-methods\n# default, Idempotency-Key opt-in makes POST/PATCH safe, Retry-After honored,\n# exponential backoff with full jitter, a fresh timeout budget per attempt), and\n# the reverse on_response onion.\nfrom __future__ import annotations\n\nimport asyncio\nimport random\nimport time\nimport uuid\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar\n\nimport httpx\n\nfrom ._errors import ApiTimeoutError\n\nT = TypeVar(\"T\")\n\n\n@dataclass\nclass Envelope(Generic[T]):\n \"\"\"A *_with_headers() result: decoded body + coerced declared headers + raw response.\"\"\"\n\n data: T\n headers: Dict[str, Any]\n response: httpx.Response\n\n\ndef read_envelope_headers(\n response: httpx.Response, specs: List[Tuple[str, str, str]]\n) -> Dict[str, Any]:\n \"\"\"Coerce declared response headers per (name, key, type) specs; absent/unparsable omitted.\"\"\"\n headers: Dict[str, Any] = {}\n for name, key, type_ in specs:\n raw = response.headers.get(name)\n if raw is None:\n continue\n if type_ in (\"integer\", \"number\"):\n try:\n headers[key] = int(raw) if type_ == \"integer\" else float(raw)\n except ValueError:\n pass\n elif type_ == \"boolean\":\n lower = raw.strip().lower()\n if lower in (\"true\", \"false\"):\n headers[key] = lower == \"true\"\n else:\n headers[key] = raw\n return headers\n\n\n_IDEMPOTENT_METHODS = {\"GET\", \"HEAD\", \"PUT\", \"DELETE\", \"OPTIONS\"}\n_TRANSIENT_STATUS = {408, 429, 500, 502, 503, 504}\n\n\ndef _default_retry_on(method: str, headers: Dict[str, str], response: Optional[httpx.Response]) -> bool:\n safe = method.upper() in _IDEMPOTENT_METHODS or \"Idempotency-Key\" in headers\n if not safe:\n return False\n return response is None or response.status_code in _TRANSIENT_STATUS\n\n\ndef _retry_delay(retry: Dict[str, Any], attempt: int, retry_after: Optional[str]) -> float:\n if retry_after:\n try:\n return float(retry_after)\n except ValueError:\n pass # HTTP-date form: fall through to backoff\n base = float(retry.get(\"retry_delay\", 1.0))\n raw = base if retry.get(\"retry_strategy\") == \"fixed\" else base * (2 ** (attempt - 1))\n return random.uniform(0, raw) if retry.get(\"jitter\", True) is not False else raw\n\n\ndef send(\n client: httpx.Client,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n merged_retry: Dict[str, Any] = {**(config.get(\"retry\") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get(\"timeout\")\n merged_headers: Dict[str, str] = {**(config.get(\"headers\") or {}), **(headers or {})}\n\n # One stable key per LOGICAL call — set before the retry loop so every\n # attempt re-sends the same key; a caller-provided header always wins.\n key = idempotency_key if idempotency_key is not None else config.get(\"idempotency_key\")\n if (\n key not in (None, False)\n and method.upper() in (\"POST\", \"PATCH\")\n and \"Idempotency-Key\" not in merged_headers\n ):\n merged_headers[\"Idempotency-Key\"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n # The declared content type fills the gap; a caller-provided header always wins.\n if content_type is not None and not any(name.lower() == \"content-type\" for name in merged_headers):\n merged_headers[\"Content-Type\"] = content_type\n\n context = {\n \"url\": url,\n \"method\": method.upper(),\n \"headers\": merged_headers,\n \"body\": json_body,\n \"operation\": op,\n }\n middleware: List[Any] = config.get(\"middleware\") or []\n for mw in middleware:\n on_request = getattr(mw, \"on_request\", None) or (mw.get(\"on_request\") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get(\"retries\", 0)) if replayable else 1\n retry_on = merged_retry.get(\"retry_on\") or (\n lambda ctx: _default_retry_on(context[\"method\"], context[\"headers\"], ctx.get(\"response\"))\n )\n\n attempt = 0\n while True:\n attempt += 1\n try:\n response = client.request(\n context[\"method\"],\n context[\"url\"],\n headers=context[\"headers\"],\n params=params,\n json=context[\"body\"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get(\"id\", \"?\"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n\n for mw in reversed(middleware):\n on_response = getattr(mw, \"on_response\", None) or (mw.get(\"on_response\") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({\"attempt\": attempt, \"response\": response})\n ):\n time.sleep(_retry_delay(merged_retry, attempt, response.headers.get(\"retry-after\")))\n continue\n return response\n\n\nasync def send_async(\n client: httpx.AsyncClient,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n \"\"\"The async mirror of send() — same retry/timeout/idempotency semantics.\"\"\"\n merged_retry: Dict[str, Any] = {**(config.get(\"retry\") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get(\"timeout\")\n merged_headers: Dict[str, str] = {**(config.get(\"headers\") or {}), **(headers or {})}\n key = idempotency_key if idempotency_key is not None else config.get(\"idempotency_key\")\n if (\n key not in (None, False)\n and method.upper() in (\"POST\", \"PATCH\")\n and \"Idempotency-Key\" not in merged_headers\n ):\n merged_headers[\"Idempotency-Key\"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n if content_type is not None and not any(name.lower() == \"content-type\" for name in merged_headers):\n merged_headers[\"Content-Type\"] = content_type\n context = {\n \"url\": url,\n \"method\": method.upper(),\n \"headers\": merged_headers,\n \"body\": json_body,\n \"operation\": op,\n }\n middleware: List[Any] = config.get(\"middleware\") or []\n for mw in middleware:\n on_request = getattr(mw, \"on_request\", None) or (mw.get(\"on_request\") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get(\"retries\", 0)) if replayable else 1\n retry_on = merged_retry.get(\"retry_on\") or (\n lambda ctx: _default_retry_on(context[\"method\"], context[\"headers\"], ctx.get(\"response\"))\n )\n attempt = 0\n while True:\n attempt += 1\n try:\n response = await client.request(\n context[\"method\"],\n context[\"url\"],\n headers=context[\"headers\"],\n params=params,\n json=context[\"body\"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get(\"id\", \"?\"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n for mw in reversed(middleware):\n on_response = getattr(mw, \"on_response\", None) or (mw.get(\"on_response\") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({\"attempt\": attempt, \"response\": response})\n ):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, response.headers.get(\"retry-after\")))\n continue\n return response\n";
|
|
5
|
+
readonly '_decode.py': "# Reflective JSON <-> model conversion for generated Python clients. Models are\n# plain dataclasses by default, or pydantic BaseModels under `models: pydantic`;\n# one decoder serves both. For a dataclass it hydrates parsed JSON reflectively,\n# honoring each class's `_field_map` (python name -> wire name) and the typing\n# constructs the generator emits: Optional/Union, List, Dict, Enum, Literal, Any.\n# For a pydantic model it defers to pydantic, which already knows the aliases.\n# encode() mirrors whichever it was given back to wire shape.\nfrom __future__ import annotations\n\nimport dataclasses\nimport typing\nfrom datetime import date, datetime\nfrom enum import Enum\nfrom typing import Any, Dict, Tuple, get_args, get_origin, get_type_hints\n\n# Discriminated unions: resolved Union annotation -> (wire property, {value: class}).\n# The generated module registers its unions here; decode() dispatches through it\n# before falling back to trying members in order.\nDISCRIMINATORS: Dict[Any, Tuple[str, Dict[str, Any]]] = {}\n\n\ndef decode(type_: Any, data: Any) -> Any:\n \"\"\"Best-effort hydration: wire data -> the annotated Python shape. Unknown or\n mismatched shapes pass through unchanged (the server is the source of truth).\"\"\"\n if data is None or type_ is Any or type_ is None:\n return data\n # `Annotated[Union[...], Field(discriminator=...)]`: pydantic reads that annotation on a\n # model's own field, so here only the union underneath matters.\n if hasattr(type_, \"__metadata__\"):\n type_ = get_args(type_)[0]\n origin = get_origin(type_)\n if origin is typing.Union:\n discriminator = DISCRIMINATORS.get(type_)\n if discriminator is not None and isinstance(data, dict):\n wire_property, mapping = discriminator\n value = data.get(wire_property)\n target = mapping.get(value) if isinstance(value, str) else None\n if target is not None:\n try:\n return decode(target, data)\n except (TypeError, ValueError, KeyError):\n pass\n for member in get_args(type_):\n if member is type(None):\n continue\n try:\n return decode(member, data)\n except (TypeError, ValueError, KeyError):\n continue\n return data\n if origin is list:\n (item_type,) = get_args(type_) or (Any,)\n return [decode(item_type, item) for item in data]\n if origin is dict:\n args = get_args(type_)\n value_type = args[1] if len(args) == 2 else Any\n return {key: decode(value_type, value) for key, value in data.items()}\n if origin is typing.Literal:\n return data\n if isinstance(type_, type) and issubclass(type_, Enum):\n return type_(data)\n # `dateType: Date` annotates date/date-time fields as datetime objects; a value that\n # doesn't parse passes through unchanged (the server is the source of truth).\n if type_ is datetime or type_ is date:\n if not isinstance(data, str):\n return data\n try:\n # `datetime` accepts a bare date too; `date` rejects a timestamp, so trim it.\n return (\n datetime.fromisoformat(data)\n if type_ is datetime\n else date.fromisoformat(data[:10])\n )\n except ValueError:\n return data\n # A pydantic model validates itself, aliases included. `ValidationError`\n # subclasses `ValueError`, so union member probing above still works.\n if isinstance(type_, type) and hasattr(type_, \"model_validate\"):\n return type_.model_validate(data)\n if dataclasses.is_dataclass(type_) and isinstance(type_, type):\n hints = get_type_hints(type_)\n field_map = getattr(type_, \"_field_map\", {})\n kwargs: Dict[str, Any] = {}\n for field in dataclasses.fields(type_):\n wire = field_map.get(field.name, field.name)\n if isinstance(data, dict) and wire in data:\n kwargs[field.name] = decode(hints.get(field.name, Any), data[wire])\n return type_(**kwargs)\n return data\n\n\ndef encode(value: Any) -> Any:\n \"\"\"Python shape -> wire (JSON) shape; inverse of decode for request bodies.\"\"\"\n # `mode=\"json\"` resolves datetimes and enums the same way the branches below do,\n # and `exclude_none` matches the dataclass path: an unset optional is not sent.\n if hasattr(value, \"model_dump\") and not isinstance(value, type):\n return value.model_dump(by_alias=True, exclude_none=True, mode=\"json\")\n if dataclasses.is_dataclass(value) and not isinstance(value, type):\n field_map = getattr(type(value), \"_field_map\", {})\n out = {}\n for field in dataclasses.fields(value):\n item = getattr(value, field.name)\n if item is None:\n continue\n out[field_map.get(field.name, field.name)] = encode(item)\n return out\n if isinstance(value, Enum):\n return value.value\n # A date-only value must not gain a time component on the way out.\n if isinstance(value, datetime):\n return value.isoformat()\n if isinstance(value, date):\n return value.isoformat()\n if isinstance(value, list):\n return [encode(item) for item in value]\n if isinstance(value, dict):\n return {key: encode(item) for key, item in value.items()}\n return value\n";
|
|
6
|
+
readonly '_send.py': "# The request core for generated Python clients — mirror of the TypeScript\n# runtime's send.ts: default + config + per-call headers, on_request middleware\n# BEFORE serialization (mutations are sent), the retry loop (idempotent-methods\n# default, Idempotency-Key opt-in makes POST/PATCH safe, Retry-After honored,\n# exponential backoff with full jitter, a fresh timeout budget per attempt), and\n# the reverse on_response onion.\nfrom __future__ import annotations\n\nimport asyncio\nimport random\nimport time\nimport uuid\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar\n\nimport httpx\n\nfrom ._errors import ApiTimeoutError\n\n# Not `T`: the runtime modules share one generated file, where `_errors.py` defines `T`.\nTData = TypeVar(\"TData\")\n\n\n@dataclass\nclass Envelope(Generic[TData]):\n \"\"\"A *_with_headers() result: decoded body + coerced declared headers + raw response.\"\"\"\n\n data: TData\n headers: Dict[str, Any]\n response: httpx.Response\n\n\ndef read_envelope_headers(\n response: httpx.Response, specs: List[Tuple[str, str, str]]\n) -> Dict[str, Any]:\n \"\"\"Coerce declared response headers per (name, key, type) specs; absent/unparsable omitted.\"\"\"\n headers: Dict[str, Any] = {}\n for name, key, type_ in specs:\n raw = response.headers.get(name)\n if raw is None:\n continue\n if type_ in (\"integer\", \"number\"):\n try:\n headers[key] = int(raw) if type_ == \"integer\" else float(raw)\n except ValueError:\n pass\n elif type_ == \"boolean\":\n lower = raw.strip().lower()\n if lower in (\"true\", \"false\"):\n headers[key] = lower == \"true\"\n else:\n headers[key] = raw\n return headers\n\n\n_IDEMPOTENT_METHODS = {\"GET\", \"HEAD\", \"PUT\", \"DELETE\", \"OPTIONS\"}\n_TRANSIENT_STATUS = {408, 429, 500, 502, 503, 504}\n\n\ndef _default_retry_on(method: str, headers: Dict[str, str], response: Optional[httpx.Response]) -> bool:\n safe = method.upper() in _IDEMPOTENT_METHODS or \"Idempotency-Key\" in headers\n if not safe:\n return False\n return response is None or response.status_code in _TRANSIENT_STATUS\n\n\ndef _retry_delay(retry: Dict[str, Any], attempt: int, retry_after: Optional[str]) -> float:\n if retry_after:\n try:\n return float(retry_after)\n except ValueError:\n pass # HTTP-date form: fall through to backoff\n base = float(retry.get(\"retry_delay\", 1.0))\n raw = base if retry.get(\"retry_strategy\") == \"fixed\" else base * (2 ** (attempt - 1))\n return random.uniform(0, raw) if retry.get(\"jitter\", True) is not False else raw\n\n\ndef send(\n client: httpx.Client,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n merged_retry: Dict[str, Any] = {**(config.get(\"retry\") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get(\"timeout\")\n merged_headers: Dict[str, str] = {**(config.get(\"headers\") or {}), **(headers or {})}\n\n # One stable key per LOGICAL call — set before the retry loop so every\n # attempt re-sends the same key; a caller-provided header always wins.\n key = idempotency_key if idempotency_key is not None else config.get(\"idempotency_key\")\n if (\n key not in (None, False)\n and method.upper() in (\"POST\", \"PATCH\")\n and \"Idempotency-Key\" not in merged_headers\n ):\n merged_headers[\"Idempotency-Key\"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n # The declared content type fills the gap; a caller-provided header always wins.\n if content_type is not None and not any(name.lower() == \"content-type\" for name in merged_headers):\n merged_headers[\"Content-Type\"] = content_type\n\n context = {\n \"url\": url,\n \"method\": method.upper(),\n \"headers\": merged_headers,\n \"body\": json_body,\n \"operation\": op,\n }\n middleware: List[Any] = config.get(\"middleware\") or []\n for mw in middleware:\n on_request = getattr(mw, \"on_request\", None) or (mw.get(\"on_request\") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get(\"retries\", 0)) if replayable else 1\n retry_on = merged_retry.get(\"retry_on\") or (\n lambda ctx: _default_retry_on(context[\"method\"], context[\"headers\"], ctx.get(\"response\"))\n )\n\n attempt = 0\n while True:\n attempt += 1\n try:\n response = client.request(\n context[\"method\"],\n context[\"url\"],\n headers=context[\"headers\"],\n params=params,\n json=context[\"body\"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get(\"id\", \"?\"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n\n for mw in reversed(middleware):\n on_response = getattr(mw, \"on_response\", None) or (mw.get(\"on_response\") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({\"attempt\": attempt, \"response\": response})\n ):\n time.sleep(_retry_delay(merged_retry, attempt, response.headers.get(\"retry-after\")))\n continue\n return response\n\n\nasync def send_async(\n client: httpx.AsyncClient,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n \"\"\"The async mirror of send() — same retry/timeout/idempotency semantics.\"\"\"\n merged_retry: Dict[str, Any] = {**(config.get(\"retry\") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get(\"timeout\")\n merged_headers: Dict[str, str] = {**(config.get(\"headers\") or {}), **(headers or {})}\n key = idempotency_key if idempotency_key is not None else config.get(\"idempotency_key\")\n if (\n key not in (None, False)\n and method.upper() in (\"POST\", \"PATCH\")\n and \"Idempotency-Key\" not in merged_headers\n ):\n merged_headers[\"Idempotency-Key\"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n if content_type is not None and not any(name.lower() == \"content-type\" for name in merged_headers):\n merged_headers[\"Content-Type\"] = content_type\n context = {\n \"url\": url,\n \"method\": method.upper(),\n \"headers\": merged_headers,\n \"body\": json_body,\n \"operation\": op,\n }\n middleware: List[Any] = config.get(\"middleware\") or []\n for mw in middleware:\n on_request = getattr(mw, \"on_request\", None) or (mw.get(\"on_request\") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get(\"retries\", 0)) if replayable else 1\n retry_on = merged_retry.get(\"retry_on\") or (\n lambda ctx: _default_retry_on(context[\"method\"], context[\"headers\"], ctx.get(\"response\"))\n )\n attempt = 0\n while True:\n attempt += 1\n try:\n response = await client.request(\n context[\"method\"],\n context[\"url\"],\n headers=context[\"headers\"],\n params=params,\n json=context[\"body\"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get(\"id\", \"?\"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({\"attempt\": attempt, \"response\": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n for mw in reversed(middleware):\n on_response = getattr(mw, \"on_response\", None) or (mw.get(\"on_response\") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({\"attempt\": attempt, \"response\": response})\n ):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, response.headers.get(\"retry-after\")))\n continue\n return response\n";
|
|
7
7
|
readonly '_paginate.py': "# Auto-pagination iterators for generated Python clients — the TypeScript\n# runtime's paginate.ts semantics ported: cursor (next-cursor pointer, optional\n# has-more flag, repeated-cursor guard), offset/page (advance by count/one,\n# repeated-page guard, null start treated as absent), link (RFC 8288\n# `Link: rel=\"next\"` following) and body-link (the next-link pointer's URL), both\n# with relative resolution and a loop guard.\nfrom __future__ import annotations\n\nimport re\nfrom typing import Any, AsyncIterator, Awaitable, Callable, Dict, Iterator, Optional, Tuple\nfrom urllib.parse import parse_qsl, urljoin, urlparse\n\n# call(params) -> (parsed_json, httpx.Response)\nPageCall = Callable[[Dict[str, Any]], Tuple[Any, Any]]\n\n\ndef resolve_pointer(data: Any, pointer: str) -> Any:\n \"\"\"RFC 6901 JSON pointer over parsed JSON; None on any miss.\"\"\"\n if pointer == \"\":\n return data\n if not pointer.startswith(\"/\"):\n return None\n current = data\n for token in pointer[1:].split(\"/\"):\n key = token.replace(\"~1\", \"/\").replace(\"~0\", \"~\")\n if isinstance(current, dict):\n current = current.get(key)\n elif isinstance(current, list) and key.isdigit():\n index = int(key)\n current = current[index] if index < len(current) else None\n else:\n return None\n if current is None:\n return None\n return current\n\n\ndef iter_pages(call: PageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None) -> Iterator[Any]:\n \"\"\"Yield raw page JSON per the pagination spec; every page is yielded before\n the stop condition is evaluated, so the last page always arrives.\"\"\"\n style = spec[\"style\"]\n base = dict(params or {})\n if style == \"cursor\":\n cursor = base.get(spec[\"param\"])\n while True:\n page_params = dict(base)\n if cursor is not None:\n page_params[spec[\"param\"]] = cursor\n page, _response = call(page_params)\n yield page\n if spec.get(\"has_more\") is not None and resolve_pointer(page, spec[\"has_more\"]) is False:\n return\n nxt = resolve_pointer(page, spec.get(\"next_cursor\", \"\"))\n if nxt is None or nxt == \"\":\n return\n if not isinstance(nxt, (str, int, float)):\n raise ValueError(f\"Pagination cursor at {spec['next_cursor']} is not a string or number\")\n if nxt == cursor:\n raise ValueError(\"Pagination did not advance: the operation returned the same cursor twice\")\n cursor = nxt\n elif style in (\"link\", \"body-link\"):\n yield from _iter_pages_by_link(call, spec, base)\n else: # offset / page\n start = base.get(spec[\"param\"])\n fallback = 1 if style == \"page\" else 0\n try:\n position = fallback if start in (None, \"\") else int(start)\n except (TypeError, ValueError):\n position = fallback\n previous_items = None\n while True:\n page, _response = call({**base, spec[\"param\"]: position})\n items = resolve_pointer(page, spec.get(\"items\", \"\"))\n serialized = repr(items) if isinstance(items, list) else None\n if serialized is not None and serialized == previous_items:\n raise ValueError(\"Pagination did not advance: the operation returned the same page twice\")\n yield page\n if not isinstance(items, list) or len(items) == 0:\n return\n previous_items = serialized\n position += 1 if style == \"page\" else len(items)\n\n\ndef _link_next(header: Optional[str]) -> Optional[str]:\n if not header:\n return None\n for entry in re.split(r\",\\s*(?=<)\", header):\n match = re.match(r\"^\\s*<([^>]*)>(.*)$\", entry)\n if not match:\n continue\n rel = re.search(r';\\s*rel\\s*=\\s*\"?([^\";]+)\"?', match.group(2), re.IGNORECASE)\n if rel and \"next\" in rel.group(1).split():\n return match.group(1)\n return None\n\n\ndef _next_link(spec: Dict[str, Any], page: Any, response: Any) -> Optional[str]:\n \"\"\"The next page's URL: the `Link` header's rel=\"next\" target for `link`, the value at\n the `next_link` pointer for `body-link`; None when absent, null, or empty.\"\"\"\n if spec[\"style\"] == \"link\":\n return _link_next(response.headers.get(\"link\"))\n pointer = spec[\"next_link\"]\n target = resolve_pointer(page, pointer)\n if target is None or target == \"\":\n return None\n if not isinstance(target, str):\n raise ValueError(f\"Pagination link at {pointer} is not a string\")\n return target\n\n\ndef _iter_pages_by_link(call: PageCall, spec: Dict[str, Any], base: Dict[str, Any]) -> Iterator[Any]:\n params = dict(base)\n previous = None\n while True:\n page, response = call(params)\n yield page\n target = _next_link(spec, page, response)\n if target is None:\n return\n page_url = str(response.request.url) if response.request is not None else \"\"\n nxt = urljoin(page_url or \"http://relative.invalid\", target)\n if nxt in (previous, page_url):\n raise ValueError('Pagination did not advance: the Link rel=\"next\" target repeats')\n previous = nxt\n link_params: Dict[str, Any] = {}\n for key, value in parse_qsl(urlparse(nxt).query):\n if key in link_params:\n existing = link_params[key]\n link_params[key] = [*existing, value] if isinstance(existing, list) else [existing, value]\n else:\n link_params[key] = value\n params = {**base, **link_params}\n\n\ndef iter_items(call: PageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None) -> Iterator[Any]:\n \"\"\"Each page's `items` pointer, flattened.\"\"\"\n for page in iter_pages(call, spec, params):\n items = resolve_pointer(page, spec.get(\"items\", \"\"))\n if isinstance(items, list):\n yield from items\n\n\n# call(params) -> awaitable of (parsed_json, httpx.Response)\nAsyncPageCall = Callable[[Dict[str, Any]], Awaitable[Tuple[Any, Any]]]\n\n\nasync def aiter_pages(\n call: AsyncPageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None\n) -> AsyncIterator[Any]:\n \"\"\"Async mirror of iter_pages — same stop conditions and guards.\"\"\"\n style = spec[\"style\"]\n base = dict(params or {})\n if style == \"cursor\":\n cursor = base.get(spec[\"param\"])\n while True:\n page_params = dict(base)\n if cursor is not None:\n page_params[spec[\"param\"]] = cursor\n page, _response = await call(page_params)\n yield page\n if spec.get(\"has_more\") is not None and resolve_pointer(page, spec[\"has_more\"]) is False:\n return\n nxt = resolve_pointer(page, spec.get(\"next_cursor\", \"\"))\n if nxt is None or nxt == \"\":\n return\n if not isinstance(nxt, (str, int, float)):\n raise ValueError(f\"Pagination cursor at {spec['next_cursor']} is not a string or number\")\n if nxt == cursor:\n raise ValueError(\"Pagination did not advance: the operation returned the same cursor twice\")\n cursor = nxt\n elif style in (\"link\", \"body-link\"):\n previous = None\n link_params: Dict[str, Any] = dict(base)\n while True:\n page, response = await call(link_params)\n yield page\n target = _next_link(spec, page, response)\n if target is None:\n return\n page_url = str(response.request.url) if response.request is not None else \"\"\n nxt = urljoin(page_url or \"http://relative.invalid\", target)\n if nxt in (previous, page_url):\n raise ValueError('Pagination did not advance: the Link rel=\"next\" target repeats')\n previous = nxt\n merged: Dict[str, Any] = {}\n for key, value in parse_qsl(urlparse(nxt).query):\n if key in merged:\n existing = merged[key]\n merged[key] = [*existing, value] if isinstance(existing, list) else [existing, value]\n else:\n merged[key] = value\n link_params = {**base, **merged}\n else:\n start = base.get(spec[\"param\"])\n fallback = 1 if style == \"page\" else 0\n try:\n position = fallback if start in (None, \"\") else int(start)\n except (TypeError, ValueError):\n position = fallback\n previous_items = None\n while True:\n page, _response = await call({**base, spec[\"param\"]: position})\n items = resolve_pointer(page, spec.get(\"items\", \"\"))\n serialized = repr(items) if isinstance(items, list) else None\n if serialized is not None and serialized == previous_items:\n raise ValueError(\"Pagination did not advance: the operation returned the same page twice\")\n yield page\n if not isinstance(items, list) or len(items) == 0:\n return\n previous_items = serialized\n position += 1 if style == \"page\" else len(items)\n\n\nasync def aiter_items(\n call: AsyncPageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None\n) -> AsyncIterator[Any]:\n async for page in aiter_pages(call, spec, params):\n items = resolve_pointer(page, spec.get(\"items\", \"\"))\n if isinstance(items, list):\n for item in items:\n yield item\n";
|
|
8
8
|
readonly '_sse.py': "# Server-Sent Events for generated Python clients — the TypeScript runtime's\n# sse.ts semantics ported: frame parsing per the EventSource spec (retry must be\n# ASCII digits; comment-only frames skipped; multi-line data joined with \\n) and\n# auto-reconnect resuming from the last event id via Last-Event-ID, with\n# exponential backoff capped at 30s. JSON payloads are parsed when the operation\n# declares a JSON event stream.\nfrom __future__ import annotations\n\nimport asyncio\nimport json\nimport random\nimport time\nfrom dataclasses import dataclass\nfrom typing import Any, AsyncIterator, Callable, Dict, Iterator, Optional\n\nimport httpx\n\n_FRAME_DELIMITER = \"\\n\\n\"\n\n\n@dataclass\nclass ServerSentEvent:\n data: Any\n event: Optional[str] = None\n id: Optional[str] = None\n retry: Optional[int] = None\n\n\ndef parse_sse_frame(raw: str, data_kind: str = \"text\") -> Optional[ServerSentEvent]:\n event = None\n data_lines = []\n event_id = None\n retry = None\n saw_field = False\n for line in raw.replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\").split(\"\\n\"):\n if line == \"\" or line.startswith(\":\"):\n continue\n field, _, value = line.partition(\":\")\n if value.startswith(\" \"):\n value = value[1:]\n saw_field = True\n if field == \"event\":\n event = value\n elif field == \"data\":\n data_lines.append(value)\n elif field == \"id\":\n event_id = value\n elif field == \"retry\" and value.isdigit():\n retry = int(value)\n if not saw_field:\n return None\n text = \"\\n\".join(data_lines)\n data: Any = text\n if data_kind == \"json\" and text != \"\":\n data = json.loads(text)\n return ServerSentEvent(data=data, event=event, id=event_id, retry=retry)\n\n\ndef iter_sse(\n open_stream: Callable[[Dict[str, str]], Any],\n data_kind: str = \"text\",\n reconnect: bool = True,\n reconnect_delay: float = 1.0,\n) -> Iterator[ServerSentEvent]:\n \"\"\"Iterate an event stream. `open_stream(extra_headers)` must return an\n httpx streaming-response context manager; it is reopened on dropped\n connections with Last-Event-ID set (fresh call = fresh auth).\"\"\"\n last_event_id: Optional[str] = None\n server_retry: Optional[float] = None\n failures = 0\n while True:\n headers = {\"Accept\": \"text/event-stream\"}\n if last_event_id is not None:\n headers[\"Last-Event-ID\"] = last_event_id\n try:\n with open_stream(headers) as response:\n if response.status_code >= 400:\n response.read()\n raise httpx.HTTPStatusError(\n f\"SSE request failed with status {response.status_code}\",\n request=response.request,\n response=response,\n )\n failures = 0\n buffer = \"\"\n for chunk in response.iter_text():\n buffer += chunk\n while _FRAME_DELIMITER in buffer:\n raw, buffer = buffer.split(_FRAME_DELIMITER, 1)\n parsed = parse_sse_frame(raw, data_kind)\n if parsed is not None:\n if parsed.id is not None:\n last_event_id = parsed.id\n if parsed.retry is not None:\n server_retry = parsed.retry / 1000\n yield parsed\n # Clean end: flush a trailing frame, then finish (no reconnect).\n if buffer.strip():\n parsed = parse_sse_frame(buffer, data_kind)\n if parsed is not None:\n yield parsed\n return\n except httpx.HTTPStatusError:\n raise # a 4xx/5xx is definitive, not a dropped connection\n except (httpx.TransportError, httpx.TimeoutException):\n if not reconnect:\n raise\n failures += 1\n base = server_retry if server_retry is not None else reconnect_delay\n time.sleep(random.uniform(0, min(base * (2 ** (failures - 1)), 30.0)))\n\n\nasync def aiter_sse(\n open_stream: Callable[[Dict[str, str]], Any],\n data_kind: str = \"text\",\n reconnect: bool = True,\n reconnect_delay: float = 1.0,\n) -> AsyncIterator[ServerSentEvent]:\n \"\"\"Async mirror of iter_sse; `open_stream` returns an async context manager.\"\"\"\n last_event_id: Optional[str] = None\n server_retry: Optional[float] = None\n failures = 0\n while True:\n headers = {\"Accept\": \"text/event-stream\"}\n if last_event_id is not None:\n headers[\"Last-Event-ID\"] = last_event_id\n try:\n async with open_stream(headers) as response:\n if response.status_code >= 400:\n await response.aread()\n raise httpx.HTTPStatusError(\n f\"SSE request failed with status {response.status_code}\",\n request=response.request,\n response=response,\n )\n failures = 0\n buffer = \"\"\n async for chunk in response.aiter_text():\n buffer += chunk\n while _FRAME_DELIMITER in buffer:\n raw, buffer = buffer.split(_FRAME_DELIMITER, 1)\n parsed = parse_sse_frame(raw, data_kind)\n if parsed is not None:\n if parsed.id is not None:\n last_event_id = parsed.id\n if parsed.retry is not None:\n server_retry = parsed.retry / 1000\n yield parsed\n if buffer.strip():\n parsed = parse_sse_frame(buffer, data_kind)\n if parsed is not None:\n yield parsed\n return\n except httpx.HTTPStatusError:\n raise\n except (httpx.TransportError, httpx.TimeoutException):\n if not reconnect:\n raise\n failures += 1\n base = server_retry if server_retry is not None else reconnect_delay\n await asyncio.sleep(random.uniform(0, min(base * (2 ** (failures - 1)), 30.0)))\n";
|
|
9
9
|
readonly '_multipart.py': "# Multipart bodies for generated Python clients — a typed dict/dataclass body is\n# split into httpx's (data, files): bytes and file-like values upload as parts,\n# everything else is form data (nested values JSON-encoded, mirroring the\n# TypeScript runtime's FormData serialization). A body that is already bytes, a\n# `str`, a file-like object, or an (async) iterator of bytes passes through as httpx\n# `content=` untouched; the caller sets its Content-Type.\nfrom __future__ import annotations\n\nimport json\nfrom typing import Any, Dict, Tuple\n\nfrom ._decode import encode\n\n\ndef to_multipart(body: Any) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n wire = encode(body)\n data: Dict[str, Any] = {}\n files: Dict[str, Any] = {}\n for key, value in (wire or {}).items():\n if isinstance(value, (bytes, bytearray)) or hasattr(value, \"read\"):\n files[key] = value\n elif isinstance(value, (dict, list)):\n data[key] = json.dumps(value)\n else:\n data[key] = value\n return data, files\n\n\ndef is_stream_body(body: Any) -> bool:\n return (\n isinstance(body, (bytes, bytearray, str))\n or callable(getattr(body, \"read\", None))\n or hasattr(body, \"__next__\")\n or hasattr(body, \"__aiter__\")\n )\n\n\ndef multipart_arguments(body: Any) -> Dict[str, Any]:\n if is_stream_body(body):\n return {\"content\": body}\n data, files = to_multipart(body)\n return {\"data\": data, \"files\": files}\n";
|
|
@@ -3,8 +3,8 @@ export const PYTHON_RUNTIME_SOURCES = {
|
|
|
3
3
|
'_errors.py': '# Runtime errors and the result-mode envelope for generated Python clients.\n# Hand-authored once, embedded into every generated client (see\n# scripts/generate-runtime-sources.mjs) — mirror of the TypeScript runtime\'s\n# errors.ts, kept semantically in lockstep.\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, Optional, TypeVar\n\nT = TypeVar("T")\nE = TypeVar("E")\n\n\nclass ApiError(Exception):\n """Raised (throw mode) for a non-2xx response, carrying the decoded error body."""\n\n def __init__(self, url: str, status: int, status_text: str, body: Any) -> None:\n super().__init__(f"Request failed with status {status}")\n self.url = url\n self.status = status\n self.status_text = status_text\n self.body = body\n\n\nclass ApiTimeoutError(Exception):\n """Raised when a request attempt exceeds the configured timeout — carries the\n context a log line needs (which operation, what budget, which attempt)."""\n\n def __init__(self, operation_id: str, timeout: float, attempt: int) -> None:\n super().__init__(\n f\'Request "{operation_id}" timed out after {timeout} s (attempt {attempt})\'\n )\n self.operation_id = operation_id\n self.timeout = timeout\n self.attempt = attempt\n\n\n@dataclass\nclass Result(Generic[T, E]):\n """Result-mode return shape: exactly one of `data`/`error` is set."""\n\n data: Optional[T]\n error: Optional[E]\n response: Any # httpx.Response\n\n @property\n def ok(self) -> bool:\n return self.error is None\n',
|
|
4
4
|
'_auth.py': '# Auth resolution for generated Python clients — mirror of the TypeScript\n# runtime\'s auth.ts: the first OR-alternative whose schemes are all configured\n# is applied, so "bearer OR apiKey" works with either credential and never\n# sends both. Cookie-borne api keys fold into a single Cookie header.\nfrom __future__ import annotations\n\nimport base64\nfrom typing import Any, Callable, Dict, List, Tuple, Union\nfrom urllib.parse import quote\n\nTokenProvider = Union[str, Callable[[], str]]\n\n\ndef _api_keys(auth: Dict[str, Any]) -> Dict[str, Any]:\n """The apiKey credentials. `apiKey` is the documented key (it matches the scheme\n kind and the other language SDKs); `api_key` is accepted too, so a snake_case\n config keeps working."""\n return {**(auth.get("api_key") or {}), **(auth.get("apiKey") or {})}\n\ndef _resolve_token(provider: TokenProvider) -> str:\n return provider() if callable(provider) else provider\n\n\ndef _is_configured(scheme: Dict[str, Any], auth: Dict[str, Any]) -> bool:\n kind = scheme["kind"]\n if kind == "apiKey":\n return scheme["scheme"] in _api_keys(auth)\n if kind == "bearer":\n return auth.get("bearer") is not None\n return auth.get("basic") is not None\n\n\ndef resolve_auth(\n security: List[List[Dict[str, Any]]], auth: Dict[str, Any]\n) -> Tuple[Dict[str, str], Dict[str, str]]:\n """Build (headers, query) for one operation\'s security OR-alternatives from\n the client credentials. When no alternative is fully configured, the first\n alternative\'s configured schemes are still sent (the server rejects the\n request — same behavior as the TypeScript runtime)."""\n alternative = next(\n (schemes for schemes in security if all(_is_configured(s, auth) for s in schemes)),\n security[0] if security else [],\n )\n headers: Dict[str, str] = {}\n query: Dict[str, str] = {}\n cookies: List[str] = []\n for scheme in alternative:\n kind = scheme["kind"]\n if kind == "apiKey":\n provider = _api_keys(auth).get(scheme["scheme"])\n if provider is None:\n continue\n value = _resolve_token(provider)\n location = scheme.get("in", "header")\n if location == "header":\n headers[scheme["name"]] = value\n elif location == "query":\n query[scheme["name"]] = value\n else:\n # Reserved characters (`;`, `=`, space) must not break Cookie syntax.\n cookies.append(f"{scheme[\'name\']}={quote(value, safe=\'\')}")\n elif kind == "bearer":\n provider = auth.get("bearer")\n if provider is not None:\n headers["Authorization"] = f"Bearer {_resolve_token(provider)}"\n else:\n basic = auth.get("basic")\n if basic is not None:\n username, password = basic["username"], basic["password"]\n token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")\n headers["Authorization"] = f"Basic {token}"\n if cookies:\n headers["Cookie"] = "; ".join(cookies)\n return headers, query\n',
|
|
5
5
|
'_url.py': '# URL assembly for generated Python clients — path-parameter substitution with\n# percent-encoding, mirroring the TypeScript runtime\'s url.ts semantics.\nfrom __future__ import annotations\n\nfrom typing import Any, Dict\nfrom urllib.parse import quote\n\n\ndef build_url(server_url: str, path: str, path_params: Dict[str, Any]) -> str:\n filled = path\n for name, value in path_params.items():\n filled = filled.replace("{" + name + "}", quote(str(value), safe=""))\n return server_url.rstrip("/") + filled\n',
|
|
6
|
-
'_decode.py': '# Reflective JSON <-> model conversion for generated Python clients. Models are\n# plain dataclasses by default, or pydantic BaseModels under `models: pydantic`;\n# one decoder serves both. For a dataclass it hydrates parsed JSON reflectively,\n# honoring each class\'s `_field_map` (python name -> wire name) and the typing\n# constructs the generator emits: Optional/Union, List, Dict, Enum, Literal, Any.\n# For a pydantic model it defers to pydantic, which already knows the aliases.\n# encode() mirrors whichever it was given back to wire shape.\nfrom __future__ import annotations\n\nimport dataclasses\nimport typing\nfrom datetime import date, datetime\nfrom enum import Enum\nfrom typing import Any, Dict, Tuple, get_args, get_origin, get_type_hints\n\n# Discriminated unions: resolved Union annotation -> (wire property, {value: class}).\n# The generated module registers its unions here; decode() dispatches through it\n# before falling back to trying members in order.\nDISCRIMINATORS: Dict[Any, Tuple[str, Dict[str, Any]]] = {}\n\n\ndef decode(type_: Any, data: Any):\n """Best-effort hydration: wire data -> the annotated Python shape. Unknown or\n mismatched shapes pass through unchanged (the server is the source of truth)."""\n if data is None or type_ is Any or type_ is None:\n return data\n # `Annotated[Union[...], Field(discriminator=...)]`: pydantic reads that annotation on a\n # model\'s own field, so here only the union underneath matters.\n if hasattr(type_, "__metadata__"):\n type_ = get_args(type_)[0]\n origin = get_origin(type_)\n if origin is typing.Union:\n discriminator = DISCRIMINATORS.get(type_)\n if discriminator is not None and isinstance(data, dict):\n wire_property, mapping = discriminator\n
|
|
7
|
-
'_send.py': '# The request core for generated Python clients — mirror of the TypeScript\n# runtime\'s send.ts: default + config + per-call headers, on_request middleware\n# BEFORE serialization (mutations are sent), the retry loop (idempotent-methods\n# default, Idempotency-Key opt-in makes POST/PATCH safe, Retry-After honored,\n# exponential backoff with full jitter, a fresh timeout budget per attempt), and\n# the reverse on_response onion.\nfrom __future__ import annotations\n\nimport asyncio\nimport random\nimport time\nimport uuid\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar\n\nimport httpx\n\nfrom ._errors import ApiTimeoutError\n\nT = TypeVar("T")\n\n\n@dataclass\nclass Envelope(Generic[T]):\n """A *_with_headers() result: decoded body + coerced declared headers + raw response."""\n\n data: T\n headers: Dict[str, Any]\n response: httpx.Response\n\n\ndef read_envelope_headers(\n response: httpx.Response, specs: List[Tuple[str, str, str]]\n) -> Dict[str, Any]:\n """Coerce declared response headers per (name, key, type) specs; absent/unparsable omitted."""\n headers: Dict[str, Any] = {}\n for name, key, type_ in specs:\n raw = response.headers.get(name)\n if raw is None:\n continue\n if type_ in ("integer", "number"):\n try:\n headers[key] = int(raw) if type_ == "integer" else float(raw)\n except ValueError:\n pass\n elif type_ == "boolean":\n lower = raw.strip().lower()\n if lower in ("true", "false"):\n headers[key] = lower == "true"\n else:\n headers[key] = raw\n return headers\n\n\n_IDEMPOTENT_METHODS = {"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}\n_TRANSIENT_STATUS = {408, 429, 500, 502, 503, 504}\n\n\ndef _default_retry_on(method: str, headers: Dict[str, str], response: Optional[httpx.Response]) -> bool:\n safe = method.upper() in _IDEMPOTENT_METHODS or "Idempotency-Key" in headers\n if not safe:\n return False\n return response is None or response.status_code in _TRANSIENT_STATUS\n\n\ndef _retry_delay(retry: Dict[str, Any], attempt: int, retry_after: Optional[str]) -> float:\n if retry_after:\n try:\n return float(retry_after)\n except ValueError:\n pass # HTTP-date form: fall through to backoff\n base = float(retry.get("retry_delay", 1.0))\n raw = base if retry.get("retry_strategy") == "fixed" else base * (2 ** (attempt - 1))\n return random.uniform(0, raw) if retry.get("jitter", True) is not False else raw\n\n\ndef send(\n client: httpx.Client,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n merged_retry: Dict[str, Any] = {**(config.get("retry") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get("timeout")\n merged_headers: Dict[str, str] = {**(config.get("headers") or {}), **(headers or {})}\n\n # One stable key per LOGICAL call — set before the retry loop so every\n # attempt re-sends the same key; a caller-provided header always wins.\n key = idempotency_key if idempotency_key is not None else config.get("idempotency_key")\n if (\n key not in (None, False)\n and method.upper() in ("POST", "PATCH")\n and "Idempotency-Key" not in merged_headers\n ):\n merged_headers["Idempotency-Key"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n # The declared content type fills the gap; a caller-provided header always wins.\n if content_type is not None and not any(name.lower() == "content-type" for name in merged_headers):\n merged_headers["Content-Type"] = content_type\n\n context = {\n "url": url,\n "method": method.upper(),\n "headers": merged_headers,\n "body": json_body,\n "operation": op,\n }\n middleware: List[Any] = config.get("middleware") or []\n for mw in middleware:\n on_request = getattr(mw, "on_request", None) or (mw.get("on_request") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get("retries", 0)) if replayable else 1\n retry_on = merged_retry.get("retry_on") or (\n lambda ctx: _default_retry_on(context["method"], context["headers"], ctx.get("response"))\n )\n\n attempt = 0\n while True:\n attempt += 1\n try:\n response = client.request(\n context["method"],\n context["url"],\n headers=context["headers"],\n params=params,\n json=context["body"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get("id", "?"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n\n for mw in reversed(middleware):\n on_response = getattr(mw, "on_response", None) or (mw.get("on_response") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({"attempt": attempt, "response": response})\n ):\n time.sleep(_retry_delay(merged_retry, attempt, response.headers.get("retry-after")))\n continue\n return response\n\n\nasync def send_async(\n client: httpx.AsyncClient,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n """The async mirror of send() — same retry/timeout/idempotency semantics."""\n merged_retry: Dict[str, Any] = {**(config.get("retry") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get("timeout")\n merged_headers: Dict[str, str] = {**(config.get("headers") or {}), **(headers or {})}\n key = idempotency_key if idempotency_key is not None else config.get("idempotency_key")\n if (\n key not in (None, False)\n and method.upper() in ("POST", "PATCH")\n and "Idempotency-Key" not in merged_headers\n ):\n merged_headers["Idempotency-Key"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n if content_type is not None and not any(name.lower() == "content-type" for name in merged_headers):\n merged_headers["Content-Type"] = content_type\n context = {\n "url": url,\n "method": method.upper(),\n "headers": merged_headers,\n "body": json_body,\n "operation": op,\n }\n middleware: List[Any] = config.get("middleware") or []\n for mw in middleware:\n on_request = getattr(mw, "on_request", None) or (mw.get("on_request") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get("retries", 0)) if replayable else 1\n retry_on = merged_retry.get("retry_on") or (\n lambda ctx: _default_retry_on(context["method"], context["headers"], ctx.get("response"))\n )\n attempt = 0\n while True:\n attempt += 1\n try:\n response = await client.request(\n context["method"],\n context["url"],\n headers=context["headers"],\n params=params,\n json=context["body"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get("id", "?"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n for mw in reversed(middleware):\n on_response = getattr(mw, "on_response", None) or (mw.get("on_response") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({"attempt": attempt, "response": response})\n ):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, response.headers.get("retry-after")))\n continue\n return response\n',
|
|
6
|
+
'_decode.py': '# Reflective JSON <-> model conversion for generated Python clients. Models are\n# plain dataclasses by default, or pydantic BaseModels under `models: pydantic`;\n# one decoder serves both. For a dataclass it hydrates parsed JSON reflectively,\n# honoring each class\'s `_field_map` (python name -> wire name) and the typing\n# constructs the generator emits: Optional/Union, List, Dict, Enum, Literal, Any.\n# For a pydantic model it defers to pydantic, which already knows the aliases.\n# encode() mirrors whichever it was given back to wire shape.\nfrom __future__ import annotations\n\nimport dataclasses\nimport typing\nfrom datetime import date, datetime\nfrom enum import Enum\nfrom typing import Any, Dict, Tuple, get_args, get_origin, get_type_hints\n\n# Discriminated unions: resolved Union annotation -> (wire property, {value: class}).\n# The generated module registers its unions here; decode() dispatches through it\n# before falling back to trying members in order.\nDISCRIMINATORS: Dict[Any, Tuple[str, Dict[str, Any]]] = {}\n\n\ndef decode(type_: Any, data: Any) -> Any:\n """Best-effort hydration: wire data -> the annotated Python shape. Unknown or\n mismatched shapes pass through unchanged (the server is the source of truth)."""\n if data is None or type_ is Any or type_ is None:\n return data\n # `Annotated[Union[...], Field(discriminator=...)]`: pydantic reads that annotation on a\n # model\'s own field, so here only the union underneath matters.\n if hasattr(type_, "__metadata__"):\n type_ = get_args(type_)[0]\n origin = get_origin(type_)\n if origin is typing.Union:\n discriminator = DISCRIMINATORS.get(type_)\n if discriminator is not None and isinstance(data, dict):\n wire_property, mapping = discriminator\n value = data.get(wire_property)\n target = mapping.get(value) if isinstance(value, str) else None\n if target is not None:\n try:\n return decode(target, data)\n except (TypeError, ValueError, KeyError):\n pass\n for member in get_args(type_):\n if member is type(None):\n continue\n try:\n return decode(member, data)\n except (TypeError, ValueError, KeyError):\n continue\n return data\n if origin is list:\n (item_type,) = get_args(type_) or (Any,)\n return [decode(item_type, item) for item in data]\n if origin is dict:\n args = get_args(type_)\n value_type = args[1] if len(args) == 2 else Any\n return {key: decode(value_type, value) for key, value in data.items()}\n if origin is typing.Literal:\n return data\n if isinstance(type_, type) and issubclass(type_, Enum):\n return type_(data)\n # `dateType: Date` annotates date/date-time fields as datetime objects; a value that\n # doesn\'t parse passes through unchanged (the server is the source of truth).\n if type_ is datetime or type_ is date:\n if not isinstance(data, str):\n return data\n try:\n # `datetime` accepts a bare date too; `date` rejects a timestamp, so trim it.\n return (\n datetime.fromisoformat(data)\n if type_ is datetime\n else date.fromisoformat(data[:10])\n )\n except ValueError:\n return data\n # A pydantic model validates itself, aliases included. `ValidationError`\n # subclasses `ValueError`, so union member probing above still works.\n if isinstance(type_, type) and hasattr(type_, "model_validate"):\n return type_.model_validate(data)\n if dataclasses.is_dataclass(type_) and isinstance(type_, type):\n hints = get_type_hints(type_)\n field_map = getattr(type_, "_field_map", {})\n kwargs: Dict[str, Any] = {}\n for field in dataclasses.fields(type_):\n wire = field_map.get(field.name, field.name)\n if isinstance(data, dict) and wire in data:\n kwargs[field.name] = decode(hints.get(field.name, Any), data[wire])\n return type_(**kwargs)\n return data\n\n\ndef encode(value: Any) -> Any:\n """Python shape -> wire (JSON) shape; inverse of decode for request bodies."""\n # `mode="json"` resolves datetimes and enums the same way the branches below do,\n # and `exclude_none` matches the dataclass path: an unset optional is not sent.\n if hasattr(value, "model_dump") and not isinstance(value, type):\n return value.model_dump(by_alias=True, exclude_none=True, mode="json")\n if dataclasses.is_dataclass(value) and not isinstance(value, type):\n field_map = getattr(type(value), "_field_map", {})\n out = {}\n for field in dataclasses.fields(value):\n item = getattr(value, field.name)\n if item is None:\n continue\n out[field_map.get(field.name, field.name)] = encode(item)\n return out\n if isinstance(value, Enum):\n return value.value\n # A date-only value must not gain a time component on the way out.\n if isinstance(value, datetime):\n return value.isoformat()\n if isinstance(value, date):\n return value.isoformat()\n if isinstance(value, list):\n return [encode(item) for item in value]\n if isinstance(value, dict):\n return {key: encode(item) for key, item in value.items()}\n return value\n',
|
|
7
|
+
'_send.py': '# The request core for generated Python clients — mirror of the TypeScript\n# runtime\'s send.ts: default + config + per-call headers, on_request middleware\n# BEFORE serialization (mutations are sent), the retry loop (idempotent-methods\n# default, Idempotency-Key opt-in makes POST/PATCH safe, Retry-After honored,\n# exponential backoff with full jitter, a fresh timeout budget per attempt), and\n# the reverse on_response onion.\nfrom __future__ import annotations\n\nimport asyncio\nimport random\nimport time\nimport uuid\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar\n\nimport httpx\n\nfrom ._errors import ApiTimeoutError\n\n# Not `T`: the runtime modules share one generated file, where `_errors.py` defines `T`.\nTData = TypeVar("TData")\n\n\n@dataclass\nclass Envelope(Generic[TData]):\n """A *_with_headers() result: decoded body + coerced declared headers + raw response."""\n\n data: TData\n headers: Dict[str, Any]\n response: httpx.Response\n\n\ndef read_envelope_headers(\n response: httpx.Response, specs: List[Tuple[str, str, str]]\n) -> Dict[str, Any]:\n """Coerce declared response headers per (name, key, type) specs; absent/unparsable omitted."""\n headers: Dict[str, Any] = {}\n for name, key, type_ in specs:\n raw = response.headers.get(name)\n if raw is None:\n continue\n if type_ in ("integer", "number"):\n try:\n headers[key] = int(raw) if type_ == "integer" else float(raw)\n except ValueError:\n pass\n elif type_ == "boolean":\n lower = raw.strip().lower()\n if lower in ("true", "false"):\n headers[key] = lower == "true"\n else:\n headers[key] = raw\n return headers\n\n\n_IDEMPOTENT_METHODS = {"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}\n_TRANSIENT_STATUS = {408, 429, 500, 502, 503, 504}\n\n\ndef _default_retry_on(method: str, headers: Dict[str, str], response: Optional[httpx.Response]) -> bool:\n safe = method.upper() in _IDEMPOTENT_METHODS or "Idempotency-Key" in headers\n if not safe:\n return False\n return response is None or response.status_code in _TRANSIENT_STATUS\n\n\ndef _retry_delay(retry: Dict[str, Any], attempt: int, retry_after: Optional[str]) -> float:\n if retry_after:\n try:\n return float(retry_after)\n except ValueError:\n pass # HTTP-date form: fall through to backoff\n base = float(retry.get("retry_delay", 1.0))\n raw = base if retry.get("retry_strategy") == "fixed" else base * (2 ** (attempt - 1))\n return random.uniform(0, raw) if retry.get("jitter", True) is not False else raw\n\n\ndef send(\n client: httpx.Client,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n merged_retry: Dict[str, Any] = {**(config.get("retry") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get("timeout")\n merged_headers: Dict[str, str] = {**(config.get("headers") or {}), **(headers or {})}\n\n # One stable key per LOGICAL call — set before the retry loop so every\n # attempt re-sends the same key; a caller-provided header always wins.\n key = idempotency_key if idempotency_key is not None else config.get("idempotency_key")\n if (\n key not in (None, False)\n and method.upper() in ("POST", "PATCH")\n and "Idempotency-Key" not in merged_headers\n ):\n merged_headers["Idempotency-Key"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n # The declared content type fills the gap; a caller-provided header always wins.\n if content_type is not None and not any(name.lower() == "content-type" for name in merged_headers):\n merged_headers["Content-Type"] = content_type\n\n context = {\n "url": url,\n "method": method.upper(),\n "headers": merged_headers,\n "body": json_body,\n "operation": op,\n }\n middleware: List[Any] = config.get("middleware") or []\n for mw in middleware:\n on_request = getattr(mw, "on_request", None) or (mw.get("on_request") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get("retries", 0)) if replayable else 1\n retry_on = merged_retry.get("retry_on") or (\n lambda ctx: _default_retry_on(context["method"], context["headers"], ctx.get("response"))\n )\n\n attempt = 0\n while True:\n attempt += 1\n try:\n response = client.request(\n context["method"],\n context["url"],\n headers=context["headers"],\n params=params,\n json=context["body"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get("id", "?"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n time.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n\n for mw in reversed(middleware):\n on_response = getattr(mw, "on_response", None) or (mw.get("on_response") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({"attempt": attempt, "response": response})\n ):\n time.sleep(_retry_delay(merged_retry, attempt, response.headers.get("retry-after")))\n continue\n return response\n\n\nasync def send_async(\n client: httpx.AsyncClient,\n config: Dict[str, Any],\n op: Dict[str, Any],\n url: str,\n *,\n method: str,\n headers: Optional[Dict[str, str]] = None,\n params: Optional[Dict[str, Any]] = None,\n json_body: Any = None,\n content: Any = None,\n content_type: Optional[str] = None,\n data: Any = None,\n files: Any = None,\n timeout: Optional[float] = None,\n idempotency_key: Any = None,\n retry: Optional[Dict[str, Any]] = None,\n) -> httpx.Response:\n """The async mirror of send() — same retry/timeout/idempotency semantics."""\n merged_retry: Dict[str, Any] = {**(config.get("retry") or {}), **(retry or {})}\n effective_timeout = timeout if timeout is not None else config.get("timeout")\n merged_headers: Dict[str, str] = {**(config.get("headers") or {}), **(headers or {})}\n key = idempotency_key if idempotency_key is not None else config.get("idempotency_key")\n if (\n key not in (None, False)\n and method.upper() in ("POST", "PATCH")\n and "Idempotency-Key" not in merged_headers\n ):\n merged_headers["Idempotency-Key"] = (\n key if isinstance(key, str) else key() if callable(key) else str(uuid.uuid4())\n )\n if content_type is not None and not any(name.lower() == "content-type" for name in merged_headers):\n merged_headers["Content-Type"] = content_type\n context = {\n "url": url,\n "method": method.upper(),\n "headers": merged_headers,\n "body": json_body,\n "operation": op,\n }\n middleware: List[Any] = config.get("middleware") or []\n for mw in middleware:\n on_request = getattr(mw, "on_request", None) or (mw.get("on_request") if isinstance(mw, dict) else None)\n if on_request:\n on_request(context)\n # A file-like object or iterator is consumed by the first attempt and cannot be replayed, so it never retries.\n replayable = content is None or isinstance(content, (bytes, bytearray, str))\n max_attempts = 1 + int(merged_retry.get("retries", 0)) if replayable else 1\n retry_on = merged_retry.get("retry_on") or (\n lambda ctx: _default_retry_on(context["method"], context["headers"], ctx.get("response"))\n )\n attempt = 0\n while True:\n attempt += 1\n try:\n response = await client.request(\n context["method"],\n context["url"],\n headers=context["headers"],\n params=params,\n json=context["body"] if content is None and files is None and data is None else None,\n content=content,\n data=data,\n files=files,\n timeout=effective_timeout if effective_timeout is not None else httpx.USE_CLIENT_DEFAULT,\n )\n except httpx.TimeoutException:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise ApiTimeoutError(op.get("id", "?"), float(effective_timeout or 0), attempt) from None\n except httpx.TransportError:\n if attempt < max_attempts and retry_on({"attempt": attempt, "response": None}):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, None))\n continue\n raise\n for mw in reversed(middleware):\n on_response = getattr(mw, "on_response", None) or (mw.get("on_response") if isinstance(mw, dict) else None)\n if on_response:\n replaced = on_response(response, context)\n if replaced is not None:\n response = replaced\n if (\n not response.is_success\n and attempt < max_attempts\n and retry_on({"attempt": attempt, "response": response})\n ):\n await asyncio.sleep(_retry_delay(merged_retry, attempt, response.headers.get("retry-after")))\n continue\n return response\n',
|
|
8
8
|
'_paginate.py': '# Auto-pagination iterators for generated Python clients — the TypeScript\n# runtime\'s paginate.ts semantics ported: cursor (next-cursor pointer, optional\n# has-more flag, repeated-cursor guard), offset/page (advance by count/one,\n# repeated-page guard, null start treated as absent), link (RFC 8288\n# `Link: rel="next"` following) and body-link (the next-link pointer\'s URL), both\n# with relative resolution and a loop guard.\nfrom __future__ import annotations\n\nimport re\nfrom typing import Any, AsyncIterator, Awaitable, Callable, Dict, Iterator, Optional, Tuple\nfrom urllib.parse import parse_qsl, urljoin, urlparse\n\n# call(params) -> (parsed_json, httpx.Response)\nPageCall = Callable[[Dict[str, Any]], Tuple[Any, Any]]\n\n\ndef resolve_pointer(data: Any, pointer: str) -> Any:\n """RFC 6901 JSON pointer over parsed JSON; None on any miss."""\n if pointer == "":\n return data\n if not pointer.startswith("/"):\n return None\n current = data\n for token in pointer[1:].split("/"):\n key = token.replace("~1", "/").replace("~0", "~")\n if isinstance(current, dict):\n current = current.get(key)\n elif isinstance(current, list) and key.isdigit():\n index = int(key)\n current = current[index] if index < len(current) else None\n else:\n return None\n if current is None:\n return None\n return current\n\n\ndef iter_pages(call: PageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None) -> Iterator[Any]:\n """Yield raw page JSON per the pagination spec; every page is yielded before\n the stop condition is evaluated, so the last page always arrives."""\n style = spec["style"]\n base = dict(params or {})\n if style == "cursor":\n cursor = base.get(spec["param"])\n while True:\n page_params = dict(base)\n if cursor is not None:\n page_params[spec["param"]] = cursor\n page, _response = call(page_params)\n yield page\n if spec.get("has_more") is not None and resolve_pointer(page, spec["has_more"]) is False:\n return\n nxt = resolve_pointer(page, spec.get("next_cursor", ""))\n if nxt is None or nxt == "":\n return\n if not isinstance(nxt, (str, int, float)):\n raise ValueError(f"Pagination cursor at {spec[\'next_cursor\']} is not a string or number")\n if nxt == cursor:\n raise ValueError("Pagination did not advance: the operation returned the same cursor twice")\n cursor = nxt\n elif style in ("link", "body-link"):\n yield from _iter_pages_by_link(call, spec, base)\n else: # offset / page\n start = base.get(spec["param"])\n fallback = 1 if style == "page" else 0\n try:\n position = fallback if start in (None, "") else int(start)\n except (TypeError, ValueError):\n position = fallback\n previous_items = None\n while True:\n page, _response = call({**base, spec["param"]: position})\n items = resolve_pointer(page, spec.get("items", ""))\n serialized = repr(items) if isinstance(items, list) else None\n if serialized is not None and serialized == previous_items:\n raise ValueError("Pagination did not advance: the operation returned the same page twice")\n yield page\n if not isinstance(items, list) or len(items) == 0:\n return\n previous_items = serialized\n position += 1 if style == "page" else len(items)\n\n\ndef _link_next(header: Optional[str]) -> Optional[str]:\n if not header:\n return None\n for entry in re.split(r",\\s*(?=<)", header):\n match = re.match(r"^\\s*<([^>]*)>(.*)$", entry)\n if not match:\n continue\n rel = re.search(r\';\\s*rel\\s*=\\s*"?([^";]+)"?\', match.group(2), re.IGNORECASE)\n if rel and "next" in rel.group(1).split():\n return match.group(1)\n return None\n\n\ndef _next_link(spec: Dict[str, Any], page: Any, response: Any) -> Optional[str]:\n """The next page\'s URL: the `Link` header\'s rel="next" target for `link`, the value at\n the `next_link` pointer for `body-link`; None when absent, null, or empty."""\n if spec["style"] == "link":\n return _link_next(response.headers.get("link"))\n pointer = spec["next_link"]\n target = resolve_pointer(page, pointer)\n if target is None or target == "":\n return None\n if not isinstance(target, str):\n raise ValueError(f"Pagination link at {pointer} is not a string")\n return target\n\n\ndef _iter_pages_by_link(call: PageCall, spec: Dict[str, Any], base: Dict[str, Any]) -> Iterator[Any]:\n params = dict(base)\n previous = None\n while True:\n page, response = call(params)\n yield page\n target = _next_link(spec, page, response)\n if target is None:\n return\n page_url = str(response.request.url) if response.request is not None else ""\n nxt = urljoin(page_url or "http://relative.invalid", target)\n if nxt in (previous, page_url):\n raise ValueError(\'Pagination did not advance: the Link rel="next" target repeats\')\n previous = nxt\n link_params: Dict[str, Any] = {}\n for key, value in parse_qsl(urlparse(nxt).query):\n if key in link_params:\n existing = link_params[key]\n link_params[key] = [*existing, value] if isinstance(existing, list) else [existing, value]\n else:\n link_params[key] = value\n params = {**base, **link_params}\n\n\ndef iter_items(call: PageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None) -> Iterator[Any]:\n """Each page\'s `items` pointer, flattened."""\n for page in iter_pages(call, spec, params):\n items = resolve_pointer(page, spec.get("items", ""))\n if isinstance(items, list):\n yield from items\n\n\n# call(params) -> awaitable of (parsed_json, httpx.Response)\nAsyncPageCall = Callable[[Dict[str, Any]], Awaitable[Tuple[Any, Any]]]\n\n\nasync def aiter_pages(\n call: AsyncPageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None\n) -> AsyncIterator[Any]:\n """Async mirror of iter_pages — same stop conditions and guards."""\n style = spec["style"]\n base = dict(params or {})\n if style == "cursor":\n cursor = base.get(spec["param"])\n while True:\n page_params = dict(base)\n if cursor is not None:\n page_params[spec["param"]] = cursor\n page, _response = await call(page_params)\n yield page\n if spec.get("has_more") is not None and resolve_pointer(page, spec["has_more"]) is False:\n return\n nxt = resolve_pointer(page, spec.get("next_cursor", ""))\n if nxt is None or nxt == "":\n return\n if not isinstance(nxt, (str, int, float)):\n raise ValueError(f"Pagination cursor at {spec[\'next_cursor\']} is not a string or number")\n if nxt == cursor:\n raise ValueError("Pagination did not advance: the operation returned the same cursor twice")\n cursor = nxt\n elif style in ("link", "body-link"):\n previous = None\n link_params: Dict[str, Any] = dict(base)\n while True:\n page, response = await call(link_params)\n yield page\n target = _next_link(spec, page, response)\n if target is None:\n return\n page_url = str(response.request.url) if response.request is not None else ""\n nxt = urljoin(page_url or "http://relative.invalid", target)\n if nxt in (previous, page_url):\n raise ValueError(\'Pagination did not advance: the Link rel="next" target repeats\')\n previous = nxt\n merged: Dict[str, Any] = {}\n for key, value in parse_qsl(urlparse(nxt).query):\n if key in merged:\n existing = merged[key]\n merged[key] = [*existing, value] if isinstance(existing, list) else [existing, value]\n else:\n merged[key] = value\n link_params = {**base, **merged}\n else:\n start = base.get(spec["param"])\n fallback = 1 if style == "page" else 0\n try:\n position = fallback if start in (None, "") else int(start)\n except (TypeError, ValueError):\n position = fallback\n previous_items = None\n while True:\n page, _response = await call({**base, spec["param"]: position})\n items = resolve_pointer(page, spec.get("items", ""))\n serialized = repr(items) if isinstance(items, list) else None\n if serialized is not None and serialized == previous_items:\n raise ValueError("Pagination did not advance: the operation returned the same page twice")\n yield page\n if not isinstance(items, list) or len(items) == 0:\n return\n previous_items = serialized\n position += 1 if style == "page" else len(items)\n\n\nasync def aiter_items(\n call: AsyncPageCall, spec: Dict[str, Any], params: Optional[Dict[str, Any]] = None\n) -> AsyncIterator[Any]:\n async for page in aiter_pages(call, spec, params):\n items = resolve_pointer(page, spec.get("items", ""))\n if isinstance(items, list):\n for item in items:\n yield item\n',
|
|
9
9
|
'_sse.py': '# Server-Sent Events for generated Python clients — the TypeScript runtime\'s\n# sse.ts semantics ported: frame parsing per the EventSource spec (retry must be\n# ASCII digits; comment-only frames skipped; multi-line data joined with \\n) and\n# auto-reconnect resuming from the last event id via Last-Event-ID, with\n# exponential backoff capped at 30s. JSON payloads are parsed when the operation\n# declares a JSON event stream.\nfrom __future__ import annotations\n\nimport asyncio\nimport json\nimport random\nimport time\nfrom dataclasses import dataclass\nfrom typing import Any, AsyncIterator, Callable, Dict, Iterator, Optional\n\nimport httpx\n\n_FRAME_DELIMITER = "\\n\\n"\n\n\n@dataclass\nclass ServerSentEvent:\n data: Any\n event: Optional[str] = None\n id: Optional[str] = None\n retry: Optional[int] = None\n\n\ndef parse_sse_frame(raw: str, data_kind: str = "text") -> Optional[ServerSentEvent]:\n event = None\n data_lines = []\n event_id = None\n retry = None\n saw_field = False\n for line in raw.replace("\\r\\n", "\\n").replace("\\r", "\\n").split("\\n"):\n if line == "" or line.startswith(":"):\n continue\n field, _, value = line.partition(":")\n if value.startswith(" "):\n value = value[1:]\n saw_field = True\n if field == "event":\n event = value\n elif field == "data":\n data_lines.append(value)\n elif field == "id":\n event_id = value\n elif field == "retry" and value.isdigit():\n retry = int(value)\n if not saw_field:\n return None\n text = "\\n".join(data_lines)\n data: Any = text\n if data_kind == "json" and text != "":\n data = json.loads(text)\n return ServerSentEvent(data=data, event=event, id=event_id, retry=retry)\n\n\ndef iter_sse(\n open_stream: Callable[[Dict[str, str]], Any],\n data_kind: str = "text",\n reconnect: bool = True,\n reconnect_delay: float = 1.0,\n) -> Iterator[ServerSentEvent]:\n """Iterate an event stream. `open_stream(extra_headers)` must return an\n httpx streaming-response context manager; it is reopened on dropped\n connections with Last-Event-ID set (fresh call = fresh auth)."""\n last_event_id: Optional[str] = None\n server_retry: Optional[float] = None\n failures = 0\n while True:\n headers = {"Accept": "text/event-stream"}\n if last_event_id is not None:\n headers["Last-Event-ID"] = last_event_id\n try:\n with open_stream(headers) as response:\n if response.status_code >= 400:\n response.read()\n raise httpx.HTTPStatusError(\n f"SSE request failed with status {response.status_code}",\n request=response.request,\n response=response,\n )\n failures = 0\n buffer = ""\n for chunk in response.iter_text():\n buffer += chunk\n while _FRAME_DELIMITER in buffer:\n raw, buffer = buffer.split(_FRAME_DELIMITER, 1)\n parsed = parse_sse_frame(raw, data_kind)\n if parsed is not None:\n if parsed.id is not None:\n last_event_id = parsed.id\n if parsed.retry is not None:\n server_retry = parsed.retry / 1000\n yield parsed\n # Clean end: flush a trailing frame, then finish (no reconnect).\n if buffer.strip():\n parsed = parse_sse_frame(buffer, data_kind)\n if parsed is not None:\n yield parsed\n return\n except httpx.HTTPStatusError:\n raise # a 4xx/5xx is definitive, not a dropped connection\n except (httpx.TransportError, httpx.TimeoutException):\n if not reconnect:\n raise\n failures += 1\n base = server_retry if server_retry is not None else reconnect_delay\n time.sleep(random.uniform(0, min(base * (2 ** (failures - 1)), 30.0)))\n\n\nasync def aiter_sse(\n open_stream: Callable[[Dict[str, str]], Any],\n data_kind: str = "text",\n reconnect: bool = True,\n reconnect_delay: float = 1.0,\n) -> AsyncIterator[ServerSentEvent]:\n """Async mirror of iter_sse; `open_stream` returns an async context manager."""\n last_event_id: Optional[str] = None\n server_retry: Optional[float] = None\n failures = 0\n while True:\n headers = {"Accept": "text/event-stream"}\n if last_event_id is not None:\n headers["Last-Event-ID"] = last_event_id\n try:\n async with open_stream(headers) as response:\n if response.status_code >= 400:\n await response.aread()\n raise httpx.HTTPStatusError(\n f"SSE request failed with status {response.status_code}",\n request=response.request,\n response=response,\n )\n failures = 0\n buffer = ""\n async for chunk in response.aiter_text():\n buffer += chunk\n while _FRAME_DELIMITER in buffer:\n raw, buffer = buffer.split(_FRAME_DELIMITER, 1)\n parsed = parse_sse_frame(raw, data_kind)\n if parsed is not None:\n if parsed.id is not None:\n last_event_id = parsed.id\n if parsed.retry is not None:\n server_retry = parsed.retry / 1000\n yield parsed\n if buffer.strip():\n parsed = parse_sse_frame(buffer, data_kind)\n if parsed is not None:\n yield parsed\n return\n except httpx.HTTPStatusError:\n raise\n except (httpx.TransportError, httpx.TimeoutException):\n if not reconnect:\n raise\n failures += 1\n base = server_retry if server_retry is not None else reconnect_delay\n await asyncio.sleep(random.uniform(0, min(base * (2 ** (failures - 1)), 30.0)))\n',
|
|
10
10
|
'_multipart.py': '# Multipart bodies for generated Python clients — a typed dict/dataclass body is\n# split into httpx\'s (data, files): bytes and file-like values upload as parts,\n# everything else is form data (nested values JSON-encoded, mirroring the\n# TypeScript runtime\'s FormData serialization). A body that is already bytes, a\n# `str`, a file-like object, or an (async) iterator of bytes passes through as httpx\n# `content=` untouched; the caller sets its Content-Type.\nfrom __future__ import annotations\n\nimport json\nfrom typing import Any, Dict, Tuple\n\nfrom ._decode import encode\n\n\ndef to_multipart(body: Any) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n wire = encode(body)\n data: Dict[str, Any] = {}\n files: Dict[str, Any] = {}\n for key, value in (wire or {}).items():\n if isinstance(value, (bytes, bytearray)) or hasattr(value, "read"):\n files[key] = value\n elif isinstance(value, (dict, list)):\n data[key] = json.dumps(value)\n else:\n data[key] = value\n return data, files\n\n\ndef is_stream_body(body: Any) -> bool:\n return (\n isinstance(body, (bytes, bytearray, str))\n or callable(getattr(body, "read", None))\n or hasattr(body, "__next__")\n or hasattr(body, "__aiter__")\n )\n\n\ndef multipart_arguments(body: Any) -> Dict[str, Any]:\n if is_stream_body(body):\n return {"content": body}\n data, files = to_multipart(body)\n return {"data": data, "files": files}\n',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"python.js","sourceRoot":"","sources":["../../src/runtime-sources/python.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,YAAY,EACV,+lDAA+lD;IACjmD,UAAU,EACR,spGAAspG;IACxpG,SAAS,EACP,ghBAAghB;IAClhB,YAAY,EACV
|
|
1
|
+
{"version":3,"file":"python.js","sourceRoot":"","sources":["../../src/runtime-sources/python.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,YAAY,EACV,+lDAA+lD;IACjmD,UAAU,EACR,spGAAspG;IACxpG,SAAS,EACP,ghBAAghB;IAClhB,YAAY,EACV,w6KAAw6K;IAC16K,UAAU,EACR,s3VAAs3V;IACx3V,cAAc,EACZ,ilTAAilT;IACnlT,SAAS,EACP,03MAA03M;IAC53M,eAAe,EACb,u+CAAu+C;CACj+C,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,
|
|
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,
|
|
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"}
|