sdkloom 0.0.0-stage → 0.1.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 (383) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +239 -2
  3. package/kits/allowed-sources.json +24 -0
  4. package/kits/csharp/kit.json +6 -0
  5. package/kits/csharp/src/Runtime/Client.cs +295 -0
  6. package/kits/csharp/src/Runtime/Context.cs +216 -0
  7. package/kits/csharp/src/Runtime/Errors.cs +121 -0
  8. package/kits/csharp/src/Runtime/Http.cs +218 -0
  9. package/kits/csharp/src/Runtime/Json.cs +650 -0
  10. package/kits/csharp/src/Runtime/Lang.cs +212 -0
  11. package/kits/csharp/src/Runtime/Models.cs +206 -0
  12. package/kits/csharp/src/Runtime/Multipart.cs +108 -0
  13. package/kits/csharp/src/Runtime/Pagination.cs +122 -0
  14. package/kits/csharp/src/Runtime/Sse.cs +197 -0
  15. package/kits/csharp/src/Runtime/Testing.cs +375 -0
  16. package/kits/csharp/src/Runtime/Transport.cs +212 -0
  17. package/kits/csharp/src/Runtime/Wait.cs +57 -0
  18. package/kits/csharp/src/Runtime/Webhooks.cs +148 -0
  19. package/kits/csharp/tests/ClientTests.cs +128 -0
  20. package/kits/csharp/tests/HttpTests.cs +44 -0
  21. package/kits/csharp/tests/JsonTests.cs +132 -0
  22. package/kits/csharp/tests/LangTests.cs +57 -0
  23. package/kits/csharp/tests/MultipartTests.cs +31 -0
  24. package/kits/csharp/tests/PaginationTests.cs +93 -0
  25. package/kits/csharp/tests/SseTests.cs +122 -0
  26. package/kits/csharp/tests/TestRunner.cs +93 -0
  27. package/kits/csharp/tests/TestingTests.cs +80 -0
  28. package/kits/csharp/tests/TransportTests.cs +145 -0
  29. package/kits/csharp/tests/WaitTests.cs +39 -0
  30. package/kits/csharp/tests/WebhooksTests.cs +46 -0
  31. package/kits/csharp/versions.json +12 -0
  32. package/kits/go/kit.json +6 -0
  33. package/kits/go/src/sdkruntime/client.go +322 -0
  34. package/kits/go/src/sdkruntime/context.go +207 -0
  35. package/kits/go/src/sdkruntime/errors.go +74 -0
  36. package/kits/go/src/sdkruntime/http.go +261 -0
  37. package/kits/go/src/sdkruntime/json.go +527 -0
  38. package/kits/go/src/sdkruntime/lang.go +462 -0
  39. package/kits/go/src/sdkruntime/multipart.go +75 -0
  40. package/kits/go/src/sdkruntime/pagination.go +150 -0
  41. package/kits/go/src/sdkruntime/sse.go +267 -0
  42. package/kits/go/src/sdkruntime/testing.go +343 -0
  43. package/kits/go/src/sdkruntime/transport.go +168 -0
  44. package/kits/go/src/sdkruntime/wait.go +49 -0
  45. package/kits/go/src/sdkruntime/webhooks.go +129 -0
  46. package/kits/go/tests/client_test.go +185 -0
  47. package/kits/go/tests/http_test.go +78 -0
  48. package/kits/go/tests/json_test.go +127 -0
  49. package/kits/go/tests/lang_test.go +98 -0
  50. package/kits/go/tests/multipart_test.go +29 -0
  51. package/kits/go/tests/pagination_test.go +69 -0
  52. package/kits/go/tests/sse_test.go +129 -0
  53. package/kits/go/tests/testing_test.go +121 -0
  54. package/kits/go/tests/transport_test.go +133 -0
  55. package/kits/go/tests/wait_test.go +46 -0
  56. package/kits/go/tests/webhooks_test.go +62 -0
  57. package/kits/go/versions.json +12 -0
  58. package/kits/java/kit.json +6 -0
  59. package/kits/java/src/dev/sdkloom/runtime/ApiException.java +63 -0
  60. package/kits/java/src/dev/sdkloom/runtime/ArgumentException.java +24 -0
  61. package/kits/java/src/dev/sdkloom/runtime/Assert.java +72 -0
  62. package/kits/java/src/dev/sdkloom/runtime/ClientRuntime.java +220 -0
  63. package/kits/java/src/dev/sdkloom/runtime/Clock.java +39 -0
  64. package/kits/java/src/dev/sdkloom/runtime/Context.java +79 -0
  65. package/kits/java/src/dev/sdkloom/runtime/Decode.java +200 -0
  66. package/kits/java/src/dev/sdkloom/runtime/DecodeException.java +26 -0
  67. package/kits/java/src/dev/sdkloom/runtime/Decoder.java +16 -0
  68. package/kits/java/src/dev/sdkloom/runtime/Emitter.java +56 -0
  69. package/kits/java/src/dev/sdkloom/runtime/ErrorFactory.java +18 -0
  70. package/kits/java/src/dev/sdkloom/runtime/EventListener.java +20 -0
  71. package/kits/java/src/dev/sdkloom/runtime/EventStream.java +232 -0
  72. package/kits/java/src/dev/sdkloom/runtime/FakeClock.java +37 -0
  73. package/kits/java/src/dev/sdkloom/runtime/Headers.java +42 -0
  74. package/kits/java/src/dev/sdkloom/runtime/HttpRequest.java +88 -0
  75. package/kits/java/src/dev/sdkloom/runtime/HttpResponse.java +69 -0
  76. package/kits/java/src/dev/sdkloom/runtime/JdkTransport.java +97 -0
  77. package/kits/java/src/dev/sdkloom/runtime/Js.java +230 -0
  78. package/kits/java/src/dev/sdkloom/runtime/Json.java +281 -0
  79. package/kits/java/src/dev/sdkloom/runtime/JsonValue.java +15 -0
  80. package/kits/java/src/dev/sdkloom/runtime/Links.java +62 -0
  81. package/kits/java/src/dev/sdkloom/runtime/Middleware.java +16 -0
  82. package/kits/java/src/dev/sdkloom/runtime/MiddlewareEntry.java +43 -0
  83. package/kits/java/src/dev/sdkloom/runtime/MockRoute.java +111 -0
  84. package/kits/java/src/dev/sdkloom/runtime/MockTransport.java +62 -0
  85. package/kits/java/src/dev/sdkloom/runtime/MultipartForm.java +111 -0
  86. package/kits/java/src/dev/sdkloom/runtime/Next.java +16 -0
  87. package/kits/java/src/dev/sdkloom/runtime/OperationInfo.java +35 -0
  88. package/kits/java/src/dev/sdkloom/runtime/OperationMock.java +105 -0
  89. package/kits/java/src/dev/sdkloom/runtime/OperationSpec.java +125 -0
  90. package/kits/java/src/dev/sdkloom/runtime/Pages.java +55 -0
  91. package/kits/java/src/dev/sdkloom/runtime/Pipeline.java +29 -0
  92. package/kits/java/src/dev/sdkloom/runtime/RawResult.java +31 -0
  93. package/kits/java/src/dev/sdkloom/runtime/RecordedEvent.java +36 -0
  94. package/kits/java/src/dev/sdkloom/runtime/SdkInfo.java +38 -0
  95. package/kits/java/src/dev/sdkloom/runtime/SendOptions.java +34 -0
  96. package/kits/java/src/dev/sdkloom/runtime/ServerSentEvent.java +58 -0
  97. package/kits/java/src/dev/sdkloom/runtime/State.java +58 -0
  98. package/kits/java/src/dev/sdkloom/runtime/Test.java +21 -0
  99. package/kits/java/src/dev/sdkloom/runtime/TestRunner.java +63 -0
  100. package/kits/java/src/dev/sdkloom/runtime/Transport.java +16 -0
  101. package/kits/java/src/dev/sdkloom/runtime/TransportException.java +30 -0
  102. package/kits/java/src/dev/sdkloom/runtime/UrlConnectionTransport.java +195 -0
  103. package/kits/java/src/dev/sdkloom/runtime/Urls.java +116 -0
  104. package/kits/java/src/dev/sdkloom/runtime/Waits.java +53 -0
  105. package/kits/java/src/dev/sdkloom/runtime/WebhookSignatureException.java +24 -0
  106. package/kits/java/src/dev/sdkloom/runtime/Webhooks.java +146 -0
  107. package/kits/java/tests/dev/sdkloom/runtime/ClientTest.java +266 -0
  108. package/kits/java/tests/dev/sdkloom/runtime/EventStreamTest.java +131 -0
  109. package/kits/java/tests/dev/sdkloom/runtime/HttpTest.java +95 -0
  110. package/kits/java/tests/dev/sdkloom/runtime/JdkTransportTest.java +12 -0
  111. package/kits/java/tests/dev/sdkloom/runtime/JsTest.java +102 -0
  112. package/kits/java/tests/dev/sdkloom/runtime/JsonTest.java +87 -0
  113. package/kits/java/tests/dev/sdkloom/runtime/LinksTest.java +22 -0
  114. package/kits/java/tests/dev/sdkloom/runtime/MultipartFormTest.java +30 -0
  115. package/kits/java/tests/dev/sdkloom/runtime/PagesTest.java +75 -0
  116. package/kits/java/tests/dev/sdkloom/runtime/TestData.java +53 -0
  117. package/kits/java/tests/dev/sdkloom/runtime/TestingTest.java +156 -0
  118. package/kits/java/tests/dev/sdkloom/runtime/TransportContract.java +201 -0
  119. package/kits/java/tests/dev/sdkloom/runtime/UrlConnectionTransportTest.java +49 -0
  120. package/kits/java/tests/dev/sdkloom/runtime/WaitsTest.java +43 -0
  121. package/kits/java/tests/dev/sdkloom/runtime/WebhooksTest.java +45 -0
  122. package/kits/java/versions.json +41 -0
  123. package/kits/python/kit.json +6 -0
  124. package/kits/python/src/sdkloom_runtime/__init__.py +1 -0
  125. package/kits/python/src/sdkloom_runtime/client.py +232 -0
  126. package/kits/python/src/sdkloom_runtime/compat.py +195 -0
  127. package/kits/python/src/sdkloom_runtime/context.py +134 -0
  128. package/kits/python/src/sdkloom_runtime/errors.py +65 -0
  129. package/kits/python/src/sdkloom_runtime/http.py +192 -0
  130. package/kits/python/src/sdkloom_runtime/lang.py +207 -0
  131. package/kits/python/src/sdkloom_runtime/models.py +221 -0
  132. package/kits/python/src/sdkloom_runtime/multipart.py +69 -0
  133. package/kits/python/src/sdkloom_runtime/pagination.py +61 -0
  134. package/kits/python/src/sdkloom_runtime/pipeline.py +39 -0
  135. package/kits/python/src/sdkloom_runtime/sse.py +121 -0
  136. package/kits/python/src/sdkloom_runtime/testing.py +224 -0
  137. package/kits/python/src/sdkloom_runtime/transport.py +120 -0
  138. package/kits/python/src/sdkloom_runtime/wait.py +44 -0
  139. package/kits/python/src/sdkloom_runtime/webhooks.py +84 -0
  140. package/kits/python/tests/support.py +28 -0
  141. package/kits/python/tests/test_client.py +275 -0
  142. package/kits/python/tests/test_compat.py +87 -0
  143. package/kits/python/tests/test_http.py +94 -0
  144. package/kits/python/tests/test_lang.py +104 -0
  145. package/kits/python/tests/test_models.py +110 -0
  146. package/kits/python/tests/test_multipart.py +37 -0
  147. package/kits/python/tests/test_pagination.py +70 -0
  148. package/kits/python/tests/test_sse.py +61 -0
  149. package/kits/python/tests/test_testing.py +130 -0
  150. package/kits/python/tests/test_transport.py +124 -0
  151. package/kits/python/tests/test_wait.py +46 -0
  152. package/kits/python/tests/test_webhooks.py +57 -0
  153. package/kits/python/versions.json +33 -0
  154. package/kits/rust/kit.json +6 -0
  155. package/kits/rust/src/runtime/client.rs +212 -0
  156. package/kits/rust/src/runtime/context.rs +182 -0
  157. package/kits/rust/src/runtime/crypto.rs +84 -0
  158. package/kits/rust/src/runtime/errors.rs +147 -0
  159. package/kits/rust/src/runtime/http.rs +248 -0
  160. package/kits/rust/src/runtime/json.rs +424 -0
  161. package/kits/rust/src/runtime/lang.rs +296 -0
  162. package/kits/rust/src/runtime/mod.rs +30 -0
  163. package/kits/rust/src/runtime/models.rs +266 -0
  164. package/kits/rust/src/runtime/multipart.rs +81 -0
  165. package/kits/rust/src/runtime/pagination.rs +117 -0
  166. package/kits/rust/src/runtime/sse.rs +195 -0
  167. package/kits/rust/src/runtime/testing.rs +308 -0
  168. package/kits/rust/src/runtime/transport.rs +324 -0
  169. package/kits/rust/src/runtime/wait.rs +29 -0
  170. package/kits/rust/src/runtime/webhooks.rs +142 -0
  171. package/kits/rust/tests/client.rs +152 -0
  172. package/kits/rust/tests/http.rs +44 -0
  173. package/kits/rust/tests/json.rs +82 -0
  174. package/kits/rust/tests/lang.rs +74 -0
  175. package/kits/rust/tests/multipart.rs +21 -0
  176. package/kits/rust/tests/pagination.rs +61 -0
  177. package/kits/rust/tests/sse.rs +77 -0
  178. package/kits/rust/tests/testing.rs +90 -0
  179. package/kits/rust/tests/transport.rs +218 -0
  180. package/kits/rust/tests/wait.rs +32 -0
  181. package/kits/rust/tests/webhooks.rs +73 -0
  182. package/kits/rust/versions.json +6 -0
  183. package/kits/typescript/kit.json +6 -0
  184. package/kits/typescript/src/client.ts +223 -0
  185. package/kits/typescript/src/context.ts +108 -0
  186. package/kits/typescript/src/errors.ts +63 -0
  187. package/kits/typescript/src/helpers.ts +49 -0
  188. package/kits/typescript/src/http.ts +192 -0
  189. package/kits/typescript/src/models.ts +139 -0
  190. package/kits/typescript/src/multipart.ts +66 -0
  191. package/kits/typescript/src/pagination.ts +54 -0
  192. package/kits/typescript/src/pipeline.ts +25 -0
  193. package/kits/typescript/src/sse.ts +102 -0
  194. package/kits/typescript/src/testing.ts +217 -0
  195. package/kits/typescript/src/transport.ts +101 -0
  196. package/kits/typescript/src/wait.ts +36 -0
  197. package/kits/typescript/src/webhooks.ts +168 -0
  198. package/kits/typescript/tests/client.test.ts +269 -0
  199. package/kits/typescript/tests/helpers.test.ts +27 -0
  200. package/kits/typescript/tests/http.test.ts +80 -0
  201. package/kits/typescript/tests/models.test.ts +71 -0
  202. package/kits/typescript/tests/multipart.test.ts +28 -0
  203. package/kits/typescript/tests/pagination.test.ts +76 -0
  204. package/kits/typescript/tests/sse.test.ts +82 -0
  205. package/kits/typescript/tests/testing.test.ts +103 -0
  206. package/kits/typescript/tests/transport.test.ts +127 -0
  207. package/kits/typescript/tests/wait.test.ts +31 -0
  208. package/kits/typescript/tests/webhooks.test.ts +53 -0
  209. package/kits/typescript/versions.json +15 -0
  210. package/package.json +37 -4
  211. package/packages/cli/recipes/apiKeyHeader.ts +16 -0
  212. package/packages/cli/recipes/apiVersionHeader.ts +16 -0
  213. package/packages/cli/recipes/basic.ts +13 -0
  214. package/packages/cli/recipes/bearer.ts +10 -0
  215. package/packages/cli/recipes/hmacSign.ts +23 -0
  216. package/packages/cli/recipes/idempotencyKey.ts +19 -0
  217. package/packages/cli/recipes/oauthClientCredentials.ts +50 -0
  218. package/packages/cli/recipes/retry.ts +42 -0
  219. package/packages/cli/recipes/timing.ts +12 -0
  220. package/packages/cli/recipes/userAgent.ts +8 -0
  221. package/packages/cli/src/build.js +93 -0
  222. package/packages/cli/src/commands/build.js +31 -0
  223. package/packages/cli/src/commands/conformance-check.js +50 -0
  224. package/packages/cli/src/commands/contract.js +181 -0
  225. package/packages/cli/src/commands/diff.js +113 -0
  226. package/packages/cli/src/commands/doctor.js +43 -0
  227. package/packages/cli/src/commands/import-openapi.js +42 -0
  228. package/packages/cli/src/commands/init.js +27 -0
  229. package/packages/cli/src/commands/kit-check.js +145 -0
  230. package/packages/cli/src/commands/publish.js +81 -0
  231. package/packages/cli/src/commands/recipe.js +49 -0
  232. package/packages/cli/src/commands/record.js +181 -0
  233. package/packages/cli/src/commands/serve.js +156 -0
  234. package/packages/cli/src/commands/spec-check.js +57 -0
  235. package/packages/cli/src/commands/test.js +177 -0
  236. package/packages/cli/src/commands/variants.js +32 -0
  237. package/packages/cli/src/commands/verify.js +57 -0
  238. package/packages/cli/src/commands/version.js +63 -0
  239. package/packages/cli/src/containers.js +82 -0
  240. package/packages/cli/src/coverage.js +72 -0
  241. package/packages/cli/src/git.js +25 -0
  242. package/packages/cli/src/io.js +50 -0
  243. package/packages/cli/src/java/ScenarioHarness.java +297 -0
  244. package/packages/cli/src/java/SchemaRoundTrip.java +63 -0
  245. package/packages/cli/src/java.js +70 -0
  246. package/packages/cli/src/js/harness.mjs +120 -0
  247. package/packages/cli/src/kits.js +103 -0
  248. package/packages/cli/src/languages/csharp.js +274 -0
  249. package/packages/cli/src/languages/go.js +185 -0
  250. package/packages/cli/src/languages/index.js +18 -0
  251. package/packages/cli/src/languages/java.js +187 -0
  252. package/packages/cli/src/languages/python.js +120 -0
  253. package/packages/cli/src/languages/rust.js +189 -0
  254. package/packages/cli/src/languages/types.js +93 -0
  255. package/packages/cli/src/languages/typescript.js +112 -0
  256. package/packages/cli/src/main.js +13 -0
  257. package/packages/cli/src/packaging.js +39 -0
  258. package/packages/cli/src/portability.js +45 -0
  259. package/packages/cli/src/profiles.js +55 -0
  260. package/packages/cli/src/project.js +56 -0
  261. package/packages/cli/src/python/scenario_harness.py +162 -0
  262. package/packages/cli/src/python/schema_roundtrip.py +42 -0
  263. package/packages/cli/src/registries.js +214 -0
  264. package/packages/cli/src/resolve-core.js +39 -0
  265. package/packages/cli/src/run.js +133 -0
  266. package/packages/cli/src/runtimes.js +61 -0
  267. package/packages/cli/src/scenarios-java.js +82 -0
  268. package/packages/cli/src/scenarios-javascript.js +54 -0
  269. package/packages/cli/src/scenarios-python.js +90 -0
  270. package/packages/cli/src/scenarios.js +183 -0
  271. package/packages/cli/src/schema.js +84 -0
  272. package/packages/cli/src/templates.js +85 -0
  273. package/packages/cli/src/toolchains.js +68 -0
  274. package/packages/cli/src/transpiled-tests.js +92 -0
  275. package/packages/codegen/src/canonical-json.js +31 -0
  276. package/packages/codegen/src/capabilities.js +50 -0
  277. package/packages/codegen/src/code-writer.js +54 -0
  278. package/packages/codegen/src/file-tree.js +25 -0
  279. package/packages/codegen/src/hash.js +6 -0
  280. package/packages/codegen/src/index.js +16 -0
  281. package/packages/codegen/src/lock.js +106 -0
  282. package/packages/conformance/src/case.js +143 -0
  283. package/packages/conformance/src/checks.js +40 -0
  284. package/packages/conformance/src/index.js +3 -0
  285. package/packages/conformance/src/matrix.js +48 -0
  286. package/packages/conformance/src/suite.js +48 -0
  287. package/packages/differ/src/diff.js +500 -0
  288. package/packages/differ/src/index.js +3 -0
  289. package/packages/differ/src/notes.js +112 -0
  290. package/packages/differ/src/support.js +34 -0
  291. package/packages/gen-csharp/src/emit-client.js +397 -0
  292. package/packages/gen-csharp/src/emit-harness.js +333 -0
  293. package/packages/gen-csharp/src/emit-mock.js +111 -0
  294. package/packages/gen-csharp/src/emit-models.js +119 -0
  295. package/packages/gen-csharp/src/emit-webhooks.js +57 -0
  296. package/packages/gen-csharp/src/generate.js +245 -0
  297. package/packages/gen-csharp/src/index.js +5 -0
  298. package/packages/gen-csharp/src/names.js +284 -0
  299. package/packages/gen-go/src/emit-client.js +405 -0
  300. package/packages/gen-go/src/emit-harness.js +294 -0
  301. package/packages/gen-go/src/emit-mock.js +112 -0
  302. package/packages/gen-go/src/emit-models.js +146 -0
  303. package/packages/gen-go/src/emit-webhooks.js +58 -0
  304. package/packages/gen-go/src/generate.js +205 -0
  305. package/packages/gen-go/src/index.js +5 -0
  306. package/packages/gen-go/src/names.js +197 -0
  307. package/packages/gen-java/src/emit-client.js +441 -0
  308. package/packages/gen-java/src/emit-models.js +342 -0
  309. package/packages/gen-java/src/emit-testing.js +123 -0
  310. package/packages/gen-java/src/emit-webhooks.js +70 -0
  311. package/packages/gen-java/src/generate.js +244 -0
  312. package/packages/gen-java/src/index.js +4 -0
  313. package/packages/gen-java/src/names.js +197 -0
  314. package/packages/gen-python/src/emit-client.js +272 -0
  315. package/packages/gen-python/src/emit-models.js +139 -0
  316. package/packages/gen-python/src/emit-testing.js +93 -0
  317. package/packages/gen-python/src/emit-webhooks.js +48 -0
  318. package/packages/gen-python/src/generate.js +237 -0
  319. package/packages/gen-python/src/index.js +2 -0
  320. package/packages/gen-python/src/names.js +161 -0
  321. package/packages/gen-python/src/style.js +67 -0
  322. package/packages/gen-rust/src/emit-client.js +379 -0
  323. package/packages/gen-rust/src/emit-harness.js +278 -0
  324. package/packages/gen-rust/src/emit-mock.js +121 -0
  325. package/packages/gen-rust/src/emit-models.js +117 -0
  326. package/packages/gen-rust/src/emit-webhooks.js +58 -0
  327. package/packages/gen-rust/src/generate.js +243 -0
  328. package/packages/gen-rust/src/index.js +5 -0
  329. package/packages/gen-rust/src/names.js +223 -0
  330. package/packages/gen-typescript/src/emit-client.js +434 -0
  331. package/packages/gen-typescript/src/emit-models.js +93 -0
  332. package/packages/gen-typescript/src/emit-package.js +90 -0
  333. package/packages/gen-typescript/src/emit-testing.js +138 -0
  334. package/packages/gen-typescript/src/emit-webhooks.js +52 -0
  335. package/packages/gen-typescript/src/generate.js +70 -0
  336. package/packages/gen-typescript/src/index.js +3 -0
  337. package/packages/gen-typescript/src/naming.js +64 -0
  338. package/packages/gen-typescript/src/runtime.js +81 -0
  339. package/packages/gen-typescript/src/types.js +136 -0
  340. package/packages/ir/src/api-surface.js +22 -0
  341. package/packages/ir/src/checks.js +52 -0
  342. package/packages/ir/src/index.js +32 -0
  343. package/packages/ir/src/ir.js +214 -0
  344. package/packages/ir/src/pages.js +18 -0
  345. package/packages/ir/src/validate-ir.js +462 -0
  346. package/packages/ir/src/validate-types.js +140 -0
  347. package/packages/kit/src/block-parser.js +196 -0
  348. package/packages/kit/src/index.js +15 -0
  349. package/packages/kit/src/kit-check.js +203 -0
  350. package/packages/kit/src/sources.js +53 -0
  351. package/packages/kit/src/version-policy.js +133 -0
  352. package/packages/kit/src/version-range.js +132 -0
  353. package/packages/openapi/src/import.js +292 -0
  354. package/packages/openapi/src/index.js +1 -0
  355. package/packages/openapi/src/names.js +50 -0
  356. package/packages/openapi/src/schemas.js +264 -0
  357. package/packages/packager/src/archive.js +106 -0
  358. package/packages/packager/src/crate.js +39 -0
  359. package/packages/packager/src/gomodule.js +11 -0
  360. package/packages/packager/src/index.js +9 -0
  361. package/packages/packager/src/maven.js +85 -0
  362. package/packages/packager/src/metadata.js +34 -0
  363. package/packages/packager/src/npm.js +71 -0
  364. package/packages/packager/src/nuget.js +78 -0
  365. package/packages/packager/src/sbom.js +56 -0
  366. package/packages/packager/src/wheel.js +62 -0
  367. package/packages/spec/src/index.js +11 -0
  368. package/packages/spec/src/requirements.js +139 -0
  369. package/packages/transpile/src/ast.js +51 -0
  370. package/packages/transpile/src/check.js +669 -0
  371. package/packages/transpile/src/emit-csharp.js +469 -0
  372. package/packages/transpile/src/emit-go.js +529 -0
  373. package/packages/transpile/src/emit-java.js +360 -0
  374. package/packages/transpile/src/emit-python.js +320 -0
  375. package/packages/transpile/src/emit-rust.js +499 -0
  376. package/packages/transpile/src/errors.js +15 -0
  377. package/packages/transpile/src/index.js +13 -0
  378. package/packages/transpile/src/lexer.js +161 -0
  379. package/packages/transpile/src/parser.js +543 -0
  380. package/packages/transpile/src/tests/ast.js +46 -0
  381. package/packages/transpile/src/tests/parse.js +376 -0
  382. package/packages/transpile/src/tests/translate.js +849 -0
  383. package/packages/transpile/src/transpile.js +57 -0
@@ -0,0 +1,294 @@
1
+ // The program `sdkloom test` runs against a generated Go SDK: it reads a plan on stdin and prints observations.
2
+ // Scenarios: a local server answers as the scenario says and the program calls the operation with the scenario's
3
+ // arguments. Round-trips: every schema sample is decoded and encoded again. Generated per SDK, because Go code needs
4
+ // the SDK's types at compile time.
5
+
6
+
7
+ import { pagedItems, } from "@sdkloom/ir";
8
+ import { configFields, kindOf, paramsType, signature } from "./emit-client.ts";
9
+ import { decoder, encode, exported, go, local, RUNTIME, str } from "./names.ts";
10
+ import { webhookFunction } from "./emit-webhooks.ts";
11
+
12
+ /** The item type of a paginated operation, or undefined. */
13
+ function itemsType(ir , operation ) {
14
+ return operation.paginate === undefined ? undefined : pagedItems(ir, operation).item;
15
+ }
16
+
17
+ function emitCall(writer , ir , operation , pkg ) {
18
+ const prefix = `${pkg}.`;
19
+ writer.line(`case ${str(operation.name)}:`).indent((body) => {
20
+ operation.params
21
+ .filter((param) => param.in === "path")
22
+ .forEach((param) => body.line(`${local(param.name)} := arg(${decoder(ir, param.type, "args", prefix)}, args[${str(param.name)}], ${str(param.name)})`));
23
+ const kind = kindOf(operation.body);
24
+ if (kind === "json") body.line(`body := arg(${decoder(ir, operation.body , "args", prefix)}, args["body"], "body")`);
25
+ if (kind === "bytes") body.line(`body := []byte(${RUNTIME}.ToStr(args["body"]))`);
26
+ if (kind === "stream") body.line(`body := strings.NewReader(${RUNTIME}.ToStr(args["body"]))`);
27
+ if (kind === "multipart") {
28
+ // A multipart body is described as parts; files are sent as UTF-8 bytes.
29
+ body.line(`body := ${RUNTIME}.MultipartForm{}`);
30
+ body.line('for _, item := range args["body"].(map[string]any)["parts"].([]any) {').indent((loop) => {
31
+ loop.line("part := item.(map[string]any)");
32
+ loop.line(`name, value := ${RUNTIME}.ToStr(part["name"]), ${RUNTIME}.ToStr(part["value"])`);
33
+ loop.line('if filename, ok := part["filename"].(string); ok {').indent((branch) => {
34
+ branch.line('contentType, _ := part["contentType"].(string)');
35
+ branch.line("body = body.File(name, filename, contentType, []byte(value))");
36
+ });
37
+ loop.line("} else {").indent((branch) => branch.line("body = body.Field(name, value)")).line("}");
38
+ });
39
+ body.line("}");
40
+ }
41
+ const named = operation.params.filter((param) => param.in !== "path");
42
+ if (named.length > 0) {
43
+ body.line(`params := ${prefix}${paramsType(operation)}{}`);
44
+ named.forEach((param) => {
45
+ const read = `arg(${decoder(ir, param.type, "args", prefix)}, value, ${str(param.name)})`;
46
+ body.line(`if value, ok := args[${str(param.name)}]; ok {`).indent((branch) => branch.line(`params.${exported(param.name)} = ${param.optional ? `${RUNTIME}.Some(${read})` : read}`)).line("}");
47
+ });
48
+ }
49
+ const args = signature(operation).call.replace(", opts...", "");
50
+ const call = `client.${exported(operation.name)}(${args})`;
51
+ const items = itemsType(ir, operation);
52
+ if (items !== undefined) {
53
+ // all: the operation's iterator over every page.
54
+ body.line("if all {").indent((branch) => {
55
+ branch.line(`items, err := client.${exported(operation.name)}All(${args}).All()`);
56
+ branch.line("if err != nil {").indent((inner) => inner.line("return nil, err")).line("}");
57
+ branch.line("encoded := make([]any, 0, len(items))");
58
+ branch.line("for _, item := range items {").indent((loop) => loop.line(`encoded = append(encoded, ${encode(ir, items, "item", prefix)})`)).line("}");
59
+ branch.line("return encoded, nil");
60
+ });
61
+ body.line("}");
62
+ }
63
+ const result = kindOf(operation.returns);
64
+ if (operation.wait !== undefined) {
65
+ // wait: <Name>AndWait polls until the work is done.
66
+ body.line("if wait {").indent((branch) => {
67
+ branch.line(`result, err := client.${exported(operation.name)}AndWait(${args})`);
68
+ branch.line("if err != nil {").indent((inner) => inner.line("return nil, err")).line("}");
69
+ branch.line(`return ${encode(ir, operation.returns , "result", prefix)}, nil`);
70
+ });
71
+ body.line("}");
72
+ }
73
+ if (operation.events !== undefined) {
74
+ // Server-sent events: every event the stream delivers, with its data as JSON.
75
+ body.line(`events := ${call}`);
76
+ body.line("defer events.Close()");
77
+ body.line("found := []any{}");
78
+ body.line("for events.Next() {").indent((loop) => {
79
+ loop.line("event := events.Event()");
80
+ loop.line(`found = append(found, map[string]any{"event": event.Event, "id": event.ID, "data": ${encode(ir, operation.events , "event.Data", prefix)}})`);
81
+ });
82
+ body.line("}");
83
+ body.line("return found, events.Err()");
84
+ } else if (result === undefined) {
85
+ body.line(`return nil, ${call}`);
86
+ } else {
87
+ body.line(`result, err := ${call}`);
88
+ body.line("if err != nil {").indent((branch) => branch.line("return nil, err")).line("}");
89
+ if (result === "bytes") body.line("return string(result), nil");
90
+ else if (result === "stream") body.line("data, err := io.ReadAll(result)").line("return string(data), err");
91
+ else body.line(`return ${encode(ir, operation.returns , "result", prefix)}, nil`);
92
+ }
93
+ });
94
+ }
95
+
96
+ function emitRoundTrip(writer , ir , pkg ) {
97
+ writer.line("func roundTrip(name string, value any) (any, error) {").indent((fn) => {
98
+ fn.line("switch name {");
99
+ ir.types.forEach((named) => {
100
+ if (named.type.kind !== "object" && named.type.kind !== "union") return;
101
+ const name = exported(named.name);
102
+ fn.line(`case ${str(named.name)}:`).indent((branch) => {
103
+ branch.line(`decoded, err := ${pkg}.Decode${name}(value, "$")`);
104
+ branch.line("if err != nil {").indent((inner) => inner.line("return nil, err")).line("}");
105
+ branch.line(named.type.kind === "union" ? `return ${pkg}.Encode${name}(decoded), nil` : "return decoded, nil");
106
+ });
107
+ });
108
+ fn.line("}");
109
+ fn.line('return nil, fmt.Errorf("MissingDecoder: %s", name)');
110
+ });
111
+ writer.line("}").line();
112
+ }
113
+
114
+ /** A logic case: call the SDK's logic function with its inputs, converted from JSON. */
115
+ function emitLogicCall(writer , ir , pkg ) {
116
+ const convert = { int: "ToInt64", number: "ToFloat64", string: "ToStr", bool: "ToBool" };
117
+ writer.line("func logic(call map[string]any) (any, error) {").indent((fn) => {
118
+ fn.line('args, _ := call["args"].(map[string]any)');
119
+ fn.line("_ = args");
120
+ fn.line('switch call["name"] {');
121
+ (ir.logic ?? []).forEach((logic) => {
122
+ const args = logic.input.map((field) => `${RUNTIME}.${convert[field.type.kind === "primitive" ? field.type.name : "string"] ?? "ToStr"}(args[${str(field.name)}])`);
123
+ fn.line(`case ${str(logic.name)}:`).indent((branch) => branch.line(`return ${pkg}.${exported(logic.name)}(${args.join(", ")})`));
124
+ });
125
+ fn.line("}");
126
+ fn.line('return nil, harnessError{fmt.Sprint("UnknownLogic: ", call["name"])}');
127
+ });
128
+ writer.line("}").line();
129
+ }
130
+
131
+ /** A webhook case: verify and read the body with the SDK's Verify<Name>WebhookAt. */
132
+ function emitWebhook(writer , ir , pkg ) {
133
+ writer.line("func webhook(hook map[string]any) (any, error) {").indent((fn) => {
134
+ fn.line("headers := http.Header{}");
135
+ fn.line('for name, value := range hook["headers"].(map[string]any) {').indent((loop) => loop.line(`headers.Set(name, ${RUNTIME}.ToStr(value))`)).line("}");
136
+ fn.line(`body, secret, now := []byte(${RUNTIME}.ToStr(hook["body"])), ${RUNTIME}.ToStr(hook["secret"]), ${RUNTIME}.ToInt64(hook["now"])`);
137
+ fn.line("_, _, _ = body, secret, now");
138
+ fn.line('switch hook["name"] {');
139
+ (ir.webhooks ?? []).forEach((hook) => {
140
+ fn.line(`case ${str(hook.name)}:`).indent((branch) => {
141
+ branch.line(`decoded, err := ${pkg}.${webhookFunction(hook.name)}At(body, headers, secret, now)`);
142
+ branch.line("if err != nil {").indent((inner) => inner.line("return nil, err")).line("}");
143
+ branch.line(`return ${encode(ir, hook.payload, "decoded", `${pkg}.`)}, nil`);
144
+ });
145
+ });
146
+ fn.line("}");
147
+ fn.line('return nil, harnessError{fmt.Sprint("UnknownWebhook: ", hook["name"])}');
148
+ });
149
+ writer.line("}").line();
150
+ }
151
+
152
+ export function emitHarness(ir , module , pkg ) {
153
+ const prefix = `${pkg}.`;
154
+ const writer = go().line("// Generated by sdkloom for `sdkloom test`; not part of the SDK.").line("package main").line().line("import (");
155
+ writer.indent((block) =>
156
+ ["context", "encoding/json", "errors", "fmt", "io", "net/http", "net/http/httptest", "os", "strings", "sync", module, `${module}/${RUNTIME}`].forEach((path) =>
157
+ block.line(path === module ? `${pkg} ${str(path)}` : str(path)),
158
+ ),
159
+ );
160
+ writer.line(")").line();
161
+ writer.line("var (").indent((block) => block.line("_ = io.ReadAll").line("_ = strings.NewReader").line("_ = context.Background")).line(")").line();
162
+
163
+ writer.line("type harnessError struct{ message string }").line();
164
+ writer.line("func (e harnessError) Error() string { return e.message }").line();
165
+ writer.line(`func arg[T any](decode ${RUNTIME}.Decoder[T], value any, name string) T {`).indent((fn) => {
166
+ fn.line(`decoded, err := decode(value, "$.args."+name)`);
167
+ fn.line("if err != nil {").indent((branch) => branch.line("panic(harnessError{err.Error()})")).line("}");
168
+ fn.line("return decoded");
169
+ });
170
+ writer.line("}").line();
171
+
172
+ writer.line(`func options(config map[string]any) ${prefix}Options {`).indent((fn) => {
173
+ fn.line(`result := ${prefix}Options{}`);
174
+ configFields(ir).forEach((item) => {
175
+ const read = `arg(${decoder(ir, item.type, "config", prefix)}, value, ${str(item.name)})`;
176
+ fn.line(`if value, ok := config[${str(item.name)}]; ok {`).indent((branch) => branch.line(`result.${exported(item.name)} = ${item.optional ? `${RUNTIME}.Some(${read})` : read}`)).line("}");
177
+ });
178
+ if (ir.apiVersions !== undefined) fn.line('if value, ok := config["apiVersion"].(string); ok {').indent((branch) => branch.line("result.APIVersion = value")).line("}");
179
+ fn.line("return result");
180
+ });
181
+ writer.line("}").line();
182
+
183
+ writer.line(`func call(ctx context.Context, client *${prefix}Client, op string, args map[string]any, all bool, wait bool) (value any, err error) {`).indent((fn) => {
184
+ fn.line("defer func() {").indent((inner) => inner.line("if recovered := recover(); recovered != nil {").indent((branch) => branch.line('err = harnessError{fmt.Sprint(recovered)}')).line("}")).line("}()");
185
+ fn.line("switch op {");
186
+ ir.operations.forEach((operation) => emitCall(fn, ir, operation, pkg));
187
+ fn.line("}");
188
+ fn.line('return nil, harnessError{"UnknownOperation: " + op}');
189
+ });
190
+ writer.line("}").line();
191
+
192
+ emitRoundTrip(writer, ir, pkg);
193
+ emitWebhook(writer, ir, pkg);
194
+ emitLogicCall(writer, ir, pkg);
195
+
196
+ writer.line("func errorName(err error) string {").indent((fn) => {
197
+ fn.line(`var api *${RUNTIME}.APIError`);
198
+ fn.line("if errors.As(err, &api) {").indent((branch) => branch.line("return api.Name")).line("}");
199
+ fn.line(`var transport *${RUNTIME}.TransportError`);
200
+ fn.line("if errors.As(err, &transport) {").indent((branch) => branch.line('return "TransportError"')).line("}");
201
+ fn.line(`var decode *${RUNTIME}.DecodeError`);
202
+ fn.line("if errors.As(err, &decode) {").indent((branch) => branch.line('return "DecodeError"')).line("}");
203
+ fn.line(`var waitTimeout *${RUNTIME}.WaitTimeoutError`);
204
+ fn.line("if errors.As(err, &waitTimeout) {").indent((branch) => branch.line('return "WaitTimeoutError"')).line("}");
205
+ fn.line(`var signature *${RUNTIME}.WebhookSignatureError`);
206
+ fn.line("if errors.As(err, &signature) {").indent((branch) => branch.line('return "WebhookSignatureError"')).line("}");
207
+ fn.line(`var argument *${RUNTIME}.ArgumentError`);
208
+ fn.line("if errors.As(err, &argument) {").indent((branch) => branch.line('return "ArgumentError"')).line("}");
209
+ fn.line("var harness harnessError");
210
+ fn.line("if errors.As(err, &harness) {").indent((branch) => branch.line('return "HarnessError"')).line("}");
211
+ fn.line('return "Error"');
212
+ });
213
+ writer.line("}").line();
214
+
215
+ writer.line("func outcome(value any, err error) map[string]any {").indent((fn) => {
216
+ fn.line("if err != nil {").indent((branch) => branch.line('return map[string]any{"ok": false, "error": errorName(err), "message": err.Error()}')).line("}");
217
+ fn.line('return map[string]any{"ok": true, "value": value}');
218
+ });
219
+ writer.line("}").line();
220
+
221
+ writer.line("func scenario(plan map[string]any) map[string]any {").indent((fn) => {
222
+ fn.line('if hook, ok := plan["webhook"].(map[string]any); ok {').indent((branch) => branch.line('return map[string]any{"id": plan["id"], "outcome": outcome(webhook(hook))}')).line("}");
223
+ // A logic function fails only by throwing: reported as Error, as in every language.
224
+ fn.line('if call, ok := plan["logic"].(map[string]any); ok {').indent((branch) => {
225
+ branch.line("value, err := logic(call)");
226
+ branch.line("if err != nil {").indent((inner) => inner.line('return map[string]any{"id": plan["id"], "outcome": map[string]any{"ok": false, "error": "Error", "message": err.Error()}}')).line("}");
227
+ branch.line('return map[string]any{"id": plan["id"], "outcome": outcome(value, nil)}');
228
+ }).line("}");
229
+ // Answers in order, the last one repeats; every request is recorded.
230
+ fn.line('answers := plan["answers"].([]any)');
231
+ fn.line("var requests []any");
232
+ fn.line("var mutex sync.Mutex");
233
+ fn.line("server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {").indent((handler) => {
234
+ handler.line("body, _ := io.ReadAll(r.Body)");
235
+ handler.line("headers := map[string]any{}");
236
+ handler.line("for name, values := range r.Header {").indent((loop) => loop.line("headers[strings.ToLower(name)] = strings.Join(values, \", \")")).line("}");
237
+ handler.line("mutex.Lock()");
238
+ handler.line("index := len(requests)");
239
+ handler.line("if index > len(answers)-1 {").indent((branch) => branch.line("index = len(answers) - 1")).line("}");
240
+ handler.line("respond := answers[index].(map[string]any)");
241
+ handler.line('requests = append(requests, map[string]any{"method": r.Method, "url": r.RequestURI, "headers": headers, "body": string(body)})');
242
+ handler.line("mutex.Unlock()");
243
+ handler.line(`if extra, ok := respond["headers"].(map[string]any); ok {`).indent((branch) =>
244
+ branch.line("for name, value := range extra {").indent((loop) => loop.line(`w.Header().Set(name, ${RUNTIME}.ToStr(value))`)).line("}"),
245
+ );
246
+ handler.line("}");
247
+ handler.line(`payload, hasJSON := respond["json"]`);
248
+ handler.line("if hasJSON {").indent((branch) => branch.line('w.Header().Set("content-type", "application/json")')).line("}");
249
+ handler.line(`w.WriteHeader(int(${RUNTIME}.ToInt64(respond["status"])))`);
250
+ handler.line("if hasJSON {").indent((branch) => branch.line(`encoded, _ := ${RUNTIME}.EncodeJSON(payload)`).line("_, _ = w.Write(encoded)")).line("}");
251
+ handler.line(`if text, ok := respond["text"].(string); ok {`).indent((branch) => branch.line("_, _ = w.Write([]byte(text))")).line("}");
252
+ });
253
+ fn.line("}))");
254
+ fn.line("defer server.Close()");
255
+ fn.line('config, _ := plan["config"].(map[string]any)');
256
+ fn.line("settings := options(config)");
257
+ fn.line("settings.BaseURL = server.URL");
258
+ fn.line(`settings.TimeoutMs = ${RUNTIME}.Some[int64](5000)`);
259
+ fn.line(`client, err := ${prefix}NewClient(settings)`);
260
+ fn.line("var result map[string]any");
261
+ fn.line("if err != nil {").indent((branch) => branch.line("result = outcome(nil, err)")).line("} else {").indent((branch) => {
262
+ branch.line('args, _ := plan["args"].(map[string]any)');
263
+ branch.line('all, _ := plan["all"].(bool)');
264
+ branch.line('wait, _ := plan["wait"].(bool)');
265
+ branch.line('result = outcome(call(context.Background(), client, plan["op"].(string), args, all, wait))');
266
+ });
267
+ fn.line("}");
268
+ fn.line('observation := map[string]any{"id": plan["id"], "outcome": result}');
269
+ fn.line("mutex.Lock()");
270
+ fn.line("defer mutex.Unlock()");
271
+ fn.line("if len(requests) > 0 {").indent((branch) => branch.line('observation["received"] = requests[0]').line('observation["requests"] = requests')).line("}");
272
+ fn.line("return observation");
273
+ });
274
+ writer.line("}").line();
275
+
276
+ writer.line("func main() {").indent((fn) => {
277
+ fn.line("decoder := json.NewDecoder(os.Stdin)");
278
+ fn.line("decoder.UseNumber()");
279
+ fn.line("var plan map[string]any");
280
+ fn.line("if err := decoder.Decode(&plan); err != nil {").indent((branch) => branch.line("panic(err)")).line("}");
281
+ fn.line("results := []any{}");
282
+ fn.line('for _, item := range plan["cases"].([]any) {').indent((loop) => {
283
+ loop.line("entry := item.(map[string]any)");
284
+ loop.line('if plan["mode"] == "roundtrip" {').indent((branch) => branch.line('results = append(results, map[string]any{"id": entry["id"], "outcome": outcome(roundTrip(entry["type"].(string), entry["value"]))})')).line("} else {").indent((branch) => branch.line("results = append(results, scenario(entry))"));
285
+ loop.line("}");
286
+ });
287
+ fn.line("}");
288
+ fn.line(`encoded, err := ${RUNTIME}.EncodeJSON(results)`);
289
+ fn.line("if err != nil {").indent((branch) => branch.line("panic(err)")).line("}");
290
+ fn.line("_, _ = os.Stdout.Write(encoded)");
291
+ });
292
+ writer.line("}");
293
+ return writer.toString();
294
+ }
@@ -0,0 +1,112 @@
1
+ // <pkg>mock/mock.go: New() gives a client answered by typed mocks, a fake clock and recorded events; Examples gives
2
+ // small valid values.
3
+
4
+
5
+ import { configFields, kindOf, resultType, textEvents } from "./emit-client.ts";
6
+ import { decoder, doc, encoderFunc, example, exported, go, goType, RUNTIME, str } from "./names.ts";
7
+
8
+ const MOCK_BASE_URL = "http://mock.sdkloom.invalid";
9
+
10
+ function placeholder(type ) {
11
+ if (type.kind === "enum") return str(type.values[0] ?? "");
12
+ if (type.kind !== "primitive") return undefined;
13
+ if (["string", "secret", "datetime"].includes(type.name)) return str("test");
14
+ return undefined;
15
+ }
16
+
17
+ /** What Returns takes: the result, or for an event stream the events to send. */
18
+ function mockType(operation , prefix ) {
19
+ return operation.events === undefined ? resultType(operation, prefix) : `[]${RUNTIME}.ServerSentEvent[${goType(operation.events, prefix)}]`;
20
+ }
21
+
22
+ export function emitMock(ir , header , pkg , module ) {
23
+ const mockPkg = `${pkg}mock`;
24
+ const prefix = `${pkg}.`;
25
+ const writer = go().line(header);
26
+ doc(writer, [`Package ${mockPkg} tests code that uses ${pkg}: a client answered by typed mocks, a fake clock and recorded events.`]);
27
+ writer.line(`package ${mockPkg}`).line().line("import (");
28
+ writer.indent((block) => ["sync", module, `${module}/${RUNTIME}`].forEach((path) => block.line(path === module ? `${pkg} ${str(path)}` : str(path))));
29
+ writer.line(")").line();
30
+
31
+ doc(writer, ["Mock has one typed mock per operation, plus the transport, the fake clock and the events middleware emitted."]);
32
+ writer.line("type Mock struct {").indent((body) => {
33
+ body.line(`Transport *${RUNTIME}.MockTransport`);
34
+ body.line(`Clock *${RUNTIME}.FakeClock`);
35
+ ir.operations.forEach((operation) => body.line(`${exported(operation.name)} *${RUNTIME}.OperationMock[${mockType(operation, prefix)}]`));
36
+ body.line("mutex sync.Mutex");
37
+ body.line(`events []${RUNTIME}.RecordedEvent`);
38
+ });
39
+ writer.line("}").line();
40
+ doc(writer, ["Events returns the events middleware emitted, in order."]);
41
+ writer.line(`func (m *Mock) Events() []${RUNTIME}.RecordedEvent {`).indent((fn) => {
42
+ fn.line("m.mutex.Lock()").line("defer m.mutex.Unlock()");
43
+ fn.line(`return append([]${RUNTIME}.RecordedEvent(nil), m.events...)`);
44
+ });
45
+ writer.line("}").line();
46
+
47
+ const required = configFields(ir).filter((item) => !item.optional);
48
+ doc(writer, [`New returns a ${pkg}.Client whose calls the returned Mock answers; middleware still runs.`, "Required options left empty get placeholder values."]);
49
+ writer.line(`func New(options ${pkg}.Options) (*${pkg}.Client, *Mock) {`).indent((fn) => {
50
+ fn.line(`transport := ${RUNTIME}.NewMockTransport()`);
51
+ fn.line(`mock := &Mock{Transport: transport, Clock: ${RUNTIME}.NewFakeClock(0)}`);
52
+ required.forEach((item) => {
53
+ const value = placeholder(item.type);
54
+ if (value !== undefined) fn.line(`if options.${exported(item.name)} == "" {`).indent((branch) => branch.line(`options.${exported(item.name)} = ${value}`)).line("}");
55
+ });
56
+ fn.line("listener := options.OnEvent");
57
+ fn.line("options.OnEvent = func(name string, fields map[string]any) {").indent((inner) => {
58
+ inner.line("mock.mutex.Lock()");
59
+ inner.line(`mock.events = append(mock.events, ${RUNTIME}.RecordedEvent{Name: name, Fields: fields})`);
60
+ inner.line("mock.mutex.Unlock()");
61
+ inner.line("if listener != nil {").indent((branch) => branch.line("listener(name, fields)")).line("}");
62
+ });
63
+ fn.line("}");
64
+ fn.line(`options.BaseURL = ${str(MOCK_BASE_URL)}`);
65
+ fn.line("options.Transport = transport");
66
+ fn.line("options.Clock = mock.Clock");
67
+ fn.line(`client, err := ${pkg}.NewClient(options)`);
68
+ fn.line("if err != nil {").indent((branch) => branch.line("panic(err)")).line("}");
69
+ ir.operations.forEach((operation) => {
70
+ const type = resultType(operation, prefix);
71
+ if (operation.events !== undefined) {
72
+ const route = `transport.Route(${str(operation.method)}, ${str(operation.path)}, nil)`;
73
+ const text = textEvents(operation.events);
74
+ const decode = text ? "nil" : decoder(ir, operation.events, `operations.${operation.name}.events`, prefix);
75
+ const encode = text ? "nil" : encoderFunc(ir, operation.events, prefix);
76
+ fn.line(`mock.${exported(operation.name)} = ${RUNTIME}.NewEventsMock[${goType(operation.events, prefix)}](${str(operation.name)}, ${route}, ${decode}, ${encode})`);
77
+ return;
78
+ }
79
+ const route = `transport.Route(${str(operation.method)}, ${str(operation.path)}, nil)`;
80
+ const json = kindOf(operation.returns) === "json";
81
+ const decode = json ? decoder(ir, operation.returns , `operations.${operation.name}.returns`, prefix) : "nil";
82
+ const encode = json ? encoderFunc(ir, operation.returns , prefix) : "nil";
83
+ fn.line(`mock.${exported(operation.name)} = ${RUNTIME}.NewOperationMock[${type}](${str(operation.name)}, ${route}, ${decode}, ${encode})`);
84
+ });
85
+ fn.line("return client, mock");
86
+ });
87
+ writer.line("}").line();
88
+
89
+ doc(writer, ["Examples gives small, valid example values; change the fields a test cares about."]);
90
+ writer.line("var Examples examples").line();
91
+ writer.line("type examples struct{}").line();
92
+ ir.types.forEach((named) => {
93
+ const name = exported(named.name);
94
+ if (named.type.kind === "object") {
95
+ const node = named.type;
96
+ doc(writer, [`${name} returns a ${name} with every required field set.`]);
97
+ writer.line(`func (examples) ${name}() ${prefix}${name} {`).indent((fn) => {
98
+ const fields = node.fields
99
+ .filter((item) => !item.optional && !item.nullable)
100
+ .map((item) => `${exported(item.name)}: ${example(item.type, `types.${named.name}.${item.name}`, prefix, "Examples")}`);
101
+ fn.line(`return ${prefix}${name}{${fields.join(", ")}}`);
102
+ });
103
+ writer.line("}").line();
104
+ } else if (named.type.kind === "union") {
105
+ const first = named.type.variants[0];
106
+ if (first === undefined) throw new Error(`types.${named.name}: a union needs a variant`);
107
+ doc(writer, [`${name} returns its first variant, a ${exported(first.type)}.`]);
108
+ writer.line(`func (examples) ${name}() ${prefix}${name} {`).indent((fn) => fn.line(`return Examples.${exported(first.type)}()`)).line("}").line();
109
+ }
110
+ });
111
+ return writer.toString();
112
+ }
@@ -0,0 +1,146 @@
1
+ // models.go and errors.go of the SDK package.
2
+
3
+
4
+
5
+ import { decoder, doc, encodeField, exported, fieldType, go, RUNTIME, str } from "./names.ts";
6
+
7
+ const RESERVED = new Set(["ExtraFields", "ToJSON"]);
8
+
9
+ function deprecation(item ) {
10
+ return item.deprecated === undefined ? [] : ["", `Deprecated: ${item.deprecated}`];
11
+ }
12
+
13
+ function emitObject(writer , ir , named , node ) {
14
+ const name = exported(named.name);
15
+ node.fields.forEach((item) => {
16
+ if (RESERVED.has(exported(item.name))) throw new Error(`types.${named.name}.${item.name}: the Go name ${exported(item.name)} is reserved for model methods; rename the field`);
17
+ });
18
+ doc(writer, [`${name} ${named.doc ?? ""}`.trim(), "", "Fields the server adds later are kept in ExtraFields and sent back unchanged.", ...deprecation(named)]);
19
+ writer.line(`type ${name} struct {`).indent((body) => {
20
+ node.fields.forEach((item) => {
21
+ doc(body, [...(item.doc === undefined ? [] : [item.doc]), ...(item.deprecated === undefined ? [] : [`Deprecated: ${item.deprecated}`])]);
22
+ body.line(`${exported(item.name)} ${fieldType(item)}`);
23
+ });
24
+ body.line("// ExtraFields holds fields this SDK version does not know.");
25
+ body.line("ExtraFields map[string]any");
26
+ });
27
+ writer.line("}").line();
28
+
29
+ const keys = node.fields.map((item) => str(item.name)).join(", ");
30
+ doc(writer, [`Decode${name} reads a ${name} from parsed JSON; path names it in errors, e.g. "$".`]);
31
+ writer.line(`func Decode${name}(value any, path string) (${name}, error) {`).indent((fn) => {
32
+ fn.line(`object, err := ${RUNTIME}.AsObject(value, path)`);
33
+ fn.line("if err != nil {").indent((branch) => branch.line(`return ${name}{}, err`)).line("}");
34
+ fn.line(`var result ${name}`);
35
+ node.fields.forEach((item) => {
36
+ const base = decoder(ir, item.type, `types.${named.name}.${item.name}`);
37
+ const decode = item.nullable ? `${RUNTIME}.Nullable(${base})` : base;
38
+ fn.line(`if result.${exported(item.name)}, err = ${RUNTIME}.${item.optional ? "Optional" : "Required"}(object, ${str(item.name)}, path, ${decode}); err != nil {`);
39
+ fn.indent((branch) => branch.line(`return ${name}{}, err`)).line("}");
40
+ });
41
+ fn.line(`result.ExtraFields = ${RUNTIME}.Extra(object${keys === "" ? "" : `, ${keys}`})`);
42
+ fn.line("return result, nil");
43
+ });
44
+ writer.line("}").line();
45
+
46
+ doc(writer, ["ToJSON is the JSON form, extra fields included."]);
47
+ writer.line(`func (m ${name}) ToJSON() map[string]any {`).indent((fn) => {
48
+ fn.line("data := map[string]any{}");
49
+ fn.line("for key, value := range m.ExtraFields {").indent((loop) => loop.line("data[key] = value")).line("}");
50
+ node.fields.forEach((item) => {
51
+ const field = `m.${exported(item.name)}`;
52
+ if (item.optional) {
53
+ fn.line(`if value, ok := ${field}.Get(); ok {`).indent((branch) => branch.line(`data[${str(item.name)}] = ${encodeField(ir, item, "value")}`)).line("}");
54
+ } else {
55
+ fn.line(`data[${str(item.name)}] = ${encodeField(ir, item, field)}`);
56
+ }
57
+ });
58
+ fn.line("return data");
59
+ });
60
+ writer.line("}").line();
61
+ }
62
+
63
+ function emitUnion(writer , named , node ) {
64
+ const name = exported(named.name);
65
+ const unknown = `Unknown${name}`;
66
+ const marker = `is${name}`;
67
+ doc(writer, [`${name} ${named.doc ?? ""}`.trim(), "", `One of ${[...node.variants.map((variant) => exported(variant.type)), unknown].join(", ")}; switch on its type.`, ...deprecation(named)]);
68
+ writer.line(`type ${name} interface {`).indent((body) => body.line(`${marker}()`)).line("}").line();
69
+ node.variants.forEach((variant) => writer.line(`func (${exported(variant.type)}) ${marker}() {}`));
70
+ writer.line();
71
+ doc(writer, [`${unknown} is a ${name} variant this SDK version does not know yet; Raw keeps the data.`]);
72
+ writer.line(`type ${unknown} struct {`).indent((body) => body.line("Tag string").line("Raw map[string]any")).line("}").line();
73
+ writer.line(`func (${unknown}) ${marker}() {}`).line();
74
+ doc(writer, ["ToJSON is the data as received."]);
75
+ writer.line(`func (u ${unknown}) ToJSON() map[string]any {`).indent((fn) => {
76
+ fn.line("data := map[string]any{}");
77
+ fn.line("for key, value := range u.Raw {").indent((loop) => loop.line("data[key] = value")).line("}");
78
+ fn.line("return data");
79
+ });
80
+ writer.line("}").line();
81
+
82
+ doc(writer, [`Decode${name} reads a ${name} by its ${str(node.discriminator)} tag; an unknown tag gives ${unknown}.`]);
83
+ writer.line(`func Decode${name}(value any, path string) (${name}, error) {`).indent((fn) => {
84
+ fn.line(`object, err := ${RUNTIME}.AsObject(value, path)`);
85
+ fn.line("if err != nil {").indent((branch) => branch.line("return nil, err")).line("}");
86
+ fn.line(`tag, err := ${RUNTIME}.AsString(object[${str(node.discriminator)}], path+${str(`.${node.discriminator}`)})`);
87
+ fn.line("if err != nil {").indent((branch) => branch.line("return nil, err")).line("}");
88
+ fn.line("switch tag {");
89
+ node.variants.forEach((variant) => {
90
+ fn.line(`case ${str(variant.tag)}:`);
91
+ fn.indent((branch) => branch.line(`return Decode${exported(variant.type)}(object, path)`));
92
+ });
93
+ fn.line("}");
94
+ fn.line(`return ${unknown}{Tag: tag, Raw: object}, nil`);
95
+ });
96
+ writer.line("}").line();
97
+
98
+ doc(writer, [`Encode${name} is the JSON form of a ${name}, including its ${str(node.discriminator)} tag.`]);
99
+ writer.line(`func Encode${name}(value ${name}) any {`).indent((fn) => {
100
+ fn.line("switch v := value.(type) {");
101
+ node.variants.forEach((variant) => {
102
+ fn.line(`case ${exported(variant.type)}:`);
103
+ fn.indent((branch) => {
104
+ branch.line("data := v.ToJSON()");
105
+ branch.line(`data[${str(node.discriminator)}] = ${str(variant.tag)}`);
106
+ branch.line("return data");
107
+ });
108
+ });
109
+ fn.line(`case ${unknown}:`).indent((branch) => branch.line("return v.ToJSON()"));
110
+ fn.line("}");
111
+ fn.line("return nil");
112
+ });
113
+ writer.line("}").line();
114
+ }
115
+
116
+ export function emitModels(ir , header , pkg , module ) {
117
+ const body = go();
118
+ ir.types.filter((named) => named.type.kind === "object").forEach((named) => emitObject(body, ir, named, named.type ));
119
+ ir.types.filter((named) => named.type.kind === "union").forEach((named) => emitUnion(body, named, named.type ));
120
+ const writer = go().line(header).line(`package ${pkg}`).line();
121
+ writer.line(`import ${str(`${module}/${RUNTIME}`)}`).line();
122
+ writer.line(`var _ = ${RUNTIME}.AsString`).line();
123
+ return `${writer.toString()}${body.toString()}`;
124
+ }
125
+
126
+ export function errorType(name ) {
127
+ return `${exported(name.replace(/(Error|Exception)$/, ""))}Error`;
128
+ }
129
+
130
+ export function emitErrors(ir , header , pkg , module ) {
131
+ const statuses = new Map ();
132
+ ir.operations.forEach((operation) => operation.errors.forEach((error) => statuses.set(error.name, [...(statuses.get(error.name) ?? []), error.status])));
133
+ const writer = go().line(header).line(`package ${pkg}`).line();
134
+ writer.line(`import ${str(`${module}/${RUNTIME}`)}`).line();
135
+ writer.line(`var _ *${RUNTIME}.APIError`).line();
136
+ [...statuses.entries()]
137
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
138
+ .forEach(([name, codes]) => {
139
+ const type = errorType(name);
140
+ doc(writer, [`${type} is returned for HTTP ${[...new Set(codes)].sort().join(", ")} (${name}); match it with errors.As.`]);
141
+ writer.line(`type ${type} struct {`).indent((body) => body.line(`*${RUNTIME}.APIError`)).line("}").line();
142
+ doc(writer, ["Unwrap gives the APIError, so errors.As finds it too."]);
143
+ writer.line(`func (e ${type}) Unwrap() error {`).indent((fn) => fn.line("return e.APIError")).line("}").line();
144
+ });
145
+ return writer.toString();
146
+ }
@@ -0,0 +1,58 @@
1
+ // webhooks.go: Verify<Name>Webhook per webhook, which checks the signature (kit block webhooks.verify) and decodes the
2
+ // body into the payload type.
3
+
4
+
5
+ import { decoder, doc, exported, go, goType, RUNTIME, str } from "./names.ts";
6
+
7
+ export function webhookFunction(name ) {
8
+ return `Verify${exported(name)}Webhook`;
9
+ }
10
+
11
+ function signature(hook ) {
12
+ const spec = hook.signature;
13
+ const fields = [
14
+ ["Header", str(spec.header)],
15
+ ["Encoding", str(spec.encoding)],
16
+ ["Prefix", spec.prefix === undefined ? undefined : str(spec.prefix)],
17
+ ["Separator", spec.separator === undefined ? undefined : str(spec.separator)],
18
+ ["Signed", str(spec.signed)],
19
+ ["TimestampHeader", spec.timestamp === undefined ? undefined : str(spec.timestamp.header)],
20
+ ["ToleranceSeconds", spec.timestamp === undefined ? undefined : String(spec.timestamp.toleranceSeconds)],
21
+ ["Secret", str(spec.secret)],
22
+ ["SecretPrefix", spec.secretPrefix === undefined ? undefined : str(spec.secretPrefix)],
23
+ ];
24
+ return `${RUNTIME}.WebhookSignature{${fields.filter(([, value]) => value !== undefined).map(([name, value]) => `${name}: ${value}`).join(", ")}}`;
25
+ }
26
+
27
+ export function emitWebhooks(ir , header , pkg , module ) {
28
+ const taken = new Set(ir.types.map((named) => exported(named.name)));
29
+ if (taken.has("WebhookSignatureError")) throw new Error("type WebhookSignatureError collides with the webhook error type; rename the model");
30
+ const writer = go().line(header).line(`package ${pkg}`).line();
31
+ writer.line("import (").indent((block) => block.line('"net/http"').line('"time"').line().line(str(`${module}/${RUNTIME}`))).line(")").line();
32
+ doc(writer, ["WebhookSignatureError means a webhook was not signed with the secret, or is too old or too new; match it with errors.As."]);
33
+ writer.line(`type WebhookSignatureError = ${RUNTIME}.WebhookSignatureError`).line();
34
+ for (const hook of ir.webhooks ?? []) {
35
+ const name = webhookFunction(hook.name);
36
+ const type = goType(hook.payload);
37
+ const variable = `${hook.name.charAt(0).toLowerCase()}${exported(hook.name).slice(1)}Signature`;
38
+ writer.line(`var ${variable} = ${signature(hook)}`).line();
39
+ doc(writer, [
40
+ ...(hook.doc === undefined ? [] : [hook.doc, ""]),
41
+ `${name} verifies a ${hook.name} webhook and reads its body. Pass the raw body, exactly as received, and the request headers.`,
42
+ "It returns *WebhookSignatureError when the signature does not match the secret or the webhook is too old or too new,",
43
+ "and *DecodeError when the body does not match the payload type.",
44
+ ]);
45
+ writer.line(`func ${name}(body []byte, headers http.Header, secret string) (${type}, error) {`).indent((fn) => fn.line(`return ${name}At(body, headers, secret, time.Now().Unix())`));
46
+ writer.line("}").line();
47
+ doc(writer, [`${name}At is ${name} with the current time, in Unix seconds, given.`]);
48
+ writer.line(`func ${name}At(body []byte, headers http.Header, secret string, nowSeconds int64) (${type}, error) {`).indent((fn) => {
49
+ fn.line(`var zero ${type}`);
50
+ fn.line(`if err := ${RUNTIME}.VerifyWebhook(${variable}, body, headers, secret, nowSeconds); err != nil {`).indent((branch) => branch.line("return zero, err")).line("}");
51
+ fn.line(`value, err := ${RUNTIME}.ParseJSON(body)`);
52
+ fn.line("if err != nil {").indent((branch) => branch.line(`return zero, &${RUNTIME}.DecodeError{Path: "$", Message: err.Error()}`)).line("}");
53
+ fn.line(`return ${decoder(ir, hook.payload, `webhooks.${hook.name}.payload`)}(value, "$")`);
54
+ });
55
+ writer.line("}").line();
56
+ }
57
+ return writer.toString();
58
+ }