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.
- package/LICENSE +202 -0
- package/README.md +239 -2
- package/kits/allowed-sources.json +24 -0
- package/kits/csharp/kit.json +6 -0
- package/kits/csharp/src/Runtime/Client.cs +295 -0
- package/kits/csharp/src/Runtime/Context.cs +216 -0
- package/kits/csharp/src/Runtime/Errors.cs +121 -0
- package/kits/csharp/src/Runtime/Http.cs +218 -0
- package/kits/csharp/src/Runtime/Json.cs +650 -0
- package/kits/csharp/src/Runtime/Lang.cs +212 -0
- package/kits/csharp/src/Runtime/Models.cs +206 -0
- package/kits/csharp/src/Runtime/Multipart.cs +108 -0
- package/kits/csharp/src/Runtime/Pagination.cs +122 -0
- package/kits/csharp/src/Runtime/Sse.cs +197 -0
- package/kits/csharp/src/Runtime/Testing.cs +375 -0
- package/kits/csharp/src/Runtime/Transport.cs +212 -0
- package/kits/csharp/src/Runtime/Wait.cs +57 -0
- package/kits/csharp/src/Runtime/Webhooks.cs +148 -0
- package/kits/csharp/tests/ClientTests.cs +128 -0
- package/kits/csharp/tests/HttpTests.cs +44 -0
- package/kits/csharp/tests/JsonTests.cs +132 -0
- package/kits/csharp/tests/LangTests.cs +57 -0
- package/kits/csharp/tests/MultipartTests.cs +31 -0
- package/kits/csharp/tests/PaginationTests.cs +93 -0
- package/kits/csharp/tests/SseTests.cs +122 -0
- package/kits/csharp/tests/TestRunner.cs +93 -0
- package/kits/csharp/tests/TestingTests.cs +80 -0
- package/kits/csharp/tests/TransportTests.cs +145 -0
- package/kits/csharp/tests/WaitTests.cs +39 -0
- package/kits/csharp/tests/WebhooksTests.cs +46 -0
- package/kits/csharp/versions.json +12 -0
- package/kits/go/kit.json +6 -0
- package/kits/go/src/sdkruntime/client.go +322 -0
- package/kits/go/src/sdkruntime/context.go +207 -0
- package/kits/go/src/sdkruntime/errors.go +74 -0
- package/kits/go/src/sdkruntime/http.go +261 -0
- package/kits/go/src/sdkruntime/json.go +527 -0
- package/kits/go/src/sdkruntime/lang.go +462 -0
- package/kits/go/src/sdkruntime/multipart.go +75 -0
- package/kits/go/src/sdkruntime/pagination.go +150 -0
- package/kits/go/src/sdkruntime/sse.go +267 -0
- package/kits/go/src/sdkruntime/testing.go +343 -0
- package/kits/go/src/sdkruntime/transport.go +168 -0
- package/kits/go/src/sdkruntime/wait.go +49 -0
- package/kits/go/src/sdkruntime/webhooks.go +129 -0
- package/kits/go/tests/client_test.go +185 -0
- package/kits/go/tests/http_test.go +78 -0
- package/kits/go/tests/json_test.go +127 -0
- package/kits/go/tests/lang_test.go +98 -0
- package/kits/go/tests/multipart_test.go +29 -0
- package/kits/go/tests/pagination_test.go +69 -0
- package/kits/go/tests/sse_test.go +129 -0
- package/kits/go/tests/testing_test.go +121 -0
- package/kits/go/tests/transport_test.go +133 -0
- package/kits/go/tests/wait_test.go +46 -0
- package/kits/go/tests/webhooks_test.go +62 -0
- package/kits/go/versions.json +12 -0
- package/kits/java/kit.json +6 -0
- package/kits/java/src/dev/sdkloom/runtime/ApiException.java +63 -0
- package/kits/java/src/dev/sdkloom/runtime/ArgumentException.java +24 -0
- package/kits/java/src/dev/sdkloom/runtime/Assert.java +72 -0
- package/kits/java/src/dev/sdkloom/runtime/ClientRuntime.java +220 -0
- package/kits/java/src/dev/sdkloom/runtime/Clock.java +39 -0
- package/kits/java/src/dev/sdkloom/runtime/Context.java +79 -0
- package/kits/java/src/dev/sdkloom/runtime/Decode.java +200 -0
- package/kits/java/src/dev/sdkloom/runtime/DecodeException.java +26 -0
- package/kits/java/src/dev/sdkloom/runtime/Decoder.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/Emitter.java +56 -0
- package/kits/java/src/dev/sdkloom/runtime/ErrorFactory.java +18 -0
- package/kits/java/src/dev/sdkloom/runtime/EventListener.java +20 -0
- package/kits/java/src/dev/sdkloom/runtime/EventStream.java +232 -0
- package/kits/java/src/dev/sdkloom/runtime/FakeClock.java +37 -0
- package/kits/java/src/dev/sdkloom/runtime/Headers.java +42 -0
- package/kits/java/src/dev/sdkloom/runtime/HttpRequest.java +88 -0
- package/kits/java/src/dev/sdkloom/runtime/HttpResponse.java +69 -0
- package/kits/java/src/dev/sdkloom/runtime/JdkTransport.java +97 -0
- package/kits/java/src/dev/sdkloom/runtime/Js.java +230 -0
- package/kits/java/src/dev/sdkloom/runtime/Json.java +281 -0
- package/kits/java/src/dev/sdkloom/runtime/JsonValue.java +15 -0
- package/kits/java/src/dev/sdkloom/runtime/Links.java +62 -0
- package/kits/java/src/dev/sdkloom/runtime/Middleware.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/MiddlewareEntry.java +43 -0
- package/kits/java/src/dev/sdkloom/runtime/MockRoute.java +111 -0
- package/kits/java/src/dev/sdkloom/runtime/MockTransport.java +62 -0
- package/kits/java/src/dev/sdkloom/runtime/MultipartForm.java +111 -0
- package/kits/java/src/dev/sdkloom/runtime/Next.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/OperationInfo.java +35 -0
- package/kits/java/src/dev/sdkloom/runtime/OperationMock.java +105 -0
- package/kits/java/src/dev/sdkloom/runtime/OperationSpec.java +125 -0
- package/kits/java/src/dev/sdkloom/runtime/Pages.java +55 -0
- package/kits/java/src/dev/sdkloom/runtime/Pipeline.java +29 -0
- package/kits/java/src/dev/sdkloom/runtime/RawResult.java +31 -0
- package/kits/java/src/dev/sdkloom/runtime/RecordedEvent.java +36 -0
- package/kits/java/src/dev/sdkloom/runtime/SdkInfo.java +38 -0
- package/kits/java/src/dev/sdkloom/runtime/SendOptions.java +34 -0
- package/kits/java/src/dev/sdkloom/runtime/ServerSentEvent.java +58 -0
- package/kits/java/src/dev/sdkloom/runtime/State.java +58 -0
- package/kits/java/src/dev/sdkloom/runtime/Test.java +21 -0
- package/kits/java/src/dev/sdkloom/runtime/TestRunner.java +63 -0
- package/kits/java/src/dev/sdkloom/runtime/Transport.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/TransportException.java +30 -0
- package/kits/java/src/dev/sdkloom/runtime/UrlConnectionTransport.java +195 -0
- package/kits/java/src/dev/sdkloom/runtime/Urls.java +116 -0
- package/kits/java/src/dev/sdkloom/runtime/Waits.java +53 -0
- package/kits/java/src/dev/sdkloom/runtime/WebhookSignatureException.java +24 -0
- package/kits/java/src/dev/sdkloom/runtime/Webhooks.java +146 -0
- package/kits/java/tests/dev/sdkloom/runtime/ClientTest.java +266 -0
- package/kits/java/tests/dev/sdkloom/runtime/EventStreamTest.java +131 -0
- package/kits/java/tests/dev/sdkloom/runtime/HttpTest.java +95 -0
- package/kits/java/tests/dev/sdkloom/runtime/JdkTransportTest.java +12 -0
- package/kits/java/tests/dev/sdkloom/runtime/JsTest.java +102 -0
- package/kits/java/tests/dev/sdkloom/runtime/JsonTest.java +87 -0
- package/kits/java/tests/dev/sdkloom/runtime/LinksTest.java +22 -0
- package/kits/java/tests/dev/sdkloom/runtime/MultipartFormTest.java +30 -0
- package/kits/java/tests/dev/sdkloom/runtime/PagesTest.java +75 -0
- package/kits/java/tests/dev/sdkloom/runtime/TestData.java +53 -0
- package/kits/java/tests/dev/sdkloom/runtime/TestingTest.java +156 -0
- package/kits/java/tests/dev/sdkloom/runtime/TransportContract.java +201 -0
- package/kits/java/tests/dev/sdkloom/runtime/UrlConnectionTransportTest.java +49 -0
- package/kits/java/tests/dev/sdkloom/runtime/WaitsTest.java +43 -0
- package/kits/java/tests/dev/sdkloom/runtime/WebhooksTest.java +45 -0
- package/kits/java/versions.json +41 -0
- package/kits/python/kit.json +6 -0
- package/kits/python/src/sdkloom_runtime/__init__.py +1 -0
- package/kits/python/src/sdkloom_runtime/client.py +232 -0
- package/kits/python/src/sdkloom_runtime/compat.py +195 -0
- package/kits/python/src/sdkloom_runtime/context.py +134 -0
- package/kits/python/src/sdkloom_runtime/errors.py +65 -0
- package/kits/python/src/sdkloom_runtime/http.py +192 -0
- package/kits/python/src/sdkloom_runtime/lang.py +207 -0
- package/kits/python/src/sdkloom_runtime/models.py +221 -0
- package/kits/python/src/sdkloom_runtime/multipart.py +69 -0
- package/kits/python/src/sdkloom_runtime/pagination.py +61 -0
- package/kits/python/src/sdkloom_runtime/pipeline.py +39 -0
- package/kits/python/src/sdkloom_runtime/sse.py +121 -0
- package/kits/python/src/sdkloom_runtime/testing.py +224 -0
- package/kits/python/src/sdkloom_runtime/transport.py +120 -0
- package/kits/python/src/sdkloom_runtime/wait.py +44 -0
- package/kits/python/src/sdkloom_runtime/webhooks.py +84 -0
- package/kits/python/tests/support.py +28 -0
- package/kits/python/tests/test_client.py +275 -0
- package/kits/python/tests/test_compat.py +87 -0
- package/kits/python/tests/test_http.py +94 -0
- package/kits/python/tests/test_lang.py +104 -0
- package/kits/python/tests/test_models.py +110 -0
- package/kits/python/tests/test_multipart.py +37 -0
- package/kits/python/tests/test_pagination.py +70 -0
- package/kits/python/tests/test_sse.py +61 -0
- package/kits/python/tests/test_testing.py +130 -0
- package/kits/python/tests/test_transport.py +124 -0
- package/kits/python/tests/test_wait.py +46 -0
- package/kits/python/tests/test_webhooks.py +57 -0
- package/kits/python/versions.json +33 -0
- package/kits/rust/kit.json +6 -0
- package/kits/rust/src/runtime/client.rs +212 -0
- package/kits/rust/src/runtime/context.rs +182 -0
- package/kits/rust/src/runtime/crypto.rs +84 -0
- package/kits/rust/src/runtime/errors.rs +147 -0
- package/kits/rust/src/runtime/http.rs +248 -0
- package/kits/rust/src/runtime/json.rs +424 -0
- package/kits/rust/src/runtime/lang.rs +296 -0
- package/kits/rust/src/runtime/mod.rs +30 -0
- package/kits/rust/src/runtime/models.rs +266 -0
- package/kits/rust/src/runtime/multipart.rs +81 -0
- package/kits/rust/src/runtime/pagination.rs +117 -0
- package/kits/rust/src/runtime/sse.rs +195 -0
- package/kits/rust/src/runtime/testing.rs +308 -0
- package/kits/rust/src/runtime/transport.rs +324 -0
- package/kits/rust/src/runtime/wait.rs +29 -0
- package/kits/rust/src/runtime/webhooks.rs +142 -0
- package/kits/rust/tests/client.rs +152 -0
- package/kits/rust/tests/http.rs +44 -0
- package/kits/rust/tests/json.rs +82 -0
- package/kits/rust/tests/lang.rs +74 -0
- package/kits/rust/tests/multipart.rs +21 -0
- package/kits/rust/tests/pagination.rs +61 -0
- package/kits/rust/tests/sse.rs +77 -0
- package/kits/rust/tests/testing.rs +90 -0
- package/kits/rust/tests/transport.rs +218 -0
- package/kits/rust/tests/wait.rs +32 -0
- package/kits/rust/tests/webhooks.rs +73 -0
- package/kits/rust/versions.json +6 -0
- package/kits/typescript/kit.json +6 -0
- package/kits/typescript/src/client.ts +223 -0
- package/kits/typescript/src/context.ts +108 -0
- package/kits/typescript/src/errors.ts +63 -0
- package/kits/typescript/src/helpers.ts +49 -0
- package/kits/typescript/src/http.ts +192 -0
- package/kits/typescript/src/models.ts +139 -0
- package/kits/typescript/src/multipart.ts +66 -0
- package/kits/typescript/src/pagination.ts +54 -0
- package/kits/typescript/src/pipeline.ts +25 -0
- package/kits/typescript/src/sse.ts +102 -0
- package/kits/typescript/src/testing.ts +217 -0
- package/kits/typescript/src/transport.ts +101 -0
- package/kits/typescript/src/wait.ts +36 -0
- package/kits/typescript/src/webhooks.ts +168 -0
- package/kits/typescript/tests/client.test.ts +269 -0
- package/kits/typescript/tests/helpers.test.ts +27 -0
- package/kits/typescript/tests/http.test.ts +80 -0
- package/kits/typescript/tests/models.test.ts +71 -0
- package/kits/typescript/tests/multipart.test.ts +28 -0
- package/kits/typescript/tests/pagination.test.ts +76 -0
- package/kits/typescript/tests/sse.test.ts +82 -0
- package/kits/typescript/tests/testing.test.ts +103 -0
- package/kits/typescript/tests/transport.test.ts +127 -0
- package/kits/typescript/tests/wait.test.ts +31 -0
- package/kits/typescript/tests/webhooks.test.ts +53 -0
- package/kits/typescript/versions.json +15 -0
- package/package.json +37 -4
- package/packages/cli/recipes/apiKeyHeader.ts +16 -0
- package/packages/cli/recipes/apiVersionHeader.ts +16 -0
- package/packages/cli/recipes/basic.ts +13 -0
- package/packages/cli/recipes/bearer.ts +10 -0
- package/packages/cli/recipes/hmacSign.ts +23 -0
- package/packages/cli/recipes/idempotencyKey.ts +19 -0
- package/packages/cli/recipes/oauthClientCredentials.ts +50 -0
- package/packages/cli/recipes/retry.ts +42 -0
- package/packages/cli/recipes/timing.ts +12 -0
- package/packages/cli/recipes/userAgent.ts +8 -0
- package/packages/cli/src/build.js +93 -0
- package/packages/cli/src/commands/build.js +31 -0
- package/packages/cli/src/commands/conformance-check.js +50 -0
- package/packages/cli/src/commands/contract.js +181 -0
- package/packages/cli/src/commands/diff.js +113 -0
- package/packages/cli/src/commands/doctor.js +43 -0
- package/packages/cli/src/commands/import-openapi.js +42 -0
- package/packages/cli/src/commands/init.js +27 -0
- package/packages/cli/src/commands/kit-check.js +145 -0
- package/packages/cli/src/commands/publish.js +81 -0
- package/packages/cli/src/commands/recipe.js +49 -0
- package/packages/cli/src/commands/record.js +181 -0
- package/packages/cli/src/commands/serve.js +156 -0
- package/packages/cli/src/commands/spec-check.js +57 -0
- package/packages/cli/src/commands/test.js +177 -0
- package/packages/cli/src/commands/variants.js +32 -0
- package/packages/cli/src/commands/verify.js +57 -0
- package/packages/cli/src/commands/version.js +63 -0
- package/packages/cli/src/containers.js +82 -0
- package/packages/cli/src/coverage.js +72 -0
- package/packages/cli/src/git.js +25 -0
- package/packages/cli/src/io.js +50 -0
- package/packages/cli/src/java/ScenarioHarness.java +297 -0
- package/packages/cli/src/java/SchemaRoundTrip.java +63 -0
- package/packages/cli/src/java.js +70 -0
- package/packages/cli/src/js/harness.mjs +120 -0
- package/packages/cli/src/kits.js +103 -0
- package/packages/cli/src/languages/csharp.js +274 -0
- package/packages/cli/src/languages/go.js +185 -0
- package/packages/cli/src/languages/index.js +18 -0
- package/packages/cli/src/languages/java.js +187 -0
- package/packages/cli/src/languages/python.js +120 -0
- package/packages/cli/src/languages/rust.js +189 -0
- package/packages/cli/src/languages/types.js +93 -0
- package/packages/cli/src/languages/typescript.js +112 -0
- package/packages/cli/src/main.js +13 -0
- package/packages/cli/src/packaging.js +39 -0
- package/packages/cli/src/portability.js +45 -0
- package/packages/cli/src/profiles.js +55 -0
- package/packages/cli/src/project.js +56 -0
- package/packages/cli/src/python/scenario_harness.py +162 -0
- package/packages/cli/src/python/schema_roundtrip.py +42 -0
- package/packages/cli/src/registries.js +214 -0
- package/packages/cli/src/resolve-core.js +39 -0
- package/packages/cli/src/run.js +133 -0
- package/packages/cli/src/runtimes.js +61 -0
- package/packages/cli/src/scenarios-java.js +82 -0
- package/packages/cli/src/scenarios-javascript.js +54 -0
- package/packages/cli/src/scenarios-python.js +90 -0
- package/packages/cli/src/scenarios.js +183 -0
- package/packages/cli/src/schema.js +84 -0
- package/packages/cli/src/templates.js +85 -0
- package/packages/cli/src/toolchains.js +68 -0
- package/packages/cli/src/transpiled-tests.js +92 -0
- package/packages/codegen/src/canonical-json.js +31 -0
- package/packages/codegen/src/capabilities.js +50 -0
- package/packages/codegen/src/code-writer.js +54 -0
- package/packages/codegen/src/file-tree.js +25 -0
- package/packages/codegen/src/hash.js +6 -0
- package/packages/codegen/src/index.js +16 -0
- package/packages/codegen/src/lock.js +106 -0
- package/packages/conformance/src/case.js +143 -0
- package/packages/conformance/src/checks.js +40 -0
- package/packages/conformance/src/index.js +3 -0
- package/packages/conformance/src/matrix.js +48 -0
- package/packages/conformance/src/suite.js +48 -0
- package/packages/differ/src/diff.js +500 -0
- package/packages/differ/src/index.js +3 -0
- package/packages/differ/src/notes.js +112 -0
- package/packages/differ/src/support.js +34 -0
- package/packages/gen-csharp/src/emit-client.js +397 -0
- package/packages/gen-csharp/src/emit-harness.js +333 -0
- package/packages/gen-csharp/src/emit-mock.js +111 -0
- package/packages/gen-csharp/src/emit-models.js +119 -0
- package/packages/gen-csharp/src/emit-webhooks.js +57 -0
- package/packages/gen-csharp/src/generate.js +245 -0
- package/packages/gen-csharp/src/index.js +5 -0
- package/packages/gen-csharp/src/names.js +284 -0
- package/packages/gen-go/src/emit-client.js +405 -0
- package/packages/gen-go/src/emit-harness.js +294 -0
- package/packages/gen-go/src/emit-mock.js +112 -0
- package/packages/gen-go/src/emit-models.js +146 -0
- package/packages/gen-go/src/emit-webhooks.js +58 -0
- package/packages/gen-go/src/generate.js +205 -0
- package/packages/gen-go/src/index.js +5 -0
- package/packages/gen-go/src/names.js +197 -0
- package/packages/gen-java/src/emit-client.js +441 -0
- package/packages/gen-java/src/emit-models.js +342 -0
- package/packages/gen-java/src/emit-testing.js +123 -0
- package/packages/gen-java/src/emit-webhooks.js +70 -0
- package/packages/gen-java/src/generate.js +244 -0
- package/packages/gen-java/src/index.js +4 -0
- package/packages/gen-java/src/names.js +197 -0
- package/packages/gen-python/src/emit-client.js +272 -0
- package/packages/gen-python/src/emit-models.js +139 -0
- package/packages/gen-python/src/emit-testing.js +93 -0
- package/packages/gen-python/src/emit-webhooks.js +48 -0
- package/packages/gen-python/src/generate.js +237 -0
- package/packages/gen-python/src/index.js +2 -0
- package/packages/gen-python/src/names.js +161 -0
- package/packages/gen-python/src/style.js +67 -0
- package/packages/gen-rust/src/emit-client.js +379 -0
- package/packages/gen-rust/src/emit-harness.js +278 -0
- package/packages/gen-rust/src/emit-mock.js +121 -0
- package/packages/gen-rust/src/emit-models.js +117 -0
- package/packages/gen-rust/src/emit-webhooks.js +58 -0
- package/packages/gen-rust/src/generate.js +243 -0
- package/packages/gen-rust/src/index.js +5 -0
- package/packages/gen-rust/src/names.js +223 -0
- package/packages/gen-typescript/src/emit-client.js +434 -0
- package/packages/gen-typescript/src/emit-models.js +93 -0
- package/packages/gen-typescript/src/emit-package.js +90 -0
- package/packages/gen-typescript/src/emit-testing.js +138 -0
- package/packages/gen-typescript/src/emit-webhooks.js +52 -0
- package/packages/gen-typescript/src/generate.js +70 -0
- package/packages/gen-typescript/src/index.js +3 -0
- package/packages/gen-typescript/src/naming.js +64 -0
- package/packages/gen-typescript/src/runtime.js +81 -0
- package/packages/gen-typescript/src/types.js +136 -0
- package/packages/ir/src/api-surface.js +22 -0
- package/packages/ir/src/checks.js +52 -0
- package/packages/ir/src/index.js +32 -0
- package/packages/ir/src/ir.js +214 -0
- package/packages/ir/src/pages.js +18 -0
- package/packages/ir/src/validate-ir.js +462 -0
- package/packages/ir/src/validate-types.js +140 -0
- package/packages/kit/src/block-parser.js +196 -0
- package/packages/kit/src/index.js +15 -0
- package/packages/kit/src/kit-check.js +203 -0
- package/packages/kit/src/sources.js +53 -0
- package/packages/kit/src/version-policy.js +133 -0
- package/packages/kit/src/version-range.js +132 -0
- package/packages/openapi/src/import.js +292 -0
- package/packages/openapi/src/index.js +1 -0
- package/packages/openapi/src/names.js +50 -0
- package/packages/openapi/src/schemas.js +264 -0
- package/packages/packager/src/archive.js +106 -0
- package/packages/packager/src/crate.js +39 -0
- package/packages/packager/src/gomodule.js +11 -0
- package/packages/packager/src/index.js +9 -0
- package/packages/packager/src/maven.js +85 -0
- package/packages/packager/src/metadata.js +34 -0
- package/packages/packager/src/npm.js +71 -0
- package/packages/packager/src/nuget.js +78 -0
- package/packages/packager/src/sbom.js +56 -0
- package/packages/packager/src/wheel.js +62 -0
- package/packages/spec/src/index.js +11 -0
- package/packages/spec/src/requirements.js +139 -0
- package/packages/transpile/src/ast.js +51 -0
- package/packages/transpile/src/check.js +669 -0
- package/packages/transpile/src/emit-csharp.js +469 -0
- package/packages/transpile/src/emit-go.js +529 -0
- package/packages/transpile/src/emit-java.js +360 -0
- package/packages/transpile/src/emit-python.js +320 -0
- package/packages/transpile/src/emit-rust.js +499 -0
- package/packages/transpile/src/errors.js +15 -0
- package/packages/transpile/src/index.js +13 -0
- package/packages/transpile/src/lexer.js +161 -0
- package/packages/transpile/src/parser.js +543 -0
- package/packages/transpile/src/tests/ast.js +46 -0
- package/packages/transpile/src/tests/parse.js +376 -0
- package/packages/transpile/src/tests/translate.js +849 -0
- package/packages/transpile/src/transpile.js +57 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// @requirement SDKL-HTTP-004
|
|
2
|
+
use sdkruntime::runtime::{Error, Request, SendOptions, StdTransport, Transport};
|
|
3
|
+
use std::io::{BufRead, BufReader, Read, Write};
|
|
4
|
+
use std::net::TcpListener;
|
|
5
|
+
use std::thread;
|
|
6
|
+
use std::time::Duration;
|
|
7
|
+
|
|
8
|
+
/// A one-request-per-connection HTTP server answering by path; returns its base URL.
|
|
9
|
+
fn server() -> String {
|
|
10
|
+
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
11
|
+
let address = listener.local_addr().unwrap();
|
|
12
|
+
thread::spawn(move || {
|
|
13
|
+
for stream in listener.incoming() {
|
|
14
|
+
let mut stream = stream.unwrap();
|
|
15
|
+
thread::spawn(move || {
|
|
16
|
+
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
|
17
|
+
let mut request_line = String::new();
|
|
18
|
+
reader.read_line(&mut request_line).unwrap();
|
|
19
|
+
let mut length = 0;
|
|
20
|
+
let mut test = String::new();
|
|
21
|
+
loop {
|
|
22
|
+
let mut line = String::new();
|
|
23
|
+
reader.read_line(&mut line).unwrap();
|
|
24
|
+
if line.trim().is_empty() {
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
let (name, value) = line.split_once(':').unwrap();
|
|
28
|
+
match name.to_ascii_lowercase().as_str() {
|
|
29
|
+
"content-length" => length = value.trim().parse().unwrap(),
|
|
30
|
+
"x-test" => test = value.trim().to_string(),
|
|
31
|
+
_ => {}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let mut body = vec![0; length];
|
|
35
|
+
reader.read_exact(&mut body).unwrap();
|
|
36
|
+
let parts: Vec<&str> = request_line.split_whitespace().collect();
|
|
37
|
+
let (method, target) = (parts[0], parts[1]);
|
|
38
|
+
let reply = match target {
|
|
39
|
+
"/slow" => {
|
|
40
|
+
thread::sleep(Duration::from_millis(500));
|
|
41
|
+
"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n".to_string()
|
|
42
|
+
}
|
|
43
|
+
"/missing" => "HTTP/1.1 404 Not Found\r\ncontent-length: 16\r\n\r\n{\"message\":\"no\"}".to_string(),
|
|
44
|
+
"/redirect" => "HTTP/1.1 302 Found\r\nlocation: /elsewhere\r\ncontent-length: 0\r\n\r\n".to_string(),
|
|
45
|
+
"/chunked" => "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n4\r\nWiki\r\n5\r\npedia\r\n0\r\n\r\n".to_string(),
|
|
46
|
+
_ => {
|
|
47
|
+
let text = format!("got:{}:{}", target, String::from_utf8_lossy(&body));
|
|
48
|
+
format!("HTTP/1.1 201 Created\r\nx-echo: {}\r\nx-method: {}\r\nx-length: {}\r\ncontent-length: {}\r\n\r\n{}", test, method, length, text.len(), text)
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
let _ = stream.write_all(reply.as_bytes());
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
format!("http://{}", address)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
#[test]
|
|
59
|
+
fn sends_method_headers_and_body() {
|
|
60
|
+
let base = server();
|
|
61
|
+
let request = Request::new("PATCH", &format!("{}/echo", base)).with_header("x-test", "1").with_body(Some(b"hi".to_vec()));
|
|
62
|
+
let response = StdTransport::default().send(&request, &SendOptions::default()).unwrap();
|
|
63
|
+
assert_eq!((response.status, response.header("x-echo").as_deref(), response.header("X-Method").as_deref(), response.text()), (201, Some("1"), Some("PATCH"), "got:/echo:hi".to_string()));
|
|
64
|
+
let empty = StdTransport::default().send(&Request::new("POST", &format!("{}/empty", base)), &SendOptions::default()).unwrap();
|
|
65
|
+
assert_eq!(empty.header("x-length").as_deref(), Some("0"));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
#[test]
|
|
69
|
+
fn error_statuses_redirects_and_chunked_bodies_are_responses() {
|
|
70
|
+
let base = server();
|
|
71
|
+
let transport = StdTransport::default();
|
|
72
|
+
let missing = transport.send(&Request::new("GET", &format!("{}/missing", base)), &SendOptions::default()).unwrap();
|
|
73
|
+
assert_eq!((missing.status, missing.text()), (404, r#"{"message":"no"}"#.to_string()));
|
|
74
|
+
assert_eq!(transport.send(&Request::new("GET", &format!("{}/redirect", base)), &SendOptions::default()).unwrap().status, 302);
|
|
75
|
+
assert_eq!(transport.send(&Request::new("GET", &format!("{}/chunked", base)), &SendOptions::default()).unwrap().text(), "Wikipedia");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
#[test]
|
|
79
|
+
fn reports_timeouts_network_failures_and_https() {
|
|
80
|
+
let base = server();
|
|
81
|
+
let transport = StdTransport::default();
|
|
82
|
+
match transport.send(&Request::new("GET", &format!("{}/slow", base)), &SendOptions { timeout_ms: Some(50), ..SendOptions::default() }) {
|
|
83
|
+
Err(Error::Transport(error)) => assert_eq!(error.reason, "timeout"),
|
|
84
|
+
other => panic!("{:?}", other),
|
|
85
|
+
}
|
|
86
|
+
let closed = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap();
|
|
87
|
+
match transport.send(&Request::new("GET", &format!("http://{}/", closed)), &SendOptions::default()) {
|
|
88
|
+
Err(Error::Transport(error)) => assert_eq!(error.reason, "network"),
|
|
89
|
+
other => panic!("{:?}", other),
|
|
90
|
+
}
|
|
91
|
+
let https = transport.send(&Request::new("GET", "https://example.com/"), &SendOptions::default()).unwrap_err();
|
|
92
|
+
assert!(https.to_string().contains("network"));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
#[test]
|
|
96
|
+
fn routes_requests_through_a_proxy() {
|
|
97
|
+
let base = server();
|
|
98
|
+
let transport = StdTransport { proxy: Some(base) };
|
|
99
|
+
let response = transport.send(&Request::new("GET", "http://api.example.invalid/proxied"), &SendOptions::default()).unwrap();
|
|
100
|
+
assert_eq!(response.text(), "got:http://api.example.invalid/proxied:");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// A server that answers the first request on a connection with `reply` as raw bytes, then closes; returns its URL and
|
|
104
|
+
/// the request it received.
|
|
105
|
+
fn raw_server(reply: &'static [u8]) -> (String, thread::JoinHandle<String>) {
|
|
106
|
+
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
107
|
+
let port = listener.local_addr().unwrap().port();
|
|
108
|
+
let handle = thread::spawn(move || {
|
|
109
|
+
let (mut stream, _) = listener.accept().unwrap();
|
|
110
|
+
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
|
111
|
+
let mut head = String::new();
|
|
112
|
+
loop {
|
|
113
|
+
let mut line = String::new();
|
|
114
|
+
if reader.read_line(&mut line).unwrap() == 0 || line.trim().is_empty() {
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
head.push_str(&line);
|
|
118
|
+
}
|
|
119
|
+
let _ = stream.write_all(reply);
|
|
120
|
+
head
|
|
121
|
+
});
|
|
122
|
+
(format!("http://127.0.0.1:{}", port), handle)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
fn get(url: &str) -> Result<sdkruntime::runtime::Response, Error> {
|
|
126
|
+
StdTransport::default().send(&Request::new("GET", url), &SendOptions { timeout_ms: Some(5000), ..SendOptions::default() })
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#[test]
|
|
130
|
+
fn a_huge_content_length_fails_without_allocating_it() {
|
|
131
|
+
let (url, _) = raw_server(b"HTTP/1.1 200 OK\r\ncontent-length: 900000000000000\r\n\r\nshort");
|
|
132
|
+
|
|
133
|
+
let error = get(&format!("{}/", url)).unwrap_err();
|
|
134
|
+
|
|
135
|
+
assert_eq!(error.name(), "TransportError");
|
|
136
|
+
assert!(error.to_string().contains("ended early"), "{}", error);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
#[test]
|
|
140
|
+
fn head_and_304_responses_have_no_body_and_interim_responses_are_skipped() {
|
|
141
|
+
let (url, _) = raw_server(b"HTTP/1.1 200 OK\r\ncontent-length: 120\r\ntransfer-encoding: chunked\r\n\r\n");
|
|
142
|
+
let head = StdTransport::default().send(&Request::new("HEAD", &format!("{}/", url)), &SendOptions { timeout_ms: Some(5000), ..SendOptions::default() }).unwrap();
|
|
143
|
+
assert_eq!((head.status, head.body.len()), (200, 0));
|
|
144
|
+
|
|
145
|
+
let (url, _) = raw_server(b"HTTP/1.1 304 Not Modified\r\ncontent-length: 50\r\n\r\n");
|
|
146
|
+
assert_eq!(get(&format!("{}/", url)).unwrap().status, 304);
|
|
147
|
+
|
|
148
|
+
let (url, _) = raw_server(b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 201 Created\r\ncontent-length: 2\r\nx-name: caf\xe9\r\n\r\nok");
|
|
149
|
+
let created = get(&format!("{}/", url)).unwrap();
|
|
150
|
+
assert_eq!((created.status, created.text()), (201, "ok".to_string()));
|
|
151
|
+
assert_eq!(created.header("x-name").as_deref(), Some("caf\u{FFFD}"));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
#[test]
|
|
155
|
+
fn ipv6_hosts_and_urls_without_a_path_are_understood() {
|
|
156
|
+
let listener = TcpListener::bind("[::1]:0");
|
|
157
|
+
if let Ok(listener) = listener {
|
|
158
|
+
let port = listener.local_addr().unwrap().port();
|
|
159
|
+
let handle = thread::spawn(move || {
|
|
160
|
+
let (mut stream, _) = listener.accept().unwrap();
|
|
161
|
+
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
|
162
|
+
let mut head = String::new();
|
|
163
|
+
loop {
|
|
164
|
+
let mut line = String::new();
|
|
165
|
+
if reader.read_line(&mut line).unwrap() == 0 || line.trim().is_empty() {
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
head.push_str(&line);
|
|
169
|
+
}
|
|
170
|
+
let _ = stream.write_all(b"HTTP/1.1 204 No Content\r\n\r\n");
|
|
171
|
+
head
|
|
172
|
+
});
|
|
173
|
+
assert_eq!(get(&format!("http://[::1]:{}?x=1", port)).unwrap().status, 204);
|
|
174
|
+
let head = handle.join().unwrap();
|
|
175
|
+
assert!(head.starts_with("GET /?x=1 HTTP/1.1\r\n"), "{}", head);
|
|
176
|
+
assert!(head.contains(&format!("host: [::1]:{}\r\n", port)), "{}", head);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
#[test]
|
|
181
|
+
fn line_breaks_in_headers_are_refused() {
|
|
182
|
+
let request = Request::new("GET", "http://127.0.0.1:1/").with_header("x-a", "1\r\nx-injected: yes");
|
|
183
|
+
|
|
184
|
+
let error = StdTransport::default().send(&request, &SendOptions::default()).unwrap_err();
|
|
185
|
+
|
|
186
|
+
assert!(error.to_string().contains("line break"), "{}", error);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
#[test]
|
|
190
|
+
fn stream_hands_over_a_chunked_body_as_it_arrives_past_the_whole_response_timeout() {
|
|
191
|
+
use sdkruntime::runtime::EventStream;
|
|
192
|
+
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
193
|
+
let address = listener.local_addr().unwrap();
|
|
194
|
+
thread::spawn(move || {
|
|
195
|
+
let (mut stream, _) = listener.accept().unwrap();
|
|
196
|
+
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
|
197
|
+
let mut line = String::new();
|
|
198
|
+
while reader.read_line(&mut line).unwrap() > 0 && line != "\r\n" {
|
|
199
|
+
line.clear();
|
|
200
|
+
}
|
|
201
|
+
stream.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\nb\r\ndata: one\n\n\r\n").unwrap();
|
|
202
|
+
stream.flush().unwrap();
|
|
203
|
+
// Each wait is shorter than the timeout, together they are longer: only a whole-response deadline would end it.
|
|
204
|
+
for _ in 0..3 {
|
|
205
|
+
thread::sleep(Duration::from_millis(100));
|
|
206
|
+
stream.write_all(b"1\r\n:\r\n1\r\n\n\r\n").unwrap();
|
|
207
|
+
stream.flush().unwrap();
|
|
208
|
+
}
|
|
209
|
+
stream.write_all(b"b\r\ndata: two\n\n\r\n0\r\n\r\n").unwrap();
|
|
210
|
+
});
|
|
211
|
+
let response = StdTransport::default()
|
|
212
|
+
.send(&Request::new("GET", &format!("http://{}/events", address)), &SendOptions { timeout_ms: Some(250), stream: true })
|
|
213
|
+
.unwrap();
|
|
214
|
+
let events: Vec<String> = EventStream::text(&response).map(|event| event.unwrap().data).collect();
|
|
215
|
+
|
|
216
|
+
assert_eq!(response.body, Vec::<u8>::new());
|
|
217
|
+
assert_eq!(events, vec!["one".to_string(), "two".to_string()]);
|
|
218
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// @requirement SDKL-WAIT-001
|
|
2
|
+
use sdkruntime::runtime::wait::wait_until;
|
|
3
|
+
use sdkruntime::runtime::{Clock, Error, FakeClock};
|
|
4
|
+
|
|
5
|
+
#[test]
|
|
6
|
+
fn polls_on_the_clock_until_done_and_returns_a_done_result_without_polling() {
|
|
7
|
+
let clock = FakeClock::new(0);
|
|
8
|
+
let mut states = vec!["done", "running", "running"];
|
|
9
|
+
let mut polled = Vec::new();
|
|
10
|
+
let result = wait_until("pending".to_string(), |_| {
|
|
11
|
+
let status = states.pop().unwrap().to_string();
|
|
12
|
+
polled.push(status.clone());
|
|
13
|
+
Ok(status)
|
|
14
|
+
}, |current| current == "done", clock.as_ref(), 500, 10_000).unwrap();
|
|
15
|
+
let immediate = wait_until("done".to_string(), |_| panic!("polled"), |current| current == "done", clock.as_ref(), 500, 10_000).unwrap();
|
|
16
|
+
|
|
17
|
+
assert_eq!((result.as_str(), polled, clock.now()), ("done", vec!["running".to_string(), "running".to_string(), "done".to_string()], 1500));
|
|
18
|
+
assert_eq!(immediate, "done");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
#[test]
|
|
22
|
+
fn fails_with_wait_timeout_when_the_next_poll_would_pass_the_deadline() {
|
|
23
|
+
let clock = FakeClock::new(0);
|
|
24
|
+
let mut polls = 0;
|
|
25
|
+
let error = wait_until("pending".to_string(), |_| {
|
|
26
|
+
polls += 1;
|
|
27
|
+
Ok(format!("running {}", polls))
|
|
28
|
+
}, |_| false, clock.as_ref(), 400, 1000).unwrap_err();
|
|
29
|
+
|
|
30
|
+
assert_eq!(error, Error::WaitTimeout("the work did not finish within 1000 ms".to_string()));
|
|
31
|
+
assert_eq!((error.name(), polls, clock.now()), ("WaitTimeoutError", 2, 800));
|
|
32
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// @requirement SDKL-HOOK-001
|
|
2
|
+
use sdkruntime::runtime::crypto::{hmac_sha256, sha256};
|
|
3
|
+
use sdkruntime::runtime::webhooks::{verify_webhook, WebhookSignature};
|
|
4
|
+
use sdkruntime::runtime::Error;
|
|
5
|
+
|
|
6
|
+
fn hex(bytes: &[u8]) -> String {
|
|
7
|
+
bytes.iter().map(|byte| format!("{:02x}", byte)).collect()
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const STANDARD: WebhookSignature = WebhookSignature {
|
|
11
|
+
header: "webhook-signature",
|
|
12
|
+
encoding: "base64",
|
|
13
|
+
prefix: "v1,",
|
|
14
|
+
separator: Some(" "),
|
|
15
|
+
signed: "{webhook-id}.{webhook-timestamp}.{body}",
|
|
16
|
+
timestamp: Some(("webhook-timestamp", 300)),
|
|
17
|
+
secret: "base64",
|
|
18
|
+
secret_prefix: "whsec_",
|
|
19
|
+
};
|
|
20
|
+
const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
|
|
21
|
+
|
|
22
|
+
fn headers(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
|
|
23
|
+
pairs.iter().map(|(name, value)| (name.to_string(), value.to_string())).collect()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
fn standard_headers() -> Vec<(String, String)> {
|
|
27
|
+
headers(&[("Webhook-Id", "msg_p5jXN8AQM9LWM0D4loKWxJek"), ("webhook-timestamp", "1614265330"), ("webhook-signature", "v1,bad v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=")])
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
#[test]
|
|
31
|
+
fn sha256_and_hmac_match_the_published_test_vectors() {
|
|
32
|
+
assert_eq!(hex(&sha256(b"")), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
|
|
33
|
+
assert_eq!(hex(&sha256(b"abc")), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
|
34
|
+
assert_eq!(hex(&sha256(&[b'a'; 1000])), "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3");
|
|
35
|
+
// RFC 4231 test cases 1, 2 and 6 (a key longer than a block).
|
|
36
|
+
assert_eq!(hex(&hmac_sha256(&[0x0b; 20], b"Hi There")), "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7");
|
|
37
|
+
assert_eq!(hex(&hmac_sha256(b"Jefe", b"what do ya want for nothing?")), "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");
|
|
38
|
+
assert_eq!(hex(&hmac_sha256(&[0xaa; 131], b"Test Using Larger Than Block-Size Key - Hash Key First")), "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
#[test]
|
|
42
|
+
fn verifies_the_standard_webhooks_example() {
|
|
43
|
+
let body = br#"{"test": 2432232314}"#;
|
|
44
|
+
verify_webhook(&STANDARD, body, &standard_headers(), SECRET, 1614265330).unwrap();
|
|
45
|
+
verify_webhook(&STANDARD, body, &standard_headers(), SECRET, 1614265330 + 300).unwrap();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
#[test]
|
|
49
|
+
fn refuses_changes_wrong_secrets_old_timestamps_and_missing_headers() {
|
|
50
|
+
let body = br#"{"test": 2432232314}"#;
|
|
51
|
+
let forged = verify_webhook(&STANDARD, br#"{"test": 3432232314}"#, &standard_headers(), SECRET, 1614265330).unwrap_err();
|
|
52
|
+
assert_eq!(forged, Error::WebhookSignature("no signature matches: the webhook was not signed with this secret, or was changed after signing".to_string()));
|
|
53
|
+
assert_eq!(forged.name(), "WebhookSignatureError");
|
|
54
|
+
assert!(verify_webhook(&STANDARD, body, &standard_headers(), "whsec_AAAA", 1614265330).is_err());
|
|
55
|
+
assert_eq!(
|
|
56
|
+
verify_webhook(&STANDARD, body, &standard_headers(), SECRET, 1614265330 + 301).unwrap_err().to_string(),
|
|
57
|
+
"the webhook was signed at 1614265330, more than 300 s from now"
|
|
58
|
+
);
|
|
59
|
+
assert_eq!(
|
|
60
|
+
verify_webhook(&STANDARD, body, &headers(&[("webhook-signature", "v1,x")]), SECRET, 1614265330).unwrap_err().to_string(),
|
|
61
|
+
"missing or invalid webhook-timestamp header"
|
|
62
|
+
);
|
|
63
|
+
assert_eq!(verify_webhook(&STANDARD, body, &standard_headers(), "whsec_!!!", 1614265330).unwrap_err().to_string(), "the secret is not valid base64");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
#[test]
|
|
67
|
+
fn verifies_a_hex_signature_of_the_body_with_a_text_secret() {
|
|
68
|
+
let github = WebhookSignature { header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=", separator: None, signed: "{body}", timestamp: None, secret: "text", secret_prefix: "" };
|
|
69
|
+
let body = br#"{"zen":"Design for failure."}"#;
|
|
70
|
+
let signature = "sha256=fb962995c1234ec94fb7a13c015a044d2d0ef7e076c0b619d419a8bf068cc218";
|
|
71
|
+
verify_webhook(&github, body, &headers(&[("X-Hub-Signature-256", signature)]), "It is a secret", 0).unwrap();
|
|
72
|
+
assert!(verify_webhook(&github, body, &headers(&[("x-hub-signature-256", &signature.replace("sha256=", "sha1="))]), "It is a secret", 0).is_err());
|
|
73
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// sdkloom TypeScript kit: calling one operation.
|
|
2
|
+
|
|
3
|
+
import { createEmitter, type Clock, type Context, type ContextBase, type EventListener, type SdkInfo, type State } from "./context.ts";
|
|
4
|
+
import { ApiError, type ErrorFactory } from "./errors.ts";
|
|
5
|
+
import { ArgumentError, buildUrl, collectBytes, HttpRequest, type HttpResponse, type QueryScalar, type QueryValue, type RequestBody } from "./http.ts";
|
|
6
|
+
import { encodeJson, type Decoder } from "./models.ts";
|
|
7
|
+
import { encodeMultipart, type MultipartForm } from "./multipart.ts";
|
|
8
|
+
import { runPipeline, type Handler, type Next } from "./pipeline.ts";
|
|
9
|
+
import { decodeEvents, parseEvents } from "./sse.ts";
|
|
10
|
+
import type { SendOptions, Transport } from "./transport.ts";
|
|
11
|
+
|
|
12
|
+
// @block client.call
|
|
13
|
+
// @summary Sends one operation: refuses one newer than the pinned API version, builds URL, headers (with the API version) and body, runs the middleware chain, sends it and turns the response into a result or an error.
|
|
14
|
+
// @versions >=18
|
|
15
|
+
// @source [1] https://www.rfc-editor.org/rfc/rfc9110#section-15.5
|
|
16
|
+
// @quote [1] "The 4xx (Client Error) class of status code indicates that the client seems to have erred."
|
|
17
|
+
// @source [2] https://www.rfc-editor.org/rfc/rfc9110#section-15.6
|
|
18
|
+
// @quote [2] "The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method."
|
|
19
|
+
// @retrieved 2026-12-05
|
|
20
|
+
// @tests tests/client.test.ts
|
|
21
|
+
// @requirement SDKL-ERR-001
|
|
22
|
+
// @requirement SDKL-PIPE-001
|
|
23
|
+
export type Middleware<C> = (request: HttpRequest, next: Next, ctx: Context<C>) => Promise<HttpResponse>;
|
|
24
|
+
|
|
25
|
+
export interface MiddlewareEntry {
|
|
26
|
+
readonly name: string;
|
|
27
|
+
readonly run: (request: HttpRequest, next: Next, base: ContextBase) => Promise<HttpResponse>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Binds a middleware to its configuration. */
|
|
31
|
+
export function entry<C>(name: string, middleware: Middleware<C>, config: C): MiddlewareEntry {
|
|
32
|
+
return { name, run: (request, next, base) => middleware(request, next, { ...base, config }) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type BodyKind = "json" | "bytes" | "stream" | "multipart";
|
|
36
|
+
|
|
37
|
+
/** What a successful response holds: a body kind, or a stream of server-sent events. */
|
|
38
|
+
export type ResultKind = BodyKind | "events";
|
|
39
|
+
|
|
40
|
+
export interface ParamSpec {
|
|
41
|
+
readonly name: string;
|
|
42
|
+
readonly in: "path" | "query" | "header";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface OperationSpec<R> {
|
|
46
|
+
readonly name: string;
|
|
47
|
+
readonly method: string;
|
|
48
|
+
readonly path: string;
|
|
49
|
+
readonly params: readonly ParamSpec[];
|
|
50
|
+
readonly body?: BodyKind;
|
|
51
|
+
readonly result?: ResultKind;
|
|
52
|
+
readonly decode?: Decoder<R>;
|
|
53
|
+
/** For an events result: reads each event's JSON data; without it the data stays text. */
|
|
54
|
+
readonly decodeEvent?: Decoder<unknown>;
|
|
55
|
+
readonly errors: Readonly<Record<number, ErrorFactory>>;
|
|
56
|
+
/** Operation-level middleware names, looked up in the client's registry. */
|
|
57
|
+
readonly use: readonly string[];
|
|
58
|
+
/** The first API version that has the operation. */
|
|
59
|
+
readonly since?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ClientRuntime {
|
|
63
|
+
readonly baseUrl: string;
|
|
64
|
+
readonly transport: Transport;
|
|
65
|
+
readonly middleware: readonly MiddlewareEntry[];
|
|
66
|
+
readonly registry: Readonly<Record<string, MiddlewareEntry>>;
|
|
67
|
+
readonly userMiddleware: readonly MiddlewareEntry[];
|
|
68
|
+
readonly clock: Clock;
|
|
69
|
+
readonly state: State;
|
|
70
|
+
readonly listeners: readonly EventListener[];
|
|
71
|
+
readonly timeoutMs?: number;
|
|
72
|
+
/** Shown to middleware as ctx.sdk; empty name and version when not given. */
|
|
73
|
+
readonly sdk?: SdkInfo;
|
|
74
|
+
/** The API version this client is pinned to, the header that carries it and every version, oldest first. */
|
|
75
|
+
readonly apiVersion?: ApiVersion;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ApiVersion {
|
|
79
|
+
readonly header: string;
|
|
80
|
+
readonly value: string;
|
|
81
|
+
readonly values: readonly string[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Refuses an operation newer than the pinned API version, or a version the SDK does not know. */
|
|
85
|
+
export function checkApiVersion(version: ApiVersion | undefined, operation: string, since: string | undefined): void {
|
|
86
|
+
if (version === undefined) return;
|
|
87
|
+
const pinned = version.values.indexOf(version.value);
|
|
88
|
+
if (pinned < 0) throw new ArgumentError(`unknown API version ${version.value}; this SDK knows ${version.values.join(", ")}`);
|
|
89
|
+
if (since !== undefined && version.values.indexOf(since) > pinned) {
|
|
90
|
+
throw new ArgumentError(`${operation} needs API version ${since} or later; this client uses ${version.value}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const UNKNOWN_SDK: SdkInfo = { name: "", version: "", language: "typescript" };
|
|
95
|
+
|
|
96
|
+
export interface CallOptions {
|
|
97
|
+
readonly timeoutMs?: number;
|
|
98
|
+
readonly signal?: AbortSignal;
|
|
99
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
100
|
+
readonly baseUrl?: string;
|
|
101
|
+
/**
|
|
102
|
+
* Calls this URL instead of the one built from the path and query (the next page a Link header named); a path that
|
|
103
|
+
* starts with "/" is taken from the base URL's origin, any other relative URL is put after the base URL.
|
|
104
|
+
*/
|
|
105
|
+
readonly url?: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A URL from the API (a Link header, say) resolved against the base URL. */
|
|
109
|
+
export function resolveUrl(base: string, url: string): string {
|
|
110
|
+
if (/^https?:\/\//i.test(url)) return url;
|
|
111
|
+
if (url.startsWith("/")) return `${base.replace(/^(https?:\/\/[^/]+).*$/i, "$1")}${url}`;
|
|
112
|
+
return `${base.replace(/\/+$/, "")}/${url}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface RawResult<R> {
|
|
116
|
+
readonly data: R;
|
|
117
|
+
readonly response: HttpResponse;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export type Args = Readonly<Record<string, unknown>>;
|
|
121
|
+
|
|
122
|
+
const JSON_TYPE = "application/json";
|
|
123
|
+
const EVENTS_TYPE = "text/event-stream";
|
|
124
|
+
const BYTES_TYPE = "application/octet-stream";
|
|
125
|
+
const FIRST_SUCCESS = 200;
|
|
126
|
+
const LAST_SUCCESS = 299;
|
|
127
|
+
|
|
128
|
+
async function encodeBody(kind: BodyKind | undefined, value: unknown): Promise<{ content: Uint8Array; type: string } | undefined> {
|
|
129
|
+
if (kind === undefined || value === undefined) return undefined;
|
|
130
|
+
if (kind === "json") return { content: encodeJson(value), type: JSON_TYPE };
|
|
131
|
+
if (kind === "multipart") return encodeMultipart(value as MultipartForm);
|
|
132
|
+
return { content: await collectBytes(value as RequestBody), type: BYTES_TYPE };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function buildRequest(runtime: ClientRuntime, spec: OperationSpec<unknown>, args: Args, options: CallOptions): Promise<HttpRequest> {
|
|
136
|
+
const params = (location: ParamSpec["in"]): readonly ParamSpec[] => spec.params.filter((param) => param.in === location);
|
|
137
|
+
const pathParams = Object.fromEntries(params("path").map((param) => [param.name, args[param.name] as QueryScalar]));
|
|
138
|
+
const query = params("query").map((param): [string, QueryValue] => [param.name, args[param.name] as QueryValue]);
|
|
139
|
+
const headerParams = params("header").flatMap((param): [string, string][] => {
|
|
140
|
+
const value = args[param.name];
|
|
141
|
+
return value === undefined ? [] : [[param.name, String(value)]];
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const body = await encodeBody(spec.body, args["body"]);
|
|
145
|
+
const headers: [string, string][] = [
|
|
146
|
+
["accept", spec.result === "events" ? EVENTS_TYPE : spec.result === "bytes" || spec.result === "stream" ? "*/*" : JSON_TYPE],
|
|
147
|
+
...(body === undefined ? [] : [["content-type", body.type] as [string, string]]),
|
|
148
|
+
...(runtime.apiVersion === undefined ? [] : [[runtime.apiVersion.header, runtime.apiVersion.value] as [string, string]]),
|
|
149
|
+
...headerParams,
|
|
150
|
+
...Object.entries(options.headers ?? {}),
|
|
151
|
+
];
|
|
152
|
+
const base = options.baseUrl ?? runtime.baseUrl;
|
|
153
|
+
const url = options.url === undefined ? buildUrl(base, spec.path, pathParams, query) : resolveUrl(base, options.url);
|
|
154
|
+
return headers.reduce((request, [name, value]) => request.withHeader(name, value), new HttpRequest(spec.method, url, [], body?.content));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function singleChunk(bytes: Uint8Array): Promise<AsyncIterable<Uint8Array>> {
|
|
158
|
+
return (async function* chunks(): AsyncGenerator<Uint8Array> {
|
|
159
|
+
yield bytes;
|
|
160
|
+
})();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function readResult<R>(spec: OperationSpec<R>, response: HttpResponse): Promise<R> {
|
|
164
|
+
switch (spec.result) {
|
|
165
|
+
case "json": {
|
|
166
|
+
const value = await response.json();
|
|
167
|
+
return spec.decode === undefined ? (value as R) : spec.decode(value, "$");
|
|
168
|
+
}
|
|
169
|
+
case "bytes":
|
|
170
|
+
return (await response.bytes()) as R;
|
|
171
|
+
case "stream":
|
|
172
|
+
return (await singleChunk(await response.bytes())) as R;
|
|
173
|
+
case "events":
|
|
174
|
+
return decodeEvents(parseEvents(response.chunks()), spec.decodeEvent) as R;
|
|
175
|
+
default:
|
|
176
|
+
return undefined as R;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function errorFor(spec: OperationSpec<unknown>, response: HttpResponse): Promise<ApiError> {
|
|
181
|
+
let body: unknown;
|
|
182
|
+
try {
|
|
183
|
+
body = await response.json();
|
|
184
|
+
} catch {
|
|
185
|
+
body = await response.text();
|
|
186
|
+
}
|
|
187
|
+
const factory = spec.errors[response.status];
|
|
188
|
+
return factory === undefined ? new ApiError(response.status, body, response) : factory(response.status, body, response);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function lookup(registry: Readonly<Record<string, MiddlewareEntry>>, name: string): MiddlewareEntry {
|
|
192
|
+
const found = registry[name];
|
|
193
|
+
if (found === undefined) throw new Error(`unknown middleware ${name}`);
|
|
194
|
+
return found;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function callOperation<R>(runtime: ClientRuntime, spec: OperationSpec<R>, args: Args, options: CallOptions = {}): Promise<RawResult<R>> {
|
|
198
|
+
checkApiVersion(runtime.apiVersion, spec.name, spec.since);
|
|
199
|
+
const request = await buildRequest(runtime, spec as OperationSpec<unknown>, args, options);
|
|
200
|
+
const timeoutMs = options.timeoutMs ?? runtime.timeoutMs;
|
|
201
|
+
const sendOptions: SendOptions = {
|
|
202
|
+
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
|
203
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
204
|
+
...(spec.result === "events" ? { stream: true } : {}),
|
|
205
|
+
};
|
|
206
|
+
const send: Next = (current) => runtime.transport(current, sendOptions);
|
|
207
|
+
const base: ContextBase = {
|
|
208
|
+
operation: { name: spec.name, method: spec.method, path: spec.path },
|
|
209
|
+
sdk: runtime.sdk ?? UNKNOWN_SDK,
|
|
210
|
+
clock: runtime.clock,
|
|
211
|
+
state: runtime.state,
|
|
212
|
+
emit: createEmitter(runtime.listeners),
|
|
213
|
+
request: (method, url) => new HttpRequest(method, url),
|
|
214
|
+
send,
|
|
215
|
+
};
|
|
216
|
+
const entries = [...runtime.middleware, ...spec.use.map((name) => lookup(runtime.registry, name)), ...runtime.userMiddleware];
|
|
217
|
+
const handlers: Handler[] = entries.map((item) => (current, next) => item.run(current, next, base));
|
|
218
|
+
|
|
219
|
+
const response = await runPipeline(handlers, request, send);
|
|
220
|
+
if (response.status < FIRST_SUCCESS || response.status > LAST_SUCCESS) throw await errorFor(spec as OperationSpec<unknown>, response);
|
|
221
|
+
return { data: await readResult(spec, response), response };
|
|
222
|
+
}
|
|
223
|
+
// @end
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// sdkloom TypeScript kit: the capabilities a middleware receives as ctx.
|
|
2
|
+
|
|
3
|
+
import type { HttpRequest, HttpResponse } from "./http.ts";
|
|
4
|
+
|
|
5
|
+
// @block context.create
|
|
6
|
+
// @summary The capabilities a middleware gets through ctx: clock, per-client state with expiry, and events whose listeners can never break a call.
|
|
7
|
+
// @versions >=18
|
|
8
|
+
// @source [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
|
|
9
|
+
// @quote [1] "The Date.now() static method returns the number of milliseconds elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC."
|
|
10
|
+
// @source [2] https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
|
|
11
|
+
// @quote [2] "The setTimeout() method of the Window interface sets a timer which executes a function or specified piece of code once the timer expires."
|
|
12
|
+
// @source [3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
|
|
13
|
+
// @quote [3] "The Map object holds key-value pairs and remembers the original insertion order of the keys."
|
|
14
|
+
// @retrieved 2026-12-05
|
|
15
|
+
// @tests tests/client.test.ts
|
|
16
|
+
// @requirement SDKL-PIPE-002
|
|
17
|
+
export interface Clock {
|
|
18
|
+
now(): number;
|
|
19
|
+
sleep(ms: number): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const systemClock: Clock = {
|
|
23
|
+
now: () => Date.now(),
|
|
24
|
+
sleep: (ms) =>
|
|
25
|
+
new Promise<void>((resolve) => {
|
|
26
|
+
setTimeout(resolve, ms);
|
|
27
|
+
}),
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export interface State {
|
|
31
|
+
get(key: string): unknown;
|
|
32
|
+
set(key: string, value: unknown, options?: { readonly ttlMs?: number }): void;
|
|
33
|
+
delete(key: string): void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createState(clock: Clock): State {
|
|
37
|
+
const entries = new Map<string, { readonly value: unknown; readonly expiresAt: number | undefined }>();
|
|
38
|
+
return {
|
|
39
|
+
get(key) {
|
|
40
|
+
const entry = entries.get(key);
|
|
41
|
+
if (entry === undefined) return undefined;
|
|
42
|
+
if (entry.expiresAt !== undefined && clock.now() >= entry.expiresAt) {
|
|
43
|
+
entries.delete(key);
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
return entry.value;
|
|
47
|
+
},
|
|
48
|
+
set(key, value, options) {
|
|
49
|
+
entries.set(key, { value, expiresAt: options?.ttlMs === undefined ? undefined : clock.now() + options.ttlMs });
|
|
50
|
+
},
|
|
51
|
+
delete(key) {
|
|
52
|
+
entries.delete(key);
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type EventFields = Readonly<Record<string, unknown>>;
|
|
58
|
+
export type EventListener = (name: string, fields: EventFields) => void;
|
|
59
|
+
|
|
60
|
+
export const LISTENER_ERROR = "sdkloom.listener_error";
|
|
61
|
+
|
|
62
|
+
/** Delivers events to every listener; a listener that throws is reported, never propagated. */
|
|
63
|
+
export function createEmitter(listeners: readonly EventListener[]): (name: string, fields: EventFields) => void {
|
|
64
|
+
const deliver = (name: string, fields: EventFields, skip: EventListener | undefined): void => {
|
|
65
|
+
const failures: { readonly listener: EventListener; readonly error: unknown }[] = [];
|
|
66
|
+
for (const listener of listeners) {
|
|
67
|
+
if (listener === skip) continue;
|
|
68
|
+
try {
|
|
69
|
+
listener(name, fields);
|
|
70
|
+
} catch (error: unknown) {
|
|
71
|
+
failures.push({ listener, error });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (name === LISTENER_ERROR) return;
|
|
75
|
+
failures.forEach(({ listener, error }) =>
|
|
76
|
+
deliver(LISTENER_ERROR, { event: name, error: error instanceof Error ? error.message : String(error) }, listener),
|
|
77
|
+
);
|
|
78
|
+
};
|
|
79
|
+
return (name, fields) => deliver(name, fields, undefined);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface OperationInfo {
|
|
83
|
+
readonly name: string;
|
|
84
|
+
readonly method: string;
|
|
85
|
+
readonly path: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Which generated SDK a middleware runs in, e.g. for a User-Agent such as "acme-python/1.2.0". */
|
|
89
|
+
export interface SdkInfo {
|
|
90
|
+
readonly name: string;
|
|
91
|
+
readonly version: string;
|
|
92
|
+
readonly language: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface Context<C> {
|
|
96
|
+
readonly config: C;
|
|
97
|
+
readonly operation: OperationInfo;
|
|
98
|
+
readonly sdk: SdkInfo;
|
|
99
|
+
readonly clock: Clock;
|
|
100
|
+
readonly state: State;
|
|
101
|
+
emit(name: string, fields: EventFields): void;
|
|
102
|
+
request(method: string, url: string): HttpRequest;
|
|
103
|
+
/** Sends a request straight to the transport, skipping the middleware chain. */
|
|
104
|
+
send(request: HttpRequest): Promise<HttpResponse>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export type ContextBase = Omit<Context<never>, "config">;
|
|
108
|
+
// @end
|