swagger-sdk-generator 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/README.md +58 -2
  2. package/dist/cli/commands/generate.d.ts +2 -0
  3. package/dist/cli/commands/generate.js +196 -0
  4. package/dist/cli/commands/init.d.ts +2 -0
  5. package/dist/cli/commands/init.js +130 -0
  6. package/dist/cli/commands/inspect.d.ts +2 -0
  7. package/dist/cli/commands/inspect.js +164 -0
  8. package/dist/cli/commands/templates.d.ts +2 -0
  9. package/dist/cli/commands/templates.js +126 -0
  10. package/dist/cli/context.d.ts +16 -0
  11. package/dist/cli/context.js +85 -0
  12. package/dist/cli/main.d.ts +2 -0
  13. package/dist/cli/main.js +25 -0
  14. package/dist/config/dotenv.d.ts +2 -0
  15. package/dist/config/dotenv.js +82 -0
  16. package/dist/config/interpolate.d.ts +8 -0
  17. package/dist/config/interpolate.js +85 -0
  18. package/dist/config/load.d.ts +11 -0
  19. package/dist/config/load.js +182 -0
  20. package/dist/config/migrate-v3.d.ts +5 -0
  21. package/dist/config/migrate-v3.js +6 -0
  22. package/dist/config/mode-compatibility.d.ts +9 -0
  23. package/dist/config/mode-compatibility.js +17 -0
  24. package/dist/config/modes.d.ts +13 -0
  25. package/dist/config/modes.js +27 -0
  26. package/dist/config/preset-definitions.d.ts +2 -0
  27. package/dist/config/preset-definitions.js +4 -0
  28. package/dist/config/presets.d.ts +25 -0
  29. package/dist/config/presets.js +36 -0
  30. package/dist/config/resolve.d.ts +32 -0
  31. package/dist/config/resolve.js +288 -0
  32. package/dist/config/schema.d.ts +93 -0
  33. package/dist/config/schema.js +173 -0
  34. package/dist/config/types.d.ts +42 -0
  35. package/dist/config/types.js +2 -0
  36. package/dist/config/workspace.d.ts +30 -0
  37. package/dist/config/workspace.js +95 -0
  38. package/dist/core/case-align.d.ts +5 -0
  39. package/dist/core/case-align.js +90 -0
  40. package/dist/core/deep-merge.d.ts +2 -0
  41. package/dist/core/deep-merge.js +21 -0
  42. package/dist/core/file-set.d.ts +10 -0
  43. package/dist/core/file-set.js +31 -0
  44. package/dist/core/import-module.d.ts +1 -0
  45. package/dist/core/import-module.js +61 -0
  46. package/dist/core/log.d.ts +9 -0
  47. package/dist/core/log.js +24 -0
  48. package/dist/core/manifest.d.ts +17 -0
  49. package/dist/core/manifest.js +195 -0
  50. package/dist/core/overlaps.d.ts +6 -0
  51. package/dist/core/overlaps.js +67 -0
  52. package/dist/core/package-version.d.ts +1 -0
  53. package/dist/core/package-version.js +44 -0
  54. package/dist/core/pipeline.d.ts +30 -0
  55. package/dist/core/pipeline.js +335 -0
  56. package/dist/core/plugin.d.ts +72 -0
  57. package/dist/core/plugin.js +2 -0
  58. package/dist/core/targets.d.ts +14 -0
  59. package/dist/core/targets.js +120 -0
  60. package/dist/core/unmanaged.d.ts +3 -0
  61. package/dist/core/unmanaged.js +101 -0
  62. package/dist/core/writer.d.ts +28 -0
  63. package/dist/core/writer.js +148 -0
  64. package/dist/index.d.ts +20 -0
  65. package/dist/index.js +37 -0
  66. package/dist/ir/casing.d.ts +5 -0
  67. package/dist/ir/casing.js +22 -0
  68. package/dist/ir/graph.d.ts +8 -0
  69. package/dist/ir/graph.js +95 -0
  70. package/dist/ir/operations/grouping.d.ts +17 -0
  71. package/dist/ir/operations/grouping.js +39 -0
  72. package/dist/ir/operations/legacy-naming.d.ts +2 -0
  73. package/dist/ir/operations/legacy-naming.js +8 -0
  74. package/dist/ir/operations/naming.d.ts +6 -0
  75. package/dist/ir/operations/naming.js +54 -0
  76. package/dist/ir/option-errors.d.ts +3 -0
  77. package/dist/ir/option-errors.js +68 -0
  78. package/dist/ir/transforms/builtins.d.ts +2 -0
  79. package/dist/ir/transforms/builtins.js +4 -0
  80. package/dist/ir/transforms/index.d.ts +10 -0
  81. package/dist/ir/transforms/index.js +39 -0
  82. package/dist/ir/transforms/types.d.ts +9 -0
  83. package/dist/ir/transforms/types.js +2 -0
  84. package/dist/ir/types.d.ts +140 -0
  85. package/dist/ir/types.js +2 -0
  86. package/dist/runtime/axios.d.ts +28 -0
  87. package/dist/runtime/axios.js +132 -0
  88. package/dist/runtime/fetch.d.ts +6 -0
  89. package/dist/runtime/fetch.js +38 -0
  90. package/dist/runtime/index.d.ts +54 -0
  91. package/dist/runtime/index.js +167 -0
  92. package/dist/runtime/rtk.d.ts +35 -0
  93. package/dist/runtime/rtk.js +36 -0
  94. package/dist/runtime/transport.d.ts +38 -0
  95. package/dist/runtime/transport.js +30 -0
  96. package/dist/runtime/wire.d.ts +27 -0
  97. package/dist/runtime/wire.js +148 -0
  98. package/dist/spec/html-entities.d.ts +1 -0
  99. package/dist/spec/html-entities.js +25 -0
  100. package/dist/spec/load.d.ts +26 -0
  101. package/dist/spec/load.js +130 -0
  102. package/dist/spec/openapi/all-of.d.ts +3 -0
  103. package/dist/spec/openapi/all-of.js +9 -0
  104. package/dist/spec/openapi/normalize.d.ts +4 -0
  105. package/dist/spec/openapi/normalize.js +31 -0
  106. package/dist/spec/openapi/operations.d.ts +4 -0
  107. package/dist/spec/openapi/operations.js +173 -0
  108. package/dist/spec/openapi/schema.d.ts +51 -0
  109. package/dist/spec/openapi/schema.js +307 -0
  110. package/dist/targets/declarative/config.d.ts +533 -0
  111. package/dist/targets/declarative/config.js +280 -0
  112. package/dist/targets/declarative/extensions.d.ts +45 -0
  113. package/dist/targets/declarative/extensions.js +123 -0
  114. package/dist/targets/declarative/files.d.ts +13 -0
  115. package/dist/targets/declarative/files.js +127 -0
  116. package/dist/targets/declarative/format.d.ts +4 -0
  117. package/dist/targets/declarative/format.js +104 -0
  118. package/dist/targets/declarative/index.d.ts +9 -0
  119. package/dist/targets/declarative/index.js +170 -0
  120. package/dist/targets/declarative/liquid.d.ts +8 -0
  121. package/dist/targets/declarative/liquid.js +57 -0
  122. package/dist/targets/declarative/naming-case.d.ts +3 -0
  123. package/dist/targets/declarative/naming-case.js +31 -0
  124. package/dist/targets/declarative/naming.d.ts +42 -0
  125. package/dist/targets/declarative/naming.js +174 -0
  126. package/dist/targets/declarative/scaffold.d.ts +5 -0
  127. package/dist/targets/declarative/scaffold.js +146 -0
  128. package/dist/targets/declarative/types.d.ts +52 -0
  129. package/dist/targets/declarative/types.js +287 -0
  130. package/dist/targets/declarative/views.d.ts +180 -0
  131. package/dist/targets/declarative/views.js +447 -0
  132. package/dist/targets/python/extensions.js +152 -0
  133. package/dist/targets/python/target.json +549 -0
  134. package/dist/targets/python/templates/client/client.liquid +114 -0
  135. package/dist/targets/python/templates/client/httpx_transport.liquid +172 -0
  136. package/dist/targets/python/templates/client/init.liquid +20 -0
  137. package/dist/targets/python/templates/client/partials/operation_method.liquid +41 -0
  138. package/dist/targets/python/templates/client/resource.liquid +28 -0
  139. package/dist/targets/python/templates/client/runtime.liquid +133 -0
  140. package/dist/targets/python/templates/client/transport.liquid +62 -0
  141. package/dist/targets/python/templates/models/module.liquid +48 -0
  142. package/dist/targets/python/templates/models/partials/docstring.liquid +5 -0
  143. package/dist/targets/python/templates/models/partials/enum_class.liquid +11 -0
  144. package/dist/targets/python/templates/models/partials/field_line.liquid +5 -0
  145. package/dist/targets/python/templates/models/partials/model_class.liquid +17 -0
  146. package/dist/targets/typescript/compatibility-naming.d.ts +6 -0
  147. package/dist/targets/typescript/compatibility-naming.js +28 -0
  148. package/dist/targets/typescript/compatibility-options.d.ts +5 -0
  149. package/dist/targets/typescript/compatibility-options.js +8 -0
  150. package/dist/targets/typescript/compatibility-target.d.ts +5 -0
  151. package/dist/targets/typescript/compatibility-target.js +10 -0
  152. package/dist/targets/typescript/http-operations.d.ts +34 -0
  153. package/dist/targets/typescript/http-operations.js +155 -0
  154. package/dist/targets/typescript/imports.d.ts +43 -0
  155. package/dist/targets/typescript/imports.js +154 -0
  156. package/dist/targets/typescript/index.d.ts +7 -0
  157. package/dist/targets/typescript/index.js +52 -0
  158. package/dist/targets/typescript/mock-compatibility.d.ts +4 -0
  159. package/dist/targets/typescript/mock-compatibility.js +6 -0
  160. package/dist/targets/typescript/mock-hints.d.ts +13 -0
  161. package/dist/targets/typescript/mock-hints.js +75 -0
  162. package/dist/targets/typescript/mock-reachability.d.ts +12 -0
  163. package/dist/targets/typescript/mock-reachability.js +87 -0
  164. package/dist/targets/typescript/model-compatibility.d.ts +14 -0
  165. package/dist/targets/typescript/model-compatibility.js +16 -0
  166. package/dist/targets/typescript/naming.d.ts +13 -0
  167. package/dist/targets/typescript/naming.js +50 -0
  168. package/dist/targets/typescript/options.d.ts +124 -0
  169. package/dist/targets/typescript/options.js +90 -0
  170. package/dist/targets/typescript/outputs/client.d.ts +67 -0
  171. package/dist/targets/typescript/outputs/client.js +187 -0
  172. package/dist/targets/typescript/outputs/mocks.d.ts +32 -0
  173. package/dist/targets/typescript/outputs/mocks.js +371 -0
  174. package/dist/targets/typescript/outputs/models.d.ts +85 -0
  175. package/dist/targets/typescript/outputs/models.js +246 -0
  176. package/dist/targets/typescript/outputs/rtk-query.d.ts +69 -0
  177. package/dist/targets/typescript/outputs/rtk-query.js +266 -0
  178. package/dist/targets/typescript/prettier.d.ts +7 -0
  179. package/dist/targets/typescript/prettier.js +44 -0
  180. package/dist/targets/typescript/templates/client/client.liquid +30 -0
  181. package/dist/targets/typescript/templates/client/partials/api-member.liquid +13 -0
  182. package/dist/targets/typescript/templates/client/partials/jsdoc.liquid +10 -0
  183. package/dist/targets/typescript/templates/client/partials/method.liquid +26 -0
  184. package/dist/targets/typescript/templates/client/partials/query-type.liquid +10 -0
  185. package/dist/targets/typescript/templates/client/resource.liquid +34 -0
  186. package/dist/targets/typescript/templates/mocks/mock.liquid +15 -0
  187. package/dist/targets/typescript/templates/mocks/partials/factory.liquid +12 -0
  188. package/dist/targets/typescript/templates/mocks/partials/imports.liquid +7 -0
  189. package/dist/targets/typescript/templates/models/alias.liquid +16 -0
  190. package/dist/targets/typescript/templates/models/enum.liquid +27 -0
  191. package/dist/targets/typescript/templates/models/index.liquid +14 -0
  192. package/dist/targets/typescript/templates/models/model.liquid +25 -0
  193. package/dist/targets/typescript/templates/models/partials/const.liquid +10 -0
  194. package/dist/targets/typescript/templates/models/partials/imports.liquid +9 -0
  195. package/dist/targets/typescript/templates/models/partials/jsdoc.liquid +9 -0
  196. package/dist/targets/typescript/templates/models/partials/property.liquid +7 -0
  197. package/dist/targets/typescript/templates/rtk-query/api.liquid +16 -0
  198. package/dist/targets/typescript/templates/rtk-query/partials/arg-types.liquid +6 -0
  199. package/dist/targets/typescript/templates/rtk-query/partials/endpoint-mutation.liquid +13 -0
  200. package/dist/targets/typescript/templates/rtk-query/partials/endpoint-query.liquid +13 -0
  201. package/dist/targets/typescript/templates/rtk-query/partials/file-warning.liquid +7 -0
  202. package/dist/targets/typescript/templates/rtk-query/partials/hooks.liquid +9 -0
  203. package/dist/targets/typescript/templates/rtk-query/partials/imports.liquid +7 -0
  204. package/dist/targets/typescript/templates/rtk-query/partials/request-config.liquid +9 -0
  205. package/dist/targets/typescript/templates/rtk-query/resource.liquid +40 -0
  206. package/dist/targets/typescript/ts-type.d.ts +70 -0
  207. package/dist/targets/typescript/ts-type.js +62 -0
  208. package/dist/targets/typescript/type-printer.d.ts +21 -0
  209. package/dist/targets/typescript/type-printer.js +115 -0
  210. package/dist/templates/engine.d.ts +20 -0
  211. package/dist/templates/engine.js +161 -0
  212. package/dist/templates/inspect.d.ts +27 -0
  213. package/dist/templates/inspect.js +331 -0
  214. package/package.json +65 -4
  215. package/schema/sdk-gen.local.schema.json +75 -0
  216. package/schema/sdk-gen.schema.json +980 -0
  217. package/schema/sdk-gen.target.schema.json +1384 -0
@@ -0,0 +1,172 @@
1
+ {% comment %}
2
+ Default httpx-backed transports (sync + async) for generated Python clients (docs/TRANSPORT.md).
3
+ Emitted unless the client option `transport` is "none".
4
+ Data: FileView (once)
5
+ {% endcomment -%}
6
+ # Generated by swagger-sdk-generator. Do not edit.
7
+ """Default transports over httpx. Replace them with any object that has `request(req) -> HttpResponse`."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Callable, Mapping
13
+ from typing import Any
14
+
15
+ import httpx
16
+
17
+ from .transport import ApiError, HttpRequest, HttpResponse
18
+
19
+ _MULTIPART = "multipart/form-data"
20
+ _URLENCODED = "application/x-www-form-urlencoded"
21
+
22
+
23
+ def _is_raw(body: Any) -> bool:
24
+ return isinstance(body, (bytes, bytearray, str)) or hasattr(body, "read")
25
+
26
+
27
+ def _multipart(body: Mapping[str, Any]) -> list[tuple[str, Any]]:
28
+ """Every field as a multipart part: files as given, other values as plain (filename-less) parts."""
29
+ parts: list[tuple[str, Any]] = []
30
+ for key, value in body.items():
31
+ for item in value if isinstance(value, list) else [value]:
32
+ if item is None:
33
+ continue
34
+ if isinstance(item, bytearray):
35
+ item = bytes(item)
36
+ if isinstance(item, (bytes, tuple)) or hasattr(item, "read"):
37
+ parts.append((key, item))
38
+ else:
39
+ parts.append((key, (None, str(item).encode("utf-8"))))
40
+ return parts
41
+
42
+
43
+ def _request_kwargs(
44
+ defaults: Mapping[str, str], token: str | None, req: HttpRequest, timeout: Any
45
+ ) -> dict[str, Any]:
46
+ """httpx keyword arguments. Header precedence: defaults < content type / auth < request headers."""
47
+ headers = dict(defaults)
48
+ kwargs: dict[str, Any] = {}
49
+ if req.query:
50
+ kwargs["params"] = [
51
+ (key, item) for key, value in req.query.items() for item in (value if isinstance(value, list) else [value])
52
+ ]
53
+ if req.body is not None:
54
+ content_type = req.content_type or "application/json"
55
+ lower = content_type.lower()
56
+ if lower.startswith(_MULTIPART) and isinstance(req.body, Mapping):
57
+ # httpx writes the Content-Type with the boundary itself.
58
+ kwargs["files"] = _multipart(req.body)
59
+ elif lower.startswith(_URLENCODED) and isinstance(req.body, Mapping):
60
+ kwargs["data"] = dict(req.body)
61
+ elif "json" not in lower and _is_raw(req.body):
62
+ kwargs["content"] = req.body
63
+ headers["Content-Type"] = content_type
64
+ else:
65
+ kwargs["content"] = json.dumps(req.body).encode("utf-8")
66
+ headers["Content-Type"] = content_type if "json" in lower else "application/json"
67
+ if token:
68
+ headers["Authorization"] = f"Bearer {token}"
69
+ headers.update(req.headers or {})
70
+ kwargs["headers"] = headers
71
+ if timeout is not None:
72
+ kwargs["timeout"] = timeout
73
+ return kwargs
74
+
75
+
76
+ def _parsed(response: httpx.Response) -> Any:
77
+ if not response.content:
78
+ return None
79
+ try:
80
+ return response.json()
81
+ except ValueError:
82
+ return response.text
83
+
84
+
85
+ def _response(response: httpx.Response, req: HttpRequest) -> HttpResponse:
86
+ if response.status_code < 200 or response.status_code >= 300:
87
+ raise ApiError(response.status_code, _parsed(response), req)
88
+ if req.response_type == "bytes":
89
+ data: Any = response.content
90
+ elif req.response_type == "text":
91
+ data = response.text
92
+ else:
93
+ data = _parsed(response)
94
+ return HttpResponse(response.status_code, dict(response.headers), data)
95
+
96
+
97
+ class HttpxTransport:
98
+ """Sync transport over `httpx.Client`. A client passed in is not closed by `close()`."""
99
+
100
+ def __init__(
101
+ self,
102
+ base_url: str,
103
+ *,
104
+ get_token: Callable[[], str | None] | None = None,
105
+ headers: Mapping[str, str] | None = None,
106
+ timeout: float | httpx.Timeout | None = None,
107
+ client: httpx.Client | None = None,
108
+ ) -> None:
109
+ self._base_url = base_url.rstrip("/")
110
+ self._get_token = get_token
111
+ self._headers = dict(headers or {})
112
+ self._timeout = timeout
113
+ self._owns_client = client is None
114
+ self._client = client if client is not None else httpx.Client()
115
+
116
+ def request(self, req: HttpRequest) -> HttpResponse:
117
+ token = self._get_token() if self._get_token else None
118
+ response = self._client.request(
119
+ req.method.upper(),
120
+ f"{self._base_url}{req.path}",
121
+ **_request_kwargs(self._headers, token, req, self._timeout),
122
+ )
123
+ return _response(response, req)
124
+
125
+ def close(self) -> None:
126
+ if self._owns_client:
127
+ self._client.close()
128
+
129
+ def __enter__(self) -> HttpxTransport:
130
+ return self
131
+
132
+ def __exit__(self, *exc_info: object) -> None:
133
+ self.close()
134
+
135
+
136
+ class AsyncHttpxTransport:
137
+ """Async transport over `httpx.AsyncClient`. A client passed in is not closed by `aclose()`."""
138
+
139
+ def __init__(
140
+ self,
141
+ base_url: str,
142
+ *,
143
+ get_token: Callable[[], str | None] | None = None,
144
+ headers: Mapping[str, str] | None = None,
145
+ timeout: float | httpx.Timeout | None = None,
146
+ client: httpx.AsyncClient | None = None,
147
+ ) -> None:
148
+ self._base_url = base_url.rstrip("/")
149
+ self._get_token = get_token
150
+ self._headers = dict(headers or {})
151
+ self._timeout = timeout
152
+ self._owns_client = client is None
153
+ self._client = client if client is not None else httpx.AsyncClient()
154
+
155
+ async def request(self, req: HttpRequest) -> HttpResponse:
156
+ token = self._get_token() if self._get_token else None
157
+ response = await self._client.request(
158
+ req.method.upper(),
159
+ f"{self._base_url}{req.path}",
160
+ **_request_kwargs(self._headers, token, req, self._timeout),
161
+ )
162
+ return _response(response, req)
163
+
164
+ async def aclose(self) -> None:
165
+ if self._owns_client:
166
+ await self._client.aclose()
167
+
168
+ async def __aenter__(self) -> AsyncHttpxTransport:
169
+ return self
170
+
171
+ async def __aexit__(self, *exc_info: object) -> None:
172
+ await self.aclose()
@@ -0,0 +1,20 @@
1
+ {% comment %}
2
+ Package exports for a generated Python client package.
3
+ Data: FileView (once)
4
+ {% endcomment -%}
5
+ # Generated by swagger-sdk-generator. Do not edit.
6
+
7
+ from .client import Api, AsyncApi, create_api, create_async_api
8
+ from .transport import ApiError, AsyncTransport, HttpRequest, HttpResponse, Transport
9
+
10
+ __all__ = [
11
+ "Api",
12
+ "ApiError",
13
+ "AsyncApi",
14
+ "AsyncTransport",
15
+ "HttpRequest",
16
+ "HttpResponse",
17
+ "Transport",
18
+ "create_api",
19
+ "create_async_api",
20
+ ]
@@ -0,0 +1,41 @@
1
+ {% comment %}
2
+ One operation method (sync or async) of a resource class.
3
+ Params: operation (OperationView), async (bool)
4
+ Signature: path params, body (when the operation has one), `*`, query params, header params, headers.
5
+ {% endcomment -%}
6
+ {%- assign op = operation -%}
7
+ {%- if op.body -%}
8
+ {%- assign bodyParts = op.body.type | remove: ' ' | split: '|' -%}
9
+ {%- endif -%}
10
+ {% if async %}async {% endif %}def {{ op.name }}(
11
+ self,
12
+ {% for p in op.pathParams -%}
13
+ {{ p.name }}: {{ p.type }},
14
+ {% endfor -%}
15
+ {% if op.body -%}
16
+ body: {{ op.body.type }}{% unless op.body.required %}{% unless bodyParts contains 'None' %} | None{% endunless %} = None{% endunless %},
17
+ {% endif -%}
18
+ *,
19
+ {% for p in op.queryParams -%}
20
+ {{ p.name }}: {{ p.type }}{% unless p.required %} = None{% endunless %},
21
+ {% endfor -%}
22
+ {% for p in op.headerParams -%}
23
+ {{ p.name }}: {{ p.type }}{% unless p.required %} = None{% endunless %},
24
+ {% endfor -%}
25
+ headers: dict[str, str] | None = None,
26
+ ) -> {{ op.computed.returnType }}:
27
+ {% if op.computed.returnExpression != 'None' %}response = {% endif %}{% if async %}await {% endif %}self._transport.request(
28
+ _runtime.HttpRequest(
29
+ operation={{ op.operationId | default: op.name | quote }},
30
+ method={{ op.method | quote }},
31
+ path={% if op.pathParams.size > 0 %}_runtime.path({{ op.path | quote }}, { {%- for p in op.pathParams %}{{ p.wireName | quote }}: {{ p.name }}{% unless forloop.last %}, {% endunless %}{% endfor -%} }){% else %}{{ op.path | quote }}{% endif %},
32
+ query={% if op.queryParams.size > 0 %}_runtime.query({ {%- for p in op.queryParams %}{{ p.wireName | quote }}: {{ p.name }}{% unless forloop.last %}, {% endunless %}{% endfor -%} }){% else %}None{% endif %},
33
+ headers=_runtime.headers(headers, { {%- for p in op.headerParams %}{{ p.wireName | quote }}: {{ p.name }}{% unless forloop.last %}, {% endunless %}{% endfor -%} }),
34
+ body={% if op.body %}_runtime.body(body, {{ op.body.contentType | quote }}){% else %}None{% endif %},
35
+ content_type={% if op.body %}{{ op.body.contentType | quote }}{% else %}None{% endif %},
36
+ response_type={{ op.computed.responseType | quote }},
37
+ )
38
+ )
39
+ {% if op.computed.returnExpression != 'None' -%}
40
+ return {{ op.computed.returnExpression }}
41
+ {% endif -%}
@@ -0,0 +1,28 @@
1
+ {% comment %}
2
+ One resource: a sync class over `Transport` and an async class over `AsyncTransport`.
3
+ Data: FileView (each resource) — resource (ResourceView), imports[] (types + models used by its operations)
4
+ {% endcomment -%}
5
+ # Generated by swagger-sdk-generator. Do not edit.
6
+
7
+ from __future__ import annotations
8
+ {% if imports.size > 0 %}
9
+ {% for importLine in imports -%}
10
+ {{ importLine }}
11
+ {% endfor -%}
12
+ {% endif %}
13
+ from . import _runtime
14
+
15
+
16
+ class {{ resource.name }}:
17
+ def __init__(self, transport: _runtime.Transport) -> None:
18
+ self._transport = transport
19
+ {% for operation in resource.operations %}
20
+ {% render 'client/partials/operation_method', operation: operation, async: false %}
21
+ {%- endfor %}
22
+
23
+ class Async{{ resource.name }}:
24
+ def __init__(self, transport: _runtime.AsyncTransport) -> None:
25
+ self._transport = transport
26
+ {% for operation in resource.operations %}
27
+ {% render 'client/partials/operation_method', operation: operation, async: true %}
28
+ {%- endfor %}
@@ -0,0 +1,133 @@
1
+ {% comment %}
2
+ Private helpers of the generated resource modules: parameter stringification, path filling,
3
+ query / header building, request-body dumping and response validation. Not part of the contract.
4
+ Data: FileView (once)
5
+ {% endcomment -%}
6
+ # Generated by swagger-sdk-generator. Do not edit.
7
+ """Helpers shared by the generated resource modules (private, not part of the transport contract)."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Mapping
13
+ from datetime import date, datetime, time
14
+ from enum import Enum
15
+ from typing import Any
16
+ from urllib.parse import quote
17
+
18
+ from pydantic import BaseModel, TypeAdapter
19
+ from pydantic_core import to_jsonable_python
20
+
21
+ from .transport import AsyncTransport, HttpRequest, Transport
22
+
23
+ __all__ = ["AsyncTransport", "HttpRequest", "Transport"]
24
+
25
+ _FORM = ("multipart/form-data", "application/x-www-form-urlencoded")
26
+
27
+
28
+ def param_str(value: Any) -> str:
29
+ """Wire form of a path / query / header value."""
30
+ if isinstance(value, Enum):
31
+ return param_str(value.value)
32
+ if isinstance(value, bool):
33
+ return "true" if value else "false"
34
+ if isinstance(value, (datetime, date, time)):
35
+ return value.isoformat()
36
+ if isinstance(value, (list, tuple)):
37
+ return ",".join(param_str(item) for item in value)
38
+ if isinstance(value, (Mapping, BaseModel)):
39
+ return json.dumps(to_jsonable(value), separators=(",", ":"))
40
+ return str(value)
41
+
42
+
43
+ def path(template: str, params: Mapping[str, Any]) -> str:
44
+ """Fill `{name}` placeholders with percent-encoded parameter values."""
45
+ filled = template
46
+ for name, value in params.items():
47
+ filled = filled.replace("{" + name + "}", quote(param_str(value), safe=""))
48
+ return filled
49
+
50
+
51
+ def query(params: Mapping[str, Any]) -> dict[str, str | list[str]] | None:
52
+ """Query values as strings (lists stay lists: repeated keys); None is dropped."""
53
+ out: dict[str, str | list[str]] = {}
54
+ for key, value in params.items():
55
+ if value is None:
56
+ continue
57
+ if isinstance(value, (list, tuple, set, frozenset)):
58
+ out[key] = [param_str(item) for item in value if item is not None]
59
+ else:
60
+ out[key] = param_str(value)
61
+ return out or None
62
+
63
+
64
+ def headers(extra: Mapping[str, Any] | None, params: Mapping[str, Any]) -> dict[str, str] | None:
65
+ """Header params of the operation, then per-call headers (they win); values as strings, None dropped."""
66
+ merged = {key: param_str(value) for key, value in params.items() if value is not None}
67
+ if extra:
68
+ merged.update({key: param_str(value) for key, value in extra.items() if value is not None})
69
+ return merged or None
70
+
71
+
72
+ def to_jsonable(value: Any) -> Any:
73
+ """JSON-ready data: models by alias with only the fields that were set (PATCH-safe), dates ISO, enums by value."""
74
+ if isinstance(value, BaseModel):
75
+ return value.model_dump(mode="json", by_alias=True, exclude_unset=True)
76
+ if isinstance(value, (list, tuple)):
77
+ return [to_jsonable(item) for item in value]
78
+ if isinstance(value, Mapping):
79
+ return {key if isinstance(key, str) else param_str(key): to_jsonable(item) for key, item in value.items()}
80
+ return to_jsonable_python(value)
81
+
82
+
83
+ def _is_file(value: Any) -> bool:
84
+ return isinstance(value, (bytes, bytearray, tuple)) or hasattr(value, "read")
85
+
86
+
87
+ def _form_value(value: Any) -> Any:
88
+ if _is_file(value):
89
+ return bytes(value) if isinstance(value, bytearray) else value
90
+ return param_str(value)
91
+
92
+
93
+ def form(value: Any) -> Any:
94
+ """Form fields: files (bytes / file objects / httpx-style tuples) kept, everything else stringified, None dropped."""
95
+ if isinstance(value, BaseModel):
96
+ value = value.model_dump(by_alias=True, exclude_unset=True)
97
+ if not isinstance(value, Mapping):
98
+ return value
99
+ out: dict[str, Any] = {}
100
+ for key, item in value.items():
101
+ if item is None:
102
+ continue
103
+ if isinstance(item, list):
104
+ out[key] = [_form_value(entry) for entry in item if entry is not None]
105
+ else:
106
+ out[key] = _form_value(item)
107
+ return out
108
+
109
+
110
+ def body(value: Any, content_type: str | None) -> Any:
111
+ """Request body for the transport: form fields, raw bytes / text / file objects, or JSON-ready data."""
112
+ if value is None:
113
+ return None
114
+ lower = (content_type or "").lower()
115
+ if lower.startswith(_FORM):
116
+ return form(value)
117
+ if "json" not in lower and (isinstance(value, (bytes, bytearray, str)) or hasattr(value, "read")):
118
+ return value
119
+ return to_jsonable(value)
120
+
121
+
122
+ _ADAPTERS: dict[Any, TypeAdapter[Any]] = {}
123
+
124
+
125
+ def validate(tp: Any, data: Any) -> Any:
126
+ """Validate response data against a type (pydantic TypeAdapter, cached per type)."""
127
+ try:
128
+ adapter = _ADAPTERS.get(tp)
129
+ except TypeError:
130
+ return TypeAdapter(tp).validate_python(data)
131
+ if adapter is None:
132
+ adapter = _ADAPTERS[tp] = TypeAdapter(tp)
133
+ return adapter.validate_python(data)
@@ -0,0 +1,62 @@
1
+ {% comment %}
2
+ Transport contract for generated Python clients (docs/TRANSPORT.md): request/response DTOs,
3
+ sync and async protocols, and ApiError. Dependency-free.
4
+ Data: FileView (once)
5
+ {% endcomment -%}
6
+ # Generated by swagger-sdk-generator. Do not edit.
7
+ """The transport contract: the only HTTP surface the generated client calls."""
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import Any, Literal, Protocol
13
+
14
+
15
+ @dataclass
16
+ class HttpRequest:
17
+ """One operation call, already mapped to HTTP (no base URL, no auth)."""
18
+
19
+ #: Operation id / generated method name, for logging, mocking, metrics.
20
+ operation: str
21
+ method: str
22
+ #: Path with path params filled in and percent-encoded, relative to the base URL.
23
+ path: str
24
+ #: Query values as strings; a list means a repeated key.
25
+ query: dict[str, str | list[str]] | None
26
+ #: Header params of the operation + per-call headers; the transport adds auth/defaults.
27
+ headers: dict[str, str] | None
28
+ #: JSON-ready data, form fields (dict; file values are bytes / file objects / tuples), bytes or text.
29
+ body: Any
30
+ #: Request media type from the spec (`application/json`, `multipart/form-data`, ...).
31
+ content_type: str | None
32
+ #: How to read the response, from the spec's success media type.
33
+ response_type: Literal["json", "text", "bytes"]
34
+
35
+
36
+ @dataclass
37
+ class HttpResponse:
38
+ status: int
39
+ headers: dict[str, str]
40
+ data: Any
41
+
42
+
43
+ class Transport(Protocol):
44
+ """Sends a request; raises ApiError for non-2xx responses."""
45
+
46
+ def request(self, req: HttpRequest) -> HttpResponse: ...
47
+
48
+
49
+ class AsyncTransport(Protocol):
50
+ """Sends a request; raises ApiError for non-2xx responses."""
51
+
52
+ async def request(self, req: HttpRequest) -> HttpResponse: ...
53
+
54
+
55
+ class ApiError(Exception):
56
+ """A non-2xx response: status, parsed body (JSON when possible, else text) and the request."""
57
+
58
+ def __init__(self, status: int, data: Any, request: HttpRequest, message: str | None = None) -> None:
59
+ super().__init__(message or f"{request.operation} failed with status {status}")
60
+ self.status = status
61
+ self.data = data
62
+ self.request = request
@@ -0,0 +1,48 @@
1
+ {% comment %}
2
+ Entry point for a Python pydantic models module: every model, dependencies first.
3
+ Data: FileView (once) — models[] (ModelView), imports[]
4
+ {% endcomment -%}
5
+ {%- assign enums = models | where: 'kind', 'enum' -%}
6
+ {%- assign classes = models | where: 'kind', 'object' -%}
7
+ {%- assign aliases = models | where: 'kind', 'alias' -%}
8
+ {% block header -%}
9
+ # Generated by swagger-sdk-generator. Do not edit.
10
+ {% endblock %}
11
+
12
+ {% block imports -%}
13
+ from __future__ import annotations
14
+ {% if imports.size > 0 %}
15
+
16
+ {% for importLine in imports -%}
17
+ {{ importLine }}
18
+ {% endfor -%}
19
+ {% endif -%}
20
+ {% endblock %}
21
+
22
+ {% block enums -%}
23
+ {% for enum in enums -%}
24
+ {% render 'models/partials/enum_class', model: enum %}
25
+ {% unless forloop.last and classes.size == 0 and aliases.size == 0 %}
26
+
27
+ {% endunless -%}
28
+ {% endfor -%}
29
+ {% endblock -%}
30
+ {% block models -%}
31
+ {% for class in classes -%}
32
+ {% render 'models/partials/model_class', model: class %}
33
+ {% unless forloop.last and aliases.size == 0 and classes.size == 0 %}
34
+
35
+ {% endunless -%}
36
+ {% endfor -%}
37
+ {% for alias in aliases -%}
38
+ {{ alias.name }} = {{ alias.type }}{% if alias.typeComment %} # {{ alias.typeComment }}{% endif %}
39
+ {% unless forloop.last and classes.size == 0 %}
40
+
41
+ {% endunless -%}
42
+ {% endfor -%}
43
+ {% endblock -%}
44
+ {% block rebuild -%}
45
+ {% for class in classes -%}
46
+ {{ class.name }}.model_rebuild()
47
+ {% endfor -%}
48
+ {% endblock %}
@@ -0,0 +1,5 @@
1
+ {% comment %}
2
+ Renders a Python docstring literal with its caller-provided indentation.
3
+ Data: text (string), indent (string)
4
+ {% endcomment -%}
5
+ {{ indent }}{{ text | quote }}
@@ -0,0 +1,11 @@
1
+ {% comment %}
2
+ Renders a top-level Python enum class.
3
+ Data: ModelView (kind enum, as `model`); computed.bases from extensions.js
4
+ {% endcomment -%}
5
+ class {{ model.name }}({{ model.computed.bases }}):
6
+ {% if model.doc -%}
7
+ {% render 'models/partials/docstring', text: model.doc, indent: ' ' %}
8
+ {% endif -%}
9
+ {% for member in model.members -%}
10
+ {{ member.key }} = {{ member.literal }}
11
+ {% endfor -%}
@@ -0,0 +1,5 @@
1
+ {% comment %}
2
+ Renders one Python pydantic model field.
3
+ Data: PropertyView (as `property`); computed.default from extensions.js
4
+ {% endcomment -%}
5
+ {{ property.name }}: {{ property.type }}{% if property.computed.default %} = {{ property.computed.default }}{% endif %}{% if property.typeComment %} # {{ property.typeComment }}{% endif %}
@@ -0,0 +1,17 @@
1
+ {% comment %}
2
+ Renders a top-level Python pydantic model class.
3
+ Data: ModelView (kind object, as `model`); computed.config from extensions.js
4
+ {% endcomment -%}
5
+ class {{ model.name }}(BaseModel):
6
+ {% if model.doc -%}
7
+ {% render 'models/partials/docstring', text: model.doc, indent: ' ' %}
8
+ {% endif -%}
9
+ {% if model.computed.config -%}
10
+ model_config = {{ model.computed.config }}
11
+ {% endif -%}
12
+ {% for property in model.properties -%}
13
+ {% render 'models/partials/field_line', property: property %}
14
+ {% endfor -%}
15
+ {% unless model.properties.size > 0 or model.computed.config or model.doc -%}
16
+ pass
17
+ {% endunless -%}
@@ -0,0 +1,6 @@
1
+ import type { EnumType } from '../../ir/types';
2
+ import { propertyKey, type ConstMember } from './naming';
3
+ export declare const legacyPropertyKey: typeof propertyKey;
4
+ export declare function legacyConstMembers(node: EnumType): ConstMember[];
5
+ export declare function objectTypeMember(_modelId: string): never;
6
+ export declare function tsEnumMembers(node: EnumType): ConstMember[];
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.legacyPropertyKey = void 0;
4
+ exports.legacyConstMembers = legacyConstMembers;
5
+ exports.objectTypeMember = objectTypeMember;
6
+ exports.tsEnumMembers = tsEnumMembers;
7
+ const imports_1 = require("./imports");
8
+ const naming_1 = require("./naming");
9
+ exports.legacyPropertyKey = naming_1.propertyKey;
10
+ function legacyConstMembers(node) {
11
+ return (0, naming_1.constMembers)(node.values);
12
+ }
13
+ function objectTypeMember(_modelId) {
14
+ throw new Error('Unsupported model discriminator option');
15
+ }
16
+ function tsEnumMembers(node) {
17
+ const used = new Set();
18
+ return node.values.flatMap((value, index) => {
19
+ if (value === null)
20
+ return [];
21
+ const base = typeof value === 'string' && value ? (0, imports_1.toIdentifier)(value) : `VALUE_${index}`;
22
+ let key = base;
23
+ for (let suffix = 2; used.has(key); suffix++)
24
+ key = `${base}_${suffix}`;
25
+ used.add(key);
26
+ return [{ key, value: typeof value === 'boolean' ? (0, naming_1.literal)(String(value)) : (0, naming_1.literal)(value) }];
27
+ });
28
+ }
@@ -0,0 +1,5 @@
1
+ import { z } from 'zod';
2
+ export declare const engineSchema: z.ZodLiteral<"ir">;
3
+ export declare const legacyQuirksSchema: z.ZodOptional<z.ZodLiteral<false>>;
4
+ export declare const mockStyleSchema: z.ZodLiteral<"seeded">;
5
+ export declare const objectTypeSchema: z.ZodLiteral<false>;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.objectTypeSchema = exports.mockStyleSchema = exports.legacyQuirksSchema = exports.engineSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ exports.engineSchema = zod_1.z.literal('ir');
6
+ exports.legacyQuirksSchema = zod_1.z.literal(false).optional();
7
+ exports.mockStyleSchema = zod_1.z.literal('seeded');
8
+ exports.objectTypeSchema = zod_1.z.literal(false);
@@ -0,0 +1,5 @@
1
+ import type { Formatter, OutputPlugin } from '../../core/plugin';
2
+ export interface TypeScriptCompatibilityOptions {
3
+ }
4
+ export declare const compatibilityOutputs: OutputPlugin<any>[];
5
+ export declare function compatibilityFormatter(options: TypeScriptCompatibilityOptions): Formatter | undefined;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compatibilityOutputs = void 0;
4
+ exports.compatibilityFormatter = compatibilityFormatter;
5
+ exports.compatibilityOutputs = [];
6
+ function compatibilityFormatter(options) {
7
+ if ('biome' in options && options.biome)
8
+ throw new Error('The public SDK generator supports the Prettier formatter');
9
+ return undefined;
10
+ }
@@ -0,0 +1,34 @@
1
+ import type { OutputContext } from '../../core/plugin';
2
+ import type { ResourceGroup } from '../../ir/operations/grouping';
3
+ import type { MediaContent, Operation, Parameter, Response } from '../../ir/types';
4
+ import { type PrintContext } from './type-printer';
5
+ export type HttpVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';
6
+ export type ResponseKind = 'json' | 'text' | 'blob';
7
+ export declare function endpointFullPath(pathString: string, options: {
8
+ stripPrefixes: string[];
9
+ basePath: string;
10
+ }): string;
11
+ export declare function withUndeclaredPathParams(operation: Operation, legacy: boolean): Operation;
12
+ export declare function pathParamLocals(operation: Operation, reserved: readonly string[]): Map<string, string>;
13
+ export declare function safeLocalName(name: string): string;
14
+ export declare function pathTemplateWithLocals(fullPath: string, localNames: Map<string, string>, encode?: boolean): string;
15
+ export interface HeaderParamView {
16
+ key: string;
17
+ name: string;
18
+ }
19
+ export declare function headerParamKeys(parameters: Parameter[]): Map<Parameter, string>;
20
+ export declare function renamedHeaderDoc(param: Parameter, key: string | undefined): string[];
21
+ export declare function pickJsonContent(contents: MediaContent[]): MediaContent | undefined;
22
+ export declare function pickContent(contents: MediaContent[]): MediaContent | undefined;
23
+ export declare function requestMedia(contents: MediaContent[], print: PrintContext): {
24
+ contentType: string;
25
+ type: string;
26
+ };
27
+ export declare function isBinaryResponse(responses: Response[]): boolean;
28
+ export declare function successContent(responses: Response[]): MediaContent | undefined;
29
+ export declare function responseKind(responses: Response[]): ResponseKind;
30
+ export declare function supportedOperations(output: string, operations: Operation[], group: ResourceGroup, warn: (message: string) => void): Operation[];
31
+ export declare function docLines(text: string | undefined): string[];
32
+ export declare function claimUnique(base: string, claimed: Set<string>, keyOf?: (name: string) => string): string;
33
+ export declare const JS_RESERVED: string[];
34
+ export declare function modelPeersWithFallback(ctx: OutputContext<unknown>): OutputContext<unknown>['peers'];