diff --git a/docs/content/docs/web-client/adapters.mdx b/docs/content/docs/web-client/adapters.mdx
index eb074ba53..f93263eef 100644
--- a/docs/content/docs/web-client/adapters.mdx
+++ b/docs/content/docs/web-client/adapters.mdx
@@ -248,6 +248,46 @@ They also need a manifest whose `streams` table is populated, which today means
A channel served by `extensions/streaming` should also pass `decode: forgeStreamingDecoder()`. Its domain frames bind under the default decoder, but its transport frames — presence, typing, join — are reported as unknown messages without it. See [Which field carries the name](/docs/web-client/invalidation#which-field-carries-the-name).
+### Wiring a stream runtime
+
+The runtime opens nothing itself. You hand `SubscriptionManager` a `connect` function that returns an open connection for an endpoint, and one adapter per transport turns what the browser gives you into the connection the manager drives.
+
+```ts
+import {
+ channelMessages,
+ eventSourceConnection,
+ StreamBinder,
+ SubscriptionManager,
+ webSocketConnection,
+ webTransportConnection,
+} from '@forge-go/client-core';
+import { streams } from './generated';
+
+const manager = new SubscriptionManager({
+ connect: ({ endpoint }) => {
+ if (endpoint.startsWith('/sse/')) {
+ // An EventSource delivers a named event only to a listener that asked
+ // for it by name, so the channel's message names come from the table.
+ return eventSourceConnection(new EventSource(endpoint), {
+ events: channelMessages(streams, endpoint),
+ });
+ }
+
+ if (endpoint.startsWith('/wt/')) {
+ return webTransportConnection(new WebTransport(`https://api.example.com${endpoint}`));
+ }
+
+ return webSocketConnection(new WebSocket(`wss://api.example.com${endpoint}`));
+ },
+});
+
+const binder = new StreamBinder({ cache, manager, streams });
+```
+
+`streams` is the generated `streams` table. Its rows are what tell the binder which entity each message carries, what the message does to the cache, and, under a renaming configuration, how to decode the payload before it is normalized. A channel served by `extensions/streaming` passes `decode: forgeStreamingDecoder()` to the binder as well.
+
+The adapters take an already-open transport rather than a URL, so the same code runs wherever the application can construct one, including a server-side test with a fake. An error on an `EventSource` closes it and is reported as a drop, so the manager reconnects with its own backoff and the binder recovers the gap the way it does for a socket.
+
## Guarantees
- **One request per query, not per component.** Two components calling `useQuery(useListOrders)` are one cache entry, one registry mount and one request. They settle together.
diff --git a/docs/content/docs/web-client/invalidation.mdx b/docs/content/docs/web-client/invalidation.mdx
index 85fe5362b..0ec1e8d4a 100644
--- a/docs/content/docs/web-client/invalidation.mdx
+++ b/docs/content/docs/web-client/invalidation.mdx
@@ -98,6 +98,10 @@ A tag naming a specific record needs a value from the request or the response. T
Prefer the explicit forms. A bare `{customerId}` is readable until two of those four sources have one, and then it silently resolves to whichever comes first.
+Name the property as it appears on the wire. A snake_case API declares `Customer:{req.customer_id}`, and the generator renames the placeholder to whatever the client-side field is called under its naming configuration, so the emitted manifest reads `Customer:{req.customerId}` and resolves against the body the caller built and the response the codec decoded. Path and query parameters are the exception: they keep their wire names, because that is the key you pass them under. The runtime also accepts the wire spelling as a fallback, so a hand-written document, or a package generated before the rename existed, still resolves `{req.customer_id}` against a `customerId` field. An exact key always wins.
+
+A collection read resolves its item template once per record returned, so `GET /orders` declaring `Order:{id}` registers `Order:7`, `Order:8` and so on. An empty list resolves to no item tags, which is not a failure.
+
A template that resolves to nothing invalidates nothing and reports nothing — it is the one failure in this system with no symptom at all. `@forge-go/client-devtools` surfaces it as `cause.unresolved`; see [Devtools](/docs/web-client/devtools).
@@ -161,13 +165,15 @@ That declaration produces this, in the AsyncAPI document:
```json
"x-forge-stream": [
- { "message": "order.created", "entityType": "Order", "intent": "upsert", "invalidates": ["Order[]"] },
- { "message": "order.updated", "entityType": "Order", "intent": "patch", "invalidates": null },
- { "message": "order.deleted", "entityType": "Order", "intent": "evict", "invalidates": ["Order[]"] },
- { "message": "order.fulfilled", "entityType": "Order", "intent": "patch", "invalidates": ["Shipment[]"] }
+ { "message": "order.created", "entityType": "Order", "intent": "upsert", "invalidates": ["Order[]"], "type": "github.com/acme/shop.Order" },
+ { "message": "order.updated", "entityType": "Order", "intent": "patch", "invalidates": null, "type": "github.com/acme/shop.Order" },
+ { "message": "order.deleted", "entityType": "Order", "intent": "evict", "invalidates": ["Order[]"], "type": "github.com/acme/shop.Order" },
+ { "message": "order.fulfilled", "entityType": "Order", "intent": "patch", "invalidates": ["Shipment[]"], "type": "github.com/acme/shop.Order" }
]
```
+`entityType` is the Go type's bare name, which is also its component name until something contests it: a second `Order` in another package, a `schema:"..."` pin, a generic instantiation. A component that ended up under another name carries `x-forge-type` naming the Go type it came from, and the generator matches the binding to it on `type`. Nothing in the generated package changes shape; the `streams` table simply names the component the `entities` table holds.
+
`order.updated` costs no request: the payload is an `Order`, the normalizer patches `Order:7`, and every mounted view depending on it re-renders. Only `created` and `deleted` reach the network, and only for the collection.
@@ -182,6 +188,23 @@ Forge parses each one, merges them, and emits a single package where `ops.ts` ca
`WithWebSocketMessages` is what puts message schemas in the AsyncAPI document. Without it the channel is declared but carries no message types, and no WebSocket client is generated for it.
+A WebTransport route is described the same way, with `WithWebTransportMessages` naming a type per way a message travels: a datagram, and the send and receive halves of unidirectional and bidirectional streams. AsyncAPI has no WebTransport binding, so the channel is written with an `x-forge-protocol: webtransport` marker and messages named `datagram`, `uniSend`, `uniReceive`, `bidiSend` and `bidiReceive`. The generated `webtransport.ts` is typed from them, and `WithStreamBinding` on the route lands in the `streams` table exactly as it does for a socket, so a datagram carrying an `Order` takes part in the cache like any frame.
+
+```go
+_ = r.WebTransport("/wt/orders", ordersSession,
+ forge.WithWebTransportMessages(forge.WebTransportMessages{
+ Datagram: &OrderTick{},
+ BidiSend: &OrderCommand{},
+ BidiReceive: &Order{},
+ }),
+ forge.WithStreamBinding(forge.Emits[Order]("order.updated")),
+)
+```
+
+### Frames are decoded before they are normalized
+
+A REST response goes through the generated codec before it reaches the store, so under camelCase naming the store sees `customerId`. A frame now takes the same path: each row in the `streams` table whose entity is a component carries a `decode` built from that entity's codec, and the runtime runs it before normalizing the payload or reading its identity for an evict. Under `preserve` naming the wire shape is the client shape and no `decode` is emitted. A hand-written row without one is written to the store as the wire spelled it.
+
### Which field carries the name
`order.created` is what the binding is keyed on, but a binding matches a frame only if the client can find that name in the envelope — and Forge sends two envelopes.
@@ -212,5 +235,7 @@ It is a superset of the default decoder, not an alternative to it — it reads `
| `WithInvalidates` | `x-forge-invalidates` on the operation | OpenAPI |
| `WithoutInvalidation` | `x-forge-no-invalidation` on the operation | OpenAPI |
| `WithStreamBinding` | `x-forge-stream` on the channel | AsyncAPI |
+| `WithWebTransportMessages` | `x-forge-protocol` on the channel, plus its messages | AsyncAPI |
+| a component renamed at generation | `x-forge-type` on the schema | OpenAPI and AsyncAPI |
All of them round-trip through YAML as well as JSON.
diff --git a/docs/content/docs/web-client/not-yet-shipped.mdx b/docs/content/docs/web-client/not-yet-shipped.mdx
index 7473dac7c..69a459f6d 100644
--- a/docs/content/docs/web-client/not-yet-shipped.mdx
+++ b/docs/content/docs/web-client/not-yet-shipped.mdx
@@ -51,7 +51,9 @@ For balance, everything below is built, tested, and used by the examples in thes
- Optimistic overlays: a rebasing overlay stack, derived targets, and pending state in all three adapters
- React, Vue and Angular adapters
- Server rendering: `dehydrate` and `hydrate`, a reachability-closed payload, principal assertions on both sides, a hydration boundary in all three adapters, and `streamingDehydrator` for flushing a payload part-way through a stream
-- A WebTransport binding, `webTransportConnection`
+- Stream adapters for all three transports: `webSocketConnection`, `eventSourceConnection` and `webTransportConnection` turn an open socket, an `EventSource` or a WebTransport session into the connection the subscription manager drives, and `channelMessages` reads a channel's event names out of the `streams` table
+- WebTransport routes described in the AsyncAPI document through `WithWebTransportMessages`, so `webtransport.ts` is typed per stream kind and the route's stream bindings reach the `streams` table
+- Frames decoded through the entity's codec before normalization, so a live query under camelCase naming sees the same shape a response produces
- The devtools inspector
What is left is a handful of runtime edges and a freshness model that is deliberately narrow, not the core of the thing.
diff --git a/extensions/streaming/contract/manifest_test.go b/extensions/streaming/contract/manifest_test.go
index ee555b6c6..bd9237bff 100644
--- a/extensions/streaming/contract/manifest_test.go
+++ b/extensions/streaming/contract/manifest_test.go
@@ -24,6 +24,15 @@ func TestEmbeddedManifest_LoadsAndValidates(t *testing.T) {
}
}
-func TestRegister_BindsAllIntentsToTheDispatcher(t *testing.T) {
- t.Skip("dispatcher.Dispatcher exercised via unit tests; full Register e2e is covered by the dashboard discovery loop integration test")
-}
+// Register is covered end to end by
+// TestDashboardDiscovery_PublishesStreamingContract in the parent package,
+// which boots a real Forge app with the real dashboard extension and asserts
+// streaming-contract reaches the capabilities endpoint. It lives there rather
+// than here because only a package outside contract/ can import the dashboard
+// extension without a cycle.
+//
+// The distinction matters: the test above stops at loader.Validate, and
+// contract.Registry.Register enforces rules the loader does not. A manifest
+// that loads and validates here can still be rejected at registration, and the
+// dashboard logs that rejection and carries on, so the only visible symptom
+// is streaming-contract missing from /capabilities.
diff --git a/extensions/streaming/dashboard_contract_test.go b/extensions/streaming/dashboard_contract_test.go
new file mode 100644
index 000000000..b0d2834cc
--- /dev/null
+++ b/extensions/streaming/dashboard_contract_test.go
@@ -0,0 +1,113 @@
+package streaming
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/xraph/forge"
+ "github.com/xraph/forge/extensions/dashboard"
+)
+
+// capabilitiesResponse is the shape the dashboard's discovery endpoint serves.
+// Only the fields this test asserts on are modelled.
+type capabilitiesResponse struct {
+ Contributors []struct {
+ Name string `json:"name"`
+ Intents []struct {
+ Name string `json:"name"`
+ } `json:"intents"`
+ } `json:"contributors"`
+}
+
+// TestDashboardDiscovery_PublishesStreamingContract boots a real Forge app with
+// the real dashboard and streaming extensions, lets the dashboard's own
+// auto-discovery loop register streaming's contract contributor, and asks the
+// real capabilities endpoint what it ended up with.
+//
+// This covers a gap that unit-level manifest tests cannot: loader.Load and
+// loader.Validate both accept a manifest that contract.Registry.Register then
+// rejects, and the discovery loop logs that rejection and carries on. The
+// visible symptom is not an error anywhere. It is streaming-contract quietly
+// missing from /capabilities, with none of its intents reachable through the
+// dispatcher. Asserting on the served capabilities is the only assertion that
+// catches it.
+func TestDashboardDiscovery_PublishesStreamingContract(t *testing.T) {
+ app := forge.New(
+ forge.WithAppName("streaming-contract-discovery-test"),
+ forge.WithAppVersion("1.0.0"),
+ forge.WithAppLogger(forge.NewNoopLogger()),
+ forge.WithConfig(forge.DefaultAppConfig()),
+ forge.WithExtensions(NewExtension(), dashboard.NewExtension()),
+ )
+
+ ctx := context.Background()
+ if err := app.Start(ctx); err != nil {
+ t.Fatalf("start app: %v", err)
+ }
+
+ t.Cleanup(func() {
+ if err := app.Stop(context.Background()); err != nil {
+ t.Errorf("stop app: %v", err)
+ }
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/dashboard/api/dashboard/v1/capabilities", nil)
+ w := httptest.NewRecorder()
+ app.Router().ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("capabilities status = %d, body = %s", w.Code, w.Body)
+ }
+
+ var resp capabilitiesResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("unmarshal capabilities %s: %v", w.Body.Bytes(), err)
+ }
+
+ var streamingIntents []string
+
+ names := make([]string, 0, len(resp.Contributors))
+
+ for _, c := range resp.Contributors {
+ names = append(names, c.Name)
+
+ if c.Name != "streaming-contract" {
+ continue
+ }
+
+ for _, in := range c.Intents {
+ streamingIntents = append(streamingIntents, in.Name)
+ }
+ }
+
+ if streamingIntents == nil {
+ t.Fatalf("streaming-contract absent from capabilities; contributors = %v.\n"+
+ "The dashboard swallows contributor registration errors, so this is what a "+
+ "rejected manifest looks like from the outside. Check the dashboard's startup "+
+ "log for \"failed to register contract contributor\".", names)
+ }
+
+ // Every intent the manifest declares has to survive registration, not just
+ // the contributor name. A partial manifest would still produce a
+ // contributor entry here.
+ want := []string{
+ "stats", "connections.list", "rooms.list", "rooms.detail", "rooms.members",
+ "rooms.moderation", "channels.list", "presence.list", "config",
+ "rooms.create", "rooms.delete", "rooms.send-message", "presence.set",
+ "connections.kick",
+ }
+
+ got := make(map[string]bool, len(streamingIntents))
+ for _, in := range streamingIntents {
+ got[in] = true
+ }
+
+ for _, w := range want {
+ if !got[w] {
+ t.Errorf("intent %q missing from streaming-contract capabilities; got %v", w, streamingIntents)
+ }
+ }
+}
diff --git a/extensions/streaming/go.mod b/extensions/streaming/go.mod
index f6000eb7a..47c15c164 100644
--- a/extensions/streaming/go.mod
+++ b/extensions/streaming/go.mod
@@ -14,9 +14,11 @@ require (
require (
github.com/BurntSushi/toml v1.6.0 // indirect
+ github.com/Oudwins/tailwind-merge-go v0.2.1 // indirect
github.com/a-h/templ v0.3.1001 // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
+ github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dunglas/httpsfv v1.1.0 // indirect
@@ -26,6 +28,7 @@ require (
github.com/fxamacker/cbor/v2 v2.9.2 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/go-logr/logr v1.4.4 // indirect
+ github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/jsonpointer v1.0.0 // indirect
github.com/go-openapi/jsonreference v1.0.0 // indirect
github.com/go-openapi/swag v0.28.0 // indirect
@@ -48,6 +51,7 @@ require (
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/google/gnostic-models v0.7.1 // indirect
+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
github.com/hashicorp/consul/api v1.34.4 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
@@ -83,8 +87,15 @@ require (
github.com/xraph/forgeui v1.4.1 // indirect
github.com/xraph/go-utils v1.3.0 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
+ go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
+ go.opentelemetry.io/otel/exporters/jaeger v1.17.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 // indirect
+ go.opentelemetry.io/otel/metric v1.44.0 // indirect
+ go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
+ go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
@@ -96,6 +107,9 @@ require (
golang.org/x/term v0.45.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/time v0.15.0 // indirect
+ google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
+ google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
@@ -106,6 +120,7 @@ require (
k8s.io/klog/v2 v2.140.0 // indirect
k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect
k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3 // indirect
+ nhooyr.io/websocket v1.8.17 // indirect
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
sigs.k8s.io/randfill v1.0.0 // indirect
sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect
diff --git a/extensions/streaming/go.sum b/extensions/streaming/go.sum
index ecd203413..37d5fc691 100644
--- a/extensions/streaming/go.sum
+++ b/extensions/streaming/go.sum
@@ -1,6 +1,8 @@
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
+github.com/Oudwins/tailwind-merge-go v0.2.1 h1:jxRaEqGtwwwF48UuFIQ8g8XT7YSualNuGzCvQ89nPFE=
+github.com/Oudwins/tailwind-merge-go v0.2.1/go.mod h1:kkZodgOPvZQ8f7SIrlWkG/w1g9JTbtnptnePIh3V72U=
github.com/a-h/templ v0.3.1001 h1:yHDTgexACdJttyiyamcTHXr2QkIeVF1MukLy44EAhMY=
github.com/a-h/templ v0.3.1001/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
@@ -19,6 +21,8 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
+github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
@@ -45,6 +49,7 @@ github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
@@ -104,6 +109,8 @@ github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7a
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c=
@@ -115,6 +122,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
github.com/hashicorp/consul/api v1.34.4 h1:0U4YZ1Yp7K9WK9ex0gTJraFim26l02wCvsmf2ukalVE=
github.com/hashicorp/consul/api v1.34.4/go.mod h1:vz5gBNeycefpAAVNVbLBFObUu3isju6EK8UVZjXSTWc=
github.com/hashicorp/consul/sdk v0.18.1 h1:RDTeBvAeOveI2xI86sV+8WkaN7OkP4zz+cG3fOobDCM=
@@ -284,12 +293,22 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
+go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4=
+go.opentelemetry.io/otel/exporters/jaeger v1.17.0/go.mod h1:nPCqOnEH9rNLKqH/+rrUjiMzHJdV1BlpKcTwRTyKkKI=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 h1:3iZJKlCZufyRzPzlQhUIWVmfltrXuGyfjREgGP3UUjc=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0/go.mod h1:/G+nUPfhq2e+qiXMGxMwumDrP5jtzU+mWN7/sjT2rak=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
+go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
+go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
+go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
+go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
@@ -342,6 +361,14 @@ golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
+google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
+google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
+google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI=
google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
@@ -371,6 +398,8 @@ k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3d
k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I=
k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3 h1:jVkFFVfXdXP74B/zbO3hM3hpSFD0xvhQ5U686DPurkE=
k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3/go.mod h1:M2s5JB1lIYP3jzZdorPLHXIPJzt9vv2muW5a6L9DtNM=
+nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y=
+nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c=
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg=
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU=
diff --git a/internal/client/README.md b/internal/client/README.md
index 5d6f5c469..166650615 100644
--- a/internal/client/README.md
+++ b/internal/client/README.md
@@ -506,10 +506,19 @@ follow, and they are one change because either alone is a regression:
reason: the runtime resolves a `provides` template against the decoded
response (`QueryRegistry#settle`), so `Order:{order_number}` would resolve
to nothing, the query would be registered under no item tag, and a later
- write to that order would invalidate nothing. Only the exact tag
- `DeriveTags` builds is rewritten -- a hand-declared template
- (`Shipment:{res.shipment.id}`) names properties of types the manifest
- cannot resolve a namespace for, and is left alone rather than guessed at.
+ write to that order would invalidate nothing. The exact tag `DeriveTags`
+ builds is rewritten by `renameDerivedIDTags`.
+- A HAND-DECLARED template (`Customer:{req.customer_id}`,
+ `Shipment:{res.shipment.external_id}`) is renamed by `renameDeclaredTags`,
+ which walks each dotted segment through the schema graph from the
+ operation's body or response type, so every segment is renamed under the
+ type it belongs to (the same namespace a `FieldOverride` for it is keyed
+ under). Path and query parameters keep their wire names, because the
+ transport substitutes them by that name and that is the key the caller
+ supplies. A segment the schema cannot answer for stops the rewrite there.
+ Before this, a server declaring `WithInvalidates` against a snake_case wire
+ produced a manifest whose templates named nothing the runtime could see,
+ and the tag invalidated nothing.
All of the above are identity under `preserve` with no `FieldOverrides`, so
that configuration emits a byte-identical `ops.ts`.
@@ -526,10 +535,15 @@ that configuration emits a byte-identical `ops.ts`.
- `additionalProperties` declared on an `allOf` composition is dropped by
both the type renderer and the codec table (so it is silently untyped and
unrenamed), though the collision guard still walks it.
-- WebSocket and SSE payload types do not go through the codec at all --
- `types.User` renders camelCase, but a streamed payload is parsed/
- stringified raw, so a streaming consumer reading a renamed field is
- reading a value that was never actually renamed.
+- A stream payload the application handles itself, off the generated
+ `WebSocketClient`/`SSEClient` message handlers, is decoded through the
+ message's codec; the live-query path decodes through the ENTITY's codec,
+ emitted as `decode` on each `streams` row (see writeStreams). The two are
+ the same codec whenever the message payload is the entity. A message whose
+ payload is an envelope around the entity is decoded whole by the class and
+ by the binding's entity codec on the live path, which renames only the
+ entity's own fields; declare the envelope as the message type and bind the
+ entity if both need renaming.
- A media type of `application/json; charset=utf-8` (or any other
parameterized JSON content type) is not recognized by the generator's
spec-side content-type lookups, which match `"application/json"`
diff --git a/internal/client/extension_coverage_test.go b/internal/client/extension_coverage_test.go
index efb764dbd..b1a0efc19 100644
--- a/internal/client/extension_coverage_test.go
+++ b/internal/client/extension_coverage_test.go
@@ -51,6 +51,10 @@ var extensionDecisions = map[string]struct {
"x-forge-envelope": {emitOnly, "read by envelope.go, which distinguishes declared-from-absent itself and has its own refusal cases"},
"x-forge-id": {knownGap, "read in entity.go's isMarkedIdentityField, which takes no *APISpec and is reached through anyMatch. Threading a spec through that call chain is a wider change than the warning is worth today. A wrong type here comes only from a hand-written document, since the generator emits a bool."},
+
+ "x-forge-protocol": {knownGap, "read by isWebTransportChannel; a non-string value is treated as absent and the channel is classified as a socket or SSE stream by its messages, which is what it would have been before the marker existed. The value is generated, never hand-written."},
+
+ "x-forge-type": {knownGap, "read by resolveStreamEntityNames to match a stream binding to a renamed component. A non-string value is treated as absent, and the binding then falls through to the bare-name lookup, whose miss registerStreamBindingEntities already reports; the value is generated, never hand-written."},
}
// extensionNamePattern matches the literal names, wherever they are written.
diff --git a/internal/client/generators/typescript/facades.go b/internal/client/generators/typescript/facades.go
index 98a9bd273..9c5629088 100644
--- a/internal/client/generators/typescript/facades.go
+++ b/internal/client/generators/typescript/facades.go
@@ -183,25 +183,84 @@ func hookFileStems(spec *client.APISpec) []string {
// over an operation whose response nothing describes; it is wrong for a
// generated one, where the response document's typename is already known.
//
-// Only RootType is needed here, and that is the whole difference from
-// mutationTypeArgs. A mutation takes two parameters and refuses to emit either
-// unless it can emit both, because `mutation` leaves the ENTITY as
-// unknown and an optimistic patch checked against unknown accepts every
-// misspelling. A query binding has one parameter, so there is no partial
-// argument list to get wrong: RootType alone is the complete answer.
+// A query needs the complete response payload type. RootType supplies it for
+// normalized object responses. When normalization is explicitly disabled and
+// RootType is empty, the success response schema supplies it instead, including
+// the array wrapper for a top-level array.
//
// The declaredSchema guard is the same one mutationTypeArgs applies, for the
// same reason -- a name types.ts does not export is not a subtly wrong type but
// a client that does not compile -- and an endpoint whose response no component
// describes still emits a bare `query(...)`, exactly as before.
func queryTypeArg(ep *client.Endpoint, spec *client.APISpec, imports map[string]bool) string {
- if !declaredSchema(spec, ep.RootType) {
+ responseType := ep.RootType
+ importType := ep.RootType
+
+ if responseType == "" {
+ responseType, importType = queryResponseType(ep)
+ }
+
+ if !declaredSchema(spec, importType) {
return ""
}
- imports[ep.RootType] = true
+ imports[importType] = true
+
+ return fmt.Sprintf("<%s>", responseType)
+}
+
+// queryResponseType returns the named payload type of the lowest successful
+// JSON response. It is deliberately independent of endpoint cache metadata:
+// WithoutEntity clears RootType so the runtime will not normalize the response,
+// but the response schema still describes the value returned by the hook.
+func queryResponseType(ep *client.Endpoint) (payloadType, importType string) {
+ if ep == nil {
+ return "", ""
+ }
+
+ codes := make([]int, 0, len(ep.Responses))
+ for code := range ep.Responses {
+ if code >= 200 && code < 300 {
+ codes = append(codes, code)
+ }
+ }
+
+ if len(codes) == 0 {
+ return "", ""
+ }
+
+ sort.Ints(codes)
+
+ response := ep.Responses[codes[0]]
+ if response == nil {
+ return "", ""
+ }
+
+ media := response.Content["application/json"]
+ if media == nil || media.Schema == nil {
+ return "", ""
+ }
+
+ schema := media.Schema
+ isArray := false
+
+ if schema.Type == "array" && schema.Items != nil {
+ schema = schema.Items
+ isArray = true
+ }
+
+ if schema.Ref == "" {
+ return "", ""
+ }
+
+ parts := strings.Split(schema.Ref, "/")
+ name := parts[len(parts)-1]
+
+ if isArray {
+ return name + "[]", name
+ }
- return fmt.Sprintf("<%s>", ep.RootType)
+ return name, name
}
// mutationTypeArgs renders the `` a mutation binding carries,
diff --git a/internal/client/generators/typescript/facades_test.go b/internal/client/generators/typescript/facades_test.go
index c31d1cde9..6ec8c3d7c 100644
--- a/internal/client/generators/typescript/facades_test.go
+++ b/internal/client/generators/typescript/facades_test.go
@@ -257,6 +257,74 @@ func TestFacadeTypesMutationBindings(t *testing.T) {
}
}
+func TestFacadeQueryKeepsResponseTypeWhenNormalizationIsDisabled(t *testing.T) {
+ spec := &client.APISpec{
+ Endpoints: []client.Endpoint{{
+ ID: "accessResourcesList",
+ Method: "GET",
+ Path: "/access/resources",
+ Responses: map[int]*client.Response{
+ 200: {
+ Content: map[string]*client.MediaType{
+ "application/json": {Schema: &client.Schema{Ref: "#/components/schemas/ResourceListResponse"}},
+ },
+ },
+ },
+ // WithoutEntity intentionally leaves both cache fields empty. The
+ // response document is still described by the response schema and the
+ // hook must retain that payload type.
+ RootType: "",
+ Entity: nil,
+ }},
+ Schemas: map[string]*client.Schema{
+ "ResourceListResponse": objectSchema(),
+ },
+ }
+
+ out := hooksText(spec, client.GeneratorConfig{Language: "typescript"})
+ for _, want := range []string{
+ "import type { ResourceListResponse } from '../types';",
+ "export const useAccessResourcesList = /*#__PURE__*/ query(op_accessResourcesList);",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("no-entity query lost its response payload type; missing %q:\n%s", want, out)
+ }
+ }
+}
+
+func TestFacadeQueryKeepsArrayResponseShapeWhenNormalizationIsDisabled(t *testing.T) {
+ spec := &client.APISpec{
+ Endpoints: []client.Endpoint{{
+ ID: "accessResourcesList",
+ Method: "GET",
+ Path: "/access/resources",
+ Responses: map[int]*client.Response{
+ 200: {
+ Content: map[string]*client.MediaType{
+ "application/json": {
+ Schema: &client.Schema{
+ Type: "array",
+ Items: &client.Schema{Ref: "#/components/schemas/Resource"},
+ },
+ },
+ },
+ },
+ },
+ }},
+ Schemas: map[string]*client.Schema{"Resource": objectSchema()},
+ }
+
+ out := hooksText(spec, client.GeneratorConfig{Language: "typescript"})
+ for _, want := range []string{
+ "import type { Resource } from '../types';",
+ "export const useAccessResourcesList = /*#__PURE__*/ query(op_accessResourcesList);",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("no-entity array query lost its response shape; missing %q:\n%s", want, out)
+ }
+ }
+}
+
// TestMutationImportMatchesGeneratedTypeName guards against reintroducing a
// PascalCase renderer (toPascal, or anything else) on RootType/Entity.Type.
//
diff --git a/internal/client/generators/typescript/fixtures_test.go b/internal/client/generators/typescript/fixtures_test.go
index f693e1971..e800a748b 100644
--- a/internal/client/generators/typescript/fixtures_test.go
+++ b/internal/client/generators/typescript/fixtures_test.go
@@ -10,7 +10,7 @@ import (
)
func TestGateFixturesCoverKnownDefects(t *testing.T) {
- want := []string{"default", "apiname", "odd-keys", "with-auth", "no-streaming", "no-auth-streaming", "ws-sse", "no-auth-ws-sse", "allof", "preserve", "preserve-ws-sse", "webtransport", "capabilities"}
+ want := []string{"default", "apiname", "odd-keys", "with-auth", "no-streaming", "no-auth-streaming", "ws-sse", "no-auth-ws-sse", "allof", "preserve", "preserve-ws-sse", "webtransport", "ws-multiplexed", "capabilities"}
fixtures := gateFixtures()
@@ -34,10 +34,11 @@ func TestGateFixturesCoverKnownDefects(t *testing.T) {
// grew it to 11 (the "preserve-ws-sse" fixture); task 5c fix round 1
// (coordinator's Important-2 finding) grows it to 12 (the "webtransport"
// fixture below); capability gating grows it to 13 (the "capabilities"
- // fixture) -- this number must move in lockstep with `want` and with
+ // fixture); multiplexed WebSocket generation grows it to 14 (the
+ // "ws-multiplexed" fixture) -- this number must move in lockstep with `want` and with
// gateFixtures' own fixture literal.
- if len(fixtures) != 13 {
- t.Errorf("expected exactly 13 gate fixtures, got %d: %v", len(fixtures), fixtureNames(fixtures))
+ if len(fixtures) != 14 {
+ t.Errorf("expected exactly 14 gate fixtures, got %d: %v", len(fixtures), fixtureNames(fixtures))
}
}
@@ -265,6 +266,9 @@ func gateFixtures() []gateFixture {
// with a BiStreamSchema, one with ONLY a DatagramSchema, coexisting in
// the same generated webtransport.ts.
{Name: "webtransport", Spec: wtMixedEndpointsSpec(), Config: baseConfig()},
+ // A multiplexed socket: two send message types and one receive type,
+ // so the generated `send` takes a union and tsc proves it compiles.
+ {Name: "ws-multiplexed", Spec: wsMultiplexedSpec(), Config: baseConfig()},
// Capability gating: the only fixture whose endpoints declare scopes, and
// therefore the only one for which src/capabilities.ts is emitted at all.
// It earns its place in the corpus twice over -- TestGeneratedClientsTypeCheck
@@ -435,3 +439,26 @@ func generateTo(t *testing.T, f gateFixture) string {
return dir
}
+
+// wsMultiplexedSpec is baseSpec plus one channel that sends two message types
+// and receives one, each a component of its own.
+func wsMultiplexedSpec() *client.APISpec {
+ spec := baseSpec()
+ obj := func(field, typ string) *client.Schema {
+ return &client.Schema{Type: "object", Properties: map[string]*client.Schema{field: {Type: typ}}}
+ }
+ ref := func(name string) *client.Schema { return &client.Schema{Ref: "#/components/schemas/" + name} }
+
+ spec.Schemas["ChatSay"] = obj("text_body", "string")
+ spec.Schemas["ChatTyping"] = obj("is_on", "boolean")
+ spec.Schemas["ChatSaid"] = obj("id", "string")
+ spec.WebSockets = []client.WebSocketEndpoint{{
+ ID: "chat", Path: "/ws/chat", Summary: "Multiplexed chat socket",
+ SendSchema: ref("ChatSay"),
+ ReceiveSchema: ref("ChatSaid"),
+ SendMessages: map[string]*client.Schema{"say": ref("ChatSay"), "typed": ref("ChatTyping")},
+ ReceiveMessages: map[string]*client.Schema{"said": ref("ChatSaid")},
+ }}
+
+ return spec
+}
diff --git a/internal/client/generators/typescript/opsmanifest.go b/internal/client/generators/typescript/opsmanifest.go
index 3db6fc4b9..3d575e47b 100644
--- a/internal/client/generators/typescript/opsmanifest.go
+++ b/internal/client/generators/typescript/opsmanifest.go
@@ -51,9 +51,18 @@ func (g *OpsManifestGenerator) Generate(spec *client.APISpec, config client.Gene
// The type is erased and the table is not: ops.ts names every operation
// anyway, so reading their codecs out of CODECS costs it one import where
// naming each codec module would have cost it hundreds.
+ decodeStreams := needsCodecs && streamsWithCodecs(spec)
+
if needsCodecs {
buf.WriteString("import type { CodecRef } from './codec-runtime';\n")
- buf.WriteString("import { CODECS } from './codecs';\n\n")
+
+ // `decode` only when a stream row will call it, so a client of REST
+ // operations alone emits the import it always has.
+ if decodeStreams {
+ buf.WriteString("import { CODECS, decode } from './codecs';\n\n")
+ } else {
+ buf.WriteString("import { CODECS } from './codecs';\n\n")
+ }
}
buf.WriteString(g.generateMeta(needsCodecs))
@@ -69,7 +78,7 @@ func (g *OpsManifestGenerator) Generate(spec *client.APISpec, config client.Gene
g.writeSecuritySchemes(&buf, spec)
g.writeOps(&buf, spec, config, known, needsCodecs)
g.writeEntities(&buf, rows)
- g.writeStreams(&buf, spec)
+ g.writeStreams(&buf, spec, decodeStreams)
return buf.String()
}
@@ -130,7 +139,14 @@ func (g *OpsManifestGenerator) GenerateModules(
var streamBuf strings.Builder
- g.writeStreams(&streamBuf, spec)
+ // Same gate as ops.ts: the table calls `decode` only when a binding's
+ // entity has a codec to decode through.
+ decodeStreams := needsCodecs && streamsWithCodecs(spec)
+ if decodeStreams {
+ streamBuf.WriteString("import { CODECS, decode } from './codecs';\n\n")
+ }
+
+ g.writeStreams(&streamBuf, spec, decodeStreams)
files["src/stream-bindings.ts"] = endWithNewline(streamBuf.String())
naming := newOpModuleNaming(operationKeys(spec.Endpoints))
@@ -154,7 +170,7 @@ func (g *OpsManifestGenerator) GenerateModules(
buf.WriteString("\n")
buf.WriteString(fmt.Sprintf("export const %s = {\n", naming.consts[i]))
- writeOperationFields(&buf, &spec.Endpoints[i], config, known, needsCodecs, " ", codecConstName)
+ writeOperationFields(&buf, &spec.Endpoints[i], spec, config, known, needsCodecs, " ", codecConstName)
buf.WriteString("} as const satisfies OperationMeta;\n")
files["src/ops/"+naming.files[i]+".ts"] = buf.String()
@@ -529,7 +545,7 @@ func (g *OpsManifestGenerator) writeOps(
for i := range spec.Endpoints {
buf.WriteString(fmt.Sprintf(" %s: {\n", tsKey(keys[i])))
- writeOperationFields(buf, &spec.Endpoints[i], config, known, needsCodecs, " ", tableCodecRef)
+ writeOperationFields(buf, &spec.Endpoints[i], spec, config, known, needsCodecs, " ", tableCodecRef)
buf.WriteString(" },\n")
}
@@ -544,7 +560,7 @@ func (g *OpsManifestGenerator) writeOps(
// differently. They no longer both render it -- only this does, and the table
// now holds a reference -- but the extraction is what made that possible.
func writeOperationFields(
- buf *strings.Builder, ep *client.Endpoint, config client.GeneratorConfig,
+ buf *strings.Builder, ep *client.Endpoint, spec *client.APISpec, config client.GeneratorConfig,
known map[string]bool, needsCodecs bool, indent string, codecRef func(string) string,
) {
buf.WriteString(fmt.Sprintf("%smethod: %s,\n", indent, tsString(ep.Method)))
@@ -568,12 +584,17 @@ func writeOperationFields(
}
// Renamed for the same reason the entities table is: these templates
- // are resolved against a response the codec has already decoded. See
- // renameDerivedIDTags.
- buf.WriteString(fmt.Sprintf("%sprovides: %s,\n", indent,
- tsStringArray(renameDerivedIDTags(ep.CacheTags.Provides, ep.Entity, config))))
- buf.WriteString(fmt.Sprintf("%sinvalidates: %s,\n", indent,
- tsStringArray(renameDerivedIDTags(ep.CacheTags.Invalidates, ep.Entity, config))))
+ // are resolved against a body the caller built in TypeScript and a
+ // response the codec has already decoded. Declared templates are renamed
+ // through the schema graph (renameDeclaredTags); the one template the
+ // generator derives itself is renamed by exact match (renameDerivedIDTags).
+ provides := renameDerivedIDTags(
+ renameDeclaredTags(ep.CacheTags.Provides, ep, spec, config), ep.Entity, config)
+ invalidates := renameDerivedIDTags(
+ renameDeclaredTags(ep.CacheTags.Invalidates, ep, spec, config), ep.Entity, config)
+
+ fmt.Fprintf(buf, "%sprovides: %s,\n", indent, tsStringArray(provides))
+ fmt.Fprintf(buf, "%sinvalidates: %s,\n", indent, tsStringArray(invalidates))
// Unlike provides/invalidates above, which always emit `[]` when
// empty, an unsecured operation drops the field entirely: bundle
@@ -673,8 +694,48 @@ func tsFieldMap(fields map[string]string) string {
return "{ " + strings.Join(parts, ", ") + " }"
}
-// writeStreams emits channel bindings from both WebSocket and SSE endpoints.
-func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.APISpec) {
+// streamsWithCodecs reports whether any stream binding names an entity the
+// codec table can decode: a component schema, whose codec id is its name.
+func streamsWithCodecs(spec *client.APISpec) bool {
+ for _, bindings := range streamBindingSets(spec) {
+ for _, b := range bindings {
+ if spec.Schemas[b.EntityType] != nil {
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
+// streamBindingSets returns every endpoint's bindings, whichever transport
+// carries them.
+func streamBindingSets(spec *client.APISpec) [][]client.StreamBinding {
+ sets := make([][]client.StreamBinding, 0, len(spec.WebSockets)+len(spec.SSEs))
+
+ for i := range spec.WebSockets {
+ sets = append(sets, spec.WebSockets[i].StreamBindings)
+ }
+
+ for i := range spec.SSEs {
+ sets = append(sets, spec.SSEs[i].StreamBindings)
+ }
+
+ for i := range spec.WebTransports {
+ sets = append(sets, spec.WebTransports[i].StreamBindings)
+ }
+
+ return sets
+}
+
+// writeStreams emits channel bindings from WebSocket, SSE and WebTransport endpoints.
+//
+// With decode set, a row whose entity is a component schema carries the
+// entity's codec, so the runtime decodes a frame the way it decodes a
+// response before normalizing it. Without it -- `preserve` naming, or an
+// entity no component describes -- the row is what it always was, and the
+// runtime writes the frame as the wire spelled it.
+func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.APISpec, decode bool) {
type channel struct {
path string
bindings []client.StreamBinding
@@ -712,6 +773,12 @@ func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.A
}
}
+ for i := range spec.WebTransports {
+ if b := spec.WebTransports[i].StreamBindings; len(b) > 0 {
+ channels = append(channels, channel{spec.WebTransports[i].Path, b})
+ }
+ }
+
sort.Slice(channels, func(i, j int) bool { return channels[i].path < channels[j].path })
sort.Slice(duplexes, func(i, j int) bool { return duplexes[i].path < duplexes[j].path })
@@ -726,6 +793,15 @@ func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.A
buf.WriteString(fmt.Sprintf(" entity: %s,\n", tsString(b.EntityType)))
buf.WriteString(fmt.Sprintf(" intent: %s,\n", tsString(string(b.Intent))))
buf.WriteString(fmt.Sprintf(" invalidates: %s,\n", tsStringArray(b.Invalidates)))
+
+ if decode && spec.Schemas[b.EntityType] != nil {
+ // Typed, because the table is `as const` with no contextual
+ // type to infer the parameter from, and an implicit `any`
+ // does not compile under the generated package's strictness.
+ fmt.Fprintf(buf, " decode: (payload: unknown) => decode(payload, %s),\n",
+ tableCodecRef(b.EntityType))
+ }
+
buf.WriteString(" },\n")
}
}
diff --git a/internal/client/generators/typescript/opsmanifest_test.go b/internal/client/generators/typescript/opsmanifest_test.go
index 022dcf8a5..8eaeea470 100644
--- a/internal/client/generators/typescript/opsmanifest_test.go
+++ b/internal/client/generators/typescript/opsmanifest_test.go
@@ -182,3 +182,211 @@ func TestOpsManifestEscapesHostileValues(t *testing.T) {
t.Fatalf("unescaped quote broke out of the string literal\n\n%s", out)
}
}
+
+// declaredTagSpec is an API whose wire is snake_case and whose routes declare
+// cross-entity templates in that wire spelling, exactly as WithInvalidates
+// asks for them on the server: the JSON property name, not the Go field.
+//
+// It exercises every source a template can name. `customer_id` is a body
+// property on the create, a response property on the order, and a path
+// parameter on the fetch; `shop_id` is a query parameter; `external_id` sits
+// one $ref hop into the response.
+func declaredTagSpec() *client.APISpec {
+ order := &client.EntityRef{Type: "Order", IDField: "id"}
+
+ return &client.APISpec{
+ Schemas: map[string]*client.Schema{
+ "Order": {Type: "object", Properties: map[string]*client.Schema{
+ "id": {Type: "string"},
+ "customer_id": {Type: "string"},
+ "customer": {Ref: "#/components/schemas/Customer"},
+ }},
+ "Customer": {Type: "object", Properties: map[string]*client.Schema{
+ "id": {Type: "string"},
+ "external_id": {Type: "string"},
+ }},
+ "CreateOrderRequest": {Type: "object", Properties: map[string]*client.Schema{
+ "customer_id": {Type: "string"},
+ }},
+ },
+ Endpoints: []client.Endpoint{
+ {
+ ID: "orderCreate", Method: "POST", Path: "/orders",
+ Entity: order,
+ QueryParams: []client.Parameter{
+ {Name: "shop_id", In: "query", Schema: &client.Schema{Type: "string"}},
+ },
+ RequestBody: &client.RequestBody{Content: map[string]*client.MediaType{
+ "application/json": {Schema: &client.Schema{Ref: "#/components/schemas/CreateOrderRequest"}},
+ }},
+ Responses: map[int]*client.Response{201: {Content: map[string]*client.MediaType{
+ "application/json": {Schema: &client.Schema{Ref: "#/components/schemas/Order"}},
+ }}},
+ CacheTags: client.TagSet{
+ Provides: []string{"Order:{id}"},
+ Invalidates: []string{
+ "Customer:{req.customer_id}",
+ "Customer:{res.customer_id}",
+ "Customer:{customer_id}",
+ "Ledger:{res.customer.external_id}",
+ "Shop:{req.shop_id}",
+ "Order[]",
+ },
+ },
+ },
+ {
+ ID: "orderFetch", Method: "GET", Path: "/customers/{customer_id}/orders/{id}",
+ Entity: order,
+ PathParams: []client.Parameter{
+ {Name: "customer_id", In: "path", Required: true, Schema: &client.Schema{Type: "string"}},
+ {Name: "id", In: "path", Required: true, Schema: &client.Schema{Type: "string"}},
+ },
+ Responses: map[int]*client.Response{200: {Content: map[string]*client.MediaType{
+ "application/json": {Schema: &client.Schema{Ref: "#/components/schemas/Order"}},
+ }}},
+ CacheTags: client.TagSet{Provides: []string{"Order:{id}", "Customer:{customer_id}"}},
+ },
+ },
+ Entities: map[string]*client.EntityRef{"Order": order},
+ }
+}
+
+// A template names a property of the wire document, because that is what the
+// server-side declaration can see. The runtime resolves it against a body the
+// caller built in TypeScript and a response the codec has already decoded, so
+// under camelCase naming the wire spelling names nothing and the tag
+// silently invalidates nothing. The manifest has to rename the placeholder
+// through the same schema-aware rename the entities table and the derived
+// item tag already go through.
+//
+// Path and query parameters are NOT renamed: the transport substitutes them by
+// their wire name, and that is the key the caller supplies them under.
+func TestOpsManifestRenamesDeclaredTemplatesThroughTheSchema(t *testing.T) {
+ out := manifestText(declaredTagSpec(), client.GeneratorConfig{Language: "typescript"})
+
+ for _, want := range []string{
+ // body property, explicit and bare
+ `'Customer:{req.customerId}'`,
+ `'Customer:{customerId}'`,
+ // response property, explicit
+ `'Customer:{res.customerId}'`,
+ // one $ref hop into the response
+ `'Ledger:{res.customer.externalId}'`,
+ // a query parameter keeps its wire name
+ `'Shop:{req.shop_id}'`,
+ // a path parameter keeps its wire name, even bare
+ `provides: ['Order:{id}', 'Customer:{customer_id}']`,
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("ops.ts missing %q", want)
+ }
+ }
+
+ for _, stale := range []string{
+ `{req.customer_id}`,
+ `{res.customer_id}`,
+ `{res.customer.external_id}`,
+ } {
+ if strings.Contains(out, stale) {
+ t.Errorf("ops.ts still carries wire-cased template %q", stale)
+ }
+ }
+
+ if t.Failed() {
+ t.Logf("\n%s", out)
+ }
+}
+
+// Under preserve the rename is the identity, so the file the generator wrote
+// before this existed is the file it writes now.
+func TestOpsManifestLeavesDeclaredTemplatesAloneUnderPreserve(t *testing.T) {
+ out := manifestText(declaredTagSpec(), client.GeneratorConfig{
+ Language: "typescript", FieldNaming: client.NamingPreserve,
+ })
+
+ for _, want := range []string{
+ `'Customer:{req.customer_id}'`,
+ `'Customer:{res.customer_id}'`,
+ `'Ledger:{res.customer.external_id}'`,
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("ops.ts missing %q\n\n%s", want, out)
+ }
+ }
+}
+
+// streamSpec is one channel emitting Orders, with the Order component present
+// so the entity has a codec to decode through.
+func streamSpec() *client.APISpec {
+ return &client.APISpec{
+ Schemas: map[string]*client.Schema{
+ "Order": {Type: "object", Properties: map[string]*client.Schema{
+ "id": {Type: "string"},
+ "customer_id": {Type: "string"},
+ }},
+ },
+ WebSockets: []client.WebSocketEndpoint{{
+ ID: "orders", Path: "/ws/orders",
+ StreamBindings: []client.StreamBinding{
+ {Message: "order.created", EntityType: "Order", Intent: client.StreamUpsert, Invalidates: []string{"Order[]"}},
+ {Message: "audit.logged", EntityType: "AuditEvent", Intent: client.StreamPatch},
+ },
+ }},
+ Entities: map[string]*client.EntityRef{"Order": {Type: "Order", IDField: "id"}},
+ }
+}
+
+// A frame is normalized against an entities table that names client-side
+// fields, so under a renaming configuration the row has to carry the entity's
+// codec. A binding whose entity no component describes has no codec to carry.
+func TestOpsManifestStreamsDecodeThroughTheEntityCodec(t *testing.T) {
+ out := manifestText(streamSpec(), client.GeneratorConfig{Language: "typescript"})
+
+ for _, want := range []string{
+ "import { CODECS, decode } from './codecs';",
+ "decode: (payload: unknown) => decode(payload, CODECS['Order']),",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("ops.ts missing %q", want)
+ }
+ }
+
+ if strings.Contains(out, "CODECS['AuditEvent']") {
+ t.Errorf("ops.ts decodes an entity no component describes")
+ }
+
+ if t.Failed() {
+ t.Logf("\n%s", out)
+ }
+}
+
+// Under preserve the wire shape is the client shape, and the table is what it
+// was before decode existed.
+func TestOpsManifestStreamsCarryNoDecodeUnderPreserve(t *testing.T) {
+ out := manifestText(streamSpec(), client.GeneratorConfig{
+ Language: "typescript", FieldNaming: client.NamingPreserve,
+ })
+
+ if strings.Contains(out, "decode") {
+ t.Fatalf("ops.ts carries a decode under preserve:\n%s", out)
+ }
+}
+
+// A WebTransport endpoint's bindings reach the streams table like a socket's.
+func TestOpsManifestStreamsIncludeWebTransport(t *testing.T) {
+ spec := streamSpec()
+ spec.WebTransports = []client.WebTransportEndpoint{{
+ ID: "ticks", Path: "/wt/ticks",
+ StreamBindings: []client.StreamBinding{
+ {Message: "order.ticked", EntityType: "Order", Intent: client.StreamPatch},
+ },
+ }}
+
+ out := manifestText(spec, client.GeneratorConfig{})
+
+ for _, want := range []string{"channel: '/wt/ticks'", "message: 'order.ticked'"} {
+ if !strings.Contains(out, want) {
+ t.Errorf("ops.ts missing %q\n\n%s", want, out)
+ }
+ }
+}
diff --git a/internal/client/generators/typescript/tagrename.go b/internal/client/generators/typescript/tagrename.go
new file mode 100644
index 000000000..0a3eeba32
--- /dev/null
+++ b/internal/client/generators/typescript/tagrename.go
@@ -0,0 +1,265 @@
+package typescript
+
+import (
+ "regexp"
+ "strings"
+
+ "github.com/xraph/forge/internal/client"
+)
+
+// placeholderPattern matches one `{...}` placeholder of a cache tag template.
+// The same shape the runtime's resolver reads, so the two agree on what a
+// placeholder is.
+var placeholderPattern = regexp.MustCompile(`\{([^{}]*)\}`)
+
+// renameDeclaredTags rewrites the placeholders of hand-declared tag templates
+// from wire property names to the client-side names the runtime resolves
+// against.
+//
+// A route declares `WithInvalidates("Customer:{req.customer_id}")` naming the
+// JSON property, because that is what the server can see. The runtime resolves
+// that template against a body the caller built in TypeScript and a response
+// the codec has already decoded, both of which carry the CLIENT-side name
+// under FieldNaming. Under the default camelCase that is `customerId`, so the
+// wire spelling names nothing, the template resolves to nothing, and the tag
+// invalidates nothing. The declaration is correct, the manifest is what has to
+// change, and this is the same rename the entities table and the derived item
+// tag already go through -- see renameDerivedIDTags, which handles the one
+// template the generator writes itself and leaves the declared ones to this.
+//
+// Each dotted segment is resolved through the schema graph, one hop at a time,
+// so `{res.customer.external_id}` renames `external_id` under `Customer` --
+// the type the hop landed on, which is also the namespace a FieldOverride for
+// it is keyed under. A segment that names no property of the type reached
+// stops the rewrite there: the rest of the path is left as written, because
+// guessing at it would be inventing a name.
+//
+// Path and query parameters are NOT renamed, in either scope. The transport
+// substitutes them into the URL by their wire name, and that is the key the
+// caller supplies them under, so `{customer_id}` naming a path parameter
+// stays `{customer_id}`. The one thing this cannot settle is a bare placeholder
+// that names both a parameter and a body property under different spellings;
+// the parameter wins here, exactly as it wins at runtime.
+//
+// Under NamingPreserve with no FieldOverrides the rename is the identity, and
+// the input slice is returned as is, so the file the generator wrote before this
+// existed is the file it writes now.
+func renameDeclaredTags(
+ tags []string, ep *client.Endpoint, spec *client.APISpec, config client.GeneratorConfig,
+) []string {
+ if len(tags) == 0 || ep == nil || spec == nil {
+ return tags
+ }
+
+ var out []string
+
+ for i, tag := range tags {
+ renamed := placeholderPattern.ReplaceAllStringFunc(tag, func(match string) string {
+ expr := strings.TrimSpace(match[1 : len(match)-1])
+
+ if next := renamePlaceholder(expr, ep, spec, config); next != expr {
+ return "{" + next + "}"
+ }
+
+ return match
+ })
+
+ if renamed == tag {
+ if out != nil {
+ out[i] = tag
+ }
+
+ continue
+ }
+
+ if out == nil {
+ out = make([]string, len(tags))
+ copy(out, tags[:i])
+ }
+
+ out[i] = renamed
+ }
+
+ if out == nil {
+ return tags
+ }
+
+ return out
+}
+
+// renamePlaceholder renames one placeholder expression, `req.a.b`, `res.a.b`
+// or a bare `a.b`, following the runtime's own lookup order: an explicit scope
+// searches only its side; a bare expression searches the request first and the
+// response second.
+func renamePlaceholder(
+ expr string, ep *client.Endpoint, spec *client.APISpec, config client.GeneratorConfig,
+) string {
+ segments := strings.Split(expr, ".")
+
+ prefix := ""
+ request, response := true, true
+
+ switch segments[0] {
+ case "req":
+ prefix, response = "req.", false
+ segments = segments[1:]
+ case "res":
+ prefix, request = "res.", false
+ segments = segments[1:]
+ }
+
+ if len(segments) == 0 || segments[0] == "" {
+ return expr
+ }
+
+ if request && isParameterName(ep, segments[0]) {
+ return expr
+ }
+
+ root := ""
+
+ if request {
+ root = rootOf(spec, requestBodyRoot(ep), segments[0])
+ }
+
+ if root == "" && response {
+ root = rootOf(spec, responseRoot(ep), segments[0])
+ }
+
+ if root == "" {
+ return expr
+ }
+
+ return prefix + strings.Join(renameSegments(segments, root, spec, config), ".")
+}
+
+// renameSegments walks a dotted path from a named root type, renaming each
+// segment under the type it belongs to and descending into the type the
+// property names. Stops at the first segment the schema cannot answer for and
+// leaves the remainder as written. Numeric segments index an array and pass
+// through unchanged: the element type was already resolved at the hop before.
+func renameSegments(
+ segments []string, root string, spec *client.APISpec, config client.GeneratorConfig,
+) []string {
+ out := make([]string, len(segments))
+ copy(out, segments)
+
+ typ := root
+ props := schemaProperties(spec, spec.Schemas[root])
+
+ for i, segment := range segments {
+ if props == nil {
+ break
+ }
+
+ if isIndex(segment) {
+ continue
+ }
+
+ prop, ok := props[segment]
+ if !ok {
+ break
+ }
+
+ out[i] = tsFieldName(typ, segment, config)
+ typ, props = descend(spec, typ, segment, prop)
+ }
+
+ return out
+}
+
+// descend resolves the type a property lands on: the component a $ref names,
+// the element of an array, or an inline object. The inline case keeps the
+// parent's name qualified by the property, which is the namespace the codec
+// table keys a nested inline shape under.
+func descend(
+ spec *client.APISpec, parent, property string, prop *client.Schema,
+) (string, map[string]*client.Schema) {
+ if prop == nil {
+ return "", nil
+ }
+
+ if name := client.ComponentRefName(prop.Ref); name != "" {
+ return name, schemaProperties(spec, spec.Schemas[name])
+ }
+
+ if prop.Type == "array" && prop.Items != nil {
+ return descend(spec, parent, property, prop.Items)
+ }
+
+ if props := schemaProperties(spec, prop); props != nil {
+ return parent + "." + property, props
+ }
+
+ return "", nil
+}
+
+// rootOf returns root when the named type carries a property called head, and
+// "" otherwise -- the check that decides which side of a bare placeholder the
+// rename follows.
+func rootOf(spec *client.APISpec, root, head string) string {
+ if root == "" {
+ return ""
+ }
+
+ if _, ok := schemaProperties(spec, spec.Schemas[root])[head]; !ok {
+ return ""
+ }
+
+ return root
+}
+
+// requestBodyRoot is the component the JSON request body is, or the element
+// type when it is an array of one. "" when the body has no named type.
+func requestBodyRoot(ep *client.Endpoint) string {
+ id, _ := requestBodyCodecRef(ep)
+
+ return strings.TrimPrefix(id, "[]")
+}
+
+// responseRoot is requestBodyRoot's twin for the success response.
+func responseRoot(ep *client.Endpoint) string {
+ id, _ := responseCodecRef(ep)
+
+ return strings.TrimPrefix(id, "[]")
+}
+
+// schemaProperties is EntityProperties with a nil guard, so a root the schema
+// table does not hold reads as "no properties" rather than a crash.
+func schemaProperties(spec *client.APISpec, schema *client.Schema) map[string]*client.Schema {
+ if schema == nil {
+ return nil
+ }
+
+ return client.EntityProperties(spec, schema)
+}
+
+// isParameterName reports whether the endpoint has a path or query parameter
+// with this exact wire name. Header and cookie parameters are not part of a
+// tag context and are not consulted.
+func isParameterName(ep *client.Endpoint, name string) bool {
+ for _, params := range [][]client.Parameter{ep.PathParams, ep.QueryParams} {
+ for _, p := range params {
+ if p.Name == name {
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
+// isIndex reports whether a segment is an array index: all digits, non-empty.
+func isIndex(segment string) bool {
+ if segment == "" {
+ return false
+ }
+
+ for _, r := range segment {
+ if r < '0' || r > '9' {
+ return false
+ }
+ }
+
+ return true
+}
diff --git a/internal/client/generators/typescript/websocket.go b/internal/client/generators/typescript/websocket.go
index 064a73ccc..817b9b5ec 100644
--- a/internal/client/generators/typescript/websocket.go
+++ b/internal/client/generators/typescript/websocket.go
@@ -277,8 +277,8 @@ func (w *WebSocketGenerator) generateWebSocketClient(ws client.WebSocketEndpoint
var buf strings.Builder
className := w.generateClassName(ws)
- sendType := w.getSchemaTypeName(ws.SendSchema, spec)
- receiveType := w.getSchemaTypeName(ws.ReceiveSchema, spec)
+ sendType := w.directionTypeName(ws.SendMessages, ws.SendSchema, spec)
+ receiveType := w.directionTypeName(ws.ReceiveMessages, ws.ReceiveSchema, spec)
// Codec ids for the send/receive message schemas, resolved only when
// codecsNeeded(config) -- under NamingPreserve with no FieldOverrides
@@ -294,12 +294,12 @@ func (w *WebSocketGenerator) generateWebSocketClient(ws client.WebSocketEndpoint
if needsCodecs {
var warning string
- sendCodecID, warning = messageCodecRef(ws.SendSchema, ws, "send")
+ sendCodecID, warning = directionCodecRef(ws.SendMessages, ws.SendSchema, ws, "send")
if warning != "" {
w.warnings = append(w.warnings, warning)
}
- receiveCodecID, warning = messageCodecRef(ws.ReceiveSchema, ws, "receive")
+ receiveCodecID, warning = directionCodecRef(ws.ReceiveMessages, ws.ReceiveSchema, ws, "receive")
if warning != "" {
w.warnings = append(w.warnings, warning)
}
@@ -809,6 +809,100 @@ func (w *WebSocketGenerator) generateClassName(ws client.WebSocketEndpoint) stri
return "WebSocketClient"
}
+// directionTypeName types one direction of a channel.
+//
+// A multiplexed channel names several messages in one direction, and typing
+// it from a single schema types it from whichever message the parser settled
+// on: the caller's `send` accepts one of the shapes and rejects the others,
+// and `onMessage` promises one shape for frames that carry several. The
+// direction is a union of every distinct named type instead, in sorted order
+// so the file does not churn. With one message, or none named, the single
+// schema is what it always was.
+func (w *WebSocketGenerator) directionTypeName(
+ messages map[string]*client.Schema, single *client.Schema, spec *client.APISpec,
+) string {
+ seen := make(map[string]bool, len(messages))
+ names := make([]string, 0, len(messages))
+
+ for _, name := range sortedSchemaKeys(messages) {
+ typ := w.getSchemaTypeName(messages[name], spec)
+ if seen[typ] {
+ continue
+ }
+
+ seen[typ] = true
+ names = append(names, typ)
+ }
+
+ if len(names) == 0 {
+ return w.getSchemaTypeName(single, spec)
+ }
+
+ return strings.Join(names, " | ")
+}
+
+// directionCodecRef resolves the one codec a direction is encoded or decoded
+// with, following the policy responseCodecRef applies to a set of 2xx
+// responses: every message in the direction has to resolve to the same id,
+// because one call site renames every frame and cannot tell which message a
+// frame is. Messages that agree get that id. Messages that disagree get none,
+// with a warning naming them, rather than a codec that renames some frames
+// by the wrong table. A direction with no named messages falls back to the
+// single schema exactly as before.
+func directionCodecRef(
+ messages map[string]*client.Schema, single *client.Schema, ws client.WebSocketEndpoint, direction string,
+) (id string, warning string) {
+ if len(messages) == 0 {
+ return messageCodecRef(single, ws, direction)
+ }
+
+ ids := make(map[string]bool)
+
+ for _, name := range sortedSchemaKeys(messages) {
+ ref := schemaCodecRef(messages[name])
+ if ref == "" {
+ return "", fmt.Sprintf(
+ "websocket endpoint %q: %s message %q is not a direct $ref (or an array of one) to a named component schema -- frames in this direction are sent/received wire-cased, unrenamed, because one codec cannot be chosen for the direction",
+ wsLabel(ws), direction, name)
+ }
+
+ ids[ref] = true
+ }
+
+ if len(ids) == 1 {
+ for ref := range ids {
+ return ref, ""
+ }
+ }
+
+ return "", fmt.Sprintf(
+ "websocket endpoint %q: %s messages resolve to %d different codecs (%s) -- frames in this direction are sent/received wire-cased, unrenamed, because a single call site cannot tell which message a frame is; the live-query path decodes per binding and is unaffected",
+ wsLabel(ws), direction, len(ids), strings.Join(sortedStringSet(ids), ", "))
+}
+
+// sortedSchemaKeys is the message names of a direction, sorted.
+func sortedSchemaKeys(m map[string]*client.Schema) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+
+ sort.Strings(keys)
+
+ return keys
+}
+
+func sortedStringSet(m map[string]bool) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+
+ sort.Strings(keys)
+
+ return keys
+}
+
// getSchemaTypeName gets the type name for a schema.
func (w *WebSocketGenerator) getSchemaTypeName(schema *client.Schema, spec *client.APISpec) string {
if schema == nil {
diff --git a/internal/client/generators/typescript/websocket_multiplex_test.go b/internal/client/generators/typescript/websocket_multiplex_test.go
new file mode 100644
index 000000000..1ebcde039
--- /dev/null
+++ b/internal/client/generators/typescript/websocket_multiplex_test.go
@@ -0,0 +1,79 @@
+package typescript
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/xraph/forge/internal/client"
+)
+
+// multiplexedSpec is a channel that sends two message types and receives one,
+// with every type a component so each has a codec.
+func multiplexedSpec() *client.APISpec {
+ obj := func(field, typ string) *client.Schema {
+ return &client.Schema{Type: "object", Properties: map[string]*client.Schema{field: {Type: typ}}}
+ }
+ ref := func(name string) *client.Schema { return &client.Schema{Ref: "#/components/schemas/" + name} }
+
+ return &client.APISpec{
+ Schemas: map[string]*client.Schema{
+ "Say": obj("text_body", "string"),
+ "Typing": obj("is_on", "boolean"),
+ "Said": obj("id", "string"),
+ },
+ WebSockets: []client.WebSocketEndpoint{{
+ ID: "chat", Path: "/ws/chat",
+ SendSchema: ref("Say"),
+ ReceiveSchema: ref("Said"),
+ SendMessages: map[string]*client.Schema{"say": ref("Say"), "typed": ref("Typing")},
+ ReceiveMessages: map[string]*client.Schema{"said": ref("Said")},
+ }},
+ }
+}
+
+// A direction carrying several message types is typed as their union, in a
+// fixed order, rather than as whichever message the parser settled on.
+func TestWebSocketDirectionIsTypedAsAUnion(t *testing.T) {
+ out, _ := NewWebSocketGenerator().Generate(multiplexedSpec(), client.GeneratorConfig{Language: "typescript"})
+
+ for _, want := range []string{
+ "async send(message: types.Say | types.Typing): Promise",
+ "sendSync(message: types.Say | types.Typing): void",
+ "onMessage(handler: (message: types.Said) => void): void",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("websocket.ts missing %q", want)
+ }
+ }
+
+ if t.Failed() {
+ t.Logf("\n%s", out)
+ }
+}
+
+// One call site encodes every outgoing frame, so a direction whose messages
+// resolve to different codecs gets none, said out loud; a direction whose
+// messages agree gets the one they agree on.
+func TestWebSocketDirectionCodecFollowsAgreement(t *testing.T) {
+ out, warnings := NewWebSocketGenerator().Generate(multiplexedSpec(), client.GeneratorConfig{Language: "typescript"})
+
+ if strings.Contains(out, `encode(message, "Say")`) || strings.Contains(out, `encode(message, "Typing")`) {
+ t.Errorf("send direction encoded through one of two disagreeing codecs:\n%s", out)
+ }
+
+ if !strings.Contains(out, `decode(JSON.parse(data), "Said")`) {
+ t.Errorf("receive direction, whose one message has a codec, is not decoded:\n%s", out)
+ }
+
+ var named bool
+
+ for _, w := range warnings {
+ if strings.Contains(w, "send messages resolve to 2 different codecs (Say, Typing)") {
+ named = true
+ }
+ }
+
+ if !named {
+ t.Errorf("no warning names the disagreeing send codecs; warnings = %v", warnings)
+ }
+}
diff --git a/internal/client/introspector.go b/internal/client/introspector.go
index 0f05d7a0d..e833a63f1 100644
--- a/internal/client/introspector.go
+++ b/internal/client/introspector.go
@@ -50,6 +50,16 @@ func (i *Introspector) Introspect(ctx context.Context) (*APISpec, error) {
routes := i.router.Routes()
for _, route := range routes {
endpoint := i.routeToEndpoint(route)
+
+ // The same resolution the OpenAPI path runs, over the same
+ // declarations, translated by the same function the document
+ // generator uses. There is no schema here for inference to read,
+ // so only what the route declared -- WithEntity, WithInvalidates,
+ // WithoutInvalidation, WithStaleTime -- can take effect; before
+ // this call none of it did, and the metadata was copied onto the
+ // endpoint and never read.
+ resolveEndpointCacheMeta(spec, &endpoint, router.ClientExtensions(route.Metadata))
+
spec.Endpoints = append(spec.Endpoints, endpoint)
}
}
@@ -247,6 +257,14 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async
// Extract streaming features from known channel patterns
i.extractStreamingFeatures(spec, asyncAPI)
+ // One endpoint per channel, whichever of its operations comes first. A
+ // socket channel carries a send and a receive operation, and converting
+ // it once per operation gave websocket.ts two clients for one path. The
+ // file parser merges the same way; the two paths have to agree.
+ wsSeen := make(map[string]int)
+ sseSeen := make(map[string]bool)
+ wtSeen := make(map[string]bool)
+
// Extract operations and map them to channels, in sorted operation-id
// order -- this appends to spec.WebSockets/spec.SSEs, and the streaming
// generators emit in that order.
@@ -274,14 +292,62 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async
continue
}
+ // A WebTransport channel is marked as such, because AsyncAPI has no
+ // binding for it; the marker is what keeps it from being read as a
+ // socket. One channel carries a send and a receive operation, so it
+ // is converted on the first and skipped on the second.
+ if isWebTransportChannel(channel) {
+ if wtSeen[channelName] {
+ continue
+ }
+
+ wtSeen[channelName] = true
+
+ wt := buildWebTransportEndpoint(spec, opID, channel, i.extractTagNames(channel.Tags), i.convertSchema)
+ spec.WebTransports = append(spec.WebTransports, wt)
+
+ continue
+ }
+
// Determine if this is WebSocket or SSE based on protocol
isWebSocket := i.isWebSocketChannel(asyncAPI, channel)
if isWebSocket {
- ws := i.channelToWebSocket(spec, opID, channel, operation)
- spec.WebSockets = append(spec.WebSockets, ws)
+ if idx, seen := wsSeen[channelName]; seen {
+ // The other direction of a channel already converted: fill
+ // the half this operation describes, if the first left it.
+ existing := &spec.WebSockets[idx]
+ named := operationMessageSchemas(channel, operation, i.convertSchema)
+
+ switch operation.Action {
+ case "send":
+ if existing.SendSchema == nil {
+ existing.SendSchema = i.firstPayload(channel)
+ }
+
+ existing.SendMessages = mergeMessageSchemas(existing.SendMessages, named)
+ case "receive":
+ if existing.ReceiveSchema == nil {
+ existing.ReceiveSchema = i.firstPayload(channel)
+ }
+
+ existing.ReceiveMessages = mergeMessageSchemas(existing.ReceiveMessages, named)
+ }
+
+ continue
+ }
+
+ wsSeen[channelName] = len(spec.WebSockets)
+ spec.WebSockets = append(spec.WebSockets, i.channelToWebSocket(spec, opID, channel, operation))
} else {
- // Treat as SSE
+ // Treat as SSE. channelToSSE reads every message on the channel,
+ // so a second operation has nothing left to add.
+ if sseSeen[channelName] {
+ continue
+ }
+
+ sseSeen[channelName] = true
+
sse := i.channelToSSE(spec, opID, channel, operation)
spec.SSEs = append(spec.SSEs, sse)
}
@@ -290,6 +356,76 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async
return nil
}
+// operationMessageSchemas returns the schemas of the messages one operation
+// names on a channel, keyed by message name. An operation that lists none is
+// read as carrying every message on the channel, which is what the router's
+// generator means when it writes one; a reference to a message the channel
+// does not declare is skipped.
+func operationMessageSchemas(
+ channel *shared.AsyncAPIChannel, operation *shared.AsyncAPIOperation, convert func(*shared.Schema) *Schema,
+) map[string]*Schema {
+ names := make([]string, 0, len(operation.Messages))
+
+ for _, ref := range operation.Messages {
+ if i := strings.LastIndex(ref.Ref, "/"); i >= 0 && i < len(ref.Ref)-1 {
+ names = append(names, ref.Ref[i+1:])
+ }
+ }
+
+ if len(names) == 0 {
+ names = sortedStringKeys(channel.Messages)
+ }
+
+ var out map[string]*Schema
+
+ for _, name := range names {
+ msg := channel.Messages[name]
+ if msg == nil || msg.Payload == nil {
+ continue
+ }
+
+ if out == nil {
+ out = make(map[string]*Schema)
+ }
+
+ out[name] = convert(msg.Payload)
+ }
+
+ return out
+}
+
+// mergeMessageSchemas adds the messages of a second operation in the same
+// direction to those already recorded, keeping the first schema for a name.
+func mergeMessageSchemas(into, add map[string]*Schema) map[string]*Schema {
+ if len(add) == 0 {
+ return into
+ }
+
+ if into == nil {
+ into = make(map[string]*Schema, len(add))
+ }
+
+ for name, schema := range add {
+ if _, ok := into[name]; !ok {
+ into[name] = schema
+ }
+ }
+
+ return into
+}
+
+// firstPayload is the schema of a channel's lowest-named message, which is
+// the one channelToWebSocket's last-write-wins loop settles on as well.
+func (i *Introspector) firstPayload(channel *shared.AsyncAPIChannel) *Schema {
+ for _, name := range sortedStringKeys(channel.Messages) {
+ if msg := channel.Messages[name]; msg != nil && msg.Payload != nil {
+ return i.convertSchema(msg.Payload)
+ }
+ }
+
+ return nil
+}
+
// isStreamingFeatureChannel checks if a channel is a streaming extension feature channel.
func (i *Introspector) isStreamingFeatureChannel(channelName string) bool {
streamingChannels := []string{"rooms", "channels", "presence", "typing"}
@@ -740,12 +876,83 @@ func (i *Introspector) channelToWebSocket(spec *APISpec, opID string, channel *s
}
}
+ switch operation.Action {
+ case "send":
+ ws.SendMessages = operationMessageSchemas(channel, operation, i.convertSchema)
+ case "receive":
+ ws.ReceiveMessages = operationMessageSchemas(channel, operation, i.convertSchema)
+ }
+
ws.StreamBindings = streamBindings(channel.Extensions)
registerStreamBindingEntities(spec, channel.Address, ws.StreamBindings)
return ws
}
+// protocolExtension marks a channel with the protocol it is served over when
+// AsyncAPI has no binding to say so. Written by the router's AsyncAPI generator
+// for WebTransport routes.
+const protocolExtension = "x-forge-protocol"
+
+// isWebTransportChannel reports whether a channel was generated from a
+// WebTransport route.
+func isWebTransportChannel(channel *shared.AsyncAPIChannel) bool {
+ if channel == nil {
+ return false
+ }
+
+ protocol, _ := channel.Extensions[protocolExtension].(string)
+
+ return protocol == "webtransport"
+}
+
+// buildWebTransportEndpoint converts a marked channel into a WebTransport
+// endpoint. Shared by both intermediate-representation builders, with the
+// schema converter of whichever parser is calling, so a live router and a
+// spec file cannot describe the same channel differently.
+//
+// Messages are read by the names the router wrote: `datagram`, `uniSend`,
+// `uniReceive`, `bidiSend`, `bidiReceive`. A stream kind with neither half
+// declared is left nil, which is what the generator reads as "this endpoint
+// does not use that kind".
+func buildWebTransportEndpoint(
+ spec *APISpec, opID string, channel *shared.AsyncAPIChannel, tags []string,
+ convert func(*shared.Schema) *Schema,
+) WebTransportEndpoint {
+ wt := WebTransportEndpoint{
+ ID: opID,
+ Path: channel.Address,
+ Summary: channel.Summary,
+ Description: channel.Description,
+ Tags: tags,
+ Metadata: make(map[string]any),
+ }
+
+ payload := func(name string) *Schema {
+ msg := channel.Messages[name]
+ if msg == nil || msg.Payload == nil {
+ return nil
+ }
+
+ return convert(msg.Payload)
+ }
+
+ wt.DatagramSchema = payload("datagram")
+
+ if send, receive := payload("uniSend"), payload("uniReceive"); send != nil || receive != nil {
+ wt.UniStreamSchema = &StreamSchema{SendSchema: send, ReceiveSchema: receive}
+ }
+
+ if send, receive := payload("bidiSend"), payload("bidiReceive"); send != nil || receive != nil {
+ wt.BiStreamSchema = &StreamSchema{SendSchema: send, ReceiveSchema: receive}
+ }
+
+ wt.StreamBindings = streamBindings(channel.Extensions)
+ registerStreamBindingEntities(spec, channel.Address, wt.StreamBindings)
+
+ return wt
+}
+
// channelToSSE converts an AsyncAPI channel to an SSE endpoint.
func (i *Introspector) channelToSSE(spec *APISpec, opID string, channel *shared.AsyncAPIChannel, operation *shared.AsyncAPIOperation) SSEEndpoint {
sse := SSEEndpoint{
@@ -1069,6 +1276,7 @@ func endpointEntity(
if typ != "" && idField != "" {
validateDeclaredIDField(spec, ep, typ, idField, schema)
+ validateDeclaredType(spec, ep, typ, schema)
return &EntityRef{Type: typ, IDField: idField}, isList
}
@@ -1104,6 +1312,39 @@ func endpointEntity(
return inferCollectionEnvelope(spec, ep.Method, name)
}
+// validateDeclaredType warns when a declared entity names a type that is
+// neither the response's own component nor any component in the document.
+//
+// The declared name becomes the entities-table key, and the response's
+// component name becomes the operation's rootType. The runtime starts
+// normalizing at rootType and descends only through rows it can find, so a
+// declared type that matches no component leaves the response with no row to
+// start from: the cache tags are live, `provides` still resolves, but nothing
+// is ever stored under them, which presents as a cache that quietly does not
+// normalize rather than as an error. A declaration that names some OTHER
+// component is left alone: sharing one cache key between a record and a
+// projection of it is what the option exists for.
+func validateDeclaredType(spec *APISpec, ep *Endpoint, typ string, schema *Schema) {
+ if schema == nil || spec == nil {
+ return
+ }
+
+ response := schemaName(schema)
+ if response == "" || typ == response {
+ return
+ }
+
+ if _, ok := spec.Schemas[typ]; ok {
+ return
+ }
+
+ spec.Warnings = append(spec.Warnings, fmt.Sprintf(
+ "client: %s declares x-forge-entity type %q, but the response is component %q and no"+
+ " component named %q exists; the response will not normalize. Declare Type %q, or"+
+ " implement ForgeEntity on the response type so identity travels with it.",
+ endpointOrigin(ep), typ, response, typ, response))
+}
+
// validateDeclaredIDField warns when a declared entity names an id field the
// response schema does not have.
//
@@ -1385,18 +1626,87 @@ func streamBindings(ext map[string]any) []StreamBinding {
message, _ := entry["message"].(string)
entityType, _ := entry["entityType"].(string)
intent, _ := entry["intent"].(string)
+ goType, _ := entry["type"].(string)
bindings = append(bindings, StreamBinding{
Message: message,
EntityType: entityType,
Intent: StreamIntent(intent),
Invalidates: stringSlice(entry["invalidates"]),
+ Type: goType,
})
}
return bindings
}
+// resolveStreamEntityNames rewrites, in place, each binding whose entity the
+// document carries under a name other than the bare Go type name.
+//
+// Emits[T] records T's bare name, and that is the component name only until
+// finalization contests it: a second type with the same name in another
+// package, a `schema:"..."` pin, a generic instantiation. The document marks
+// such a component with the qualified Go type it was generated from, and the
+// binding carries the same qualified type, so the two are matched here on that
+// and the binding is renamed to the component the generated entity table will
+// actually hold. The derived collection tag `[]` follows; a tag the
+// author declared by hand names whatever the author meant and is left alone.
+//
+// A binding without a qualified type, or one naming a type no component is
+// marked with, is left as written and falls through to the bare-name lookup
+// below, which reports a miss.
+func resolveStreamEntityNames(spec *APISpec, bindings []StreamBinding) {
+ if spec == nil || len(bindings) == 0 {
+ return
+ }
+
+ var byType map[string]string
+
+ for name, schema := range spec.Schemas {
+ if schema == nil {
+ continue
+ }
+
+ typ, ok := schema.Extensions[goTypeExtension].(string)
+ if !ok || typ == "" {
+ continue
+ }
+
+ if byType == nil {
+ byType = make(map[string]string)
+ }
+
+ byType[typ] = name
+ }
+
+ if byType == nil {
+ return
+ }
+
+ for i := range bindings {
+ b := &bindings[i]
+
+ name, ok := byType[b.Type]
+ if !ok || b.Type == "" || name == b.EntityType {
+ continue
+ }
+
+ bare := b.EntityType
+ b.EntityType = name
+
+ for j, tag := range b.Invalidates {
+ if tag == bare+"[]" {
+ b.Invalidates[j] = name + "[]"
+ }
+ }
+ }
+}
+
+// goTypeExtension marks a component schema with the qualified Go type it was
+// generated from, written by the router's schema generator only for a
+// component whose name is not its type's bare name.
+const goTypeExtension = "x-forge-type"
+
// registerStreamBindingEntities registers the entity type named by each
// stream binding into spec.Entities, so the browser runtime knows which JSON
// property identifies a record it receives over that channel.
@@ -1439,6 +1749,8 @@ func streamBindings(ext map[string]any) []StreamBinding {
// carries the channel address and is where its two sibling failure modes are
// reported, so an unnamed type argument is reported the same way.
func registerStreamBindingEntities(spec *APISpec, channelAddress string, bindings []StreamBinding) {
+ resolveStreamEntityNames(spec, bindings)
+
for _, b := range bindings {
if b.EntityType == "" {
spec.Warnings = append(spec.Warnings, fmt.Sprintf(
diff --git a/internal/client/introspector_client_meta_test.go b/internal/client/introspector_client_meta_test.go
index 77ea21d3e..2f9b33eb1 100644
--- a/internal/client/introspector_client_meta_test.go
+++ b/internal/client/introspector_client_meta_test.go
@@ -6,6 +6,7 @@ import (
"strings"
"testing"
+ "github.com/xraph/forge/internal/router"
"github.com/xraph/forge/internal/shared"
)
@@ -802,3 +803,267 @@ func TestInvalidatesIsSilentForAValidList(t *testing.T) {
t.Fatalf("Warnings = %v, want none for a valid list", spec.Warnings)
}
}
+
+// routeTableRouter has no OpenAPI document, so Introspect falls back to the raw
+// route table. The embedded nil router.Router satisfies the rest of the
+// interface; only the three methods Introspect calls are implemented.
+type routeTableRouter struct {
+ router.Router
+
+ routes []router.RouteInfo
+}
+
+func (r routeTableRouter) OpenAPISpec() *router.OpenAPISpec { return nil }
+func (r routeTableRouter) AsyncAPISpec() *router.AsyncAPISpec { return nil }
+func (r routeTableRouter) Routes() []router.RouteInfo { return r.routes }
+
+// A server without OpenAPI still declares its cache contract on its routes,
+// and the fallback path used to copy that metadata onto the endpoint and
+// resolve none of it: entity nil, tags empty, a generated client that never
+// invalidates. The route path has to read the same declarations the
+// document path does.
+func TestIntrospectResolvesCacheMetaFromRawRoutes(t *testing.T) {
+ r := routeTableRouter{routes: []router.RouteInfo{{
+ Method: "POST", Path: "/orders",
+ Metadata: map[string]any{
+ "forge.client.entity": router.EntityDef{Type: "Order", IDField: "id"},
+ "forge.client.invalidates": []string{"Inventory[]"},
+ },
+ }, {
+ Method: "GET", Path: "/orders",
+ Metadata: map[string]any{
+ "forge.client.entity": router.EntityDef{Type: "Order", IDField: "id"},
+ "forge.client.staleTime": int64(30000),
+ },
+ }}}
+
+ spec, err := NewIntrospector(r).Introspect(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(spec.Endpoints) != 2 {
+ t.Fatalf("endpoints = %d, want 2", len(spec.Endpoints))
+ }
+
+ create := spec.Endpoints[0]
+ if create.Entity == nil || create.Entity.Type != "Order" {
+ t.Fatalf("POST entity = %+v, want Order", create.Entity)
+ }
+
+ if !slices.Equal(create.CacheTags.Invalidates, []string{"Inventory[]", "Order[]"}) {
+ t.Fatalf("POST invalidates = %v, want [Inventory[] Order[]]", create.CacheTags.Invalidates)
+ }
+
+ list := spec.Endpoints[1]
+ if list.StaleTime != 30000 {
+ t.Fatalf("GET staleTime = %d, want 30000", list.StaleTime)
+ }
+
+ if _, ok := spec.Entities["Order"]; !ok {
+ t.Fatalf("entities = %v, want Order registered", spec.Entities)
+ }
+}
+
+// A declared type that names no component leaves the response with no
+// entities-table row to start normalizing from. The tags stay live and the
+// cache stores nothing under them, so the only symptom is a warning here.
+func TestDeclaredEntityTypeNamingNoComponentWarns(t *testing.T) {
+ spec := &APISpec{Schemas: map[string]*Schema{"OrderResponse": orderSchema()}}
+ ep := &Endpoint{
+ Method: "GET", Path: "/orders/{id}",
+ Responses: map[int]*Response{200: {Content: map[string]*MediaType{
+ "application/json": {Schema: &Schema{Ref: "#/components/schemas/OrderResponse"}},
+ }}},
+ }
+
+ resolveEndpointCacheMeta(spec, ep, map[string]any{
+ "x-forge-entity": map[string]any{"type": "Order", "idField": "id"},
+ })
+
+ if ep.Entity == nil || ep.Entity.Type != "Order" {
+ t.Fatalf("Entity = %+v, want the declaration honoured", ep.Entity)
+ }
+
+ if len(spec.Warnings) != 1 || !strings.Contains(spec.Warnings[0], `type "Order"`) ||
+ !strings.Contains(spec.Warnings[0], `component "OrderResponse"`) {
+ t.Fatalf("warnings = %v, want one naming both the declared type and the component", spec.Warnings)
+ }
+}
+
+// Naming the response's own component, or another component that exists, is
+// the ordinary use and says nothing.
+func TestDeclaredEntityTypeNamingAComponentIsSilent(t *testing.T) {
+ for _, typ := range []string{"Order", "OrderSummary"} {
+ spec := &APISpec{Schemas: map[string]*Schema{
+ "Order": orderSchema(),
+ "OrderSummary": orderSchema(),
+ }}
+ ep := &Endpoint{
+ Method: "GET", Path: "/orders/{id}",
+ Responses: map[int]*Response{200: {Content: map[string]*MediaType{
+ "application/json": {Schema: &Schema{Ref: "#/components/schemas/Order"}},
+ }}},
+ }
+
+ resolveEndpointCacheMeta(spec, ep, map[string]any{
+ "x-forge-entity": map[string]any{"type": typ, "idField": "id"},
+ })
+
+ if len(spec.Warnings) != 0 {
+ t.Fatalf("type %q: warnings = %v, want none", typ, spec.Warnings)
+ }
+ }
+}
+
+// asyncOnlyRouter serves a prepared AsyncAPI document and nothing else.
+type asyncOnlyRouter struct {
+ router.Router
+
+ async *router.AsyncAPISpec
+}
+
+func (r asyncOnlyRouter) OpenAPISpec() *router.OpenAPISpec { return nil }
+func (r asyncOnlyRouter) AsyncAPISpec() *router.AsyncAPISpec { return r.async }
+func (r asyncOnlyRouter) Routes() []router.RouteInfo { return nil }
+
+// The live-router path reads a WebTransport channel exactly as the file path
+// does; both go through buildWebTransportEndpoint.
+func TestIntrospectReadsAWebTransportChannel(t *testing.T) {
+ order := &shared.Schema{Ref: "#/components/schemas/Order"}
+ doc := &shared.AsyncAPISpec{
+ AsyncAPI: "3.0.0",
+ Info: shared.AsyncAPIInfo{Title: "Orders", Version: "1.0.0"},
+ Channels: map[string]*shared.AsyncAPIChannel{
+ "wt_orders": {
+ Address: "/wt/orders",
+ Messages: map[string]*shared.AsyncAPIMessage{
+ "datagram": {Payload: order},
+ "bidiSend": {Payload: order},
+ "bidiReceive": {Payload: order},
+ },
+ Extensions: map[string]any{
+ "x-forge-protocol": "webtransport",
+ "x-forge-stream": []map[string]any{{
+ "message": "order.created", "entityType": "Order", "intent": "upsert",
+ "invalidates": []string{"Order[]"},
+ }},
+ },
+ },
+ },
+ Operations: map[string]*shared.AsyncAPIOperation{
+ "ordersSend": {Action: "send", Channel: &shared.AsyncAPIChannelReference{Ref: "#/channels/wt_orders"}},
+ "ordersReceive": {Action: "receive", Channel: &shared.AsyncAPIChannelReference{Ref: "#/channels/wt_orders"}},
+ },
+ Components: &shared.AsyncAPIComponents{Schemas: map[string]*shared.Schema{
+ "Order": {Type: "object", Properties: map[string]*shared.Schema{"id": {Type: "string"}}},
+ }},
+ }
+
+ spec, err := NewIntrospector(asyncOnlyRouter{async: doc}).Introspect(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ assertWebTransportEndpoint(t, spec)
+}
+
+// A socket channel carries a send and a receive operation. The file parser
+// merges the two into one endpoint; the live-router path has to as well, or
+// websocket.ts gets two clients for one path.
+func TestIntrospectConvertsAWebSocketChannelOnce(t *testing.T) {
+ order := &shared.Schema{Ref: "#/components/schemas/Order"}
+ doc := &shared.AsyncAPISpec{
+ AsyncAPI: "3.0.0",
+ Info: shared.AsyncAPIInfo{Title: "Orders", Version: "1.0.0"},
+ Servers: map[string]*shared.AsyncAPIServer{
+ "ws": {Host: "localhost", Protocol: "ws"},
+ },
+ Channels: map[string]*shared.AsyncAPIChannel{
+ "ws_orders": {
+ Address: "/ws/orders",
+ Servers: []shared.AsyncAPIServerReference{{Ref: "#/servers/ws"}},
+ Messages: map[string]*shared.AsyncAPIMessage{
+ "send": {Payload: order},
+ "receive": {Payload: order},
+ },
+ },
+ },
+ Operations: map[string]*shared.AsyncAPIOperation{
+ "ordersSend": {Action: "send", Channel: &shared.AsyncAPIChannelReference{Ref: "#/channels/ws_orders"}},
+ "ordersReceive": {Action: "receive", Channel: &shared.AsyncAPIChannelReference{Ref: "#/channels/ws_orders"}},
+ },
+ Components: &shared.AsyncAPIComponents{Schemas: map[string]*shared.Schema{
+ "Order": {Type: "object", Properties: map[string]*shared.Schema{"id": {Type: "string"}}},
+ }},
+ }
+
+ spec, err := NewIntrospector(asyncOnlyRouter{async: doc}).Introspect(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(spec.WebSockets) != 1 {
+ t.Fatalf("WebSockets = %d, want one endpoint for one channel", len(spec.WebSockets))
+ }
+
+ ws := spec.WebSockets[0]
+ if ws.SendSchema == nil || ws.ReceiveSchema == nil {
+ t.Fatalf("endpoint = %+v, want both directions typed from the two operations", ws)
+ }
+}
+
+// A multiplexed channel names several messages in one direction. The
+// endpoint records each by name, per direction, so the generator can type the
+// direction as what it carries rather than as whichever message sorts last.
+func TestIntrospectRecordsEachMessagePerDirection(t *testing.T) {
+ ref := func(name string) *shared.Schema { return &shared.Schema{Ref: "#/components/schemas/" + name} }
+ doc := &shared.AsyncAPISpec{
+ AsyncAPI: "3.0.0",
+ Info: shared.AsyncAPIInfo{Title: "Chat", Version: "1.0.0"},
+ Servers: map[string]*shared.AsyncAPIServer{"ws": {Host: "localhost", Protocol: "ws"}},
+ Channels: map[string]*shared.AsyncAPIChannel{
+ "ws_chat": {
+ Address: "/ws/chat",
+ Servers: []shared.AsyncAPIServerReference{{Ref: "#/servers/ws"}},
+ Messages: map[string]*shared.AsyncAPIMessage{
+ "say": {Payload: ref("Say")},
+ "typed": {Payload: ref("Typing")},
+ "said": {Payload: ref("Said")},
+ },
+ },
+ },
+ Operations: map[string]*shared.AsyncAPIOperation{
+ "chatSend": {Action: "send", Channel: &shared.AsyncAPIChannelReference{Ref: "#/channels/ws_chat"},
+ Messages: []shared.AsyncAPIMessageReference{
+ {Ref: "#/channels/ws_chat/messages/say"}, {Ref: "#/channels/ws_chat/messages/typed"},
+ }},
+ "chatReceive": {Action: "receive", Channel: &shared.AsyncAPIChannelReference{Ref: "#/channels/ws_chat"},
+ Messages: []shared.AsyncAPIMessageReference{{Ref: "#/channels/ws_chat/messages/said"}}},
+ },
+ Components: &shared.AsyncAPIComponents{Schemas: map[string]*shared.Schema{
+ "Say": {Type: "object", Properties: map[string]*shared.Schema{"text": {Type: "string"}}},
+ "Typing": {Type: "object", Properties: map[string]*shared.Schema{"on": {Type: "boolean"}}},
+ "Said": {Type: "object", Properties: map[string]*shared.Schema{"id": {Type: "string"}}},
+ }},
+ }
+
+ spec, err := NewIntrospector(asyncOnlyRouter{async: doc}).Introspect(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(spec.WebSockets) != 1 {
+ t.Fatalf("WebSockets = %d, want 1", len(spec.WebSockets))
+ }
+
+ ws := spec.WebSockets[0]
+
+ if got := sortedStringKeys(ws.SendMessages); !slices.Equal(got, []string{"say", "typed"}) {
+ t.Errorf("SendMessages = %v, want [say typed]", got)
+ }
+
+ if got := sortedStringKeys(ws.ReceiveMessages); !slices.Equal(got, []string{"said"}) {
+ t.Errorf("ReceiveMessages = %v, want [said]", got)
+ }
+}
diff --git a/internal/client/ir.go b/internal/client/ir.go
index 1d6be4480..e4c137a52 100644
--- a/internal/client/ir.go
+++ b/internal/client/ir.go
@@ -300,6 +300,15 @@ type WebSocketEndpoint struct {
// Metadata
Metadata map[string]any
+ // SendMessages and ReceiveMessages hold every message an operation in
+ // that direction names, keyed by message name. SendSchema and
+ // ReceiveSchema above are one schema per direction, which is right for
+ // the ordinary channel with one message each way and wrong for a
+ // multiplexed one: the generator types a direction from these when they
+ // disagree, and from the single schema when they do not.
+ SendMessages map[string]*Schema
+ ReceiveMessages map[string]*Schema
+
// Cache metadata
StreamBindings []StreamBinding
@@ -400,6 +409,11 @@ type WebTransportEndpoint struct {
BiStreamSchema *StreamSchema // Bidirectional streams
DatagramSchema *Schema // Unreliable datagrams
+ // StreamBindings is what each message does to the cache, from the
+ // channel's x-forge-stream extension. A datagram or stream frame is a
+ // mutation the client did not initiate, exactly as a socket frame is.
+ StreamBindings []StreamBinding
+
// Security
Security []SecurityRequirement
@@ -828,4 +842,12 @@ type StreamBinding struct {
EntityType string
Intent StreamIntent
Invalidates []string
+
+ // Type is the fully qualified Go type the binding was declared with,
+ // `github.com/acme/billing.Invoice`, carried by the extension's `type`
+ // field. EntityType is that type's bare name, which is also the component
+ // name until something contests it. When it did, the component the
+ // document carries is marked with the same qualified type, and that is how
+ // the two are matched back up. Empty for a document that did not record it.
+ Type string
}
diff --git a/internal/client/spec_parser.go b/internal/client/spec_parser.go
index 2207e88f6..4cd0bae5f 100644
--- a/internal/client/spec_parser.go
+++ b/internal/client/spec_parser.go
@@ -334,6 +334,7 @@ func (p *SpecParser) parseAsyncAPI(data []byte, isYAML bool) (*APISpec, error) {
// Extract operations and channels
wsEndpoints := make(map[string]*WebSocketEndpoint)
sseEndpoints := make(map[string]*SSEEndpoint)
+ wtEndpoints := make(map[string]*WebTransportEndpoint)
// Sorted operation ids, for the same reason paths are sorted above: this
// loop decides both the order streaming endpoints reach the IR and, where
@@ -357,6 +358,18 @@ func (p *SpecParser) parseAsyncAPI(data []byte, isYAML bool) (*APISpec, error) {
continue
}
+ // Marked, because AsyncAPI has no binding for it. Same rule as the
+ // live-router path: converted once per channel, whichever of its
+ // operations comes first.
+ if isWebTransportChannel(channel) {
+ if wtEndpoints[channelName] == nil {
+ wt := buildWebTransportEndpoint(spec, opID, channel, extractAsyncTagNames(channel.Tags), convertSchema)
+ wtEndpoints[channelName] = &wt
+ }
+
+ continue
+ }
+
// Determine if WebSocket or SSE
isWebSocket := detectWebSocketChannel(&asyncAPISpec, channel)
@@ -368,10 +381,21 @@ func (p *SpecParser) parseAsyncAPI(data []byte, isYAML bool) (*APISpec, error) {
} else {
// Merge with existing endpoint
existing := wsEndpoints[channelName]
- if operation.Action == "send" && existing.SendSchema == nil {
- existing.SendSchema = convertSchemaFromChannel(channel, operation)
- } else if operation.Action == "receive" && existing.ReceiveSchema == nil {
- existing.ReceiveSchema = convertSchemaFromChannel(channel, operation)
+ named := operationMessageSchemas(channel, operation, convertSchema)
+
+ switch operation.Action {
+ case "send":
+ if existing.SendSchema == nil {
+ existing.SendSchema = convertSchemaFromChannel(channel, operation)
+ }
+
+ existing.SendMessages = mergeMessageSchemas(existing.SendMessages, named)
+ case "receive":
+ if existing.ReceiveSchema == nil {
+ existing.ReceiveSchema = convertSchemaFromChannel(channel, operation)
+ }
+
+ existing.ReceiveMessages = mergeMessageSchemas(existing.ReceiveMessages, named)
}
}
} else {
@@ -403,6 +427,10 @@ func (p *SpecParser) parseAsyncAPI(data []byte, isYAML bool) (*APISpec, error) {
spec.SSEs = append(spec.SSEs, *sseEndpoints[name])
}
+ for _, name := range sortedStringKeys(wtEndpoints) {
+ spec.WebTransports = append(spec.WebTransports, *wtEndpoints[name])
+ }
+
return spec, nil
}
@@ -845,6 +873,13 @@ func convertWebSocketChannel(spec *APISpec, opID string, channel *shared.AsyncAP
}
}
+ switch operation.Action {
+ case "send":
+ ws.SendMessages = operationMessageSchemas(channel, operation, convertSchema)
+ case "receive":
+ ws.ReceiveMessages = operationMessageSchemas(channel, operation, convertSchema)
+ }
+
ws.StreamBindings = streamBindings(channel.Extensions)
registerStreamBindingEntities(spec, channel.Address, ws.StreamBindings)
diff --git a/internal/client/spec_parser_stream_entity_test.go b/internal/client/spec_parser_stream_entity_test.go
index 808a09b34..554b015d4 100644
--- a/internal/client/spec_parser_stream_entity_test.go
+++ b/internal/client/spec_parser_stream_entity_test.go
@@ -2,6 +2,7 @@ package client
import (
"context"
+ "slices"
"strings"
"testing"
)
@@ -235,3 +236,224 @@ func TestRegisterStreamBindingEntitiesWarnsOnUnnamedEntityType(t *testing.T) {
t.Fatalf("Warnings = %v, want one naming channel /live/updates and message tick", spec.Warnings)
}
}
+
+// Two Go types named Invoice were qualified apart when the document was
+// generated, and the component carries the qualified type it came from. The
+// binding was declared with the bare name and carries the same qualified type,
+// so it is matched to the component the entity table will hold, and its
+// derived collection tag follows.
+func TestStreamBindingResolvesARenamedComponentByGoType(t *testing.T) {
+ spec := &APISpec{Schemas: map[string]*Schema{
+ "BillingInvoice": {Type: "object",
+ Properties: map[string]*Schema{"id": {Type: "string"}},
+ Extensions: map[string]any{"x-forge-type": "github.com/acme/billing.Invoice"},
+ },
+ "ShippingInvoice": {Type: "object",
+ Properties: map[string]*Schema{"id": {Type: "string"}},
+ Extensions: map[string]any{"x-forge-type": "github.com/acme/shipping.Invoice"},
+ },
+ }}
+
+ bindings := []StreamBinding{
+ {Message: "invoice.created", EntityType: "Invoice", Intent: StreamUpsert,
+ Invalidates: []string{"Invoice[]", "Ledger[]"}, Type: "github.com/acme/shipping.Invoice"},
+ }
+
+ registerStreamBindingEntities(spec, "/ws/shipping", bindings)
+
+ if bindings[0].EntityType != "ShippingInvoice" {
+ t.Fatalf("EntityType = %q, want ShippingInvoice", bindings[0].EntityType)
+ }
+
+ if !slices.Equal(bindings[0].Invalidates, []string{"ShippingInvoice[]", "Ledger[]"}) {
+ t.Fatalf("Invalidates = %v, want the derived tag renamed and the declared one kept", bindings[0].Invalidates)
+ }
+
+ if _, ok := spec.Entities["ShippingInvoice"]; !ok {
+ t.Fatalf("entities = %v, want ShippingInvoice registered", spec.Entities)
+ }
+
+ if len(spec.Warnings) != 0 {
+ t.Fatalf("warnings = %v, want none", spec.Warnings)
+ }
+}
+
+// A binding whose qualified type marks no component keeps its bare name and
+// reports the miss exactly as before.
+func TestStreamBindingWithUnmatchedGoTypeKeepsTheBareName(t *testing.T) {
+ spec := &APISpec{Schemas: map[string]*Schema{
+ "BillingInvoice": {Type: "object",
+ Properties: map[string]*Schema{"id": {Type: "string"}},
+ Extensions: map[string]any{"x-forge-type": "github.com/acme/billing.Invoice"},
+ },
+ }}
+
+ bindings := []StreamBinding{
+ {Message: "invoice.created", EntityType: "Invoice", Intent: StreamUpsert,
+ Invalidates: []string{"Invoice[]"}, Type: "github.com/acme/shipping.Invoice"},
+ }
+
+ registerStreamBindingEntities(spec, "/ws/shipping", bindings)
+
+ if bindings[0].EntityType != "Invoice" {
+ t.Fatalf("EntityType = %q, want Invoice", bindings[0].EntityType)
+ }
+
+ if len(spec.Warnings) != 1 || !strings.Contains(spec.Warnings[0], "no matching schema component") {
+ t.Fatalf("warnings = %v, want the unmatched binding reported", spec.Warnings)
+ }
+}
+
+// The extension's `type` field survives a JSON round trip into the binding.
+func TestStreamBindingsReadTheQualifiedType(t *testing.T) {
+ bindings := streamBindings(map[string]any{"x-forge-stream": []any{map[string]any{
+ "message": "invoice.created",
+ "entityType": "Invoice",
+ "intent": "upsert",
+ "invalidates": []any{"Invoice[]"},
+ "type": "github.com/acme/billing.Invoice",
+ }}})
+
+ if len(bindings) != 1 || bindings[0].Type != "github.com/acme/billing.Invoice" {
+ t.Fatalf("bindings = %+v, want the qualified type carried", bindings)
+ }
+}
+
+// wtChannelDocument is an AsyncAPI document with one WebTransport channel, as
+// the router's generator writes it: marked with its protocol, messages named
+// for how they travel, one operation per direction, and a stream binding.
+func wtChannelDocument() map[string]any {
+ order := map[string]any{"$ref": "#/components/schemas/Order"}
+
+ return map[string]any{
+ "asyncapi": "3.0.0",
+ "info": map[string]any{"title": "Orders", "version": "1.0.0"},
+ "components": map[string]any{
+ "schemas": map[string]any{"Order": orderComponent()},
+ },
+ "channels": map[string]any{
+ "wt_orders": map[string]any{
+ "address": "/wt/orders",
+ "x-forge-protocol": "webtransport",
+ "messages": map[string]any{
+ "datagram": map[string]any{"payload": order},
+ "bidiSend": map[string]any{"payload": order},
+ "bidiReceive": map[string]any{"payload": order},
+ },
+ "x-forge-stream": []any{map[string]any{
+ "message": "order.created", "entityType": "Order", "intent": "upsert",
+ "invalidates": []any{"Order[]"},
+ }},
+ },
+ },
+ "operations": map[string]any{
+ "ordersSend": map[string]any{
+ "action": "send", "channel": map[string]any{"$ref": "#/channels/wt_orders"},
+ },
+ "ordersReceive": map[string]any{
+ "action": "receive", "channel": map[string]any{"$ref": "#/channels/wt_orders"},
+ },
+ },
+ }
+}
+
+// A marked channel is a WebTransport endpoint, converted once for its two
+// operations, typed per stream kind, and carrying its bindings, which is what
+// lets a datagram take part in the cache the way a socket frame does.
+func TestSpecParserReadsAWebTransportChannel(t *testing.T) {
+ spec, err := NewSpecParser().ParseFile(context.Background(), writeSpec(t, wtChannelDocument()))
+ if err != nil {
+ t.Fatalf("ParseFile: %v", err)
+ }
+
+ assertWebTransportEndpoint(t, spec)
+}
+
+func assertWebTransportEndpoint(t *testing.T, spec *APISpec) {
+ t.Helper()
+
+ if len(spec.WebSockets) != 0 || len(spec.SSEs) != 0 {
+ t.Fatalf("marked channel was read as a socket or SSE stream: ws=%d sse=%d", len(spec.WebSockets), len(spec.SSEs))
+ }
+
+ if len(spec.WebTransports) != 1 {
+ t.Fatalf("WebTransports = %d, want the one channel converted once", len(spec.WebTransports))
+ }
+
+ wt := spec.WebTransports[0]
+
+ if wt.Path != "/wt/orders" || wt.DatagramSchema == nil || wt.BiStreamSchema == nil ||
+ wt.BiStreamSchema.SendSchema == nil || wt.BiStreamSchema.ReceiveSchema == nil {
+ t.Fatalf("endpoint = %+v, want datagram and both bidi halves typed", wt)
+ }
+
+ if wt.UniStreamSchema != nil {
+ t.Fatalf("UniStreamSchema = %+v, want nil for an undeclared kind", wt.UniStreamSchema)
+ }
+
+ if len(wt.StreamBindings) != 1 || wt.StreamBindings[0].EntityType != "Order" {
+ t.Fatalf("StreamBindings = %+v, want the Order binding", wt.StreamBindings)
+ }
+
+ if _, ok := spec.Entities["Order"]; !ok {
+ t.Fatalf("entities = %v, want Order registered from the binding", spec.Entities)
+ }
+}
+
+// The file path records the same per-direction messages the live path does.
+func TestSpecParserRecordsEachMessagePerDirection(t *testing.T) {
+ ref := func(name string) map[string]any { return map[string]any{"$ref": "#/components/schemas/" + name} }
+ path := writeSpec(t, map[string]any{
+ "asyncapi": "3.0.0",
+ "info": map[string]any{"title": "Chat", "version": "1.0.0"},
+ "servers": map[string]any{"ws": map[string]any{"host": "localhost", "protocol": "ws"}},
+ "components": map[string]any{"schemas": map[string]any{
+ "Say": map[string]any{"type": "object", "properties": map[string]any{"text": map[string]any{"type": "string"}}},
+ "Typing": map[string]any{"type": "object", "properties": map[string]any{"on": map[string]any{"type": "boolean"}}},
+ "Said": map[string]any{"type": "object", "properties": map[string]any{"id": map[string]any{"type": "string"}}},
+ }},
+ "channels": map[string]any{
+ "ws_chat": map[string]any{
+ "address": "/ws/chat",
+ "servers": []any{map[string]any{"$ref": "#/servers/ws"}},
+ "messages": map[string]any{
+ "say": map[string]any{"payload": ref("Say")},
+ "typed": map[string]any{"payload": ref("Typing")},
+ "said": map[string]any{"payload": ref("Said")},
+ },
+ },
+ },
+ "operations": map[string]any{
+ "chatSend": map[string]any{
+ "action": "send", "channel": map[string]any{"$ref": "#/channels/ws_chat"},
+ "messages": []any{
+ map[string]any{"$ref": "#/channels/ws_chat/messages/say"},
+ map[string]any{"$ref": "#/channels/ws_chat/messages/typed"},
+ },
+ },
+ "chatReceive": map[string]any{
+ "action": "receive", "channel": map[string]any{"$ref": "#/channels/ws_chat"},
+ "messages": []any{map[string]any{"$ref": "#/channels/ws_chat/messages/said"}},
+ },
+ },
+ })
+
+ spec, err := NewSpecParser().ParseFile(context.Background(), path)
+ if err != nil {
+ t.Fatalf("ParseFile: %v", err)
+ }
+
+ if len(spec.WebSockets) != 1 {
+ t.Fatalf("WebSockets = %d, want 1", len(spec.WebSockets))
+ }
+
+ ws := spec.WebSockets[0]
+
+ if got := sortedStringKeys(ws.SendMessages); !slices.Equal(got, []string{"say", "typed"}) {
+ t.Errorf("SendMessages = %v, want [say typed]", got)
+ }
+
+ if got := sortedStringKeys(ws.ReceiveMessages); !slices.Equal(got, []string{"said"}) {
+ t.Errorf("ReceiveMessages = %v, want [said]", got)
+ }
+}
diff --git a/internal/client/stripprefix.go b/internal/client/stripprefix.go
index cd5788f72..eae117951 100644
--- a/internal/client/stripprefix.go
+++ b/internal/client/stripprefix.go
@@ -460,6 +460,7 @@ func applyRenames(spec *APISpec, rename map[string]string, prefixes []string) {
wt := &spec.WebTransports[i]
wt.ID = trimAny(wt.ID, prefixes)
+ wt.StreamBindings = renameBindings(wt.StreamBindings, rename, prefixes)
}
}
diff --git a/internal/router/asyncapi_client_meta_test.go b/internal/router/asyncapi_client_meta_test.go
index 00752a331..885b3629f 100644
--- a/internal/router/asyncapi_client_meta_test.go
+++ b/internal/router/asyncapi_client_meta_test.go
@@ -2,8 +2,11 @@
package router
import (
+ "reflect"
"testing"
+ "github.com/xraph/forge/internal/router/testtypes/billing"
+ "github.com/xraph/forge/internal/router/testtypes/shipping"
"github.com/xraph/forge/internal/shared"
)
@@ -157,3 +160,124 @@ func TestWebSocketChannelWithoutStreamBindingsGetsNoExtension(t *testing.T) {
t.Fatalf("Extensions = %#v, want nil for a route with no stream bindings", channel.Extensions)
}
}
+
+// A binding carries the qualified Go type it was declared with, so the client
+// generator can find the component when finalization gave it a name other
+// than the bare one. Two channels emit two types that share the bare name
+// Invoice; each binding names its own.
+func TestStreamBindingCarriesTheQualifiedGoType(t *testing.T) {
+ router := NewRouter()
+
+ if err := router.WebSocket("/ws/billing", func(ctx Context, conn Connection) error { return nil },
+ WithWebSocketMessages(billing.Invoice{}, billing.Invoice{}),
+ WithStreamBinding(Emits[billing.Invoice]("invoice.created")),
+ ); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := router.WebSocket("/ws/shipping", func(ctx Context, conn Connection) error { return nil },
+ WithWebSocketMessages(shipping.Invoice{}, shipping.Invoice{}),
+ WithStreamBinding(Emits[shipping.Invoice]("invoice.created")),
+ ); err != nil {
+ t.Fatal(err)
+ }
+
+ spec, err := newAsyncAPIGenerator(shared.AsyncAPIConfig{Title: "T", Version: "1.0.0"}, router).Generate()
+ if err != nil {
+ t.Fatalf("Generate() error: %v", err)
+ }
+
+ for path, want := range map[string]reflect.Type{
+ "/ws/billing": reflect.TypeFor[billing.Invoice](),
+ "/ws/shipping": reflect.TypeFor[shipping.Invoice](),
+ } {
+ channel := findChannelByAddress(spec, path)
+ if channel == nil {
+ t.Fatalf("%s: channel not found", path)
+ }
+
+ stream, _ := channel.Extensions["x-forge-stream"].([]map[string]any)
+ if len(stream) != 1 {
+ t.Fatalf("%s: x-forge-stream = %#v, want one entry", path, channel.Extensions)
+ }
+
+ if stream[0]["entityType"] != "Invoice" {
+ t.Errorf("%s: entityType = %v, want the bare name Invoice", path, stream[0]["entityType"])
+ }
+
+ if stream[0]["type"] != getQualifiedTypeName(want) {
+ t.Errorf("%s: type = %v, want %q", path, stream[0]["type"], getQualifiedTypeName(want))
+ }
+ }
+}
+
+// A WebTransport route reaches the AsyncAPI document as a channel marked with
+// its protocol, its messages named for how each travels, its operations split
+// by direction, and its stream bindings alongside -- which is what lets the
+// client generator build a WebTransport client that takes part in the cache.
+func TestWebTransportChannelIsDescribedWithItsBindings(t *testing.T) {
+ router := NewRouter()
+
+ var handler WebTransportHandler
+
+ if err := router.WebTransport("/wt/orders", handler,
+ WithWebTransportMessages(WebTransportMessages{
+ Datagram: testOrder{},
+ BidiSend: ChatMessage{},
+ BidiReceive: testOrder{},
+ }),
+ WithName("orders-wt"),
+ WithStreamBinding(Emits[testOrder]("order.created")),
+ ); err != nil {
+ t.Fatalf("register: %v", err)
+ }
+
+ spec, err := newAsyncAPIGenerator(shared.AsyncAPIConfig{Title: "T", Version: "1.0.0"}, router).Generate()
+ if err != nil {
+ t.Fatalf("Generate() error: %v", err)
+ }
+
+ channel := findChannelByAddress(spec, "/wt/orders")
+ if channel == nil {
+ t.Fatal("webtransport channel not found")
+ }
+
+ if channel.Extensions["x-forge-protocol"] != "webtransport" {
+ t.Errorf("x-forge-protocol = %v, want webtransport", channel.Extensions["x-forge-protocol"])
+ }
+
+ for _, name := range []string{"datagram", "bidiSend", "bidiReceive"} {
+ if channel.Messages[name] == nil {
+ t.Errorf("message %q missing; have %v", name, channel.Messages)
+ }
+ }
+
+ if channel.Messages["uniSend"] != nil {
+ t.Errorf("an undeclared kind was written: %v", channel.Messages["uniSend"])
+ }
+
+ stream, _ := channel.Extensions["x-forge-stream"].([]map[string]any)
+ if len(stream) != 1 || stream[0]["entityType"] != "testOrder" {
+ t.Errorf("x-forge-stream = %#v, want one testOrder binding", channel.Extensions["x-forge-stream"])
+ }
+
+ var send, receive int
+
+ for _, op := range spec.Operations {
+ if op.Channel == nil || op.Channel.Ref != "#/channels/"+"wt_orders" && op.Channel.Ref != "#/channels/"+pathToChannelID("/wt/orders") {
+ continue
+ }
+
+ switch op.Action {
+ case "send":
+ send = len(op.Messages)
+ case "receive":
+ receive = len(op.Messages)
+ }
+ }
+
+ // datagram + bidiSend one way, datagram + bidiReceive the other.
+ if send != 2 || receive != 2 {
+ t.Errorf("send/receive message counts = %d/%d, want 2/2; operations: %v", send, receive, spec.Operations)
+ }
+}
diff --git a/internal/router/asyncapi_generator.go b/internal/router/asyncapi_generator.go
index 3d39610af..01b443211 100644
--- a/internal/router/asyncapi_generator.go
+++ b/internal/router/asyncapi_generator.go
@@ -169,6 +169,10 @@ func (g *asyncAPIGenerator) processRoute(spec *AsyncAPISpec, route RouteInfo) er
if err := g.processSSERoute(spec, route); err != nil {
return err
}
+ case "webtransport":
+ if err := g.processWebTransportRoute(spec, route); err != nil {
+ return err
+ }
default:
// Not a streaming route, skip
return nil
@@ -192,6 +196,10 @@ func (g *asyncAPIGenerator) getRouteType(route RouteInfo) string {
return "sse"
}
+ if _, ok := route.Metadata["asyncapi.wt.messages"]; ok {
+ return "webtransport"
+ }
+
// Kind is the typed replacement for the "route.type" metadata string.
// String() returns the same values that string carried, so the channel
// classification below is unchanged.
@@ -416,6 +424,124 @@ func (g *asyncAPIGenerator) processSSERoute(spec *AsyncAPISpec, route RouteInfo)
return nil
}
+// webTransportMessageKinds is every way a WebTransport message can travel, in
+// the order the document lists them. The name is the message key in the
+// channel; the title decorates the component id.
+var webTransportMessageKinds = []struct {
+ name, title string
+ pick func(WebTransportMessages) any
+ send bool
+ receive bool
+}{
+ {"datagram", "Datagram", func(m WebTransportMessages) any { return m.Datagram }, true, true},
+ {"uniSend", "UniSend", func(m WebTransportMessages) any { return m.UniSend }, true, false},
+ {"uniReceive", "UniReceive", func(m WebTransportMessages) any { return m.UniReceive }, false, true},
+ {"bidiSend", "BidiSend", func(m WebTransportMessages) any { return m.BidiSend }, true, false},
+ {"bidiReceive", "BidiReceive", func(m WebTransportMessages) any { return m.BidiReceive }, false, true},
+}
+
+// processWebTransportRoute writes a WebTransport route as a channel.
+//
+// AsyncAPI has no WebTransport binding, so the channel carries an
+// x-forge-protocol marker and its messages are named for the way each is
+// carried. The client generator reads the marker to build a WebTransport
+// client rather than a WebSocket one, and the names to type each stream kind.
+// Stream bindings ride on the channel exactly as they do for a socket.
+func (g *asyncAPIGenerator) processWebTransportRoute(spec *AsyncAPISpec, route RouteInfo) error {
+ channelID := g.getChannelID(route)
+
+ channel := &AsyncAPIChannel{
+ Address: createChannelAddress(route.Path),
+ Title: route.Summary,
+ Description: route.Description,
+ Parameters: extractChannelParameters(route.Path),
+ Tags: g.getAsyncAPITags(route),
+ }
+
+ if desc, ok := route.Metadata["asyncapi.channel.description"].(string); ok {
+ channel.Description = desc
+ }
+
+ if summary, ok := route.Metadata["asyncapi.channel.summary"].(string); ok {
+ channel.Summary = summary
+ }
+
+ applyForgeStreamExtension(channel, route.Metadata)
+
+ if channel.Extensions == nil {
+ channel.Extensions = make(map[string]any)
+ }
+
+ channel.Extensions["x-forge-protocol"] = "webtransport"
+
+ declared, _ := route.Metadata["asyncapi.wt.messages"].(WebTransportMessages)
+ messages := make(map[string]*AsyncAPIMessage)
+
+ var sendRefs, receiveRefs []AsyncAPIMessageReference
+
+ for _, kind := range webTransportMessageKinds {
+ schema := kind.pick(declared)
+ if schema == nil {
+ continue
+ }
+
+ msg, err := g.schemas.GenerateMessageSchema(schema, g.config.DefaultContentType)
+ if err != nil {
+ return err
+ }
+
+ if msg == nil {
+ continue
+ }
+
+ msg.Name = kind.name
+ msg.Title = kind.title + " message"
+ messages[kind.name] = msg
+ spec.Components.Messages[channelID+kind.title+"Message"] = msg
+
+ ref := AsyncAPIMessageReference{Ref: "#/channels/" + channelID + "/messages/" + kind.name}
+
+ if kind.send {
+ sendRefs = append(sendRefs, ref)
+ }
+
+ if kind.receive {
+ receiveRefs = append(receiveRefs, ref)
+ }
+ }
+
+ channel.Messages = messages
+ spec.Channels[channelID] = channel
+
+ prefix := g.getOperationID(route, channelID)
+
+ if len(sendRefs) > 0 {
+ spec.Operations[prefix+"Send"] = &AsyncAPIOperation{
+ Action: "send",
+ Channel: &AsyncAPIChannelReference{Ref: "#/channels/" + channelID},
+ Title: "Send message",
+ Summary: "Send messages to " + route.Path,
+ Description: route.Description,
+ Tags: g.getAsyncAPITags(route),
+ Messages: sendRefs,
+ }
+ }
+
+ if len(receiveRefs) > 0 {
+ spec.Operations[prefix+"Receive"] = &AsyncAPIOperation{
+ Action: "receive",
+ Channel: &AsyncAPIChannelReference{Ref: "#/channels/" + channelID},
+ Title: "Receive message",
+ Summary: "Receive messages from " + route.Path,
+ Description: route.Description,
+ Tags: g.getAsyncAPITags(route),
+ Messages: receiveRefs,
+ }
+ }
+
+ return nil
+}
+
// applyForgeStreamExtension copies stream bindings onto an AsyncAPI channel as
// the x-forge-stream extension.
//
@@ -434,12 +560,22 @@ func applyForgeStreamExtension(channel *AsyncAPIChannel, metadata map[string]any
out := make([]map[string]any, 0, len(bindings))
for _, b := range bindings {
- out = append(out, map[string]any{
+ entry := map[string]any{
"message": b.Message,
"entityType": b.EntityType,
"intent": string(b.Intent),
"invalidates": b.Invalidates,
- })
+ }
+
+ // The qualified Go type, so the client generator can find the
+ // component when finalization gave it a name other than the bare one.
+ // A component that was renamed carries the same string as x-forge-type;
+ // see schemaGenerator.markRenamedComponents.
+ if b.entity != nil {
+ entry["type"] = getQualifiedTypeName(b.entity)
+ }
+
+ out = append(out, entry)
}
if channel.Extensions == nil {
diff --git a/internal/router/client_meta.go b/internal/router/client_meta.go
index 77288215c..b9cbafd24 100644
--- a/internal/router/client_meta.go
+++ b/internal/router/client_meta.go
@@ -111,6 +111,16 @@ type StreamBinding struct {
EntityType string
Intent StreamIntent
Invalidates []string
+
+ // entity is the Go type T of Emits[T], kept so the AsyncAPI generator can
+ // name the entity by its FINAL component name once every type is known.
+ // EntityType above is T's bare name, which is also what the component is
+ // called until something contests it: a second type with the same name
+ // in another package, a `schema:"..."` pin, a generic instantiation. The
+ // generated client keys its entity table by the component name, so a
+ // binding still carrying the bare name would name a row that is not
+ // there and never normalize. Nil for a binding built without Emits.
+ entity reflect.Type
}
// EmitsBuilder accumulates one binding. Build resolves the defaults.
@@ -129,10 +139,13 @@ type EmitsBuilder struct {
// forge.Emits[Order]("order.updated")
// forge.Emits[Order]("order.deleted")
func Emits[T any](message string) *EmitsBuilder {
+ typ := reflect.TypeFor[T]()
+
return &EmitsBuilder{
binding: StreamBinding{
Message: message,
- EntityType: reflect.TypeOf((*T)(nil)).Elem().Name(),
+ EntityType: typ.Name(),
+ entity: typ,
},
}
}
diff --git a/internal/router/openapi_client_meta_test.go b/internal/router/openapi_client_meta_test.go
index f85f0c461..dfb1d3bc1 100644
--- a/internal/router/openapi_client_meta_test.go
+++ b/internal/router/openapi_client_meta_test.go
@@ -1,6 +1,15 @@
package router
-import "testing"
+import (
+ "encoding/json"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/xraph/forge/internal/router/testtypes/billing"
+ "github.com/xraph/forge/internal/router/testtypes/shipping"
+ "github.com/xraph/forge/internal/shared"
+)
func TestOperationCarriesForgeExtensions(t *testing.T) {
route := RouteInfo{
@@ -97,3 +106,96 @@ func TestEmptyInvalidatesSliceEmitsNoKey(t *testing.T) {
t.Fatalf("x-forge-no-invalidation present for an empty slice, want absent")
}
}
+
+// A component that finalization named something other than its type's bare
+// name says what it was generated from, so a stream binding declared with the
+// bare name can still be matched to it. An uncontested component is not
+// marked: its bare name already answers, and an import path on every schema
+// would be paid by all for the sake of the few that moved.
+func TestRenamedComponentCarriesItsGoType(t *testing.T) {
+ r := NewRouter(WithOpenAPI(OpenAPIConfig{Title: "T", Version: "1.0.0"}))
+
+ if err := r.GET("/billing/invoice", func(ctx shared.Context, req *collisionEmptyRequest) (*billing.Invoice, error) {
+ return &billing.Invoice{}, nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := r.GET("/shipping/invoice", func(ctx shared.Context, req *collisionEmptyRequest) (*shipping.Invoice, error) {
+ return &shipping.Invoice{}, nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ spec := r.OpenAPISpec()
+ if spec == nil {
+ t.Fatal("no spec")
+ }
+
+ // Through JSON, so the assertion is about what a consumer of the document
+ // sees: the extension has to be hoisted onto the schema, not nested.
+ raw, err := json.Marshal(spec)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var doc struct {
+ Components struct {
+ Schemas map[string]map[string]any `json:"schemas"`
+ } `json:"components"`
+ }
+
+ if err := json.Unmarshal(raw, &doc); err != nil {
+ t.Fatal(err)
+ }
+
+ marked := map[string]string{}
+
+ for name, schema := range doc.Components.Schemas {
+ if typ, ok := schema["x-forge-type"].(string); ok {
+ marked[name] = typ
+ }
+ }
+
+ if _, contested := doc.Components.Schemas["Invoice"]; contested {
+ t.Fatalf("a contested bare name reached the document: %v", doc.Components.Schemas)
+ }
+
+ // Both Invoice types moved, and both say where they came from. Their
+ // nested Note types collide too and are marked the same way.
+ want := map[string]bool{
+ getQualifiedTypeName(billingType()): false,
+ getQualifiedTypeName(shippingType()): false,
+ }
+
+ for name, typ := range marked {
+ if _, ok := want[typ]; ok {
+ want[typ] = true
+ }
+
+ // A marked component is one that moved: its name is never the bare
+ // type name the qualified string ends in.
+ if bare := typ[strings.LastIndex(typ, ".")+1:]; name == bare {
+ t.Errorf("component %q kept its bare name yet is marked with %q", name, typ)
+ }
+ }
+
+ for typ, seen := range want {
+ if !seen {
+ t.Errorf("no component is marked with %q; marked = %v", typ, marked)
+ }
+ }
+
+ for name := range doc.Components.Schemas {
+ if _, ok := marked[name]; ok {
+ continue
+ }
+
+ if _, ok := doc.Components.Schemas[name]["x-forge-type"]; ok {
+ t.Errorf("component %q is unexpectedly marked", name)
+ }
+ }
+}
+
+func billingType() reflect.Type { return reflect.TypeFor[billing.Invoice]() }
+func shippingType() reflect.Type { return reflect.TypeFor[shipping.Invoice]() }
diff --git a/internal/router/openapi_component_names.go b/internal/router/openapi_component_names.go
index 5386de9b5..299e5f35f 100644
--- a/internal/router/openapi_component_names.go
+++ b/internal/router/openapi_component_names.go
@@ -521,10 +521,41 @@ func (g *schemaGenerator) finalizeComponentNames() []componentRename {
g.applyRenames(renames)
g.reportContests(contests)
+ g.markRenamedComponents()
return renames
}
+// markRenamedComponents writes x-forge-type, the qualified Go type, onto every
+// component whose final name is not its type's bare name.
+//
+// A stream binding declared with Emits[T] knows only T's bare name, and the
+// client generator matches it to a component by that name. A component that
+// was qualified apart from a namesake, pinned with `schema:"..."`, or cleaned
+// of a generic instantiation's brackets is not findable that way, so it says
+// what it was generated from and the binding, carrying the same string, is
+// matched on that instead. Ordinary components are left unmarked: their bare
+// name already answers, and marking every one of them would put an import
+// path on every schema for the sake of the few that moved.
+func (g *schemaGenerator) markRenamedComponents() {
+ for name, reg := range g.registrations {
+ if reg == nil || reg.typ == nil || name == reg.typ.Name()+reg.suffix {
+ continue
+ }
+
+ schema := g.components[name]
+ if schema == nil {
+ continue
+ }
+
+ if schema.Extensions == nil {
+ schema.Extensions = make(map[string]any)
+ }
+
+ schema.Extensions["x-forge-type"] = getQualifiedTypeName(reg.typ)
+ }
+}
+
// nameContest is one bare component name that more than one type wanted.
//
// pinnedBy is the registration that named it explicitly, if any. It decides how
diff --git a/internal/router/openapi_generator.go b/internal/router/openapi_generator.go
index ba93e465a..5dbafb8e3 100644
--- a/internal/router/openapi_generator.go
+++ b/internal/router/openapi_generator.go
@@ -488,16 +488,39 @@ func (g *openAPIGenerator) setOperation(pathItem *PathItem, method string, opera
// Routes that declared nothing get no extensions at all, so a spec generated by
// an application that never opts in is unchanged from today's output.
func applyForgeExtensions(op *Operation, metadata map[string]any) {
+ for key, value := range ClientExtensions(metadata) {
+ if op.Extensions == nil {
+ op.Extensions = make(map[string]any)
+ }
+
+ op.Extensions[key] = value
+ }
+}
+
+// ClientExtensions translates the forge.client.* keys a route's options wrote
+// into the x-forge-* extensions the client generator reads, keyed exactly as
+// they appear on an OpenAPI operation. Nil when the route declared nothing.
+//
+// Exported because the client generator has a second way in: a router with no
+// OpenAPI document is introspected from its raw route table, and that path
+// used to copy the metadata verbatim and resolve none of it, so a route that
+// declared WithInvalidates on a server without OpenAPI generated a client with
+// an empty contract. One translation, used by both the document and the
+// fallback, is what keeps the two from saying different things about the same
+// route.
+func ClientExtensions(metadata map[string]any) map[string]any {
if metadata == nil {
- return
+ return nil
}
+ var out map[string]any
+
set := func(key string, value any) {
- if op.Extensions == nil {
- op.Extensions = make(map[string]any)
+ if out == nil {
+ out = make(map[string]any)
}
- op.Extensions[key] = value
+ out[key] = value
}
if def, ok := metadata["forge.client.entity"].(EntityDef); ok {
@@ -531,6 +554,8 @@ func applyForgeExtensions(op *Operation, metadata map[string]any) {
if ms, ok := metadata["forge.client.staleTime"].(int64); ok && ms > 0 {
set("x-forge-stale-time", ms)
}
+
+ return out
}
// RegisterEndpoints registers OpenAPI spec and Swagger UI endpoints.
diff --git a/internal/router/router_asyncapi_opts.go b/internal/router/router_asyncapi_opts.go
index d27dc757b..fb7bf8c61 100644
--- a/internal/router/router_asyncapi_opts.go
+++ b/internal/router/router_asyncapi_opts.go
@@ -261,3 +261,42 @@ func WithServerProtocol(serverNames ...string) RouteOption {
func WithAsyncAPISecurity(requirements map[string][]string) RouteOption {
return WithMetadata("asyncapi.security", requirements)
}
+
+// WebTransportMessages declares the payload types a WebTransport endpoint
+// carries, one per way a message can travel. Leave a field nil for a kind the
+// endpoint does not use.
+//
+// Datagrams are unreliable and unordered and go both ways, so one type covers
+// them. Streams are typed per direction: UniSend and UniReceive for
+// unidirectional streams the client opens and the server opens, BidiSend and
+// BidiReceive for the two halves of a bidirectional stream.
+type WebTransportMessages struct {
+ Datagram any
+ UniSend any
+ UniReceive any
+ BidiSend any
+ BidiReceive any
+}
+
+// WithWebTransportMessages defines the message schemas for a WebTransport
+// endpoint, which is what puts the endpoint in the AsyncAPI document and lets
+// the client generator type each stream kind.
+//
+// Without it the route is served but described nowhere: AsyncAPI has no
+// WebTransport binding, so the channel is written with an x-forge-protocol
+// marker and messages named for how each is carried.
+func WithWebTransportMessages(messages WebTransportMessages) RouteOption {
+ return &wtMessagesOpt{messages}
+}
+
+type wtMessagesOpt struct {
+ messages WebTransportMessages
+}
+
+func (o *wtMessagesOpt) Apply(cfg *RouteConfig) {
+ if cfg.Metadata == nil {
+ cfg.Metadata = make(map[string]any)
+ }
+
+ cfg.Metadata["asyncapi.wt.messages"] = o.messages
+}
diff --git a/internal/router/testdata/asyncapi.json b/internal/router/testdata/asyncapi.json
index 0ba9e129a..82ba9a38b 100644
--- a/internal/router/testdata/asyncapi.json
+++ b/internal/router/testdata/asyncapi.json
@@ -54,7 +54,8 @@
"entityType": "goldenOrder",
"intent": "patch",
"invalidates": null,
- "message": "order.progressed"
+ "message": "order.progressed",
+ "type": "github.com/xraph/forge/internal/router.goldenOrder"
}
]
},
@@ -126,7 +127,8 @@
"invalidates": [
"goldenOrder[]"
],
- "message": "order.created"
+ "message": "order.created",
+ "type": "github.com/xraph/forge/internal/router.goldenOrder"
},
{
"entityType": "goldenOrder",
@@ -134,7 +136,8 @@
"invalidates": [
"goldenOrder[]"
],
- "message": "order.deleted"
+ "message": "order.deleted",
+ "type": "github.com/xraph/forge/internal/router.goldenOrder"
}
]
},
diff --git a/internal/router/testdata/asyncapi.yaml b/internal/router/testdata/asyncapi.yaml
index 4d1f191ad..10194092a 100644
--- a/internal/router/testdata/asyncapi.yaml
+++ b/internal/router/testdata/asyncapi.yaml
@@ -40,6 +40,7 @@ channels:
intent: patch
invalidates: []
message: order.progressed
+ type: github.com/xraph/forge/internal/router.goldenOrder
ws-orders-roomid:
address: /ws/orders/{roomId}
messages:
@@ -89,11 +90,13 @@ channels:
invalidates:
- goldenOrder[]
message: order.created
+ type: github.com/xraph/forge/internal/router.goldenOrder
- entityType: goldenOrder
intent: evict
invalidates:
- goldenOrder[]
message: order.deleted
+ type: github.com/xraph/forge/internal/router.goldenOrder
ws-trees-treeid:
address: /ws/trees/{treeId}
messages:
diff --git a/internal/router/testdata/openapi.json b/internal/router/testdata/openapi.json
index 8bd503141..3889885eb 100644
--- a/internal/router/testdata/openapi.json
+++ b/internal/router/testdata/openapi.json
@@ -576,12 +576,6 @@
"components": {
"schemas": {
"BillingInvoice": {
- "type": "object",
- "required": [
- "invoice_number",
- "amount_cents",
- "note"
- ],
"properties": {
"amount_cents": {
"type": "integer"
@@ -592,26 +586,35 @@
"note": {
"$ref": "#/components/schemas/BillingNote"
}
- }
- },
- "BillingNote": {
- "type": "object",
+ },
"required": [
- "memo"
+ "invoice_number",
+ "amount_cents",
+ "note"
],
+ "type": "object",
+ "x-forge-type": "github.com/xraph/forge/internal/router/testtypes/billing.Invoice"
+ },
+ "BillingNote": {
"properties": {
"memo": {
"type": "string"
}
- }
+ },
+ "required": [
+ "memo"
+ ],
+ "type": "object",
+ "x-forge-type": "github.com/xraph/forge/internal/router/testtypes/billing.Note"
},
"GoldenOrderStatus": {
- "type": "string",
"enum": [
"draft",
"open",
"closed"
- ]
+ ],
+ "type": "string",
+ "x-forge-type": "github.com/xraph/forge/internal/router.goldenOrderStatus"
},
"Receipt": {
"type": "object",
@@ -625,12 +628,6 @@
}
},
"ShippingInvoice": {
- "type": "object",
- "required": [
- "tracking_code",
- "weight_kg",
- "note"
- ],
"properties": {
"note": {
"$ref": "#/components/schemas/ShippingNote"
@@ -641,18 +638,26 @@
"weight_kg": {
"type": "number"
}
- }
- },
- "ShippingNote": {
- "type": "object",
+ },
"required": [
- "courier"
+ "tracking_code",
+ "weight_kg",
+ "note"
],
+ "type": "object",
+ "x-forge-type": "github.com/xraph/forge/internal/router/testtypes/shipping.Invoice"
+ },
+ "ShippingNote": {
"properties": {
"courier": {
"type": "string"
}
- }
+ },
+ "required": [
+ "courier"
+ ],
+ "type": "object",
+ "x-forge-type": "github.com/xraph/forge/internal/router/testtypes/shipping.Note"
},
"goldenAddress": {
"type": "object",
@@ -771,11 +776,6 @@
}
},
"goldenPage_goldenWorkspace": {
- "type": "object",
- "required": [
- "items",
- "total"
- ],
"properties": {
"items": {
"type": "array",
@@ -786,7 +786,13 @@
"total": {
"type": "integer"
}
- }
+ },
+ "required": [
+ "items",
+ "total"
+ ],
+ "type": "object",
+ "x-forge-type": "github.com/xraph/forge/internal/router.goldenPage[github.com/xraph/forge/internal/router.goldenWorkspace]"
},
"goldenRecursiveRequestBody": {
"type": "object",
diff --git a/internal/router/testdata/openapi.yaml b/internal/router/testdata/openapi.yaml
index 4b24c24a5..a6daa876e 100644
--- a/internal/router/testdata/openapi.yaml
+++ b/internal/router/testdata/openapi.yaml
@@ -363,6 +363,7 @@ components:
type: string
note:
$ref: '#/components/schemas/BillingNote'
+ x-forge-type: github.com/xraph/forge/internal/router/testtypes/billing.Invoice
BillingNote:
type: object
required:
@@ -370,12 +371,14 @@ components:
properties:
memo:
type: string
+ x-forge-type: github.com/xraph/forge/internal/router/testtypes/billing.Note
GoldenOrderStatus:
type: string
enum:
- draft
- open
- closed
+ x-forge-type: github.com/xraph/forge/internal/router.goldenOrderStatus
Receipt:
type: object
required:
@@ -396,6 +399,7 @@ components:
type: string
weight_kg:
type: number
+ x-forge-type: github.com/xraph/forge/internal/router/testtypes/shipping.Invoice
ShippingNote:
type: object
required:
@@ -403,6 +407,7 @@ components:
properties:
courier:
type: string
+ x-forge-type: github.com/xraph/forge/internal/router/testtypes/shipping.Note
goldenAddress:
type: object
required:
@@ -495,6 +500,7 @@ components:
$ref: '#/components/schemas/goldenWorkspace'
total:
type: integer
+ x-forge-type: github.com/xraph/forge/internal/router.goldenPage[github.com/xraph/forge/internal/router.goldenWorkspace]
goldenRecursiveRequestBody:
type: object
required:
diff --git a/packages/client-angular/__tests__/injectMutation.test.ts b/packages/client-angular/__tests__/injectMutation.test.ts
index 8d65b450c..5f5265ab1 100644
--- a/packages/client-angular/__tests__/injectMutation.test.ts
+++ b/packages/client-angular/__tests__/injectMutation.test.ts
@@ -49,6 +49,28 @@ describe('injectMutation', () => {
expect(create.isPending()).toBe(false);
});
+ // `MutationOptions.client` is accepted per call and the raw binding honours
+ // it; the hook used to spread its own client last and silently replace it.
+ it('runs the write against a client supplied per call', async () => {
+ const hook = harness(() => ({ id: 1, total: 1 }));
+ const perCall = harness(() => ({ id: 2, total: 2 }));
+
+ configure(hook);
+
+ let create!: InjectMutationResult;
+
+ TestBed.runInInjectionContext(() => {
+ create = injectMutation(useOrderCreate);
+ });
+
+ await create.mutateAsync({ body: { total: 2 } }, { client: perCall.cache });
+ await settle();
+
+ expect(perCall.transport.calls).toHaveLength(1);
+ expect(hook.transport.calls).toHaveLength(0);
+ expect(create.data()).toEqual({ id: 2, total: 2 });
+ });
+
it('records an error, and reset returns it to idle', async () => {
const fx = harness(() => {
throw new Error('conflict');
diff --git a/packages/client-angular/src/injectMutation.ts b/packages/client-angular/src/injectMutation.ts
index a2fbdc8ed..a9dfce2e7 100644
--- a/packages/client-angular/src/injectMutation.ts
+++ b/packages/client-angular/src/injectMutation.ts
@@ -155,7 +155,12 @@ function bind(
try {
// The hook-level options are read *now*, not captured at construction.
- const data = await op(args, { ...resolve(options), ...perCall, client });
+ // The per-call client wins when given; see the React binding for why.
+ const data = await op(args, {
+ ...resolve(options),
+ ...perCall,
+ client: perCall?.client ?? client,
+ });
if (alive && seq === call) {
state.set({ status: 'success', data, error: undefined, isPending: false });
diff --git a/packages/client-core/README.md b/packages/client-core/README.md
index 56761a588..23fced64c 100644
--- a/packages/client-core/README.md
+++ b/packages/client-core/README.md
@@ -978,14 +978,14 @@ pulls:
| | limit | actual |
|---|---|---|
| entity store | 2.4 kB | **2.27 kB** |
-| tag graph | 2.25 kB | **2.12 kB** |
-| query engine and REST transport | 9.6 kB | **9.3 kB** |
-| stream binding | 3.75 kB | **3.65 kB** |
-| optimistic overlays | 1.23 kB | **1.14 kB** |
-| ssr | 2 kB | **1.82 kB** |
+| tag graph | 2.4 kB | **2.34 kB** |
+| query engine and REST transport | 9.95 kB | **9.74 kB** |
+| stream binding | 4.3 kB | **4.24 kB** |
+| optimistic overlays | 1.23 kB | **1.16 kB** |
+| ssr | 2 kB | **1.85 kB** |
| freshness | 0.5 kB | **0.38 kB** |
-| core, REST only | 9.7 kB | **9.34 kB** |
-| core with streams | 14.25 kB | **12.08 kB** |
+| core, REST only | 10 kB | **9.77 kB** |
+| core with streams | 14.25 kB | **12.92 kB** |
Streams cost 2.74 kB on top of REST-only.
@@ -1058,6 +1058,28 @@ moved together. REST-only imports the query engine's set plus `EntityStore` and
below what the query engine's line permits would fail for growth its own budget
had already approved.
+Tag resolution moved three of them again. A collection read now resolves its
+item template once per element of an array response instead of reporting
+`Order:{id}` as unresolved on every list, a settle no longer reports a template
+whose entity the deps already carry, and a placeholder that names no property
+is retried under its other spellings, so `{req.customer_id}` finds `customerId`
+in a document the generator never renamed. That is about 60 bytes in `tags.ts`
+and 50 in `registry.ts` (the second half is placement indexing the entities it placed), and it lands in every set that imports either: `tag
+graph` 2.25 kB to 2.4 kB, `query engine and REST transport` 9.6 kB to 9.95 kB,
+`stream binding` 3.75 kB to 3.9 kB, and `core, REST only` 9700 B to 10 kB. The
+last one had 13 bytes to spare after the change, which is the situation the
+paragraph above exists to prevent, so all four sit near 3 percent above what
+they measure rather than at the measured figure.
+
+The streaming pass moved one limit again. `applyFrames` now runs a binding's
+`decode` before it normalizes a frame, and the duplex path already on `main`
+shares that pull. The stream binding measures 4.24 kB, so its limit is 4.3 kB.
+A settled query also records the entities its read actually reached, and a
+confirmed optimistic delete is evicted under a frame stamp. That moved `query
+engine and REST transport` to 9.74 kB. The WebSocket and EventSource adapters
+and `channelMessages` are exports that no budget line imports, so an application
+that never calls them does not ship them.
+
The two budgets the design actually sets are 9 kB REST-only and 14 kB with
streams. With streams has been raised once, to 14.25 kB, for the inspector seam
and the runtime gap-closing work that came with it. REST-only was raised in the
diff --git a/packages/client-core/__tests__/adapters.test.ts b/packages/client-core/__tests__/adapters.test.ts
new file mode 100644
index 000000000..cae81f4c1
--- /dev/null
+++ b/packages/client-core/__tests__/adapters.test.ts
@@ -0,0 +1,145 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { channelMessages, eventSourceConnection, webSocketConnection } from '../src/stream';
+import type { EventSourceLike, StreamBinding, WebSocketLike } from '../src/stream';
+
+function fakeSocket(): WebSocketLike & { sent: string[]; closes: number } {
+ return {
+ onmessage: null,
+ onclose: null,
+ onerror: null,
+ sent: [],
+ closes: 0,
+ send(data) {
+ this.sent.push(data);
+ },
+ close() {
+ this.closes += 1;
+ },
+ };
+}
+
+describe('webSocketConnection', () => {
+ it('parses JSON text frames and passes anything else through', () => {
+ const socket = fakeSocket();
+ const conn = webSocketConnection(socket);
+ const seen: unknown[] = [];
+
+ conn.onMessage((m) => seen.push(m));
+ socket.onmessage?.({ data: '{"type":"order.created","payload":{"id":7}}' });
+ socket.onmessage?.({ data: { already: 'parsed' } });
+
+ expect(seen).toEqual([{ type: 'order.created', payload: { id: 7 } }, { already: 'parsed' }]);
+ });
+
+ it('reports a frame that does not parse and keeps the socket', () => {
+ const socket = fakeSocket();
+ const conn = webSocketConnection(socket);
+ const errors: unknown[] = [];
+
+ conn.onMessage(() => undefined);
+ conn.onError?.((e) => errors.push(e));
+ socket.onmessage?.({ data: '{not json' });
+
+ expect(errors).toHaveLength(1);
+ expect(socket.closes).toBe(0);
+ });
+
+ it('encodes what it sends, and reports a peer close once', () => {
+ const socket = fakeSocket();
+ const conn = webSocketConnection(socket);
+ const closed = vi.fn();
+
+ conn.onClose(closed);
+ conn.send?.({ type: 'system', event: 'pong' });
+ conn.send?.('raw');
+ socket.onclose?.('gone');
+ socket.onclose?.('gone again');
+
+ expect(socket.sent).toEqual(['{"type":"system","event":"pong"}', 'raw']);
+ expect(closed).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not report a close it asked for', () => {
+ const socket = fakeSocket();
+ const conn = webSocketConnection(socket);
+ const closed = vi.fn();
+
+ conn.onClose(closed);
+ conn.close();
+ socket.onclose?.();
+
+ expect(socket.closes).toBe(1);
+ expect(closed).not.toHaveBeenCalled();
+ });
+});
+
+function fakeSource(): EventSourceLike & {
+ listeners: Map void>;
+ closes: number;
+} {
+ return {
+ listeners: new Map(),
+ closes: 0,
+ onerror: null,
+ addEventListener(type, listener) {
+ this.listeners.set(type, listener);
+ },
+ close() {
+ this.closes += 1;
+ },
+ };
+}
+
+describe('eventSourceConnection', () => {
+ it('listens for the named events and the control events, delivering decodable frames', () => {
+ const source = fakeSource();
+ const conn = eventSourceConnection(source, { events: ['order.created'] });
+ const seen: unknown[] = [];
+
+ conn.onMessage((m) => seen.push(m));
+
+ expect([...source.listeners.keys()]).toEqual(['order.created', 'forge.resumed', 'forge.gap']);
+
+ source.listeners.get('order.created')?.({ data: '{"id":7}', lastEventId: '41' });
+
+ expect(seen).toEqual([{ event: 'order.created', data: { id: 7 }, id: '41' }]);
+ });
+
+ it('treats an error as a drop: reports it, closes the source, and says so once', () => {
+ const source = fakeSource();
+ const conn = eventSourceConnection(source, { events: [] });
+ const errors: unknown[] = [];
+ const closed = vi.fn();
+
+ conn.onError?.((e) => errors.push(e));
+ conn.onClose(closed);
+ source.onerror?.('network');
+ source.onerror?.('network');
+
+ expect(errors).toEqual(['network']);
+ expect(source.closes).toBe(1);
+ expect(closed).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('channelMessages', () => {
+ it('reads one channel\'s message names out of the streams table, once each', () => {
+ const row = (channel: string, message: string): StreamBinding => ({
+ channel,
+ message,
+ entity: 'Order',
+ intent: 'patch',
+ invalidates: [],
+ });
+ const streams = [
+ row('/sse/orders', 'order.created'),
+ row('/sse/orders', 'order.deleted'),
+ row('/sse/orders', 'order.created'),
+ { kind: 'duplex', channel: '/sse/orders', send: 'command', receive: 'event' } as const,
+ row('/sse/other', 'x'),
+ ];
+
+ expect(channelMessages(streams, '/sse/orders')).toEqual(['order.created', 'order.deleted']);
+ });
+});
diff --git a/packages/client-core/__tests__/cache.test.ts b/packages/client-core/__tests__/cache.test.ts
index 8da6db4c1..a87dc0941 100644
--- a/packages/client-core/__tests__/cache.test.ts
+++ b/packages/client-core/__tests__/cache.test.ts
@@ -301,6 +301,33 @@ describe('mutations', () => {
expect(transport.calls.slice(before + 1).map((call) => call.meta)).toEqual([orderList]);
});
+ // The store merges, so a refetch that returns the order without its customer
+ // leaves the customer on the record and the query still renders it. The
+ // query's deps have to say so, or an invalidation of that customer never
+ // reaches a query that is showing its data.
+ it('keeps depending on a nested entity a narrower refetch left out', async () => {
+ let call = 0;
+ const { cache: queries, transport, scheduler } = cache(() =>
+ call++ === 0 ? { id: 7, customer: { id: 3, name: 'a' } } : { id: 7 },
+ );
+ const args = { path: { id: 7 } };
+
+ queries.subscribe(orderGet, args, () => undefined);
+ await settleMicrotasks();
+ await queries.refetch(orderGet, args);
+ await settleMicrotasks();
+
+ expect(queries.getState(orderGet, args).data).toEqual({ id: 7, customer: { id: 3, name: 'a' } });
+
+ const before = transport.calls.length;
+
+ queries.invalidate(['Customer:3']);
+ scheduler.flush();
+ await settleMicrotasks();
+
+ expect(transport.calls.slice(before).map((c) => c.meta)).toEqual([orderGet]);
+ });
+
it('lets a placement callback answer for a query instead of refetching it', async () => {
const { cache: queries, transport, scheduler } = cache((request) =>
request.meta === orderCreate ? { id: 9, total: 5 } : [{ id: 7, total: 99 }],
@@ -332,6 +359,69 @@ describe('mutations', () => {
expect((queries.getState(orderList).data as { total: number }[])[0]?.total).toBe(6);
});
+ // The created order reached the list only through placement. A later
+ // invalidation naming that order -- with no response body to normalize, so
+ // the entity store alone cannot carry it -- has to reach the list, which
+ // means the list must be indexed under `Order:9` as it would be after a
+ // fetch that returned it.
+ it('indexes a placed query under the entities it placed', async () => {
+ const { cache: queries, transport, scheduler } = cache((request) =>
+ request.meta === orderCreate ? { id: 9, total: 5 } : [{ id: 7, total: 99 }],
+ );
+
+ queries.subscribe(orderList, undefined, () => undefined);
+ await settleMicrotasks();
+
+ await queries.mutate(orderCreate, { body: { total: 5 } }, {
+ place: {
+ 'Order[]': (created, current) => [created, ...(current as unknown[])],
+ },
+ });
+ scheduler.flush();
+ await settleMicrotasks();
+
+ const before = transport.calls.length;
+
+ queries.invalidate(['Order:9']);
+ scheduler.flush();
+ await settleMicrotasks();
+
+ expect(transport.calls.slice(before).map((call) => call.meta)).toEqual([orderList]);
+ });
+
+ // Placement settles the query while its own request is still out. The
+ // request is discarded, so nothing else would clear the fetching flag until
+ // the abandoned response lands, which on a slow network is a spinner over a
+ // list that is already correct.
+ it('clears isFetching when placement answers a query with a request in flight', async () => {
+ const gate = deferred();
+ const { cache: queries, scheduler } = cache((request) =>
+ request.meta === orderCreate ? { id: 9, total: 5 } : gate.promise,
+ );
+
+ queries.subscribe(orderList, undefined, () => undefined);
+ await settleMicrotasks();
+
+ expect(queries.getState(orderList).isFetching).toBe(true);
+
+ await queries.mutate(orderCreate, { body: { total: 5 } }, {
+ place: {
+ 'Order[]': (created, current) => [created, ...((current as unknown[] | undefined) ?? [])],
+ },
+ });
+ scheduler.flush();
+ await settleMicrotasks();
+
+ expect(queries.getState(orderList).isFetching).toBe(false);
+ expect(queries.getState(orderList).data).toEqual([{ id: 9, total: 5 }]);
+
+ // The pre-write answer lands and is discarded: the placed list stands.
+ gate.resolve([{ id: 7, total: 1 }]);
+ await settleMicrotasks();
+
+ expect(queries.getState(orderList).data).toEqual([{ id: 9, total: 5 }]);
+ });
+
it('falls back to a refetch when placement declines', async () => {
const { cache: queries, transport, scheduler } = cache((request) =>
request.meta === orderCreate ? { id: 9, total: 5, status: 'draft' } : [],
diff --git a/packages/client-core/__tests__/freshness.test.ts b/packages/client-core/__tests__/freshness.test.ts
index b99da704c..ab1c33242 100644
--- a/packages/client-core/__tests__/freshness.test.ts
+++ b/packages/client-core/__tests__/freshness.test.ts
@@ -128,6 +128,23 @@ describe('refetch on mount', () => {
expect(transport.calls).toHaveLength(1);
});
+ // `fetch` is what a route preload and a prefetch call. It used to serve any
+ // settled value regardless of age, so a declared staleTime held for every
+ // subscriber and for nobody who asked imperatively.
+ it('fetch runs the request again once the result has aged past staleTime', async () => {
+ const time = clock();
+ const { queries, transport } = cache({ staleTime: 1_000, now: time.now });
+
+ await queries.fetch(orderList);
+ await queries.fetch(orderList);
+ expect(transport.calls).toHaveLength(1);
+
+ time.advance(1_001);
+
+ await queries.fetch(orderList);
+ expect(transport.calls).toHaveLength(2);
+ });
+
it('refetches on mount once the result has aged past staleTime', async () => {
const time = clock();
const { queries, transport } = cache({ staleTime: 1_000, now: time.now });
diff --git a/packages/client-core/__tests__/live.test.ts b/packages/client-core/__tests__/live.test.ts
index d6088d49b..a13b4de64 100644
--- a/packages/client-core/__tests__/live.test.ts
+++ b/packages/client-core/__tests__/live.test.ts
@@ -1121,3 +1121,61 @@ describe('binderSnapshot', () => {
expect(first.channels).not.toBe(second.channels);
});
});
+
+describe('frame decoding', () => {
+ // The manifest names client-side fields, the wire carries wire-cased ones.
+ // A frame has to go through the entity's codec before it is normalized, or
+ // a renamed field is never there to read and a renamed id never matches.
+ const rename = (payload: unknown): unknown => {
+ const { customer_id: customerId, ...rest } = payload as Record;
+
+ return { ...rest, customerId };
+ };
+
+ it('decodes a frame through the binding before writing it', () => {
+ const cache = new QueryCache({ transport: fakeTransport(() => undefined), entities: schema });
+ const binding: StreamBinding = {
+ channel: '/ws/orders',
+ message: 'order.created',
+ entity: 'Order',
+ intent: 'upsert',
+ invalidates: [],
+ decode: rename,
+ };
+
+ applyFrames(cache, [{ binding, payload: { id: 7, customer_id: 'c-1' } }]);
+
+ expect(cache.store.getRecord('Order:7')?.data).toEqual({ id: 7, customerId: 'c-1' });
+ });
+
+ it('passes a bare identity through untouched and reports a codec that throws', () => {
+ const errors: string[] = [];
+ const cache = new QueryCache({
+ transport: fakeTransport(() => undefined),
+ entities: schema,
+ onError: (_error, context) => errors.push(context),
+ });
+
+ cache.store.put('Order:7', { id: 7 });
+
+ const evict: StreamBinding = {
+ channel: '/ws/orders',
+ message: 'order.deleted',
+ entity: 'Order',
+ intent: 'evict',
+ invalidates: [],
+ decode: () => {
+ throw new Error('not for identities');
+ },
+ };
+
+ applyFrames(cache, [{ binding: evict, payload: 7 }]);
+ expect(cache.store.getRecord('Order:7')).toBeUndefined();
+
+ const upsert: StreamBinding = { ...evict, message: 'order.created', intent: 'upsert' };
+
+ applyFrames(cache, [{ binding: upsert, payload: { id: 8 } }]);
+ expect(cache.store.getRecord('Order:8')).toBeUndefined();
+ expect(errors).toEqual(['decode']);
+ });
+});
diff --git a/packages/client-core/__tests__/overlay.test.ts b/packages/client-core/__tests__/overlay.test.ts
index 97fc6b45c..24af3ae56 100644
--- a/packages/client-core/__tests__/overlay.test.ts
+++ b/packages/client-core/__tests__/overlay.test.ts
@@ -360,6 +360,14 @@ const orderPatch: OperationMeta = {
invalidates: ['Order:{id}', 'Order[]'],
};
+const orderGet: OperationMeta = {
+ method: 'GET',
+ path: '/orders/{id}',
+ entity: 'Order',
+ provides: ['Order:{id}'],
+ invalidates: [],
+};
+
const orderDelete: OperationMeta = {
method: 'DELETE',
path: '/orders/{id}',
@@ -536,6 +544,48 @@ describe('optimistic mutations', () => {
expect(queries.getState(orderList).data).toEqual([{ id: 8 }]);
});
+ // The item read was dispatched before the delete and lands after the server
+ // confirmed it. Its answer predates the delete, so it must not put the row
+ // back. The declared tags do not name the record -- an explicitly targeted
+ // patch is how that happens -- so nothing restarts the read; the tombstone
+ // the confirmed eviction leaves is what withholds its answer.
+ it('does not resurrect a confirmed delete from a read dispatched before it', async () => {
+ const gate = deferred();
+ let reads = 0;
+ const listOnlyDelete: OperationMeta = { ...orderDelete, invalidates: ['Order[]'] };
+ // The first read returns the row, the second is the one caught in flight,
+ // and any read after that reaches a server that has already deleted it.
+ const { cache: queries, scheduler } = optimisticCache((request) => {
+ if (request.meta.method === 'DELETE') return undefined;
+
+ const read = reads++;
+
+ if (read === 0) return { id: 7, total: 1 };
+ if (read === 1) return gate.promise;
+
+ return null;
+ });
+ const args = { path: { id: 7 } };
+
+ queries.subscribe(orderGet, args, () => undefined);
+ await settleMicrotasks();
+
+ void queries.refetch(orderGet, args);
+
+ await queries.mutate(listOnlyDelete, args, {
+ optimistic: [{ key: 'Order:7', patch: 'delete' }],
+ });
+ scheduler.flush();
+ await settleMicrotasks();
+
+ expect(queries.store.getRecord('Order:7')).toBeUndefined();
+
+ gate.resolve({ id: 7, total: 1 });
+ await settleMicrotasks();
+
+ expect(queries.store.getRecord('Order:7')).toBeUndefined();
+ });
+
it('reports an ambiguous target and runs the mutation without an overlay', async () => {
const errors: string[] = [];
const scheduler = manualScheduler();
diff --git a/packages/client-core/__tests__/registry.test.ts b/packages/client-core/__tests__/registry.test.ts
index b4ad69364..8ec7fda27 100644
--- a/packages/client-core/__tests__/registry.test.ts
+++ b/packages/client-core/__tests__/registry.test.ts
@@ -151,6 +151,40 @@ describe('QueryRegistry settle', () => {
expect(onUnresolved).toHaveBeenCalledWith('Customer:{res.customerId}', expect.anything());
});
+ // An enveloped collection -- `{items: [...], total}` -- cannot resolve its
+ // derived item template against the response either, and the array rule
+ // does not reach inside the envelope. What the template promised is that
+ // the query provides Order records, and the store has just confirmed that
+ // it does: the item keys arrived as deps. That is the template resolved,
+ // by a different route, and not something to warn about.
+ it('does not report an item template the settled deps already satisfy', () => {
+ const onUnresolved = vi.fn();
+ const registry = new QueryRegistry({ onUnresolved });
+
+ registry.mount({ operation: 'orderPage', provides: ['Order:{id}', 'Order[]'], key: 'p' });
+ registry.settle('p', {
+ response: { items: [{ id: 7 }], total: 1 },
+ deps: ['Order:7'],
+ });
+
+ expect(onUnresolved).not.toHaveBeenCalled();
+ expect(registry.queriesFor('Order:7')).toHaveLength(1);
+ expect(registry.queriesFor('Order[]')).toHaveLength(1);
+ });
+
+ it('still reports a template naming an entity the response never normalized', () => {
+ const onUnresolved = vi.fn();
+ const registry = new QueryRegistry({ onUnresolved });
+
+ registry.mount({ operation: 'orderPage', provides: ['Customer:{customerId}'], key: 'p' });
+ registry.settle('p', {
+ response: { items: [{ id: 7 }], total: 1 },
+ deps: ['Order:7'],
+ });
+
+ expect(onUnresolved).toHaveBeenCalledWith('Customer:{customerId}', expect.anything());
+ });
+
it('re-indexes a query that settles while unmounted, without indexing it', () => {
const registry = new QueryRegistry();
diff --git a/packages/client-core/__tests__/tags.test.ts b/packages/client-core/__tests__/tags.test.ts
index 1705f148d..edc5fd048 100644
--- a/packages/client-core/__tests__/tags.test.ts
+++ b/packages/client-core/__tests__/tags.test.ts
@@ -49,6 +49,36 @@ describe('resolveTag', () => {
expect(resolveTag('Order:{req.nested.id}', ctx)).toBe('Order:b-1');
});
+ // A template names the wire property, because that is what the route can
+ // see. The body and response it resolves against carry the client-side
+ // names. The generator renames what it has a schema for; the runtime
+ // accepts the wire spelling for the document it did not.
+ it('accepts a wire-spelled placeholder against a client-cased payload', () => {
+ expect(resolveTag('Customer:{req.customer_id}', { body: { customerId: 'c-3' } })).toBe(
+ 'Customer:c-3',
+ );
+ expect(
+ resolveTag('Ledger:{res.customer.external_id}', {
+ response: { customer: { externalId: 'x-9' } },
+ }),
+ ).toBe('Ledger:x-9');
+ expect(resolveTag('Customer:{customerId}', { body: { customer_id: 'c-4' } })).toBe(
+ 'Customer:c-4',
+ );
+ });
+
+ it('reads an exact key as written when both spellings are present', () => {
+ expect(
+ resolveTag('Customer:{req.customer_id}', {
+ body: { customer_id: 'wire', customerId: 'client' },
+ }),
+ ).toBe('Customer:wire');
+ });
+
+ it('still resolves to nothing when no spelling matches', () => {
+ expect(resolveTag('Customer:{req.customer_id}', { body: { id: 1 } })).toBe(undefined);
+ });
+
// Path, then query, then body, then response -- first match wins.
it.each([
['Customer:from-path', ctx],
@@ -105,6 +135,53 @@ describe('resolveTags', () => {
expect(tags).toEqual(['Order[]', 'Order:7']);
expect(unresolved).toEqual(['Customer:{missing}']);
});
+
+ // A collection read declares `Order:{id}`: it provides one tag per record it
+ // returns, not one tag for the array. Resolving against the array as a
+ // whole finds no `id` and would report the healthiest query in the
+ // application as a declaration that resolved to nothing.
+ it('resolves a response template once per element of an array response', () => {
+ const { tags, unresolved } = resolveTags(['Order:{id}', 'Order[]'], {
+ response: [{ id: 1 }, { id: 2 }, { id: 1 }],
+ });
+
+ expect(tags).toEqual(['Order:1', 'Order:2', 'Order[]']);
+ expect(unresolved).toEqual([]);
+ });
+
+ it('treats an empty array response as providing nothing, not as unresolved', () => {
+ const { tags, unresolved } = resolveTags(['Order:{res.id}'], {
+ response: [],
+ });
+
+ expect(tags).toEqual([]);
+ expect(unresolved).toEqual([]);
+ });
+
+ it('still reports a template no element of the array can answer', () => {
+ const { unresolved } = resolveTags(['Customer:{res.customerId}'], {
+ response: [{ id: 1 }],
+ });
+
+ expect(unresolved).toEqual(['Customer:{res.customerId}']);
+ });
+
+ it('does not let an array response answer a request-only template', () => {
+ const { unresolved } = resolveTags(['Customer:{req.customerId}'], {
+ response: [{ customerId: 'r' }],
+ });
+
+ expect(unresolved).toEqual(['Customer:{req.customerId}']);
+ });
+
+ it('prefers the request over the array response for a bare placeholder', () => {
+ const { tags } = resolveTags(['Customer:{customerId}'], {
+ query: { customerId: 'q' },
+ response: [{ customerId: 'r' }],
+ });
+
+ expect(tags).toEqual(['Customer:q']);
+ });
});
describe('queryKey', () => {
diff --git a/packages/client-core/package.json b/packages/client-core/package.json
index 96f52c9be..66b251eee 100644
--- a/packages/client-core/package.json
+++ b/packages/client-core/package.json
@@ -40,21 +40,21 @@
"name": "tag graph",
"path": "dist/index.js",
"import": "{ QueryRegistry, Invalidator, manualScheduler }",
- "limit": "2.25 kB",
+ "limit": "2.4 kB",
"gzip": true
},
{
"name": "query engine and REST transport",
"path": "dist/index.js",
"import": "{ QueryCache, RestTransport, query, mutation, configureClient }",
- "limit": "9.6 kB",
+ "limit": "9.95 kB",
"gzip": true
},
{
"name": "stream binding",
"path": "dist/index.js",
"import": "{ StreamBinder, SubscriptionManager, applyFrames }",
- "limit": "4.2 kB",
+ "limit": "4.3 kB",
"gzip": true
},
{
@@ -82,7 +82,7 @@
"name": "core, REST only",
"path": "dist/index.js",
"import": "{ QueryCache, RestTransport, EntityStore, query, mutation, configureClient, manualScheduler }",
- "limit": "9700 B",
+ "limit": "10 kB",
"gzip": true
},
{
diff --git a/packages/client-core/src/cache.ts b/packages/client-core/src/cache.ts
index a5d4d6979..489e56094 100644
--- a/packages/client-core/src/cache.ts
+++ b/packages/client-core/src/cache.ts
@@ -571,7 +571,16 @@ export class QueryCache {
const record = this.open(meta, args);
const entry = this.registry.get(record.key);
- if (record.settled && record.inflight === undefined && entry?.stale !== true) {
+ // The same three conditions `subscribe` applies before it declines to
+ // fetch, plus the same clock: a result that has aged past its staleTime
+ // is not "settled and current", and serving it here would make a route
+ // preload the one caller for whom the declared staleTime does not hold.
+ if (
+ record.settled &&
+ record.inflight === undefined &&
+ entry?.stale !== true &&
+ !this.expired(record)
+ ) {
return Promise.resolve(this.value(record) as T);
}
@@ -1370,7 +1379,7 @@ export class QueryCache {
startedAt: number,
skip?: ReadonlySet,
): unknown {
- const { skeleton, deps } = staged;
+ const { skeleton } = staged;
this.store.commit(staged, skip === undefined ? {} : { skip });
@@ -1381,7 +1390,18 @@ export class QueryCache {
record.error = undefined;
record.fetching = false;
- const value = this.value(record);
+ // Deps from the live store, not from the response walk. The store merges,
+ // so a record this response returned narrower than before still carries
+ // the nested entities an earlier response supplied, and the query still
+ // renders them; the response's own key set does not know that. Collected
+ // by the same read that produces the value, so the container identity
+ // that read keeps across an unchanged refetch is not spent on a walk.
+ const deps = new Set();
+ const base = this.base(record, deps);
+ const entry = this.registry.get(record.key);
+ const value = this.overlays.empty
+ ? base
+ : this.overlays.project(record.key, base, entry);
// NOT `value`: `entry.value` is what a placement callback is handed as
// `current`, and that callback's return reaches `adopt` -> `store.commit`
@@ -1391,7 +1411,7 @@ export class QueryCache {
// output must be held to. Passing the projection through here would let a
// temp entity ride a callback's result straight into a query skeleton, with
// nothing to remove it if the create it came from later fails.
- this.registry.settle(record.key, { value: this.base(record), deps, response, startedAt });
+ this.registry.settle(record.key, { value: base, deps, response, startedAt });
this.notify(record);
return value;
@@ -1470,12 +1490,27 @@ export class QueryCache {
record.settledTime = this.now();
record.status = 'success';
record.error = undefined;
+ // Placement is a terminal transition for whatever was in flight, exactly
+ // as a settle is: the request is discarded below, and nothing else resets
+ // this before its abandoned response finally lands. Left set, a subscriber
+ // read a settled, correct list with the loading indicator still on.
+ record.fetching = false;
if (record.inflight !== undefined) {
record.restart = false;
record.discard = true;
}
+ // The entities the placed list reaches, indexed as a fetched list's are.
+ // Without this the registry keeps the pre-placement deps, and a later
+ // invalidation of an entity that arrived only through placement -- the
+ // created order itself -- never finds this query. Collected by the same
+ // read a subscriber is about to make, for the reason `settle` gives.
+ const deps = new Set();
+
+ this.base(record, deps);
+ this.registry.adopt(record.key, deps);
+
this.notify(record);
}
@@ -1500,7 +1535,7 @@ export class QueryCache {
* skipping every currently overlaid key. It is not closed here: a read
* cannot un-know what the store already resolved it to.
*/
- private base(record: Record_): unknown {
+ private base(record: Record_, collect?: Set): unknown {
const entry = this.registry.get(record.key);
// `entry.value` is still the previous read at this point, which is what
@@ -1508,7 +1543,9 @@ export class QueryCache {
// survive a refetch on their own; the skeleton does not, because a refetch
// builds a second one and the container memos are keyed by node identity.
// See `EntityStore#read`.
- const value = record.settled ? this.store.read(record.skeleton, entry?.value) : undefined;
+ const value = record.settled
+ ? this.store.read(record.skeleton, entry?.value, collect)
+ : undefined;
if (entry !== undefined) entry.value = value;
diff --git a/packages/client-core/src/index.ts b/packages/client-core/src/index.ts
index acae05873..8c349c849 100644
--- a/packages/client-core/src/index.ts
+++ b/packages/client-core/src/index.ts
@@ -157,10 +157,13 @@ export type {
} from './ssr.js';
export type { CacheEvent, CacheObserver } from './observe.js';
export {
+ channelMessages,
+ eventSourceConnection,
forgeKeepalive,
isDuplex,
socketSnapshot,
SubscriptionManager,
+ webSocketConnection,
webTransportConnection,
} from './stream.js';
export type {
@@ -168,6 +171,8 @@ export type {
ChannelSnapshot,
DuplexStreamBinding,
EntityStreamBinding,
+ EventSourceConnectionOptions,
+ EventSourceLike,
EventTargetLike,
FrameHandler,
Keepalive,
@@ -179,6 +184,8 @@ export type {
StreamIntent,
SubscribeOptions,
SubscriptionManagerOptions,
+ WebSocketConnectionOptions,
+ WebSocketLike,
WebTransportConnectionOptions,
WebTransportLike,
} from './stream.js';
diff --git a/packages/client-core/src/live.ts b/packages/client-core/src/live.ts
index a397568dc..79245e816 100644
--- a/packages/client-core/src/live.ts
+++ b/packages/client-core/src/live.ts
@@ -95,7 +95,23 @@ export function applyFrames(
const tags = new Set();
for (const frame of frames) {
- const { binding, payload } = frame;
+ const { binding } = frame;
+
+ // Through the entity's codec, as a response is, so what reaches the store
+ // is the shape the entities table describes. A bare identity -- the
+ // ordinary evict payload -- is not a document and is passed through. A
+ // codec that throws costs the one frame, reported, not the batch.
+ let payload = frame.payload;
+
+ if (binding.decode !== undefined && payload !== null && typeof payload === 'object') {
+ try {
+ payload = binding.decode(payload);
+ } catch (error) {
+ (options.onError ?? ((e, where) => cache.report(e, where)))(error, 'decode');
+
+ continue;
+ }
+ }
if (binding.intent === 'evict') {
const key = identify(cache, binding.entity, payload);
diff --git a/packages/client-core/src/overlay.ts b/packages/client-core/src/overlay.ts
index 647aaf9af..5611b6b1a 100644
--- a/packages/client-core/src/overlay.ts
+++ b/packages/client-core/src/overlay.ts
@@ -54,6 +54,12 @@ export interface OverlayHost {
read(skeleton: unknown): T;
put(key: EntityKey, data: Readonly>, frameAt?: number): boolean;
evict(key: EntityKey, frameAt?: number): boolean;
+ /**
+ * A fresh frame stamp, for a confirmed delete to be evicted under. Optional
+ * so a narrowed test host need not supply one; without it the eviction
+ * leaves no tombstone.
+ */
+ nextFrame?(): number;
}
/**
@@ -349,7 +355,13 @@ export class OverlayStack implements OverlayLayer {
const raced = overtaken?.has(key) === true;
if (patch.kind === 'delete') {
- if (!raced) this.host.evict(key);
+ // Under a fresh stamp, as a frame's eviction is. The server has
+ // confirmed the delete, so a request dispatched before this moment
+ // is carrying an answer older than it, and the tombstone is what
+ // makes that response's answer for this key be withheld when it
+ // lands. Without one, a read of the record that was already in
+ // flight put the deleted row straight back.
+ if (!raced) this.host.evict(key, this.host.nextFrame?.() ?? 0);
// Reported when base holds nothing for this key afterwards, whether
// this patch removed the row or an evicting frame already had. What
diff --git a/packages/client-core/src/registry.ts b/packages/client-core/src/registry.ts
index 5967cd310..5c789458c 100644
--- a/packages/client-core/src/registry.ts
+++ b/packages/client-core/src/registry.ts
@@ -339,11 +339,18 @@ export class QueryRegistry {
? resolveTags(entry.provides, { ...entry.args, response: result.response })
: { tags: new Set(supplied), unresolved: [] as readonly string[] };
- for (const template of resolved.unresolved) this.onUnresolved?.(template, entry);
-
if (result.deps !== undefined) entry.deps = new Set(result.deps);
if ('value' in result) entry.value = result.value;
+ // An item template the response could not answer is still satisfied when
+ // the store just normalized records of that type out of the same response:
+ // an enveloped collection cannot resolve `Order:{id}` against `{items,
+ // total}`, but the `Order:7` in its deps is that template resolved by
+ // another route. Only a type the response never normalized is reported.
+ for (const template of resolved.unresolved) {
+ if (!providedByDeps(template, entry.deps)) this.onUnresolved?.(template, entry);
+ }
+
this.retag(entry, new Set([...resolved.tags, ...entry.deps]));
entry.stale = false;
@@ -424,6 +431,30 @@ export class QueryRegistry {
entry.settledAt = this.clock;
}
+ /**
+ * Swap the entity keys a placed query reaches, keeping its resolved
+ * `provides`.
+ *
+ * Placement's half of `settle`. A placed list is normalized like a fetched
+ * one, so the entities it now references have to be indexed the same way,
+ * or a later invalidation of an entity the query acquired only through
+ * placement -- `Order:9`, minted by the create that placed it -- finds no
+ * bucket for the query and never reaches it.
+ */
+ adopt(key: string, deps: Iterable): void {
+ const entry = this.entries.get(key);
+
+ if (entry === undefined) return;
+
+ const next = new Set(deps);
+ const tags = new Set(next);
+
+ for (const tag of entry.tags) if (!entry.deps.has(tag)) tags.add(tag);
+
+ entry.deps = next;
+ this.retag(entry, tags);
+ }
+
/**
* Forget a query entirely, mounted or not.
*
@@ -558,3 +589,15 @@ export class QueryRegistry {
if (bucket.size === 0) this.index.delete(tag);
}
}
+
+/** Whether `deps` holds a key of the entity type a tag template names. */
+function providedByDeps(template: string, deps: ReadonlySet): boolean {
+ // `Order:{id}` -> `Order:`; a template with no colon names no entity.
+ const prefix = template.slice(0, template.indexOf(':') + 1);
+
+ if (prefix === '') return false;
+
+ for (const dep of deps) if (dep.startsWith(prefix)) return true;
+
+ return false;
+}
diff --git a/packages/client-core/src/store.ts b/packages/client-core/src/store.ts
index 10e0611bb..967eabbcb 100644
--- a/packages/client-core/src/store.ts
+++ b/packages/client-core/src/store.ts
@@ -442,9 +442,16 @@ export class EntityStore {
*
* Omit it and the old behaviour is what happens, which is what every caller
* that has no previous read wants.
+ *
+ * `collect` receives every entity key the read reached, which is what
+ * `dependencies` reports, from the same walk. A caller that needs both the
+ * value and its deps takes them from one read: a second walk for the deps
+ * would memoize fresh containers before the read that carries `previous`
+ * gets to compare against it, and the identity that read exists to keep
+ * would be lost.
*/
- read(skeleton: unknown, previous?: unknown): T {
- return this.materialize(skeleton, new Set(), previous) as T;
+ read(skeleton: unknown, previous?: unknown, collect?: Set): T {
+ return this.materialize(skeleton, collect ?? new Set(), previous) as T;
}
/**
diff --git a/packages/client-core/src/stream.ts b/packages/client-core/src/stream.ts
index 24396bc96..07681aaa0 100644
--- a/packages/client-core/src/stream.ts
+++ b/packages/client-core/src/stream.ts
@@ -29,6 +29,19 @@ export interface EntityStreamBinding {
readonly intent: StreamIntent;
/** Tag templates this message invalidates, unresolved. */
readonly invalidates: readonly string[];
+ /**
+ * Turns the wire payload into the client-side shape the entities table
+ * describes.
+ *
+ * A REST response is decoded through the generated codec before it is
+ * normalized, so under camelCase naming the store sees `customerId` and the
+ * entities table names `customerId`. A frame used to skip that step: the
+ * payload went into the store as the wire wrote it, so a renamed id field
+ * never matched and a renamed nested field was never there to read. The
+ * generated manifest supplies the entity's codec here; absent means the
+ * wire shape is the client shape, which is what `preserve` naming produces.
+ */
+ readonly decode?: (payload: unknown) => unknown;
}
/**
@@ -288,6 +301,187 @@ export function webTransportConnection(
};
}
+/**
+ * A WebSocket, narrowed to what the adapter below touches.
+ *
+ * Structural, so the DOM `WebSocket`, the `ws` package's, and a test fake all
+ * fit, and so importing this module on a server names no browser global.
+ */
+export interface WebSocketLike {
+ onmessage: ((event: { readonly data: unknown }) => void) | null;
+ onclose: ((event?: unknown) => void) | null;
+ onerror: ((event: unknown) => void) | null;
+ send(data: string): void;
+ close(): void;
+}
+
+export interface WebSocketConnectionOptions {
+ /**
+ * Turn one message's `data` into a frame. JSON text is parsed by default and
+ * anything else is passed through, which covers a socket the application
+ * already configured for binary frames. A throw is reported and the frame
+ * dropped.
+ */
+ readonly parse?: (data: unknown) => unknown;
+}
+
+/**
+ * Adapt an already-open WebSocket to a `StreamConnection`.
+ *
+ * The socket is passed in open, as every adapter here takes its transport:
+ * this package opens nothing. `send` is there for `forgeKeepalive`, which
+ * answers the streaming extension's ping; an object is JSON-encoded and a
+ * string is sent as is.
+ */
+export function webSocketConnection(
+ socket: WebSocketLike,
+ options: WebSocketConnectionOptions = {},
+): StreamConnection {
+ const parse = options.parse ?? parseText;
+
+ let failed: ((error: unknown) => void) | undefined;
+ let over = false;
+
+ return {
+ onMessage(handler) {
+ socket.onmessage = (event) => {
+ try {
+ handler(parse(event.data));
+ } catch (error) {
+ failed?.(error);
+ }
+ };
+ },
+ onClose(handler) {
+ socket.onclose = (reason) => {
+ if (over) return;
+
+ over = true;
+ handler(reason);
+ };
+ },
+ onError(handler) {
+ failed = handler;
+ socket.onerror = (event) => handler(event);
+ },
+ send(message) {
+ socket.send(typeof message === 'string' ? message : JSON.stringify(message));
+ },
+ close() {
+ // The manager asked; a close it asked for is not a drop to reconnect from.
+ over = true;
+ socket.close();
+ },
+ };
+}
+
+/**
+ * An `EventSource`, narrowed to what the adapter below touches.
+ *
+ * Named events reach an `EventSource` only through `addEventListener`, so
+ * that is the one method the contract needs beyond `close`. `readyState`
+ * distinguishes an error the source will retry from one it has given up on.
+ */
+export interface EventSourceLike {
+ addEventListener(
+ type: string,
+ listener: (event: { readonly data: string; readonly lastEventId?: string }) => void,
+ ): void;
+ onerror: ((event: unknown) => void) | null;
+ readonly readyState?: number;
+ close(): void;
+}
+
+export interface EventSourceConnectionOptions {
+ /**
+ * The event names to listen for: the channel's messages in the generated
+ * `streams` table, which `channelMessages` reads out for you. An
+ * `EventSource` delivers a named event to nothing unless something asked
+ * for it by name, so a name missing here is a frame that never arrives.
+ */
+ readonly events: readonly string[];
+ /** Turn an event's `data` into a payload. JSON by default. */
+ readonly parse?: (data: string) => unknown;
+}
+
+/** The two control events the streaming extension sends on a resumed stream. */
+const CONTROL_EVENTS = ['forge.resumed', 'forge.gap'] as const;
+
+/**
+ * Adapt an `EventSource` to a `StreamConnection`.
+ *
+ * Each event is delivered as `{event, data, id}`, which the default frame
+ * decoder reads as a message named by `event`. The source's own reconnect is
+ * not used: an error closes the source and reports a drop, so the manager
+ * reconnects with its backoff and `StreamBinder` recovers the gap, the same
+ * way it does for a socket. Letting the source retry on its own would leave
+ * the manager thinking a connection it could not see was still open.
+ */
+export function eventSourceConnection(
+ source: EventSourceLike,
+ options: EventSourceConnectionOptions,
+): StreamConnection {
+ const parse = options.parse ?? ((data: string): unknown => JSON.parse(data));
+
+ let closed: ((reason?: unknown) => void) | undefined;
+ let failed: ((error: unknown) => void) | undefined;
+ let over = false;
+
+ const finish = (reason?: unknown): void => {
+ if (over) return;
+
+ over = true;
+ closed?.(reason);
+ };
+
+ return {
+ onMessage(handler) {
+ for (const name of [...options.events, ...CONTROL_EVENTS]) {
+ source.addEventListener(name, (event) => {
+ try {
+ handler({ event: name, data: parse(event.data), id: event.lastEventId });
+ } catch (error) {
+ failed?.(error);
+ }
+ });
+ }
+ },
+ onClose(handler) {
+ closed = handler;
+ },
+ onError(handler) {
+ failed = handler;
+ source.onerror = (event) => {
+ // A source already closed has nothing further to say.
+ if (over) return;
+
+ handler(event);
+ source.close();
+ finish(event);
+ };
+ },
+ close() {
+ over = true;
+ source.close();
+ },
+ };
+}
+
+/** The message names the generated `streams` table binds on one channel. */
+export function channelMessages(bindings: readonly StreamBinding[], channel: string): string[] {
+ const names: string[] = [];
+
+ for (const b of bindings) {
+ if (!isDuplex(b) && b.channel === channel && !names.includes(b.message)) names.push(b.message);
+ }
+
+ return names;
+}
+
+function parseText(data: unknown): unknown {
+ return typeof data === 'string' ? JSON.parse(data) : data;
+}
+
/** Everything the factory is told about the socket it is being asked for. */
export interface StreamConnectContext {
/** The endpoint this socket serves. */
diff --git a/packages/client-core/src/tags.ts b/packages/client-core/src/tags.ts
index 0acb5fc6e..0206afa81 100644
--- a/packages/client-core/src/tags.ts
+++ b/packages/client-core/src/tags.ts
@@ -68,18 +68,47 @@ export function resolveTags(templates: readonly string[], ctx: TagContext): Reso
const unresolved: string[] = [];
const seen = new Set();
+ const push = (tag: string): void => {
+ if (!seen.has(tag)) {
+ seen.add(tag);
+ tags.push(tag);
+ }
+ };
+
for (const template of templates) {
const tag = resolveTag(template, ctx);
- if (tag === undefined) {
- unresolved.push(template);
+ if (tag !== undefined) {
+ push(tag);
continue;
}
- if (seen.has(tag)) continue;
+ // A collection answers a response template once per element. `GET /orders`
+ // declares `Order:{id}`, and what that promises is one tag per record
+ // returned, not a property the array itself carries. Resolving against the
+ // array as a whole finds nothing and would report the healthiest query in
+ // the application as a declaration that resolved to nothing. An empty
+ // array provides nothing, which is not the same as failing to resolve:
+ // the template was answered, with zero records. A template whose every
+ // placeholder is `req.`-scoped is left out, since no response answers it.
+ const response = ctx.response;
+
+ if (Array.isArray(response) && /\{(?!\s*req\.)/.test(template)) {
+ let answered = response.length === 0;
+
+ for (const item of response) {
+ const each = resolveTag(template, { ...ctx, response: item });
+
+ if (each !== undefined) {
+ answered = true;
+ push(each);
+ }
+ }
+
+ if (answered) continue;
+ }
- seen.add(tag);
- tags.push(tag);
+ unresolved.push(template);
}
return { tags, unresolved };
@@ -126,14 +155,27 @@ function fromRequest(expr: string, ctx: TagContext): unknown {
return fromQuery !== undefined ? fromQuery : dig(ctx.body, expr);
}
-/** Walk a dotted path. Numeric segments index arrays, which are objects too. */
+/**
+ * Walk a dotted path. Numeric segments index arrays, which are objects too.
+ *
+ * A segment that names no property is retried under its other spellings:
+ * `customer_id` finds `customerId`, and the reverse. A template is written
+ * against the wire, because that is what the server can see, while the body
+ * and the response it is resolved against carry the client-side names. The
+ * generator renames templates it can see the schema for; this is the
+ * fallback for a document it could not, or one generated before it did. An
+ * exact key always wins, so a payload carrying both spellings is read as
+ * written.
+ */
function dig(root: unknown, path: string): unknown {
let node: unknown = root;
for (const segment of path.split('.')) {
if (node === null || typeof node !== 'object') return undefined;
- node = (node as Record)[segment];
+ const record = node as Record;
+
+ node = record[segment in record ? segment : (spelledAs(record, segment) ?? segment)];
if (node === undefined) return undefined;
}
@@ -141,6 +183,15 @@ function dig(root: unknown, path: string): unknown {
return node;
}
+/** The key of `record` that is `name` under another casing, if there is one. */
+function spelledAs(record: Record, name: string): string | undefined {
+ // `customer_id`, `customerId`, `CustomerID` and `customer-id` all fold alike.
+ const fold = (key: string): string => key.replace(/[_-]/g, '').toLowerCase();
+ const wanted = fold(name);
+
+ return Object.keys(record).find((key) => fold(key) === wanted);
+}
+
/**
* Whether a value can stand in a tag.
*
diff --git a/packages/client-react/__tests__/useMutation.test.tsx b/packages/client-react/__tests__/useMutation.test.tsx
index f15551228..0a0936db6 100644
--- a/packages/client-react/__tests__/useMutation.test.tsx
+++ b/packages/client-react/__tests__/useMutation.test.tsx
@@ -53,6 +53,35 @@ describe('useMutation', () => {
expect(handle.isPending).toBe(false);
});
+ // `MutationOptions.client` is accepted per call, and the raw `mutation()`
+ // binding honours it. The hook resolved its own client at mount and used to
+ // spread it last, so a per-call cache was accepted by the types and then
+ // silently replaced: the write ran against the hook's cache, and the caller
+ // redirecting one mutation to a fixture or per-request cache saw it succeed
+ // in the wrong place.
+ it('runs the write against a client supplied per call', async () => {
+ const hook = harness(() => ({ id: 1, total: 1 }));
+ const perCall = harness(() => ({ id: 2, total: 2 }));
+
+ let handle!: UseMutationResult;
+
+ function Create() {
+ handle = useMutation(useOrderCreate);
+
+ return null;
+ }
+
+ render(wrap(hook, ));
+
+ await act(async () => {
+ await handle.mutateAsync({ body: { total: 2 } }, { client: perCall.cache });
+ });
+
+ expect(perCall.transport.calls).toHaveLength(1);
+ expect(hook.transport.calls).toHaveLength(0);
+ expect(handle.data).toEqual({ id: 2, total: 2 });
+ });
+
it('records an error, and reset returns it to idle', async () => {
const h = harness(() => {
throw new Error('conflict');
diff --git a/packages/client-react/src/useMutation.ts b/packages/client-react/src/useMutation.ts
index 844d17f93..1518ce86e 100644
--- a/packages/client-react/src/useMutation.ts
+++ b/packages/client-react/src/useMutation.ts
@@ -154,7 +154,16 @@ export function useMutation(
setState(PENDING);
try {
- const data = await op(args, { ...latest.current, ...perCall, client });
+ // The per-call client wins when given. `MutationOptions.client` is
+ // accepted here as it is on the raw binding, and spreading the
+ // hook's client last silently replaced it: the write ran against the
+ // cache resolved at mount, and the caller redirecting one mutation to
+ // a fixture or per-request cache saw it succeed in the wrong place.
+ const data = await op(args, {
+ ...latest.current,
+ ...perCall,
+ client: perCall?.client ?? client,
+ });
if (alive.current && seq.current === call) {
setState({ status: 'success', data, error: undefined, isPending: false });
diff --git a/packages/client-vue/__tests__/useMutation.test.ts b/packages/client-vue/__tests__/useMutation.test.ts
index ef91032f1..2587d0ff1 100644
--- a/packages/client-vue/__tests__/useMutation.test.ts
+++ b/packages/client-vue/__tests__/useMutation.test.ts
@@ -66,6 +66,26 @@ describe('useMutation', () => {
expect(create.isPending.value).toBe(false);
});
+ // `MutationOptions.client` is accepted per call and the raw binding honours
+ // it; the hook used to spread its own client last and silently replace it.
+ it('runs the write against a client supplied per call', async () => {
+ const hook = harness(() => ({ id: 1, total: 1 }));
+ const perCall = harness(() => ({ id: 2, total: 2 }));
+
+ let create!: UseMutationResult;
+
+ mountWith(hook, () => {
+ create = useMutation(useOrderCreate);
+ });
+
+ await create.mutateAsync({ body: { total: 2 } }, { client: perCall.cache });
+ await flushPromises();
+
+ expect(perCall.transport.calls).toHaveLength(1);
+ expect(hook.transport.calls).toHaveLength(0);
+ expect(create.data.value).toEqual({ id: 2, total: 2 });
+ });
+
it('records an error, and reset returns it to idle', async () => {
const fx = harness(() => {
throw new Error('conflict');
diff --git a/packages/client-vue/src/useMutation.ts b/packages/client-vue/src/useMutation.ts
index 71a3d47cd..9f1890b69 100644
--- a/packages/client-vue/src/useMutation.ts
+++ b/packages/client-vue/src/useMutation.ts
@@ -143,7 +143,12 @@ export function useMutation(
try {
// The hook-level options are read *now*, not captured at setup, so a
// getter that depends on reactive state contributes its current value.
- const data = await op(args, { ...toValue(options), ...perCall, client });
+ // The per-call client wins when given; see the React binding for why.
+ const data = await op(args, {
+ ...toValue(options),
+ ...perCall,
+ client: perCall?.client ?? client,
+ });
if (alive && seq === call) {
state.value = { status: 'success', data, error: undefined, isPending: false };
diff --git a/router_asyncapi.go b/router_asyncapi.go
index af64f82c2..38642eca5 100644
--- a/router_asyncapi.go
+++ b/router_asyncapi.go
@@ -14,6 +14,28 @@ func WithWebSocketMessages(sendSchema, receiveSchema any) RouteOption {
return router.WithWebSocketMessages(sendSchema, receiveSchema)
}
+// WebTransportMessages declares the payload types a WebTransport endpoint
+// carries. See router.WebTransportMessages.
+type WebTransportMessages = router.WebTransportMessages
+
+// WithWebTransportMessages defines the message schemas for a WebTransport
+// endpoint, which puts it in the AsyncAPI document and lets the client
+// generator type each stream kind.
+//
+// Example:
+//
+// router.WebTransport("/wt/orders", handler,
+// forge.WithWebTransportMessages(forge.WebTransportMessages{
+// Datagram: &OrderTick{},
+// BidiSend: &OrderCommand{},
+// BidiReceive: &Order{},
+// }),
+// forge.WithStreamBinding(forge.Emits[Order]("order.updated")),
+// )
+func WithWebTransportMessages(messages WebTransportMessages) RouteOption {
+ return router.WithWebTransportMessages(messages)
+}
+
// WithSSEMessages defines message schemas for SSE endpoints
// messageSchemas: map of event names to their schemas
// SSE is receive-only (server -> client), so action is always "receive".