@workerstack/clients 1.0.0-rc.27 → 1.0.0-rc.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +30 -7
  2. package/dist/emit/cli/commands.js +25 -5
  3. package/dist/emit/cli/flags.js +7 -3
  4. package/dist/emit/cli/skills.js +5 -1
  5. package/dist/emit/csharp/realtime.d.ts +1 -8
  6. package/dist/emit/csharp/realtime.js +25 -25
  7. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  8. package/dist/emit/csharp/sdk-method.js +9 -2
  9. package/dist/emit/csharp/sse.d.ts +0 -11
  10. package/dist/emit/csharp/sse.js +91 -10
  11. package/dist/emit/csharp/transport.js +3 -3
  12. package/dist/emit/csharp/types-messages.d.ts +47 -0
  13. package/dist/emit/csharp/types-messages.js +172 -0
  14. package/dist/emit/csharp/types-names.js +3 -2
  15. package/dist/emit/csharp/ws.d.ts +0 -15
  16. package/dist/emit/csharp/ws.js +26 -5
  17. package/dist/emit/go/sdk-answer.d.ts +24 -1
  18. package/dist/emit/go/sdk-method.d.ts +3 -0
  19. package/dist/emit/go/sdk-method.js +16 -10
  20. package/dist/emit/go/sse.d.ts +2 -10
  21. package/dist/emit/go/sse.js +87 -12
  22. package/dist/emit/go/types-union.d.ts +3 -2
  23. package/dist/emit/go/types-union.js +2 -0
  24. package/dist/emit/go/types.d.ts +6 -0
  25. package/dist/emit/go/types.js +12 -1
  26. package/dist/emit/go/ws.d.ts +4 -11
  27. package/dist/emit/go/ws.js +214 -58
  28. package/dist/emit/java/json.d.ts +3 -0
  29. package/dist/emit/java/layout-ast.d.ts +4 -1
  30. package/dist/emit/java/layout-types.js +1 -1
  31. package/dist/emit/java/models-names.d.ts +2 -0
  32. package/dist/emit/java/models-names.js +1 -0
  33. package/dist/emit/java/models-union.d.ts +12 -1
  34. package/dist/emit/java/models-union.js +11 -5
  35. package/dist/emit/java/models.d.ts +5 -0
  36. package/dist/emit/java/models.js +22 -7
  37. package/dist/emit/java/realtime.d.ts +29 -9
  38. package/dist/emit/java/realtime.js +45 -10
  39. package/dist/emit/java/sdk-mirror.js +6 -5
  40. package/dist/emit/java/sdk-op.js +1 -1
  41. package/dist/emit/java/sse.d.ts +11 -10
  42. package/dist/emit/java/sse.js +104 -5
  43. package/dist/emit/java/ws.d.ts +46 -7
  44. package/dist/emit/java/ws.js +89 -4
  45. package/dist/emit/mcp/output-schema.d.ts +4 -2
  46. package/dist/emit/mcp/output-schema.js +56 -12
  47. package/dist/emit/python/realtime.d.ts +9 -6
  48. package/dist/emit/python/realtime.js +21 -19
  49. package/dist/emit/python/sdk-answer.d.ts +5 -1
  50. package/dist/emit/python/sdk-method.d.ts +1 -1
  51. package/dist/emit/python/sdk-method.js +33 -6
  52. package/dist/emit/python/sdk.js +22 -2
  53. package/dist/emit/python/sse.d.ts +0 -5
  54. package/dist/emit/python/sse.js +35 -5
  55. package/dist/emit/python/types.d.ts +7 -0
  56. package/dist/emit/python/types.js +20 -3
  57. package/dist/emit/python/ws.d.ts +20 -6
  58. package/dist/emit/python/ws.js +67 -1
  59. package/dist/emit/rust/realtime.d.ts +7 -5
  60. package/dist/emit/rust/realtime.js +14 -17
  61. package/dist/emit/rust/sdk-method.js +1 -1
  62. package/dist/emit/rust/sse.d.ts +11 -7
  63. package/dist/emit/rust/sse.js +52 -6
  64. package/dist/emit/rust/types-union.d.ts +9 -1
  65. package/dist/emit/rust/types-union.js +4 -0
  66. package/dist/emit/rust/types.d.ts +9 -0
  67. package/dist/emit/rust/types.js +13 -7
  68. package/dist/emit/rust/ws.d.ts +22 -4
  69. package/dist/emit/rust/ws.js +57 -7
  70. package/dist/emit/ts/route-tree.d.ts +1 -1
  71. package/dist/emit/ts/route-tree.js +0 -11
  72. package/dist/emit/ts/sdk-types-preamble.js +4 -0
  73. package/dist/emit/ts/sdk-types.js +49 -10
  74. package/dist/emit/ts/sdk.js +2 -2
  75. package/dist/emit/ts/service-map.d.ts +8 -2
  76. package/dist/emit/ts/service-map.js +30 -2
  77. package/dist/emit/ts/type-gen.d.ts +4 -3
  78. package/dist/emit/ts/type-gen.js +83 -40
  79. package/dist/extract/chain.d.ts +10 -6
  80. package/dist/extract/chain.js +5 -19
  81. package/dist/extract/extract.d.ts +2 -2
  82. package/dist/extract/extract.js +37 -23
  83. package/dist/extract/walk.d.ts +15 -4
  84. package/dist/extract/walk.js +159 -15
  85. package/dist/ir/build.js +4 -0
  86. package/dist/ir/model.d.ts +16 -0
  87. package/dist/ir/sdk-model.d.ts +25 -1
  88. package/dist/ir/sdk-model.js +35 -5
  89. package/dist/ir/slots.d.ts +1 -1
  90. package/dist/ir/slots.js +11 -3
  91. package/dist/ir/streams.d.ts +16 -0
  92. package/dist/ir/streams.js +40 -0
  93. package/dist/runtime/cli/socket.go +107 -13
  94. package/dist/runtime/cli/stream.go +18 -11
  95. package/dist/runtime/csharp/Adapters.cs +12 -11
  96. package/dist/runtime/csharp/Events.cs +22 -17
  97. package/dist/runtime/csharp/Realtime.cs +50 -23
  98. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  99. package/dist/runtime/csharp/TransportSse.cs +3 -3
  100. package/dist/runtime/csharp/Ws.cs +1 -1
  101. package/dist/runtime/csharp/WsDial.cs +19 -1
  102. package/dist/runtime/csharp/WsTyped.cs +109 -0
  103. package/dist/runtime/go/realtime.go +125 -41
  104. package/dist/runtime/go/realtime_loop.go +21 -18
  105. package/dist/runtime/go/result.go +2 -1
  106. package/dist/runtime/go/sse.go +11 -0
  107. package/dist/runtime/go/stream.go +29 -13
  108. package/dist/runtime/go/transport.go +15 -21
  109. package/dist/runtime/go/transport_longpoll.go +3 -4
  110. package/dist/runtime/go/transport_sse.go +6 -6
  111. package/dist/runtime/go/ws.go +157 -61
  112. package/dist/runtime/java/EventStream.java +47 -29
  113. package/dist/runtime/java/Exchange.java +5 -5
  114. package/dist/runtime/java/Flight.java +3 -3
  115. package/dist/runtime/java/Realtime.java +45 -11
  116. package/dist/runtime/java/ResumableConnection.java +77 -32
  117. package/dist/runtime/java/Socket.java +8 -4
  118. package/dist/runtime/java/SseAdapter.java +1 -1
  119. package/dist/runtime/java/TypedWebSocket.java +81 -24
  120. package/dist/runtime/java/WsAdapter.java +4 -2
  121. package/dist/runtime/java/WsDial.java +12 -5
  122. package/dist/runtime/python/events.py +25 -11
  123. package/dist/runtime/python/operation.py +6 -1
  124. package/dist/runtime/python/realtime.py +47 -33
  125. package/dist/runtime/python/send_async.py +1 -0
  126. package/dist/runtime/python/transport_sse.py +2 -2
  127. package/dist/runtime/python/transport_ws.py +1 -1
  128. package/dist/runtime/python/ws.py +100 -39
  129. package/dist/runtime/rust/events.rs +64 -41
  130. package/dist/runtime/rust/realtime.rs +80 -34
  131. package/dist/runtime/rust/realtime_loop.rs +37 -12
  132. package/dist/runtime/rust/sse.rs +3 -2
  133. package/dist/runtime/rust/transport_sse.rs +1 -1
  134. package/dist/runtime/rust/transport_ws.rs +3 -2
  135. package/dist/runtime/rust/ws.rs +122 -50
  136. package/dist/runtime/ts/realtime-connection.ts +22 -0
  137. package/dist/runtime/ts/realtime-transports.ts +13 -4
  138. package/dist/runtime/ts/realtime.ts +27 -3
  139. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  140. package/dist/runtime/ts/sdk-sse.ts +31 -14
  141. package/dist/runtime/ts/sdk-ws.ts +2 -1
  142. package/dist/runtime/ts/sdk.ts +9 -2
  143. package/dist/runtime/ts/sse.ts +8 -0
  144. package/dist/runtime/ts/ws.ts +88 -50
  145. package/package.json +3 -61
@@ -1,70 +1,226 @@
1
- /**
2
- * A WebSocket or realtime operation as a Go method. A WebSocket operation dials its socket and
3
- * returns `(*TypedWebSocket, error)`: `<Op>Opts.ReconnectToken` rides as the `reconnect_token`
4
- * query param after the declared ones, and `Protocols` are the subprotocols it offers. A realtime
5
- * operation returns `(*ResumableConnection, error)`, already open over the WebSocket, SSE and
6
- * long-poll chain, its ctx bounding the open (Fd1); its Opts carry the resume cursor, the protocols
7
- * and the reconnect policy. A declared param on a resume channel the runtime sends itself is carried
8
- * by those fields, so the wire holds one pair (Fd3). Neither declares a response a caller receives.
9
- */
1
+ import { dispatchOf, isJsonEventData } from "../../ir/sdk-model.js";
2
+ import { goString, lineComment } from "../shared/escape.js";
3
+ import { goExported, NameScope } from "../shared/lang.js";
10
4
  import { sendArgs } from "./sdk-answer.js";
11
5
  import { isLastEventIdHeader } from "./sse.js";
6
+ import { goKeyedMembers, goTypeOf } from "./types.js";
12
7
  /** Whether a declared param is the `reconnect_token` query param a WebSocket dial sends. */
13
8
  const isReconnectToken = (param, where) => where === "query" && param === "reconnect_token";
14
9
  /* both open a socket: a dial fails before any stream exists */
15
10
  const FAIL = "nil, err";
16
- const WS_STREAM = {
17
- doc: "",
18
- opts: {
19
- before: [],
20
- carries: isReconnectToken,
21
- fields: [
22
- { name: "ReconnectToken", type: "string" },
23
- { name: "Protocols", type: "[]string" },
24
- ],
25
- sets: [
26
- 'if opts.ReconnectToken != "" {',
27
- '\tc.query.set("reconnect_token", opts.ReconnectToken)',
28
- "}",
29
- "c.protocols = opts.Protocols",
30
- ],
31
- },
32
- shape: {
33
- fail: FAIL,
34
- returns: "(*TypedWebSocket, error)",
35
- tail: (client) => [`\treturn dialWebSocket(${sendArgs(client)})`],
36
- },
11
+ const WS_OPTS = {
12
+ before: [],
13
+ carries: isReconnectToken,
14
+ fields: [
15
+ { name: "ReconnectToken", type: "string" },
16
+ { name: "Protocols", type: "[]string" },
17
+ ],
18
+ sets: [
19
+ 'if opts.ReconnectToken != "" {',
20
+ '\tc.query.set("reconnect_token", opts.ReconnectToken)',
21
+ "}",
22
+ "c.protocols = opts.Protocols",
23
+ ],
24
+ };
25
+ const WS = {
26
+ base: "TypedWebSocket",
27
+ handlers: ["OnMessage", "OnClose", "OnError"],
28
+ suffix: "Socket",
29
+ what: "socket",
30
+ open: (client, read, write) => `dialWebSocket(${sendArgs(client, read, write)})`,
37
31
  };
38
- /* the realtime Opts' own fields: each is the TransportOpts field of its name, which `sets` copies */
32
+ const REALTIME = {
33
+ base: "ResumableConnection",
34
+ handlers: ["OnMessage"],
35
+ suffix: "Connection",
36
+ what: "connection",
37
+ open: (client, read, write) => `newRealtime(${sendArgs(client, "topts", read, write)})`,
38
+ };
39
+ /** `<Op><direction>`, the sealed interface of the keyed union `schema`'s members, each marked as one; its lines. */
40
+ function sealed(op, members, iface, says) {
41
+ const types = [...new Set(members.map(([, type]) => type))];
42
+ return [
43
+ ...lineComment(`${iface} is a message ${says} on ${op.id}: ${types.join(", ")}.`, "//"),
44
+ `type ${iface} interface {`,
45
+ `\tis${iface}()`,
46
+ "}",
47
+ ...types.flatMap((type) => ["", `func (${type}) is${iface}() {}`]),
48
+ ];
49
+ }
50
+ /**
51
+ * The read side of `op`'s socket from what the server sends (`send`): `<Op>Inbound` when keyed, declared in `at` with
52
+ * `<Op>OtherMessage` for a value it does not declare and the decoder reading a frame by its key; else its Go type,
53
+ * read as JSON; `untyped()` when it declares none.
54
+ */
55
+ function inbound(op, send, untyped, at) {
56
+ if (send === undefined)
57
+ return untyped();
58
+ const here = { ...at, fieldName: "Send", parentName: op.id };
59
+ const dispatch = dispatchOf(send, at.names.resolve);
60
+ if (dispatch !== undefined)
61
+ return keyedInbound(op, send, dispatch, here);
62
+ const type = goTypeOf(send, here).replace(/^\*/, "");
63
+ return { codec: `frameJSON[${type}]`, type };
64
+ }
65
+ /** `<Op>Inbound`, its types, `<Op>OtherMessage` and its decoder, declared in one block in `at`. */
66
+ function keyedInbound(op, send, dispatch, at) {
67
+ const members = goKeyedMembers(send, dispatch, at);
68
+ const base = goExported(op.id);
69
+ const iface = at.names.claimConst(`${base}Inbound`);
70
+ const other = at.names.claimConst(`${base}OtherMessage`);
71
+ const decode = at.names.claimConst(`decode${iface}`);
72
+ const key = goString(dispatch.key);
73
+ at.decls.set(iface, [
74
+ ...sealed(op, [...members, ["", other]], iface, "the server sends"),
75
+ "",
76
+ ...lineComment(`${other} is a message whose ${key} ${op.id} does not declare, as sent.`, "//"),
77
+ `type ${other} struct {`,
78
+ "\tRaw json.RawMessage",
79
+ "}",
80
+ "",
81
+ "// MarshalJSON is the message as sent.",
82
+ `func (m ${other}) MarshalJSON() ([]byte, error) { return m.Raw.MarshalJSON() }`,
83
+ "",
84
+ `// ${decode} is a frame as the message its ${key} names.`,
85
+ `func ${decode}(data []byte) (${iface}, error) {`,
86
+ `\tkey, err := frameKey(data, ${key})`,
87
+ "\tif err != nil {",
88
+ "\t\treturn nil, err",
89
+ "\t}",
90
+ "\tswitch key {",
91
+ ...members.flatMap(([value, type]) => [
92
+ `\tcase ${goString(value)}:`,
93
+ `\t\tm, err := frameJSON[${type}](data)`,
94
+ "\t\treturn m, err",
95
+ ]),
96
+ "\t}",
97
+ `\treturn ${other}{Raw: data}, nil`,
98
+ "}",
99
+ ].join("\n"));
100
+ return { codec: decode, decode, key: dispatch.key, members, type: iface };
101
+ }
102
+ /* a send of an op that declares none: as given */
103
+ const UNTYPED_OUT = { codec: "messageAsIs", type: "any" };
104
+ /** The fields `schema` requires at its top level: an object's, none for any other schema. */
105
+ function requiredOf(schema, at) {
106
+ const resolved = at.names.resolve(schema);
107
+ return resolved.kind === "object" ? resolved.fields.filter((field) => field.required).map((field) => field.name) : [];
108
+ }
109
+ /** The write side of `op`'s socket from what the server receives (`receive`): `<Op>Outbound` when keyed, else its Go type, written as JSON; `any` when it declares none. */
110
+ function outbound(op, receive, at) {
111
+ if (receive === undefined)
112
+ return UNTYPED_OUT;
113
+ const here = { ...at, fieldName: "Receive", parentName: op.id };
114
+ const dispatch = dispatchOf(receive, at.names.resolve);
115
+ if (dispatch === undefined) {
116
+ const type = goTypeOf(receive, here).replace(/^\*/, "");
117
+ return { codec: `messageJSON[${type}]`, sends: { key: null, required: requiredOf(receive, at), type }, type };
118
+ }
119
+ const members = goKeyedMembers(receive, dispatch, here);
120
+ const iface = at.names.claimConst(`${goExported(op.id)}Outbound`);
121
+ at.decls.set(iface, sealed(op, members, iface, "the server receives").join("\n"));
122
+ const sends = {
123
+ key: dispatch.key,
124
+ members: members.map(([value, type], i) => ({
125
+ required: requiredOf(dispatch.members[i]?.variant, at),
126
+ type,
127
+ value,
128
+ })),
129
+ };
130
+ return { codec: `messageJSON[${iface}]`, sends, type: iface };
131
+ }
132
+ /** `<Op><suffix>` around `base`, an On<Value> per member whose method no handler names, declared in `at`; null when none is left. */
133
+ function socketType(op, kind, { base, read }, at) {
134
+ const scope = new NameScope(kind.handlers);
135
+ const handlers = read.members.flatMap(([value, type]) => {
136
+ const method = `On${goExported(value)}`;
137
+ return scope.has(method) ? [] : [{ method: scope.claim(method), type, value }];
138
+ });
139
+ if (handlers.length === 0)
140
+ return null;
141
+ const name = at.names.claimConst(`${goExported(op.id)}${kind.suffix}`);
142
+ at.decls.set(name, [
143
+ ...lineComment(`${name} is the ${kind.what} of ${op.id}: each On<Value> takes the messages whose ${goString(read.key)} is that value.`, "//"),
144
+ `type ${name} struct {`,
145
+ `\t*${base}`,
146
+ "}",
147
+ ...handlers.flatMap(({ method, type, value }) => [
148
+ "",
149
+ `// ${method} registers a handler for each ${goString(value)} message.`,
150
+ `func (s *${name}) ${method}(handler func(${type})) {`,
151
+ `\ts.OnMessage(func(m ${read.type}) {`,
152
+ `\t\tif v, ok := m.(${type}); ok {`,
153
+ "\t\t\thandler(v)",
154
+ "\t\t}",
155
+ "\t})",
156
+ "}",
157
+ ]),
158
+ ].join("\n"));
159
+ return name;
160
+ }
161
+ /** `op`'s answer of `kind`: its runtime type of both sides, or its own type around it; the call that opens it; what it sends, typed. */
162
+ function answerOf(op, kind, { read, write }, at) {
163
+ const base = `${kind.base}[${read.type}, ${write.type}]`;
164
+ const call = (client) => kind.open(client, read.codec, write.codec);
165
+ const keyed = "decode" in read ? read : undefined;
166
+ const own = keyed && socketType(op, kind, { base, read: keyed }, at);
167
+ return {
168
+ calls: keyed ? [keyed.decode] : [],
169
+ ...(write.sends === undefined ? {} : { sends: write.sends }),
170
+ shape: own
171
+ ? {
172
+ fail: FAIL,
173
+ returns: `(*${own}, error)`,
174
+ tail: (client) => [
175
+ `\tconn, err := ${call(client)}`,
176
+ "\tif err != nil {",
177
+ "\t\treturn nil, err",
178
+ "\t}",
179
+ `\treturn &${own}{conn}, nil`,
180
+ ],
181
+ }
182
+ : { fail: FAIL, returns: `(*${base}, error)`, tail: (client) => [`\treturn ${call(client)}`] },
183
+ };
184
+ }
185
+ /** The method of the WebSocket operation `op`, its message types hoisted into `at`. */
186
+ function wsStream(op, at) {
187
+ const { receive, send } = op.ir.messages ?? {};
188
+ const read = inbound(op, send, () => ({ codec: "frameBytes", type: "[]byte" }), at);
189
+ return { ...answerOf(op, WS, { read, write: outbound(op, receive, at) }, at), doc: "", opts: WS_OPTS };
190
+ }
191
+ /* the realtime Opts' one own field, which `sets` copies: the method sets its Headers and HTTPClient */
39
192
  const REALTIME_FIELDS = [
40
- { name: "LastEventID", type: "string" },
41
- { name: "ReconnectToken", type: "string" },
42
- { name: "Protocols", type: "[]string" },
43
193
  {
44
- doc: "MaxReconnectAttempts caps reconnects after a drop. Zero means 5; negative means unlimited.",
45
- name: "MaxReconnectAttempts",
46
- type: "int",
194
+ doc: "Transport is the resume cursor, the offered subprotocols and the reconnect policy; the connection advances its own copy, and the client sets Headers and HTTPClient.",
195
+ name: "Transport",
196
+ type: "TransportOpts",
47
197
  },
48
- { doc: "ReconnectDelayMs is the first backoff delay. Zero means 1000.", name: "ReconnectDelayMs", type: "int" },
49
198
  ];
50
- const REALTIME_STREAM = {
51
- doc: "The connection is open on return; Close it when done.",
52
- opts: {
53
- before: ["var topts TransportOpts"],
54
- /* the WebSocket and long-poll dials send the cursor as query params, the SSE dial its id as Last-Event-ID */
55
- carries: (param, where) => isReconnectToken(param, where) ||
56
- (where === "query" && param === "last_event_id") ||
57
- isLastEventIdHeader(param, where),
58
- fields: REALTIME_FIELDS,
59
- sets: [
60
- "topts = TransportOpts{LastEventID: opts.LastEventID, ReconnectToken: opts.ReconnectToken, Protocols: opts.Protocols, MaxReconnectAttempts: opts.MaxReconnectAttempts, ReconnectDelayMs: opts.ReconnectDelayMs}",
61
- ],
62
- },
63
- shape: {
64
- fail: FAIL,
65
- returns: "(*ResumableConnection, error)",
66
- tail: (client) => [`\treturn newRealtime(${sendArgs(client, "topts")})`],
67
- },
199
+ const REALTIME_OPTS = {
200
+ before: ["var topts TransportOpts"],
201
+ /* the WebSocket and long-poll dials send the cursor as query params, the SSE dial its id as Last-Event-ID */
202
+ carries: (param, where) => isReconnectToken(param, where) ||
203
+ (where === "query" && param === "last_event_id") ||
204
+ isLastEventIdHeader(param, where),
205
+ fields: REALTIME_FIELDS,
206
+ sets: ["topts = opts.Transport"],
68
207
  };
69
- /** The method of a WebSocket or realtime operation. */
70
- export const socketStream = (stream) => (stream === "ws" ? WS_STREAM : REALTIME_STREAM);
208
+ /** A realtime op's messages read without a declared `send`: the declared event schema's type, else each as its JSON value or text. */
209
+ function eventSide(op, at) {
210
+ if (op.events === undefined || !isJsonEventData(op.events, at.names.resolve))
211
+ return { codec: "framePayload", type: "any" };
212
+ const type = goTypeOf(op.events, { ...at, fieldName: "Event", parentName: op.id }).replace(/^\*/, "");
213
+ return { codec: `frameJSON[${type}]`, type };
214
+ }
215
+ /** The method of the realtime operation `op`, its message types hoisted into `at`. */
216
+ function realtimeStream(op, at) {
217
+ const { receive, send } = op.ir.messages ?? {};
218
+ const read = inbound(op, send, () => eventSide(op, at), at);
219
+ return {
220
+ ...answerOf(op, REALTIME, { read, write: outbound(op, receive, at) }, at),
221
+ doc: "The connection is open on return; Close it when done.",
222
+ opts: REALTIME_OPTS,
223
+ };
224
+ }
225
+ /** The method of a WebSocket or realtime operation, its message types hoisted into `at`. */
226
+ export const socketStream = (op, stream, at) => stream === "ws" ? wsStream(op, at) : realtimeStream(op, at);
@@ -1,8 +1,11 @@
1
1
  /** One dispatch: the values that select a wrapper, the wrapper, and the payload type it reads. */
2
+ /** A keyed union's arm: the values that select it, its wrapper, its payload, and what its first value spells. */
2
3
  export type Dispatch = {
3
4
  readonly values: readonly string[];
4
5
  readonly wrapper: string;
5
6
  readonly payload: string;
7
+ /** its first value as a Java type name, `Variant<index>` when none selects it */
8
+ readonly spelled: string;
6
9
  };
7
10
  /** A union's nested `Deserializer`, two spaces in: from its `final class` line to its closing brace. */
8
11
  export declare function deserializerLines(name: string, property: string, dispatch: readonly Dispatch[], unknown: string): string[];
@@ -129,7 +129,10 @@ type Header = {
129
129
  readonly name: string;
130
130
  readonly end: "{" | "{}";
131
131
  };
132
- /** A type declaration's header: a record's components and interface, a class's superclass, an interface's permits. */
132
+ /**
133
+ * A type declaration's header: a record's components and interface, a class's superclass, an interface's permits (none
134
+ * when its subtypes are nested in it).
135
+ */
133
136
  export type TypeHeader = Header & ({
134
137
  readonly kind: "enum";
135
138
  } | {
@@ -86,7 +86,7 @@ export function typeDeclaration(v, h) {
86
86
  v.type(type(h.extends));
87
87
  }
88
88
  }
89
- else
89
+ else if (h.permits.length > 0)
90
90
  typeList(v, "permits", h.permits);
91
91
  v.b.close();
92
92
  }
@@ -11,6 +11,8 @@ export type JavaTypeNames = {
11
11
  /** the schema of the component `name` when Java declares nothing for it, so a ref to it is its use type */
12
12
  alias(name: string): IRSchema | undefined;
13
13
  resolve(schema: IRSchema): IRSchema;
14
+ /** whether `name` is held: by the runtime, a type the SDK spells, `taken`, or a declaration claimed so far */
15
+ has(name: string): boolean;
14
16
  /** each component emitted under another name than its own (`<Name>Model`), for the generation's notices */
15
17
  readonly renamed: readonly Rename[];
16
18
  };
@@ -84,6 +84,7 @@ export function javaNames(schemas, taken, declares) {
84
84
  const schema = schemas[name] ?? UNKNOWN;
85
85
  return declares(schema) ? undefined : schema;
86
86
  },
87
+ has: (name) => scope.has(name),
87
88
  hoist: (key, base) => {
88
89
  const name = hoisted.get(key) ?? scope.claim(base);
89
90
  hoisted.set(key, name);
@@ -5,11 +5,15 @@
5
5
  * `<Union><Value>Body`. The nested `Deserializer` (json.ts) dispatches on the discriminator's value. Every permit and
6
6
  * wrapper is `@JsonDeserialize` with no argument; no `@JsonTypeInfo` is ever written.
7
7
  */
8
- import type { IRSchema } from "../../ir/model.ts";
8
+ import type { IRDiscriminator, IRSchema } from "../../ir/model.ts";
9
+ import { type Dispatch } from "./json.ts";
9
10
  import type { JavaTypeContext, Member } from "./models.ts";
10
11
  type Of<K extends IRSchema["kind"]> = Extract<IRSchema, {
11
12
  kind: K;
12
13
  }>;
14
+ type Discriminated = Of<"union"> & {
15
+ discriminator: IRDiscriminator;
16
+ };
13
17
  /** Declares `schema` once under `key` and `base`; its name. */
14
18
  export type Declare = (schema: IRSchema, key: string, base: string) => string;
15
19
  /** What a union's declaration reaches: the context, its members' types, and the hoist. */
@@ -22,6 +26,13 @@ export type UnionScope = {
22
26
  export declare const isLiteral: (variant: IRSchema) => variant is Of<"const"> & {
23
27
  value: string;
24
28
  };
29
+ /** Whether `union` is keyed on one field, so Java declares it as a sealed interface of wrappers. */
30
+ export declare const isKeyed: (union: Of<"union">) => union is Discriminated;
31
+ /**
32
+ * Each selectable variant's payload, wrapper and selecting values, in the Deserializer's order; the wrappers are
33
+ * declared here, under the same names however often it runs.
34
+ */
35
+ export declare function dispatchOf(name: string, union: Discriminated, scope: UnionScope): Dispatch[];
25
36
  /** The declaration of a union `declares`: a string enum of its const strings, or a discriminated interface. */
26
37
  export declare function unionDecl(name: string, union: Of<"union">, scope: UnionScope): string;
27
38
  export {};
@@ -45,16 +45,22 @@ const wrapperText = (wrapper, union, payload) => typeHeader(0, {
45
45
  modifiers: ["public"],
46
46
  name: wrapper,
47
47
  }).join("\n");
48
- /** Each selectable variant's payload, wrapper and selecting values; the wrappers are declared here. */
49
- function dispatchOf(name, union, scope) {
48
+ /** Whether `union` is keyed on one field, so Java declares it as a sealed interface of wrappers. */
49
+ export const isKeyed = (union) => union.discriminator !== undefined && union.variants.length > 0 && !union.variants.every(isLiteral);
50
+ /**
51
+ * Each selectable variant's payload, wrapper and selecting values, in the Deserializer's order; the wrappers are
52
+ * declared here, under the same names however often it runs.
53
+ */
54
+ export function dispatchOf(name, union, scope) {
50
55
  return selectedBy(union, scope.at).map(({ index, schema, values }) => {
51
56
  const first = values[0] ?? `Variant${index}`;
57
+ const spelled = javaTypeName(first);
52
58
  const payload = schema.kind === "ref"
53
59
  ? scope.member(schema, first)
54
- : scope.declare(schema, `${name}.variant${index}`, `${name}${javaTypeName(first)}Body`);
55
- const wrapper = scope.at.names.hoist(`${name}.wrap${index}`, `${name}${javaTypeName(first)}`);
60
+ : scope.declare(schema, `${name}.variant${index}`, `${name}${spelled}Body`);
61
+ const wrapper = scope.at.names.hoist(`${name}.wrap${index}`, `${name}${spelled}`);
56
62
  scope.at.decls.set(wrapper, wrapperText(wrapper, name, payload));
57
- return { payload, values, wrapper };
63
+ return { payload, spelled, values, wrapper };
58
64
  });
59
65
  }
60
66
  /** The sealed interface of `union`'s wrappers, its nested Deserializer, then the `<Union>Unknown` wrapper. */
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { IR, IRSchema } from "../../ir/model.ts";
8
8
  import { type JavaTypeNames } from "./models-names.ts";
9
+ import type { Dispatch } from "./json.ts";
9
10
  export type { JavaTypeNames } from "./models-names.ts";
10
11
  /** Where a type is being written, the declarations it hoists, and the names. */
11
12
  export type JavaTypeContext = {
@@ -24,5 +25,9 @@ export declare function javaTypeContext(ir: IR, taken?: readonly string[]): Java
24
25
  export declare function declares(ir: IRSchema): boolean;
25
26
  /** The Java type of `ir` at a use position of `at`. */
26
27
  export declare function javaTypeOf(ir: IRSchema, at: JavaTypeContext): string;
28
+ /** The Java type of `ir` at `at`, a schema that declares hoisted as `<Parent><Field>`: an inline keyed union too. */
29
+ export declare function declaredTypeOf(ir: IRSchema, at: JavaTypeContext): string;
30
+ /** The wrappers of `name`, the keyed union `ir` resolves to, in its Deserializer's order; none when `ir` is not one. */
31
+ export declare function keyedArms(name: string, ir: IRSchema, ctx: JavaTypeContext): readonly Dispatch[];
27
32
  /** The top-level declaration of the type `name` (a Java name already) for `ir`, which `declares`. */
28
33
  export declare function javaTopLevel(name: string, ir: IRSchema, ctx: JavaTypeContext): string;
@@ -2,7 +2,7 @@ import { pascalWords, javaTypeName } from "../shared/lang.js";
2
2
  import { enumDecl, enumValues } from "./models-enum.js";
3
3
  import { fieldsOf, isOpen, recordDecl } from "./models-record.js";
4
4
  import { javaNames, JSON_NODE } from "./models-names.js";
5
- import { isLiteral, unionDecl } from "./models-union.js";
5
+ import { dispatchOf, isKeyed, isLiteral, unionDecl } from "./models-union.js";
6
6
  /* deeper than this, a schema is any JSON value */
7
7
  const MAX_DEPTH = 12;
8
8
  const SCALARS = {
@@ -103,16 +103,31 @@ function use(ir, at) {
103
103
  export function javaTypeOf(ir, at) {
104
104
  return use(ir, { ...at, depth: 0, path: "" });
105
105
  }
106
+ /** The Java type of `ir` at `at`, a schema that declares hoisted as `<Parent><Field>`: an inline keyed union too. */
107
+ export function declaredTypeOf(ir, at) {
108
+ return ir.kind !== "ref" && declares(ir) ? hoist(ir, { ...at, depth: 0, path: "" }) : javaTypeOf(ir, at);
109
+ }
110
+ /** The members of the declaration `name` (a Java name already) and what its variants hoist, in `ctx`. */
111
+ const scopeOf = (name, ctx) => ({
112
+ at: ctx,
113
+ declare: (schema, key, base) => declare(schema, ctx, key, base),
114
+ member: (schema, fieldName) => javaTypeOf(schema, { ...ctx, fieldName, parentName: name }),
115
+ });
116
+ /** The wrappers of `name`, the keyed union `ir` resolves to, in its Deserializer's order; none when `ir` is not one. */
117
+ export function keyedArms(name, ir, ctx) {
118
+ const union = ctx.names.resolve(ir);
119
+ return union.kind === "union" && isKeyed(union) ? dispatchOf(name, union, scopeOf(name, ctx)) : [];
120
+ }
106
121
  /** The top-level declaration of the type `name` (a Java name already) for `ir`, which `declares`. */
107
122
  export function javaTopLevel(name, ir, ctx) {
108
- const member = (schema, fieldName) => javaTypeOf(schema, { ...ctx, fieldName, parentName: name });
123
+ const scope = scopeOf(name, ctx);
109
124
  if (ir.kind === "scalar")
110
125
  return enumDecl(name, ir);
111
126
  const open = isOpen(ir, ctx.names.resolve);
112
127
  if (ir.kind === "object")
113
- return recordDecl(name, { fields: ir.fields, open }, member, ctx);
114
- if (ir.kind === "allOf")
115
- return recordDecl(name, { fields: fieldsOf(ir, ctx.names.resolve), open }, member, ctx);
116
- const declareVariant = (schema, key, base) => declare(schema, ctx, key, base);
117
- return unionDecl(name, ir, { at: ctx, declare: declareVariant, member });
128
+ return recordDecl(name, { fields: ir.fields, open }, scope.member, ctx);
129
+ if (ir.kind === "allOf") {
130
+ return recordDecl(name, { fields: fieldsOf(ir, ctx.names.resolve), open }, scope.member, ctx);
131
+ }
132
+ return unionDecl(name, ir, scope);
118
133
  }
@@ -1,13 +1,19 @@
1
1
  /**
2
- * A realtime operation's method (bit 16 phase d2b, R1/R8; C#'s `realtime.ts`, Fd6/Fd7): `ResumableConnection<T>`, `T`
3
- * the declared event schema's type, else `JsonNode`, connected through `Realtime.open` over WebSocket, else SSE, else
4
- * long-poll before the method returns. Its five fields are `TransportOptions.of`'s: the resume cursor (`lastEventId`,
5
- * `reconnectToken`), the offered `protocols` and the reconnect policy (`maxReconnectAttempts`, `reconnectDelay`). The
6
- * runtime puts the cursor on each dial, so none of them is a Call arg; a declared `last_event_id` or `reconnect_token`
7
- * query, or a Last-Event-ID header, folds in, and a param spelled like a field claims `…2`. A realtime method is the
8
- * same text in either mode: it answers no Result.
2
+ * A realtime operation's method (bit 16 phase d2b, R1/R8, D9; C#'s `realtime.ts`, Fd6/Fd7):
3
+ * `ResumableConnection<TIn, TOut>`, `TIn` what the server sends (`send`), else the declared event schema's type, else
4
+ * `JsonNode`, and `TOut` what it receives (`receive`), else `JsonNode`; an inline side is hoisted as `<Op>Send` or
5
+ * `<Op>Receive`. A keyed read side (the sealed interface models-union.ts declares) with a member to handle answers
6
+ * `<Read>Connection<TOut>`, whose `on<Value>` per member matches inside `onMessage`, none for a `message` member; its
7
+ * name is claimed after the union's wrappers, as ws.ts claims a socket's. An op that declares its messages connects
8
+ * through `Realtime.typed`, which refuses a message that is no JSON; any other through `Realtime.open`, which reads it
9
+ * as a JSON string; either before the method returns, over WebSocket, else SSE, else long-poll. Its five fields are
10
+ * `TransportOptions.of`'s: the resume cursor (`lastEventId`, `reconnectToken`), the offered `protocols` and the
11
+ * reconnect policy (`maxReconnectAttempts`, `reconnectDelay`). The runtime puts the cursor on each dial, so none of
12
+ * them is a Call arg; a declared `last_event_id` or `reconnect_token` query, or a Last-Event-ID header, folds in, and a
13
+ * param spelled like a field claims `…2`. A realtime method is the same text in either mode: it answers no Result.
9
14
  */
10
15
  import type { SdkOp } from "../../ir/sdk-model.ts";
16
+ import { type Expr } from "./layout.ts";
11
17
  import { type JavaTypeContext } from "./models.ts";
12
18
  /** The reconnect policy's Params fields. */
13
19
  export declare const MAX_RECONNECT_ATTEMPTS = "maxReconnectAttempts";
@@ -37,8 +43,22 @@ export declare const carriesRealtime: (name: string, where: "query" | "header")
37
43
  * through).
38
44
  */
39
45
  export declare const REALTIME_FILES: string[];
40
- /** The type a realtime op's messages decode to: the declared event schema's, else `JsonNode`. */
41
- export declare const messageTypeOf: (op: SdkOp, ctx: JavaTypeContext) => string;
46
+ /**
47
+ * What a realtime method answers: its type, the type its messages decode to, whether they must be JSON (the op
48
+ * declares its messages), and the wrap of the opened connection.
49
+ */
50
+ export type RealtimeConnection = {
51
+ readonly type: string;
52
+ readonly read: string;
53
+ readonly strict: boolean;
54
+ readonly wrap: (opened: Expr) => Expr;
55
+ };
56
+ /**
57
+ * What `op`'s realtime method answers: `ResumableConnection<TIn, TOut>`, `TIn` the declared read side's type, else
58
+ * the event schema's, else `JsonNode`, `TOut` the declared write side's, else `JsonNode`; a keyed read side with a
59
+ * member to handle answers its `<Read>Connection<TOut>`, wrapping the opened one.
60
+ */
61
+ export declare function connectionOf(op: SdkOp, ctx: JavaTypeContext): RealtimeConnection;
42
62
  /** What a realtime method's lines need: its name and constant, its Params, and its Call's lines. */
43
63
  export type RealtimeSite = {
44
64
  readonly name: string;
@@ -1,8 +1,9 @@
1
- import { javaTypeOf } from "./models.js";
2
- import { call as callOf, local, methodHeader, param, newOf, returnStmt, statement } from "./layout.js";
1
+ import { call as callOf, local, methodHeader, newOf, param, returnStmt, statement, } from "./layout.js";
2
+ import { declaredTypeOf, javaTypeOf, keyedArms } from "./models.js";
3
+ import { JSON_NODE } from "./models-names.js";
3
4
  import { docOf } from "./sdk-decl.js";
4
5
  import { CURSOR, isLastEventIdHeader } from "./sse.js";
5
- import { isReconnectTokenQuery, PROTOCOLS, TOKEN } from "./ws.js";
6
+ import { handledArms, isReconnectTokenQuery, keyedReader, PROTOCOLS, TOKEN } from "./ws.js";
6
7
  /** The reconnect policy's Params fields. */
7
8
  export const MAX_RECONNECT_ATTEMPTS = "maxReconnectAttempts";
8
9
  export const RECONNECT_DELAY = "reconnectDelay";
@@ -35,22 +36,56 @@ export const REALTIME_FILES = [
35
36
  "TransportOptions",
36
37
  "WsAdapter",
37
38
  ];
38
- /** The type a realtime op's messages decode to: the declared event schema's, else `JsonNode`. */
39
- export const messageTypeOf = (op, ctx) => op.events === undefined ? "JsonNode" : javaTypeOf(op.events, { ...ctx, fieldName: "Event", parentName: op.id });
39
+ /** The connection's reader: its own handler is onMessage. */
40
+ const CONNECTION = {
41
+ base: "ResumableConnection",
42
+ handlers: ["onMessage"],
43
+ noun: "connection",
44
+ suffix: "Connection",
45
+ };
46
+ /** The opened connection as it is: one whose read side has no member to handle. */
47
+ const AS_OPENED = (opened) => opened;
48
+ /**
49
+ * What `op`'s realtime method answers: `ResumableConnection<TIn, TOut>`, `TIn` the declared read side's type, else
50
+ * the event schema's, else `JsonNode`, `TOut` the declared write side's, else `JsonNode`; a keyed read side with a
51
+ * member to handle answers its `<Read>Connection<TOut>`, wrapping the opened one.
52
+ */
53
+ export function connectionOf(op, ctx) {
54
+ const messages = op.ir.messages;
55
+ const at = (fieldName) => ({ ...ctx, fieldName, parentName: op.id, path: "" });
56
+ const strict = messages !== undefined;
57
+ const write = messages?.receive === undefined ? JSON_NODE : declaredTypeOf(messages.receive, at("Receive"));
58
+ const plain = (read) => ({
59
+ read,
60
+ strict,
61
+ type: `ResumableConnection<${read}, ${write}>`,
62
+ wrap: AS_OPENED,
63
+ });
64
+ if (messages?.send === undefined) {
65
+ const events = { ...ctx, fieldName: "Event", parentName: op.id };
66
+ return plain(op.events === undefined ? JSON_NODE : javaTypeOf(op.events, events));
67
+ }
68
+ const read = declaredTypeOf(messages.send, at("Send"));
69
+ const arms = keyedArms(read, messages.send, ctx);
70
+ if (handledArms(CONNECTION, arms).length === 0)
71
+ return plain(read);
72
+ const sub = keyedReader(CONNECTION, read, arms, ctx);
73
+ return { read, strict, type: `${sub}<${write}>`, wrap: (opened) => newOf(`${sub}<${write}>`, [opened]) };
74
+ }
40
75
  /** A realtime method's lines: `op(params)`, delegating to `op(params, options)`, which connects. */
41
76
  export function realtimeMethodLines(op, site, ctx) {
42
77
  const { call, constant, name, params } = site;
43
- const type = messageTypeOf(op, ctx);
78
+ const connection = connectionOf(op, ctx);
44
79
  const doc = docOf(`${op.id}: the connection over WebSocket, else SSE, else long-poll. It reconnects after a drop and resumes after the last message it delivered; close() ends it.`);
45
- const signature = (args) => methodHeader(2, { modifiers: ["public"], name, params: args, returns: `ResumableConnection<${type}>` });
80
+ const signature = (args) => methodHeader(2, { modifiers: ["public"], name, params: args, returns: connection.type });
46
81
  const transport = callOf("TransportOptions", "of", REALTIME_FIELDS.map((f) => callOf("params", f.field)));
47
- const open = callOf("Realtime", "open", [
82
+ const open = callOf("Realtime", connection.strict ? "typed" : "open", [
48
83
  "exchange",
49
84
  constant,
50
85
  "call",
51
86
  "options",
52
87
  "transport",
53
- newOf(`TypeReference<${type}>`, [], true),
88
+ newOf(`TypeReference<${connection.read}>`, [], true),
54
89
  ]);
55
90
  return [
56
91
  doc,
@@ -62,7 +97,7 @@ export function realtimeMethodLines(op, site, ctx) {
62
97
  ...signature([param(params, "params"), param("RequestOptions", "options")]),
63
98
  ...call,
64
99
  ...statement(4, local({ init: transport, name: "transport", type: "TransportOptions" })),
65
- ...statement(4, returnStmt(open)),
100
+ ...statement(4, returnStmt(connection.wrap(open))),
66
101
  " }",
67
102
  "",
68
103
  ];
@@ -1,19 +1,20 @@
1
- import { messageTypeOf } from "./realtime.js";
2
1
  import { accessor, assign, call, classHeader, exprStmt, finalField, lambda, methodHeader, newOf, param, returnStmt, statement, } from "./layout.js";
3
2
  import { docOf, docParagraphs } from "./sdk-decl.js";
4
3
  import { putFile } from "./sdk-models.js";
5
4
  import { answerOf, paragraphsOf } from "./sdk-op.js";
5
+ import { connectionOf } from "./realtime.js";
6
6
  import { paramsName } from "./sdk-params.js";
7
7
  import { blocks, clientLines, membersOf, nodeOf, recordSource, resourceName, } from "./sdk-client.js";
8
- import { eventTypeOf } from "./sse.js";
8
+ import { sseEventOf } from "./sse.js";
9
+ import { wsSocketOf } from "./ws.js";
9
10
  /** The type the normal method answers: a stream's, a connection's, or the answer's (`void` for none). */
10
11
  function returnsOf(op, env) {
11
12
  if (op.stream === "sse")
12
- return `EventStream<${eventTypeOf(op, env.ctx)}>`;
13
+ return `EventStream<${sseEventOf(op, env.ctx).type}>`;
13
14
  if (op.stream === "ws")
14
- return "TypedWebSocket";
15
+ return wsSocketOf(op, env.ctx).type;
15
16
  if (op.stream === "realtime")
16
- return `ResumableConnection<${messageTypeOf(op, env.ctx)}>`;
17
+ return connectionOf(op, env.ctx).type;
17
18
  return answerOf(op, env).type;
18
19
  }
19
20
  /**