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,278 @@
1
+ // The program `sdkloom test` runs against a generated Rust SDK: it reads a plan on stdin and prints observations.
2
+ // Scenarios: a local std::net server answers as the scenario says and the program calls the operation with the
3
+ // scenario's arguments. Round-trips: every schema sample is decoded and encoded again.
4
+
5
+
6
+
7
+ import { configFields, kindOf, paramsType } from "./emit-client.ts";
8
+ import { decoder, fieldDecoder, pathParamName, rust, snake, str, typeName } from "./names.ts";
9
+ import { webhookFunction } from "./emit-webhooks.ts";
10
+
11
+ function emitCall(writer , ir , operation , lib ) {
12
+ writer.line(`${str(operation.name)} => {`).indent((body) => {
13
+ const call = [];
14
+ operation.params
15
+ .filter((param) => param.in === "path")
16
+ .forEach((param) => {
17
+ body.line(`let ${pathParamName(param.name)} = arg(&args, ${str(param.name)}, ${decoder(ir, param.type, "args")})?;`);
18
+ call.push(param.type.kind === "primitive" && ["string", "secret", "datetime"].includes(param.type.name) || param.type.kind === "enum" ? `&${pathParamName(param.name)}` : pathParamName(param.name));
19
+ });
20
+ const kind = kindOf(operation.body);
21
+ if (kind === "json") {
22
+ body.line(`let body = arg(&args, "body", ${decoder(ir, operation.body , "args")})?;`);
23
+ call.push("&body");
24
+ } else if (kind === "multipart") {
25
+ // A multipart body is described as parts; files are sent as UTF-8 bytes.
26
+ body.line(`let mut body = ${lib}::MultipartForm::default();`);
27
+ body.line('for part in match args.get("body").and_then(|value| value.get("parts")) { Some(Json::Array(items)) => items.clone(), _ => vec![] } {').indent((loop) => {
28
+ loop.line('let text = |name: &str| part.get(name).and_then(Json::as_str).unwrap_or("").to_string();');
29
+ loop.line('body = match part.get("filename").and_then(Json::as_str) {').indent((arms) => {
30
+ arms.line('Some(filename) => body.file(&text("name"), filename, &text("contentType"), text("value").as_bytes()),');
31
+ arms.line('None => body.field(&text("name"), &text("value")),');
32
+ });
33
+ loop.line("};");
34
+ });
35
+ body.line("}");
36
+ call.push("&body");
37
+ } else if (kind !== undefined) {
38
+ body.line(`let body = arg(&args, "body", as_string)?.into_bytes();`);
39
+ call.push("&body");
40
+ }
41
+ const named = operation.params.filter((param) => param.in !== "path");
42
+ if (named.length > 0) {
43
+ body.line(`let mut params = ${lib}::${paramsType(operation)}::default();`);
44
+ named.forEach((param) => {
45
+ const read = `arg(&args, ${str(param.name)}, ${decoder(ir, param.type, "args")})?`;
46
+ body.line(`if args.get(${str(param.name)}).is_some() {`).indent((branch) => branch.line(`params.${snake(param.name)} = ${param.optional ? `Some(${read})` : read};`)).line("}");
47
+ });
48
+ call.push("&params");
49
+ }
50
+ if (operation.paginate !== undefined) {
51
+ // all: the operation's iterator over every page.
52
+ body.line("if all {").indent((branch) => {
53
+ branch.line(`let items: Result<Vec<_>, Error> = client.${snake(operation.name)}_all(${call.join(", ")}).collect();`);
54
+ branch.line("return Ok(Json::Array(items?.iter().map(|item| item.to_json()).collect()));");
55
+ });
56
+ body.line("}");
57
+ }
58
+ const invoke = `client.${snake(operation.name)}(${call.join(", ")})?`;
59
+ if (operation.wait !== undefined) {
60
+ // wait: <name>_and_wait polls until the work is done.
61
+ body.line("if wait {").indent((branch) => branch.line(`return Ok(client.${snake(operation.name)}_and_wait(${call.join(", ")})?.to_json());`));
62
+ body.line("}");
63
+ }
64
+ const result = kindOf(operation.returns);
65
+ if (operation.events !== undefined) {
66
+ // Server-sent events: every event the stream delivers, with its data as JSON.
67
+ body.line(`let events: Result<Vec<Json>, Error> = ${invoke}.map(|event| event.map(|event| Json::object(vec![("event", Json::String(event.event)), ("id", Json::String(event.id)), ("data", event.data.to_json())]))).collect();`);
68
+ body.line("Ok(Json::Array(events?))");
69
+ } else if (result === undefined) body.line(`${invoke};`).line("Ok(Json::Null)");
70
+ else if (result !== "json") body.line(`Ok(Json::String(String::from_utf8_lossy(&${invoke}).into_owned()))`);
71
+ else body.line(`Ok(${invoke}.to_json())`);
72
+ });
73
+ writer.line("}");
74
+ }
75
+
76
+ const SERVER = `
77
+ /// Answers requests in order (the last answer repeats) and records every request.
78
+ fn serve(answers: Vec<Json>) -> (String, Arc<Mutex<Vec<Json>>>, Arc<AtomicBool>) {
79
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
80
+ let address = listener.local_addr().unwrap();
81
+ listener.set_nonblocking(true).unwrap();
82
+ let received = Arc::new(Mutex::new(Vec::new()));
83
+ let stop = Arc::new(AtomicBool::new(false));
84
+ let (seen, done) = (received.clone(), stop.clone());
85
+ std::thread::spawn(move || {
86
+ while !done.load(Ordering::Relaxed) {
87
+ let stream = match listener.accept() {
88
+ Ok((stream, _)) => stream,
89
+ Err(_) => {
90
+ std::thread::sleep(std::time::Duration::from_millis(2));
91
+ continue;
92
+ }
93
+ };
94
+ stream.set_nonblocking(false).unwrap();
95
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
96
+ let mut line = String::new();
97
+ if reader.read_line(&mut line).is_err() {
98
+ continue;
99
+ }
100
+ let parts: Vec<String> = line.split_whitespace().map(str::to_string).collect();
101
+ let mut headers = Vec::new();
102
+ let mut length = 0usize;
103
+ loop {
104
+ let mut header = String::new();
105
+ if reader.read_line(&mut header).unwrap_or(0) == 0 || header.trim().is_empty() {
106
+ break;
107
+ }
108
+ if let Some((name, value)) = header.split_once(':') {
109
+ let name = name.trim().to_ascii_lowercase();
110
+ if name == "content-length" {
111
+ length = value.trim().parse().unwrap_or(0);
112
+ }
113
+ headers.push((name, Json::str(value.trim())));
114
+ }
115
+ }
116
+ let mut body = vec![0; length];
117
+ let _ = reader.read_exact(&mut body);
118
+ let respond = {
119
+ let mut list = seen.lock().unwrap();
120
+ list.push(Json::object(vec![
121
+ ("method", Json::str(parts.first().map(String::as_str).unwrap_or(""))),
122
+ ("url", Json::str(parts.get(1).map(String::as_str).unwrap_or(""))),
123
+ ("headers", Json::Object(headers)),
124
+ ("body", Json::String(String::from_utf8_lossy(&body).into_owned())),
125
+ ]));
126
+ answers[(list.len() - 1).min(answers.len().saturating_sub(1))].clone()
127
+ };
128
+ let status = respond.get("status").and_then(Json::as_i64).unwrap_or(200);
129
+ let payload = respond.get("text").and_then(Json::as_str).map(str::to_string).unwrap_or_else(|| respond.get("json").map(Json::to_json_string).unwrap_or_default());
130
+ let mut head = format!("HTTP/1.1 {} X\\r\\ncontent-length: {}\\r\\nconnection: close\\r\\n", status, payload.len());
131
+ if respond.get("json").is_some() {
132
+ head.push_str("content-type: application/json\\r\\n");
133
+ }
134
+ if let Some(Json::Object(extra)) = respond.get("headers") {
135
+ for (name, value) in extra {
136
+ head.push_str(&format!("{}: {}\\r\\n", name, value.as_str().unwrap_or("")));
137
+ }
138
+ }
139
+ head.push_str("\\r\\n");
140
+ let mut stream = stream;
141
+ let _ = stream.write_all(head.as_bytes());
142
+ let _ = stream.write_all(payload.as_bytes());
143
+ }
144
+ });
145
+ (format!("http://{}", address), received, stop)
146
+ }
147
+ `;
148
+
149
+ export function emitHarness(ir , lib ) {
150
+ const writer = rust().line("// Generated by sdkloom for `sdkloom test`; not part of the SDK.").line("#![allow(unused_imports, unused_variables, unused_mut, deprecated)]").line();
151
+ writer.line(`use ${lib}::*;`).line(`use ${lib}::runtime::models::*;`).line(`use ${lib}::runtime::{DecodeError, Error, Json, ToJson};`);
152
+ writer.line("use std::io::{BufRead, BufReader, Read, Write};").line("use std::net::TcpListener;").line("use std::sync::atomic::{AtomicBool, Ordering};").line("use std::sync::{Arc, Mutex};");
153
+ SERVER.trim().split("\n").forEach((line) => writer.line(line));
154
+ writer.line();
155
+
156
+ writer.line("fn arg<T>(args: &Json, name: &str, decode: impl Fn(&Json, &str) -> Result<T, DecodeError>) -> Result<T, Error> {").indent((fn) => {
157
+ fn.line('decode(args.get(name).unwrap_or(&Json::Null), &format!("$.args.{}", name)).map_err(|error| Error::thrown(format!("HarnessError: {}: {}", error.path, error.message)))');
158
+ });
159
+ writer.line("}").line();
160
+
161
+ writer.line(`fn options(config: &Json) -> Result<${lib}::Options, Error> {`).indent((fn) => {
162
+ fn.line(`let mut options = ${lib}::Options::default();`);
163
+ configFields(ir).forEach((item) => {
164
+ const read = `arg(config, ${str(item.name)}, ${fieldDecoder(ir, { type: item.type, nullable: false }, "config")})?`;
165
+ fn.line(`if config.get(${str(item.name)}).is_some() {`).indent((branch) => branch.line(`options.${snake(item.name)} = ${item.optional ? `Some(${read})` : read};`)).line("}");
166
+ });
167
+ if (ir.apiVersions !== undefined) fn.line('if let Some(version) = config.get("apiVersion").and_then(Json::as_str) {').indent((branch) => branch.line("options.api_version = Some(version.to_string());")).line("}");
168
+ fn.line("Ok(options)");
169
+ });
170
+ writer.line("}").line();
171
+
172
+ writer.line(`fn call(client: &${lib}::Client, op: &str, args: Json, all: bool, wait: bool) -> Result<Json, Error> {`).indent((fn) => {
173
+ fn.line("match op {").indent((arms) => {
174
+ ir.operations.forEach((operation) => emitCall(arms, ir, operation, lib));
175
+ arms.line('_ => Err(Error::thrown(format!("UnknownOperation: {}", op))),');
176
+ });
177
+ fn.line("}");
178
+ });
179
+ writer.line("}").line();
180
+
181
+ writer.line("fn round_trip(name: &str, value: &Json) -> Result<Json, Error> {").indent((fn) => {
182
+ fn.line("match name {").indent((arms) => {
183
+ ir.types.forEach((named) => {
184
+ if (named.type.kind === "object" || named.type.kind === "union") arms.line(`${str(named.name)} => Ok(${lib}::${typeName(named.name)}::from_json(value, "$")?.to_json()),`);
185
+ });
186
+ arms.line('_ => Err(Error::thrown(format!("MissingDecoder: {}", name))),');
187
+ });
188
+ fn.line("}");
189
+ });
190
+ writer.line("}").line();
191
+
192
+ // A webhook case: verify and read the body with the SDK's verify_<name>_webhook_at.
193
+ writer.line("fn webhook(hook: &Json) -> Result<Json, Error> {").indent((fn) => {
194
+ fn.line('let text = |name: &str| hook.get(name).and_then(Json::as_str).unwrap_or("").to_string();');
195
+ fn.line('let headers: Vec<(String, String)> = match hook.get("headers") { Some(Json::Object(entries)) => entries.iter().map(|(name, value)| (name.clone(), value.as_str().unwrap_or("").to_string())).collect(), _ => vec![] };');
196
+ fn.line('let (body, secret, now) = (text("body"), text("secret"), hook.get("now").and_then(Json::as_i64).unwrap_or(0));');
197
+ fn.line('match hook.get("name").and_then(Json::as_str).unwrap_or("") {').indent((arms) => {
198
+ (ir.webhooks ?? []).forEach((hook) => arms.line(`${str(hook.name)} => Ok(${lib}::${webhookFunction(hook.name)}_at(body.as_bytes(), &headers, &secret, now)?.to_json()),`));
199
+ arms.line('name => Err(Error::thrown(format!("UnknownWebhook: {}", name))),');
200
+ });
201
+ fn.line("}");
202
+ });
203
+ writer.line("}").line();
204
+
205
+ // A logic case: call the SDK's logic function with its inputs, read from JSON.
206
+ writer.line("fn logic(call: &Json) -> Result<Json, Error> {").indent((fn) => {
207
+ fn.line('let args = call.get("args").cloned().unwrap_or(Json::Null);');
208
+ fn.line("let _ = &args;");
209
+ fn.line('match call.get("name").and_then(Json::as_str).unwrap_or("") {').indent((arms) => {
210
+ const read = {
211
+ int: (name) => `args.get(${str(name)}).and_then(Json::as_i64).unwrap_or(0)`,
212
+ number: (name) => `args.get(${str(name)}).and_then(Json::as_f64).unwrap_or(0.0)`,
213
+ bool: (name) => `args.get(${str(name)}).and_then(Json::as_bool).unwrap_or(false)`,
214
+ string: (name) => `args.get(${str(name)}).and_then(Json::as_str).unwrap_or("")`,
215
+ };
216
+ (ir.logic ?? []).forEach((entry) => {
217
+ const args = entry.input.map((field) => (read[field.type.kind === "primitive" ? field.type.name : "string"] ?? read["string"] ?? String)(field.name));
218
+ arms.line(`${str(entry.name)} => Ok(${lib}::${snake(entry.name)}(${args.join(", ")})?.to_json()),`);
219
+ });
220
+ arms.line('name => Err(Error::thrown(format!("UnknownLogic: {}", name))),');
221
+ });
222
+ fn.line("}");
223
+ });
224
+ writer.line("}").line();
225
+
226
+ writer.line("fn outcome(result: Result<Json, Error>) -> Json {").indent((fn) => {
227
+ fn.line("match result {").indent((arms) => {
228
+ arms.line('Ok(value) => Json::object(vec![("ok", Json::Bool(true)), ("value", value)]),');
229
+ arms.line('Err(error) => Json::object(vec![("ok", Json::Bool(false)), ("error", Json::str(if error.to_string().starts_with("HarnessError") { "HarnessError" } else { error.name() })), ("message", Json::String(error.to_string()))]),');
230
+ });
231
+ fn.line("}");
232
+ });
233
+ writer.line("}").line();
234
+
235
+ writer.line("fn scenario(plan: &Json) -> Json {").indent((fn) => {
236
+ fn.line('if let Some(hook) = plan.get("webhook") {').indent((branch) => branch.line('return Json::object(vec![("id", plan.get("id").cloned().unwrap_or(Json::Null)), ("outcome", outcome(webhook(hook)))]);')).line("}");
237
+ // A logic function fails only by throwing: reported as Error, as in every language.
238
+ fn.line('if let Some(call) = plan.get("logic") {').indent((branch) => {
239
+ branch.line('let result = match logic(call) { Ok(value) => outcome(Ok(value)), Err(error) => Json::object(vec![("ok", Json::Bool(false)), ("error", Json::str("Error")), ("message", Json::String(error.to_string()))]) };');
240
+ branch.line('return Json::object(vec![("id", plan.get("id").cloned().unwrap_or(Json::Null)), ("outcome", result)]);');
241
+ }).line("}");
242
+ fn.line('let answers = match plan.get("answers") { Some(Json::Array(items)) if !items.is_empty() => items.clone(), _ => vec![Json::Null] };');
243
+ fn.line("let (base, received, stop) = serve(answers);");
244
+ fn.line('let all = plan.get("all").and_then(Json::as_bool).unwrap_or(false);');
245
+ fn.line('let wait = plan.get("wait").and_then(Json::as_bool).unwrap_or(false);');
246
+ fn.line('let result = options(plan.get("config").unwrap_or(&Json::Object(vec![]))).and_then(|mut settings| {').indent((inner) => {
247
+ inner.line("settings.base_url = Some(base);");
248
+ inner.line("settings.timeout_ms = Some(5000);");
249
+ inner.line(`let client = ${lib}::Client::new(settings)?;`);
250
+ inner.line('call(&client, plan.get("op").and_then(Json::as_str).unwrap_or(""), plan.get("args").cloned().unwrap_or(Json::Object(vec![])), all, wait)');
251
+ });
252
+ fn.line("});");
253
+ fn.line("stop.store(true, Ordering::Relaxed);");
254
+ fn.line('let mut observation = Json::object(vec![("id", plan.get("id").cloned().unwrap_or(Json::Null)), ("outcome", outcome(result))]);');
255
+ fn.line("let requests = received.lock().unwrap().clone();");
256
+ fn.line("if let Some(first) = requests.first() {").indent((branch) => branch.line('observation.set("received", first.clone());').line('observation.set("requests", Json::Array(requests.clone()));')).line("}");
257
+ fn.line("observation");
258
+ });
259
+ writer.line("}").line();
260
+
261
+ writer.line("fn main() {").indent((fn) => {
262
+ fn.line("let mut input = String::new();");
263
+ fn.line("std::io::stdin().read_to_string(&mut input).unwrap();");
264
+ fn.line('let plan = Json::parse(&input).expect("the plan is JSON");');
265
+ fn.line('let roundtrip = plan.get("mode").and_then(Json::as_str) == Some("roundtrip");');
266
+ fn.line('let cases = match plan.get("cases") { Some(Json::Array(items)) => items.clone(), _ => vec![] };');
267
+ fn.line("let results: Vec<Json> = cases.iter().map(|item| {").indent((inner) => {
268
+ inner.line("if roundtrip {").indent((branch) => {
269
+ branch.line('Json::object(vec![("id", item.get("id").cloned().unwrap_or(Json::Null)), ("outcome", outcome(round_trip(item.get("type").and_then(Json::as_str).unwrap_or(""), item.get("value").unwrap_or(&Json::Null))))])');
270
+ });
271
+ inner.line("} else {").indent((branch) => branch.line("scenario(item)")).line("}");
272
+ });
273
+ fn.line("}).collect();");
274
+ fn.line('print!("{}", Json::Array(results).to_json_string());');
275
+ });
276
+ writer.line("}");
277
+ return writer.toString();
278
+ }
@@ -0,0 +1,121 @@
1
+ // src/mock.rs: mock_client() 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 { boxed, decoder, doc, example, pascal, rust, rustType, snake, str, typeName } 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] ?? "")}.to_string()`;
12
+ if (type.kind === "primitive" && ["string", "secret", "datetime"].includes(type.name)) return '"test".to_string()';
13
+ return undefined;
14
+ }
15
+
16
+ /** Fields of Mock besides the operation mocks. */
17
+ const MOCK_FIELDS = ["transport", "clock", "events"];
18
+
19
+ /** The mock's value type: the result, or for an event stream each event's data (see OperationMock::emits). */
20
+ function mockType(operation ) {
21
+ return operation.events === undefined ? resultType(operation) : rustType(operation.events);
22
+ }
23
+
24
+ export function emitMock(ir , header ) {
25
+ ir.operations.forEach((operation) => {
26
+ if (MOCK_FIELDS.includes(snake(operation.name))) throw new Error(`operation ${operation.name} would clash with Mock::${snake(operation.name)} in the Rust test helpers; rename the operation`);
27
+ });
28
+ const writer = rust().line(header).line("//! Test helpers: a client answered by typed mocks, a fake clock, recorded events and example values.").line("#![allow(unused_imports, deprecated)]").line();
29
+ writer.line("use crate::client::{Client, Options};").line("use crate::models::*;").line("use crate::runtime::models::*;");
30
+ writer.line("use crate::runtime::{Clock, DecodeFn, Decimal, Error, EventListener, FakeClock, Json, MockTransport, OperationMock, RecordedEvent, ToJson, Transport};");
31
+ writer.line("use std::collections::BTreeMap;").line("use std::sync::{Arc, Mutex};").line();
32
+
33
+ doc(writer, ["One typed mock per operation, plus the transport, the fake clock and the events middleware emitted."]);
34
+ writer.line("pub struct Mock {").indent((body) => {
35
+ body.line("pub transport: Arc<MockTransport>,").line("pub clock: Arc<FakeClock>,");
36
+ ir.operations.forEach((operation) => body.line(`pub ${snake(operation.name)}: OperationMock<${mockType(operation)}>,`));
37
+ body.line("events: Arc<Mutex<Vec<RecordedEvent>>>,");
38
+ });
39
+ writer.line("}").line();
40
+ writer.line("impl Mock {").indent((body) => {
41
+ doc(body, ["The events middleware emitted, in order."]);
42
+ body.line("pub fn events(&self) -> Vec<RecordedEvent> {").indent((fn) => fn.line("self.events.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()")).line("}");
43
+ });
44
+ writer.line("}").line();
45
+
46
+ doc(writer, ["A Client whose calls the returned Mock answers; middleware still runs. Required options left empty get placeholders."]);
47
+ writer.line("pub fn mock_client(mut options: Options) -> (Client, Mock) {").indent((fn) => {
48
+ fn.line("let transport = MockTransport::new();").line("let clock = FakeClock::new(0);").line("let events = Arc::new(Mutex::new(Vec::new()));");
49
+ configFields(ir)
50
+ .filter((item) => !item.optional)
51
+ .forEach((item) => {
52
+ const value = placeholder(item.type);
53
+ if (value !== undefined) fn.line(`if options.${snake(item.name)}.is_empty() {`).indent((branch) => branch.line(`options.${snake(item.name)} = ${value};`)).line("}");
54
+ });
55
+ fn.line("let (log, user) = (events.clone(), options.on_event.take());");
56
+ fn.line("let listener: EventListener = Arc::new(move |name: &str, fields: &Json| {").indent((inner) => {
57
+ inner.line("log.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(RecordedEvent { name: name.to_string(), fields: fields.clone() });");
58
+ inner.line("if let Some(user) = &user {").indent((branch) => branch.line("user(name, fields);")).line("}");
59
+ });
60
+ fn.line("});");
61
+ fn.line("options.on_event = Some(listener);");
62
+ fn.line(`options.base_url = Some(${str(MOCK_BASE_URL)}.to_string());`);
63
+ fn.line("options.transport = Some(transport.clone() as Arc<dyn Transport>);");
64
+ fn.line("options.clock = Some(clock.clone() as Arc<dyn Clock>);");
65
+ fn.line('let client = Client::new(options).expect("a mock client always builds");');
66
+ fn.line("let mock = Mock {").indent((fields) => {
67
+ fields.line("transport: transport.clone(),").line("clock,");
68
+ ir.operations.forEach((operation) => {
69
+ const type = mockType(operation);
70
+ const route = `transport.route(${str(operation.method)}, ${str(operation.path)}, None)`;
71
+ if (operation.events !== undefined) {
72
+ // emits() takes the events; their data is checked and written as JSON, or as text for a string stream.
73
+ const text = textEvents(operation.events);
74
+ const decode = text ? "None" : `Some((|v: &Json, p: &str| (${decoder(ir, operation.events, `operations.${operation.name}.events`)})(v, p)) as DecodeFn<${type}>)`;
75
+ fields.line(`${snake(operation.name)}: OperationMock::new(${str(operation.name)}, ${route}, ${decode}, Some((|value: &${type}| value.to_json()) as fn(&${type}) -> Json)),`);
76
+ return;
77
+ }
78
+ const json = kindOf(operation.returns) === "json";
79
+ // Casts: Some(closure) is not an Option of a function pointer until told so.
80
+ const decode = json ? `Some((|v: &Json, p: &str| (${decoder(ir, operation.returns , `operations.${operation.name}.returns`)})(v, p)) as DecodeFn<${type}>)` : "None";
81
+ const encode = json ? `Some((|value: &${type}| value.to_json()) as fn(&${type}) -> Json)` : "None";
82
+ fields.line(`${snake(operation.name)}: OperationMock::new(${str(operation.name)}, ${route}, ${decode}, ${encode}),`);
83
+ });
84
+ fields.line("events,");
85
+ });
86
+ fn.line("};");
87
+ fn.line("(client, mock)");
88
+ });
89
+ writer.line("}").line();
90
+
91
+ doc(writer, ["Small, valid example values; change the fields a test cares about."]);
92
+ writer.line("pub mod examples {").indent((module) => {
93
+ module.line("use super::*;").line();
94
+ ir.types.forEach((named) => {
95
+ const name = typeName(named.name);
96
+ if (named.type.kind === "object") {
97
+ const node = named.type;
98
+ doc(module, [`A ${name} with every required field set.`]);
99
+ module.line(`pub fn ${snake(named.name)}() -> ${name} {`).indent((fn) => {
100
+ fn.line(`${name} {`).indent((fields) => {
101
+ node.fields.forEach((item) => {
102
+ const value = example(item.type, `types.${named.name}.${item.name}`);
103
+ // A field that refers back to its model is boxed (names.ts boxed()).
104
+ fields.line(`${snake(item.name)}: ${item.optional || item.nullable ? "None" : boxed(ir, named.name, item.type) ? `std::boxed::Box::new(${value})` : value},`);
105
+ });
106
+ fields.line("extra_fields: Vec::new(),");
107
+ });
108
+ fn.line("}");
109
+ });
110
+ module.line("}").line();
111
+ } else if (named.type.kind === "union") {
112
+ const first = named.type.variants[0];
113
+ if (first === undefined) throw new Error(`types.${named.name}: a union needs a variant`);
114
+ doc(module, [`The first variant, a ${typeName(first.type)}.`]);
115
+ module.line(`pub fn ${snake(named.name)}() -> ${name} {`).indent((fn) => fn.line(`${name}::${pascal(first.type)}(${snake(first.type)}())`)).line("}").line();
116
+ }
117
+ });
118
+ });
119
+ writer.line("}");
120
+ return writer.toString();
121
+ }
@@ -0,0 +1,117 @@
1
+ // src/models.rs: structs with extra fields, decoders and ToJson; unions as enums with an Unknown variant.
2
+
3
+
4
+
5
+ import { doc, modelFieldDecoder, modelFieldType, pascal, rust, snake, str, typeName } from "./names.ts";
6
+
7
+ const RESERVED = new Set(["extra_fields"]);
8
+
9
+ function deprecation(item ) {
10
+ return item.deprecated === undefined ? [] : [`#[deprecated(note = ${str(item.deprecated)})]`];
11
+ }
12
+
13
+ function emitObject(writer , ir , named , node ) {
14
+ const name = typeName(named.name);
15
+ node.fields.forEach((item) => {
16
+ if (RESERVED.has(snake(item.name))) throw new Error(`types.${named.name}.${item.name}: the Rust name ${snake(item.name)} is reserved; rename the field`);
17
+ });
18
+ doc(writer, [named.doc ?? name, "", "Fields the server adds later are kept in extra_fields and sent back unchanged."]);
19
+ deprecation(named).forEach((line) => writer.line(line));
20
+ writer.line("#[derive(Clone, Debug, PartialEq)]");
21
+ writer.line(`pub struct ${name} {`).indent((body) => {
22
+ node.fields.forEach((item) => {
23
+ doc(body, item.doc === undefined ? [] : [item.doc]);
24
+ deprecation(item).forEach((line) => body.line(line));
25
+ body.line(`pub ${snake(item.name)}: ${modelFieldType(ir, named.name, item)},`);
26
+ });
27
+ doc(body, ["Fields this SDK version does not know."]);
28
+ body.line("pub extra_fields: Vec<(String, Json)>,");
29
+ });
30
+ writer.line("}").line();
31
+
32
+ writer.line("#[allow(deprecated)]").line(`impl ${name} {`).indent((body) => {
33
+ doc(body, [`Reads a ${name} from JSON; path names it in errors, e.g. "$".`]);
34
+ body.line(`pub fn from_json(value: &Json, path: &str) -> Result<${name}, DecodeError> {`).indent((fn) => {
35
+ fn.line("as_object(value, path)?;");
36
+ fn.line(`Ok(${name} {`).indent((fields) => {
37
+ node.fields.forEach((item) => {
38
+ const read = item.optional ? "optional" : "required";
39
+ fields.line(`${snake(item.name)}: ${read}(value, ${str(item.name)}, path, ${modelFieldDecoder(ir, named.name, item, `types.${named.name}.${item.name}`)})?,`);
40
+ });
41
+ fields.line(`extra_fields: extra(value, &[${node.fields.map((item) => str(item.name)).join(", ")}]),`);
42
+ });
43
+ fn.line("})");
44
+ });
45
+ body.line("}");
46
+ });
47
+ writer.line("}").line();
48
+
49
+ writer.line("#[allow(deprecated)]").line(`impl ToJson for ${name} {`).indent((body) => {
50
+ body.line("fn to_json(&self) -> Json {").indent((fn) => {
51
+ fn.line("let mut data = Json::Object(self.extra_fields.clone());");
52
+ node.fields.forEach((item) => {
53
+ const field = `self.${snake(item.name)}`;
54
+ if (item.optional) fn.line(`if let Some(value) = &${field} {`).indent((branch) => branch.line(`data.set(${str(item.name)}, value.to_json());`)).line("}");
55
+ else fn.line(`data.set(${str(item.name)}, ${field}.to_json());`);
56
+ });
57
+ fn.line("data");
58
+ });
59
+ body.line("}");
60
+ });
61
+ writer.line("}").line();
62
+ }
63
+
64
+ function emitUnion(writer , named , node ) {
65
+ const name = typeName(named.name);
66
+ doc(writer, [named.doc ?? name, "", `Selected by its ${str(node.discriminator)} field; Unknown keeps a variant this SDK version does not know.`, "Non-exhaustive: later versions may add variants, so a match needs a wildcard arm."]);
67
+ deprecation(named).forEach((line) => writer.line(line));
68
+ writer.line("#[derive(Clone, Debug, PartialEq)]").line("#[non_exhaustive]");
69
+ writer.line(`pub enum ${name} {`).indent((body) => {
70
+ node.variants.forEach((variant) => body.line(`${pascal(variant.type)}(${typeName(variant.type)}),`));
71
+ body.line("Unknown { tag: String, raw: Json },");
72
+ });
73
+ writer.line("}").line();
74
+
75
+ writer.line(`impl ${name} {`).indent((body) => {
76
+ doc(body, [`Reads a ${name} by its tag.`]);
77
+ body.line(`pub fn from_json(value: &Json, path: &str) -> Result<${name}, DecodeError> {`).indent((fn) => {
78
+ fn.line("as_object(value, path)?;");
79
+ fn.line(`let tag = as_string(value.get(${str(node.discriminator)}).unwrap_or(&Json::Null), &format!("{}.{}", path, ${str(node.discriminator)}))?;`);
80
+ fn.line("match tag.as_str() {").indent((arms) => {
81
+ node.variants.forEach((variant) => arms.line(`${str(variant.tag)} => Ok(${name}::${pascal(variant.type)}(${typeName(variant.type)}::from_json(value, path)?)),`));
82
+ arms.line(`_ => Ok(${name}::Unknown { tag, raw: value.clone() }),`);
83
+ });
84
+ fn.line("}");
85
+ });
86
+ body.line("}");
87
+ });
88
+ writer.line("}").line();
89
+
90
+ writer.line(`impl ToJson for ${name} {`).indent((body) => {
91
+ doc(body, [`The JSON form, with the ${str(node.discriminator)} tag.`]);
92
+ body.line("fn to_json(&self) -> Json {").indent((fn) => {
93
+ fn.line("match self {").indent((arms) => {
94
+ node.variants.forEach((variant) => {
95
+ arms.line(`${name}::${pascal(variant.type)}(value) => {`).indent((arm) => {
96
+ arm.line("let mut data = value.to_json();");
97
+ arm.line(`data.set(${str(node.discriminator)}, Json::str(${str(variant.tag)}));`);
98
+ arm.line("data");
99
+ });
100
+ arms.line("}");
101
+ });
102
+ arms.line(`${name}::Unknown { raw, .. } => raw.clone(),`);
103
+ });
104
+ fn.line("}");
105
+ });
106
+ body.line("}");
107
+ });
108
+ writer.line("}").line();
109
+ }
110
+
111
+ export function emitModels(ir , header ) {
112
+ const writer = rust().line(header).line("#![allow(unused_imports)]").line();
113
+ writer.line("use crate::runtime::models::*;").line("use crate::runtime::{DecodeError, Json};").line("use std::collections::BTreeMap;").line();
114
+ ir.types.filter((named) => named.type.kind === "object").forEach((named) => emitObject(writer, ir, named, named.type ));
115
+ ir.types.filter((named) => named.type.kind === "union").forEach((named) => emitUnion(writer, named, named.type ));
116
+ return writer.toString();
117
+ }
@@ -0,0 +1,58 @@
1
+ // src/webhooks.rs: verify_<name>_webhook per webhook, which checks the signature (kit block webhooks.verify) and
2
+ // decodes the body into the payload type.
3
+
4
+
5
+ import { decoder, doc, rust, rustType, snake, str } from "./names.ts";
6
+
7
+ export function webhookFunction(name ) {
8
+ return `verify_${snake(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: ${str(spec.prefix ?? "")}`,
17
+ `separator: ${spec.separator === undefined ? "None" : `Some(${str(spec.separator)})`}`,
18
+ `signed: ${str(spec.signed)}`,
19
+ `timestamp: ${spec.timestamp === undefined ? "None" : `Some((${str(spec.timestamp.header)}, ${String(spec.timestamp.toleranceSeconds)}))`}`,
20
+ `secret: ${str(spec.secret)}`,
21
+ `secret_prefix: ${str(spec.secretPrefix ?? "")}`,
22
+ ];
23
+ return `WebhookSignature { ${fields.join(", ")} }`;
24
+ }
25
+
26
+ export function emitWebhooks(ir , header ) {
27
+ const writer = rust().line(header).line("#![allow(unused_imports)]").line();
28
+ writer.line("use crate::models::*;").line("use crate::runtime::models::*;").line("use crate::runtime::webhooks::{verify_webhook, WebhookSignature};");
29
+ writer.line("use crate::runtime::{DecodeError, Error, Json};").line("use std::time::{SystemTime, UNIX_EPOCH};").line();
30
+ for (const hook of ir.webhooks ?? []) {
31
+ const name = webhookFunction(hook.name);
32
+ const type = rustType(hook.payload);
33
+ const constant = `${snake(hook.name).toUpperCase()}_SIGNATURE`;
34
+ writer.line(`const ${constant}: WebhookSignature = ${signature(hook)};`).line();
35
+ doc(writer, [
36
+ ...(hook.doc === undefined ? [] : [hook.doc, ""]),
37
+ `Verifies a ${hook.name} webhook and reads its body. Pass the raw body, exactly as received, and the request headers`,
38
+ "(names in any case).",
39
+ "",
40
+ "Fails with `Error::WebhookSignature` when the signature does not match the secret or the webhook is too old or too new,",
41
+ "and `Error::Decode` when the body does not match the payload type.",
42
+ ]);
43
+ writer.line(`pub fn ${name}(body: &[u8], headers: &[(String, String)], secret: &str) -> Result<${type}, Error> {`).indent((fn) => {
44
+ fn.line("let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|elapsed| elapsed.as_secs() as i64).unwrap_or(0);");
45
+ fn.line(`${name}_at(body, headers, secret, now)`);
46
+ });
47
+ writer.line("}").line();
48
+ doc(writer, [`\`${name}\` with the current time, in Unix seconds, given.`]);
49
+ writer.line(`pub fn ${name}_at(body: &[u8], headers: &[(String, String)], secret: &str, now_seconds: i64) -> Result<${type}, Error> {`).indent((fn) => {
50
+ fn.line(`verify_webhook(&${constant}, body, headers, secret, now_seconds)?;`);
51
+ fn.line('let text = std::str::from_utf8(body).map_err(|_| DecodeError::new("$", "the body is not UTF-8"))?;');
52
+ fn.line('let value = Json::parse(text).map_err(|message| DecodeError::new("$", &message))?;');
53
+ fn.line(`Ok((${decoder(ir, hook.payload, `webhooks.${hook.name}.payload`)})(&value, "$")?)`);
54
+ });
55
+ writer.line("}").line();
56
+ }
57
+ return writer.toString();
58
+ }