@workerstack/clients 1.0.0-rc.28 → 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 (136) 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/sdk-types-preamble.js +4 -0
  71. package/dist/emit/ts/sdk-types.js +49 -10
  72. package/dist/emit/ts/sdk.js +2 -2
  73. package/dist/emit/ts/service-map.d.ts +8 -2
  74. package/dist/emit/ts/service-map.js +30 -2
  75. package/dist/emit/ts/type-gen.js +6 -4
  76. package/dist/ir/build.js +4 -0
  77. package/dist/ir/model.d.ts +14 -0
  78. package/dist/ir/sdk-model.d.ts +25 -1
  79. package/dist/ir/sdk-model.js +35 -5
  80. package/dist/ir/slots.d.ts +1 -1
  81. package/dist/ir/slots.js +9 -3
  82. package/dist/ir/streams.d.ts +16 -0
  83. package/dist/ir/streams.js +40 -0
  84. package/dist/runtime/cli/socket.go +107 -13
  85. package/dist/runtime/cli/stream.go +18 -11
  86. package/dist/runtime/csharp/Adapters.cs +12 -11
  87. package/dist/runtime/csharp/Events.cs +22 -17
  88. package/dist/runtime/csharp/Realtime.cs +50 -23
  89. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  90. package/dist/runtime/csharp/TransportSse.cs +3 -3
  91. package/dist/runtime/csharp/Ws.cs +1 -1
  92. package/dist/runtime/csharp/WsDial.cs +19 -1
  93. package/dist/runtime/csharp/WsTyped.cs +109 -0
  94. package/dist/runtime/go/realtime.go +125 -41
  95. package/dist/runtime/go/realtime_loop.go +21 -18
  96. package/dist/runtime/go/result.go +2 -1
  97. package/dist/runtime/go/sse.go +11 -0
  98. package/dist/runtime/go/stream.go +29 -13
  99. package/dist/runtime/go/transport.go +15 -21
  100. package/dist/runtime/go/transport_longpoll.go +3 -4
  101. package/dist/runtime/go/transport_sse.go +6 -6
  102. package/dist/runtime/go/ws.go +157 -61
  103. package/dist/runtime/java/EventStream.java +47 -29
  104. package/dist/runtime/java/Exchange.java +5 -5
  105. package/dist/runtime/java/Flight.java +3 -3
  106. package/dist/runtime/java/Realtime.java +45 -11
  107. package/dist/runtime/java/ResumableConnection.java +77 -32
  108. package/dist/runtime/java/Socket.java +8 -4
  109. package/dist/runtime/java/SseAdapter.java +1 -1
  110. package/dist/runtime/java/TypedWebSocket.java +81 -24
  111. package/dist/runtime/java/WsAdapter.java +4 -2
  112. package/dist/runtime/java/WsDial.java +12 -5
  113. package/dist/runtime/python/events.py +25 -11
  114. package/dist/runtime/python/operation.py +6 -1
  115. package/dist/runtime/python/realtime.py +47 -33
  116. package/dist/runtime/python/send_async.py +1 -0
  117. package/dist/runtime/python/transport_sse.py +2 -2
  118. package/dist/runtime/python/transport_ws.py +1 -1
  119. package/dist/runtime/python/ws.py +100 -39
  120. package/dist/runtime/rust/events.rs +64 -41
  121. package/dist/runtime/rust/realtime.rs +80 -34
  122. package/dist/runtime/rust/realtime_loop.rs +37 -12
  123. package/dist/runtime/rust/sse.rs +3 -2
  124. package/dist/runtime/rust/transport_sse.rs +1 -1
  125. package/dist/runtime/rust/transport_ws.rs +3 -2
  126. package/dist/runtime/rust/ws.rs +122 -50
  127. package/dist/runtime/ts/realtime-connection.ts +22 -0
  128. package/dist/runtime/ts/realtime-transports.ts +13 -4
  129. package/dist/runtime/ts/realtime.ts +27 -3
  130. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  131. package/dist/runtime/ts/sdk-sse.ts +31 -14
  132. package/dist/runtime/ts/sdk-ws.ts +2 -1
  133. package/dist/runtime/ts/sdk.ts +9 -2
  134. package/dist/runtime/ts/sse.ts +8 -0
  135. package/dist/runtime/ts/ws.ts +88 -50
  136. package/package.json +3 -34
@@ -2,7 +2,7 @@ import { pascalWords, rustTypeIdent } from "../shared/lang.js";
2
2
  import { integerValues, intEnumDecl, stringEnumDecl, stringValues } from "./types-enum.js";
3
3
  import { irNames, plainNames } from "./types-names.js";
4
4
  import { allOfDecl, DERIVE, objectDecl, unboxed } from "./types-struct.js";
5
- import { unionDecl } from "./types-union.js";
5
+ import { unionDecl, unionVariants } from "./types-union.js";
6
6
  const VALUE = "serde_json::Value";
7
7
  const MAP = "std::collections::HashMap";
8
8
  /* deeper than this, a schema is any JSON value */
@@ -19,7 +19,7 @@ export function rustTypeContext(ir) {
19
19
  return { decls: new Map(), fieldName: "", names: ir ? irNames(ir) : plainNames(), parentName: "" };
20
20
  }
21
21
  /** `ir` declared once as `names.hoist(key, base)` into `at.decls`; its name. */
22
- function declare(ir, at, key, base) {
22
+ export function rustHoisted(ir, at, key, base) {
23
23
  const name = at.names.hoist(key, base);
24
24
  if (!at.decls.has(name)) {
25
25
  /* claimed before its body: what the body hoists in turn comes after it */
@@ -29,7 +29,7 @@ function declare(ir, at, key, base) {
29
29
  return name;
30
30
  }
31
31
  /** `ir` hoisted as `<Parent><Field>`. */
32
- const hoist = (ir, at) => declare(ir, at, `${at.parentName}.${at.fieldName}`, `${rustTypeIdent(at.parentName)}${pascalWords(at.fieldName)}`);
32
+ const hoist = (ir, at) => rustHoisted(ir, at, `${at.parentName}.${at.fieldName}`, `${rustTypeIdent(at.parentName)}${pascalWords(at.fieldName)}`);
33
33
  const deeper = (at, fieldName = at.fieldName) => ({ ...at, depth: at.depth + 1, fieldName });
34
34
  /** Whether a scalar is a string or integer enum with a value of its kind: a declared enum. */
35
35
  const isEnum = (ir) => ir.enum !== undefined &&
@@ -83,6 +83,14 @@ export function rustTypeOf(ir, at) {
83
83
  }
84
84
  /** The use positions inside the declaration of `name`. */
85
85
  const memberOf = (name, at) => (schema, fieldName) => use(schema, { ...at, depth: 0, fieldName, parentName: name, self: name });
86
+ /** What the union declared as `name` reaches: its members' use positions and the hoist of its inline variants. */
87
+ const unionScope = (name, at) => ({
88
+ declare: (schema, key, base) => rustHoisted(schema, at, key, base),
89
+ member: memberOf(name, at),
90
+ names: at.names,
91
+ });
92
+ /** Each value the keyed union `union`, declared as `name`, selects a variant by, with that variant and its payload type. */
93
+ export const rustUnionVariants = (name, union, at) => unionVariants(name, union, unionScope(name, at));
86
94
  /** The top-level declaration of the type `name` (a Rust identifier already) for `ir`. */
87
95
  export function rustTopLevel(name, ir, at) {
88
96
  const member = memberOf(name, at);
@@ -97,9 +105,7 @@ export function rustTopLevel(name, ir, at) {
97
105
  /* a closed object without fields is a struct too: `{}` on the wire, where a map alias would admit any key */
98
106
  if (ir.kind === "object" && (ir.fields.length > 0 || ir.additional === false))
99
107
  return objectDecl(name, ir, member);
100
- if (ir.kind === "union" && ir.variants.length > 0) {
101
- const variant = (schema, key, base) => declare(schema, at, key, base);
102
- return unionDecl(name, ir, { declare: variant, member, names: at.names });
103
- }
108
+ if (ir.kind === "union" && ir.variants.length > 0)
109
+ return unionDecl(name, ir, unionScope(name, at));
104
110
  return `pub type ${name} = ${member(ir, "Value")};`;
105
111
  }
@@ -1,9 +1,15 @@
1
1
  /**
2
- * A WebSocket operation's answer (contract 20 §2.0, §2.2): `TypedWebSocket`, dialed offering the Opts'
2
+ * A WebSocket operation's answer (contract 20 §2.0, §2.2): `TypedWebSocket<In, Out>`, dialed offering the Opts'
3
3
  * `protocols`, its Opts' `reconnect_token` sent as one query param only when set and non-empty; a declared
4
- * `reconnect_token` query param is folded into that field (Fd3).
4
+ * `reconnect_token` query param is folded into that field (Fd3). `In` is what the server sends (`send`), `Out` what
5
+ * it receives (`receive`), an inline union hoisted as `<Op>Send` or `<Op>Receive`; an op without them keeps the
6
+ * defaults, its frames as bytes and any JSON value sent. A read side keyed on one field (D9) gets an `on_<value>` per
7
+ * member, an inherent impl in types.rs written once per read type, except a value whose method a handler holds.
5
8
  */
9
+ import type { IRSchema } from "../../ir/model.ts";
10
+ import { type SdkOp } from "../../ir/sdk-model.ts";
6
11
  import type { OptsField, StreamAnswer } from "./sdk-opts.ts";
12
+ import { type RustTypeContext } from "./types.ts";
7
13
  /** The resume cursor's token, which the WebSocket and realtime Opts carry. */
8
14
  export declare const RECONNECT_TOKEN: {
9
15
  ident: string;
@@ -17,5 +23,17 @@ export declare const PROTOCOLS: {
17
23
  };
18
24
  /** Whether a declared param is the `reconnect_token` query param, the resume channel a socket dial sends. */
19
25
  export declare const isReconnectToken: (param: string, where: OptsField["in"]) => boolean;
20
- /** A WebSocket operation's answer. */
21
- export declare const wsAnswer: () => StreamAnswer;
26
+ /** One direction of `op`'s messages as its Rust type: an inline union is declared as `<Op><side>`. */
27
+ export declare function messageType(op: SdkOp, schema: IRSchema, side: "Receive" | "Send", at: RustTypeContext): string;
28
+ /**
29
+ * The `on_<value>` methods of `<base><read, Out>`, `read` the keyed `schema`, declared once in `at`: each takes the
30
+ * messages whose key is that value; a value whose method one of `handlers` names gets none.
31
+ */
32
+ export declare function valueHandlers(base: string, handlers: readonly string[], read: {
33
+ readonly schema: IRSchema;
34
+ readonly type: string;
35
+ }, at: RustTypeContext): void;
36
+ /** The type params of a socket reading `read` and sending `write`, the defaults left out. */
37
+ export declare const typeParams: (read: string | undefined, write: string | undefined, untyped: string) => string;
38
+ /** The WebSocket operation `op`'s answer, its message types hoisted into `at`. */
39
+ export declare function wsAnswer(op: SdkOp, at: RustTypeContext): StreamAnswer;
@@ -1,3 +1,8 @@
1
+ import { dispatchOf } from "../../ir/sdk-model.js";
2
+ import { lineComment, rustString } from "../shared/escape.js";
3
+ import { NameScope, rustTypeIdent, rustValueIdent } from "../shared/lang.js";
4
+ import { typeAt } from "./sdk-body.js";
5
+ import { rustHoisted, rustUnionVariants } from "./types.js";
1
6
  /** The resume cursor's token, which the WebSocket and realtime Opts carry. */
2
7
  export const RECONNECT_TOKEN = { ident: "reconnect_token", type: "Option<String>" };
3
8
  /** The subprotocols a WebSocket or realtime dial offers. */
@@ -11,10 +16,55 @@ const WS = {
11
16
  sends: ['spec.query("reconnect_token", &crate::request::cursor(&opts.reconnect_token));'],
12
17
  };
13
18
  const DOC = "Resolves once the socket is open: a refused handshake with an error status is `Err(Error::Api)`. `cancel_on` ends its reads quietly; dropping it closes it.";
14
- /** A WebSocket operation's answer. */
15
- export const wsAnswer = () => ({
16
- doc: DOC,
17
- run: "crate::ws::dial(opts.protocols.clone())",
18
- stream: WS,
19
- type: "TypedWebSocket",
20
- });
19
+ /** One direction of `op`'s messages as its Rust type: an inline union is declared as `<Op><side>`. */
20
+ export function messageType(op, schema, side, at) {
21
+ if (schema.kind !== "union")
22
+ return typeAt(schema, op.id, side, at);
23
+ return rustHoisted(schema, at, `${op.id}.${side}`, `${rustTypeIdent(op.id)}${side}`);
24
+ }
25
+ /**
26
+ * The `on_<value>` methods of `<base><read, Out>`, `read` the keyed `schema`, declared once in `at`: each takes the
27
+ * messages whose key is that value; a value whose method one of `handlers` names gets none.
28
+ */
29
+ export function valueHandlers(base, handlers, read, at) {
30
+ const key = `${read.type}.${base}`;
31
+ const dispatch = dispatchOf(read.schema, at.names.resolve);
32
+ if (dispatch === undefined || at.decls.has(key))
33
+ return;
34
+ const scope = new NameScope(handlers);
35
+ const methods = rustUnionVariants(read.type, dispatch.union, at).flatMap(({ type, value, variant }) => {
36
+ const method = rustValueIdent(`on_${value}`);
37
+ if (scope.has(method))
38
+ return [];
39
+ return [
40
+ "",
41
+ ...lineComment(`Calls \`handler\` on each message whose ${rustString(dispatch.key)} is ${rustString(value)}.`, "///", " "),
42
+ ` pub fn ${scope.claim(method)}(&mut self, mut handler: impl FnMut(&${type}) + Send + 'static) {`,
43
+ " self.on_message(move |m| {",
44
+ ` if let ${read.type}::${variant}(v) = m {`,
45
+ " handler(v);",
46
+ " }",
47
+ " });",
48
+ " }",
49
+ ];
50
+ });
51
+ if (methods.length === 0)
52
+ return;
53
+ at.decls.set(key, [`impl<Out> crate::${base}<${read.type}, Out> {`, ...methods.slice(1), "}"].join("\n"));
54
+ }
55
+ /** The type params of a socket reading `read` and sending `write`, the defaults left out. */
56
+ export const typeParams = (read, write, untyped) => write === undefined ? (read === undefined ? "" : `<${read}>`) : `<${read ?? untyped}, ${write}>`;
57
+ /* the handlers a socket takes: a member whose on_<value> one of them names gets none */
58
+ const HANDLERS = ["on_message", "on_close", "on_error"];
59
+ /** The WebSocket operation `op`'s answer, its message types hoisted into `at`. */
60
+ export function wsAnswer(op, at) {
61
+ const { receive, send } = op.ir.messages ?? {};
62
+ const read = send && messageType(op, send, "Send", at);
63
+ const write = receive && messageType(op, receive, "Receive", at);
64
+ if (send !== undefined && read !== undefined)
65
+ valueHandlers("TypedWebSocket", HANDLERS, { schema: send, type: read }, at);
66
+ const params = typeParams(read, write, "Vec<u8>");
67
+ /* the answer type fixes both params: a socket without a read type reads bytes */
68
+ const run = `crate::ws::${read === undefined ? "dial" : "typed"}(opts.protocols.clone())`;
69
+ return { doc: DOC, run, stream: WS, type: `TypedWebSocket${params}` };
70
+ }
@@ -22,9 +22,11 @@ export const RESERVED = [
22
22
  "Result",
23
23
  "SDKConfig",
24
24
  "SSEEvent",
25
+ "SSEEventOf",
25
26
  "SseOptions",
26
27
  "TypedWebSocket",
27
28
  "Uint8Array",
29
+ "WsFrame",
28
30
  "WsOptions",
29
31
  ];
30
32
  /** What the types file may import from the runtime module, in the order the import lists them. */
@@ -34,7 +36,9 @@ const RUNTIME_TYPES = [
34
36
  "ResumableConnection",
35
37
  "SDKConfig",
36
38
  "SSEEvent",
39
+ "SSEEventOf",
37
40
  "TypedWebSocket",
41
+ "WsFrame",
38
42
  ];
39
43
  /** The input fields every call takes, by transport. */
40
44
  const OPTIONS = `export type HttpOptions = {
@@ -1,4 +1,4 @@
1
- import { irErrorEnvelope, isJsonMedia, mediaEssence, sdkModel, sseEventSchema } from "../../ir/sdk-model.js";
1
+ import { dispatchKey, irErrorEnvelope, isJsonMedia, mediaEssence, sdkModel, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
2
2
  import { bodiesOf } from "../../ir/slots.js";
3
3
  import { blockCommentText, tsString } from "../shared/escape.js";
4
4
  import { compareCodeUnits, NameTable, pascalWords } from "../shared/lang.js";
@@ -58,11 +58,13 @@ function inputOf(op, ctx) {
58
58
  /* a header or cookie is text on the wire: an enum keeps its values, anything else is a string */
59
59
  const text = (p) => (p.schema.kind === "scalar" && p.schema.enum ? irToTs(p.schema, types) : "string");
60
60
  const pathParams = op.pathParams.map((p) => ({ ...p, required: true }));
61
+ /* a browser WebSocket sends no headers and sets no cookies, so a socket call takes neither */
62
+ const socket = op.stream === "ws";
61
63
  const parts = [
62
64
  paramsPart("params", pathParams, (p) => irToTs(p.schema, types)),
63
65
  paramsPart("search", op.query, (p) => irToTs(p.schema, types)),
64
- paramsPart("headers", op.headers, text),
65
- paramsPart("cookies", op.ir.params.cookie ?? [], text),
66
+ socket ? null : paramsPart("headers", op.headers, text),
67
+ socket ? null : paramsPart("cookies", op.ir.params.cookie ?? [], text),
66
68
  ...bodyParts(op, ctx),
67
69
  ].filter((part) => part !== null);
68
70
  const ordered = [...parts.filter((p) => p.required), ...parts.filter((p) => !p.required)];
@@ -102,6 +104,46 @@ function headersOf(op) {
102
104
  const fields = [...byName].sort(([a], [b]) => compareCodeUnits(a, b));
103
105
  return objectText(fields.map(([name, required]) => `${quoteKey(name)}${required ? "" : "?"}: string`));
104
106
  }
107
+ /** A WebSocket op's socket: typed by its declared messages, `In` what the server receives, `Out` what it sends (D9). */
108
+ function socketType(op, ctx) {
109
+ const messages = op.ir.messages;
110
+ if (messages === undefined)
111
+ return "TypedWebSocket";
112
+ const { receive, send } = messages;
113
+ const key = send === undefined ? undefined : dispatchKey(send, ctx.resolve);
114
+ const args = [
115
+ receive === undefined ? "WsFrame" : irToTs(receive, ctx.types),
116
+ send === undefined ? "string" : irToTs(send, ctx.types),
117
+ ...(key === undefined ? [] : [tsString(key)]),
118
+ ];
119
+ while (args.length > 0 && args.at(-1) === ["WsFrame", "string"][args.length - 1])
120
+ args.pop();
121
+ return args.length === 0 ? "TypedWebSocket" : `TypedWebSocket<${args.join(", ")}>`;
122
+ }
123
+ /** A realtime op's connection: what it yields (the messages it hears, else its event data), sends, and dispatches on. */
124
+ function connectionType(op, ctx) {
125
+ const { receive, send } = op.ir.messages ?? {};
126
+ const yields = send ?? sseEventSchema(op.ir, ctx.resolve);
127
+ const key = send === undefined ? undefined : dispatchKey(send, ctx.resolve);
128
+ const args = [
129
+ yields === undefined ? "unknown" : irToTs(yields, ctx.types),
130
+ receive === undefined ? "unknown" : irToTs(receive, ctx.types),
131
+ ...(key === undefined ? [] : [tsString(key)]),
132
+ ];
133
+ while (args.length > 1 && args.at(-1) === "unknown")
134
+ args.pop();
135
+ return `ResumableConnection<${args.join(", ")}>`;
136
+ }
137
+ /** What an SSE op's stream yields: `SSEEventOf` its named events (D7), else `SSEEvent` of its one data schema. */
138
+ function sseEventType(op, ctx) {
139
+ const named = sseEvents(op.ir);
140
+ if (named !== undefined) {
141
+ const fields = named.map(({ data, name }) => `${quoteKey(name)}: ${irToTs(data, ctx.types)}`);
142
+ return `SSEEventOf<${objectText(fields)}>`;
143
+ }
144
+ const events = sseEventSchema(op.ir, ctx.resolve);
145
+ return events === undefined ? "SSEEvent" : `SSEEvent<${irToTs(events, ctx.types)}>`;
146
+ }
105
147
  /** `op`'s member line `name`: a REST call a HttpCall, a stream a HttpStream, defaults dropped; a connection its method. */
106
148
  function signature(name, op, ctx) {
107
149
  const input = inputOf(op, ctx);
@@ -112,16 +154,13 @@ function signature(name, op, ctx) {
112
154
  const key = quoteKey(name);
113
155
  /* a realtime op is one resumable connection of its event data; any other is typed by its transport */
114
156
  const { realtime, sse, websocket } = op.ir.extensions;
115
- if (realtime) {
116
- const events = sseEventSchema(op.ir, ctx.resolve);
117
- return `${key}(${arg("RealtimeCallOptions")}): ResumableConnection<${events ? irToTs(events, ctx.types) : "unknown"}>`;
118
- }
157
+ if (realtime)
158
+ return `${key}(${arg("RealtimeCallOptions")}): ${connectionType(op, ctx)}`;
119
159
  if (websocket)
120
- return `${key}(${arg("WsOptions")}): TypedWebSocket`;
160
+ return `${key}(${arg("WsOptions")}): ${socketType(op, ctx)}`;
121
161
  const errors = errorsOf(op, ctx.types, ctx.resolve);
122
162
  if (sse) {
123
- const events = sseEventSchema(op.ir, ctx.resolve);
124
- const event = events === undefined ? "SSEEvent" : `SSEEvent<${irToTs(events, ctx.types)}>`;
163
+ const event = sseEventType(op, ctx);
125
164
  return `${key}: HttpStream<${[input.type, event, ...(errors === null ? [] : [errors])].join(", ")}>`;
126
165
  }
127
166
  const headers = headersOf(op);
@@ -63,8 +63,8 @@ const RUNTIME_TYPES = {
63
63
  "TransportConnection",
64
64
  "TransportOpts",
65
65
  ],
66
- sse: ["SSEEvent"],
67
- ws: ["TypedWebSocket"],
66
+ sse: ["SSEEvent", "SSEEventOf"],
67
+ ws: ["TypedWebSocket", "WsFrame"],
68
68
  };
69
69
  /** The names of `lists` a runtime with `features` ships, ignoring case in their order. */
70
70
  function shipped(lists, features) {
@@ -15,10 +15,16 @@ export type ServiceEntry = {
15
15
  params?: string[];
16
16
  path: string;
17
17
  realtime?: true;
18
- /** an event stream; `"json"` when its declared event schema is not a string */
19
- sse?: "json" | true;
18
+ /** an event stream; `"json"` when its declared event schema is not a string, its JSON events' names when it names them */
19
+ sse?: "json" | string[] | true;
20
20
  wildcard?: string;
21
21
  ws?: true;
22
+ /** the server declares what it sends: the socket parses each text frame */
23
+ decode?: true;
24
+ /** the field a socket's message union is keyed on (D9) */
25
+ dispatch?: string;
26
+ /** the server declares what it receives: the socket sends JSON */
27
+ encode?: true;
22
28
  };
23
29
  export type ServiceMapNode = ServiceEntry | {
24
30
  [key: string]: ServiceMapNode;
@@ -1,4 +1,4 @@
1
- import { isJsonMedia, mediaEssence, sdkModel, sseEventSchema, } from "../../ir/sdk-model.js";
1
+ import { isJsonMedia, mediaEssence, sdkModel, dispatchKey, isJsonEventData, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
2
2
  import { openApiPathParams } from "../../ir/slots.js";
3
3
  import { tsString } from "../shared/escape.js";
4
4
  import { compareCodeUnits } from "../shared/lang.js";
@@ -69,6 +69,33 @@ function headersOf(op, status) {
69
69
  const declared = op.responses[status]?.headers ?? [];
70
70
  return [...new Set(declared.map(({ name }) => name.toLowerCase()))].sort(compareCodeUnits);
71
71
  }
72
+ /** How the runtime reads `op`'s events: the names of its JSON events when it names them (D7), else all or none. */
73
+ function sseKind(op, resolve) {
74
+ const named = sseEvents(op);
75
+ if (named !== undefined)
76
+ return named.filter(({ data }) => isJsonEventData(data, resolve)).map(({ name }) => name);
77
+ return sseEventSchema(op, resolve) === undefined ? true : "json";
78
+ }
79
+ /**
80
+ * How a socket op's declared messages read on the wire: a WebSocket's sends JSON when the server declares `receive`
81
+ * and its frames parsed when it declares `send`; either kind's messages dispatched on `send`'s key (D9).
82
+ */
83
+ function socketEntry(op, resolve) {
84
+ const { messages } = op;
85
+ if (messages === undefined)
86
+ return {};
87
+ const out = {};
88
+ if (!op.extensions.realtime) {
89
+ if (messages.receive !== undefined)
90
+ out.encode = true;
91
+ if (messages.send !== undefined)
92
+ out.decode = true;
93
+ }
94
+ const key = messages.send === undefined ? undefined : dispatchKey(messages.send, resolve);
95
+ if (key !== undefined)
96
+ out.dispatch = key;
97
+ return out;
98
+ }
72
99
  /** The service entry of `op`; `success` is its success answer as the SDK model reads it. */
73
100
  function entryOf(op, success, resolve) {
74
101
  const entry = { method: op.method, path: op.path };
@@ -79,11 +106,12 @@ function entryOf(op, success, resolve) {
79
106
  if (wildcard)
80
107
  entry.wildcard = wildcard.name;
81
108
  if (op.extensions.sse)
82
- entry.sse = sseEventSchema(op, resolve) === undefined ? true : "json";
109
+ entry.sse = sseKind(op, resolve);
83
110
  if (op.extensions.websocket)
84
111
  entry.ws = true;
85
112
  if (op.extensions.realtime)
86
113
  entry.realtime = true;
114
+ Object.assign(entry, socketEntry(op, resolve));
87
115
  if (op.extensions.idempotencyKey)
88
116
  entry.idempotent = true;
89
117
  const invalidate = op.extensions.invalidates;
@@ -204,13 +204,15 @@ function baseCtx(extracted, name) {
204
204
  }
205
205
  /**
206
206
  * A WebSocket route's ctx, as core's `WSRouteCtx` types its callbacks: the base with the pattern's params, and the
207
- * search input `.input()` declares. Extracted additions are keyed by HTTP routes only, so none join here.
207
+ * search, headers and cookies `.input()` declares. Extracted additions are keyed by HTTP routes only, so none join
208
+ * here.
208
209
  */
209
210
  function wsCtx(op, id, options, ctx) {
210
211
  const own = [];
211
- const search = wireInput(op, ctx).find(([key]) => key === "search");
212
- if (search !== undefined)
213
- own.push(["readonly input", objectText([search])]);
212
+ /* the upgrade request's validated search, headers and cookies, as core's `WithInput` holds them */
213
+ const input = wireInput(op, ctx).filter(([key]) => key === "search" || key === "headers" || key === "cookies");
214
+ if (input.length > 0)
215
+ own.push(["readonly input", objectText(input)]);
214
216
  const params = ctxParams(options.extracted, id, pathOf(id));
215
217
  if (params !== "{}")
216
218
  own.push(["readonly params", params]);
package/dist/ir/build.js CHANGED
@@ -7,6 +7,7 @@ import { compareCodeUnits, pascalWords } from "../emit/shared/lang.js";
7
7
  import { schemaToIR } from "./schema.js";
8
8
  import { buildResourceTree } from "./resource-tree.js";
9
9
  import { eventOf, extensionsOf, paramsOf, parseOpenApiPath, requestBodies, responsesOf, } from "./slots.js";
10
+ import { websocketMessagesOf } from "./streams.js";
10
11
  const METHODS = ["get", "post", "put", "patch", "delete", "head", "options"];
11
12
  /** A stable id for an operation without one: `GET /users/{id}` → `getUsersById`, `GET /` → `getRoot`. */
12
13
  export function deriveOperationId(method, path) {
@@ -42,6 +43,9 @@ function operationOf(id, op, { components, item, method, path }) {
42
43
  operation.description = op.description;
43
44
  if (typeof op.summary === "string")
44
45
  operation.summary = op.summary;
46
+ const messages = websocketMessagesOf(op["x-websocket"]);
47
+ if (messages !== undefined)
48
+ operation.messages = messages;
45
49
  return operation;
46
50
  }
47
51
  /**
@@ -102,6 +102,16 @@ export type IRBody = {
102
102
  /** the whole form, for emitters that type it as one value */
103
103
  schema: IRSchema;
104
104
  };
105
+ /** One named event an SSE response streams (an OpenAPI 3.2 `itemSchema` member): `message` when it names none. */
106
+ export type IRSseEvent = {
107
+ name: string;
108
+ data: IRSchema;
109
+ };
110
+ /** A WebSocket's message schemas from the rich `x-websocket`, named from the server's side: what it receives and sends. */
111
+ export type IRWebSocketMessages = {
112
+ receive?: IRSchema;
113
+ send?: IRSchema;
114
+ };
105
115
  export type IRResponse = {
106
116
  /** the status key as written: `200`, `4XX`, `default` */
107
117
  status: string;
@@ -121,6 +131,8 @@ export type IRResponse = {
121
131
  }[];
122
132
  /** a response a declared error produces (`x-backend-error`), never a declared output */
123
133
  error?: true;
134
+ /** the named events an SSE response's `itemSchema` declares, in order */
135
+ events?: IRSseEvent[];
124
136
  };
125
137
  export type IROperationExtensions = {
126
138
  /** the id the route declared, when the document renamed its operationId (`x-backend-declared-id`) */
@@ -161,6 +173,8 @@ export type IROperation = {
161
173
  bodies?: IRBody[];
162
174
  responses: Record<string, IRResponse>;
163
175
  extensions: IROperationExtensions;
176
+ /** the rich `x-websocket` object's messages, on a websocket or realtime operation */
177
+ messages?: IRWebSocketMessages;
164
178
  };
165
179
  export type IRTreeEntry = {
166
180
  kind: "method";
@@ -1,4 +1,4 @@
1
- import { type IR, type IRMultipartPart, type IROperation, type IRParam, type IRSchema } from "./model.ts";
1
+ import { type IR, type IRDiscriminator, type IRMultipartPart, type IROperation, type IRParam, type IRSchema, type IRSseEvent } from "./model.ts";
2
2
  import { type IRPathSegment } from "./slots.ts";
3
3
  export type SdkBody = {
4
4
  kind: "json";
@@ -70,6 +70,30 @@ export type SdkModel = {
70
70
  export declare function mediaEssence(contentType: string): string;
71
71
  export declare function isJsonMedia(contentType: string): boolean;
72
72
  export declare function isTextMedia(contentType: string): boolean;
73
+ /** The named events an SSE op's `itemSchema` declares (D7), in order; none for a stream of one `schema`. */
74
+ export declare function sseEvents(op: IROperation): readonly IRSseEvent[] | undefined;
75
+ /** Whether an event's `data` of `schema` is JSON on the wire: anything but text, which core sends as is. */
76
+ export declare const isJsonEventData: (schema: IRSchema, resolve: (schema: IRSchema) => IRSchema) => boolean;
77
+ /** A message union keyed on one field (D9): the union, the field, and each variant beside its string const there. */
78
+ export type Dispatch = {
79
+ readonly union: Extract<IRSchema, {
80
+ kind: "union";
81
+ }> & {
82
+ readonly discriminator: IRDiscriminator;
83
+ };
84
+ readonly key: string;
85
+ readonly members: readonly {
86
+ readonly variant: IRSchema;
87
+ readonly value: string;
88
+ }[];
89
+ };
90
+ /**
91
+ * How a message union dispatches (D9): on its discriminator's `propertyName` when every variant is an object whose
92
+ * field there is a string const; none for any other schema.
93
+ */
94
+ export declare function dispatchOf(schema: IRSchema, resolve: (schema: IRSchema) => IRSchema): Dispatch | undefined;
95
+ /** The field a message union dispatches on (D9); none for a schema that does not dispatch. */
96
+ export declare const dispatchKey: (schema: IRSchema, resolve: (schema: IRSchema) => IRSchema) => string | undefined;
73
97
  /**
74
98
  * The schema an SSE op declares for its events' `data`, when it is not a string: such events are
75
99
  * JSON (core JSON-encodes an object `data`) and the client parses them.
@@ -84,16 +84,46 @@ function streamOf(op) {
84
84
  /* a string-typed schema: a scalar string, or a string const or enum */
85
85
  const isStringSchema = (schema) => (schema.kind === "scalar" && schema.type === "string") ||
86
86
  (schema.kind === "const" && typeof schema.value === "string");
87
+ /** The SSE response of `op`: its `text/event-stream` answer, if any. */
88
+ const sseResponse = (op) => Object.values(op.responses).find(({ contentType }) => contentType !== undefined && mediaEssence(contentType) === "text/event-stream");
89
+ /** The named events an SSE op's `itemSchema` declares (D7), in order; none for a stream of one `schema`. */
90
+ export function sseEvents(op) {
91
+ const events = sseResponse(op)?.events;
92
+ return events === undefined || events.length === 0 ? undefined : events;
93
+ }
94
+ /** Whether an event's `data` of `schema` is JSON on the wire: anything but text, which core sends as is. */
95
+ export const isJsonEventData = (schema, resolve) => {
96
+ const resolved = resolve(schema);
97
+ return resolved.kind !== "unknown" && !isStringSchema(resolved);
98
+ };
99
+ /**
100
+ * How a message union dispatches (D9): on its discriminator's `propertyName` when every variant is an object whose
101
+ * field there is a string const; none for any other schema.
102
+ */
103
+ export function dispatchOf(schema, resolve) {
104
+ const union = resolve(schema);
105
+ if (union.kind !== "union" || union.discriminator === undefined)
106
+ return undefined;
107
+ const { discriminator } = union;
108
+ const key = discriminator.propertyName;
109
+ const members = union.variants.map((variant) => {
110
+ const object = resolve(variant);
111
+ const field = object.kind === "object" ? object.fields.find(({ name }) => name === key) : undefined;
112
+ const value = field === undefined ? undefined : resolve(field.schema);
113
+ return { value: value?.kind === "const" && typeof value.value === "string" ? value.value : undefined, variant };
114
+ });
115
+ const keyed = members.every((member) => member.value !== undefined);
116
+ return keyed ? { key, members, union: { ...union, discriminator } } : undefined;
117
+ }
118
+ /** The field a message union dispatches on (D9); none for a schema that does not dispatch. */
119
+ export const dispatchKey = (schema, resolve) => dispatchOf(schema, resolve)?.key;
87
120
  /**
88
121
  * The schema an SSE op declares for its events' `data`, when it is not a string: such events are
89
122
  * JSON (core JSON-encodes an object `data`) and the client parses them.
90
123
  */
91
124
  export function sseEventSchema(op, resolve) {
92
- const response = Object.values(op.responses).find(({ contentType }) => contentType !== undefined && mediaEssence(contentType) === "text/event-stream");
93
- if (response?.schema === undefined)
94
- return undefined;
95
- const resolved = resolve(response.schema);
96
- return resolved.kind === "unknown" || isStringSchema(resolved) ? undefined : response.schema;
125
+ const schema = sseResponse(op)?.schema;
126
+ return schema !== undefined && isJsonEventData(schema, resolve) ? schema : undefined;
97
127
  }
98
128
  function opOf(op, resolve) {
99
129
  const errorStatuses = Object.keys(op.responses)
@@ -31,7 +31,7 @@ export declare function responsesOf(op: Json, components: Components): {
31
31
  responses: Record<string, IRResponse>;
32
32
  sse: boolean;
33
33
  };
34
- /** The backend extensions: each only when it is literally `true`; invalidation targets as strings. */
34
+ /** The backend extensions: each only when it is literally `true` (`x-websocket` also as its rich object); invalidation targets as strings. */
35
35
  export declare function extensionsOf(op: Json, sse: boolean): IROperationExtensions;
36
36
  /**
37
37
  * The Standard Webhooks event the webhook `name` declares through `x-backend-webhook`, from its JSON
package/dist/ir/slots.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { schemaToIR } from "./schema.js";
2
+ import { sseEventsOf, websocketMessagesOf } from "./streams.js";
2
3
  import { compareCodeUnits } from "../emit/shared/lang.js";
3
4
  /** Splits an OpenAPI path template into literal text and `{param}` pieces. */
4
5
  export function parseOpenApiPath(path) {
@@ -159,8 +160,13 @@ export function responsesOf(op, components) {
159
160
  const type = ordered(content)[0];
160
161
  const out = { status };
161
162
  if (type !== undefined) {
162
- if (Object.keys(content).some((key) => essenceOf(key) === "text/event-stream"))
163
+ const stream = Object.keys(content).find((key) => essenceOf(key) === "text/event-stream");
164
+ if (stream !== undefined) {
163
165
  sse = true;
166
+ const events = sseEventsOf(content[stream]?.itemSchema, (value) => deref(value, components));
167
+ if (events !== undefined)
168
+ out.events = events;
169
+ }
164
170
  out.contentType = type;
165
171
  const schema = content[type]?.schema;
166
172
  if (schema !== undefined)
@@ -179,10 +185,10 @@ export function responsesOf(op, components) {
179
185
  }
180
186
  return { responses, sse };
181
187
  }
182
- /** The backend extensions: each only when it is literally `true`; invalidation targets as strings. */
188
+ /** The backend extensions: each only when it is literally `true` (`x-websocket` also as its rich object); invalidation targets as strings. */
183
189
  export function extensionsOf(op, sse) {
184
190
  const out = {};
185
- if (op["x-websocket"] === true)
191
+ if (op["x-websocket"] === true || websocketMessagesOf(op["x-websocket"]) !== undefined)
186
192
  out.websocket = true;
187
193
  if (op["x-realtime"] === true)
188
194
  out.realtime = true;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The typed stream shapes an operation declares: an OpenAPI 3.2 SSE `itemSchema`'s named events, and the
3
+ * rich `x-websocket` object's `receive` and `send` messages (realtime operations carry the same object).
4
+ * Both read any document, so a malformed shape is left out, never refused.
5
+ */
6
+ import type { IRSseEvent, IRWebSocketMessages } from "./model.ts";
7
+ type Json = Record<string, unknown>;
8
+ /**
9
+ * The events an SSE `itemSchema` declares, in order: one event object, or a `oneOf`/`anyOf` of them, each
10
+ * followed through `follow`. A member is named by its `event` const, `message` when it has none; its data
11
+ * is its `data`'s `contentSchema` when it has one, else the `data` schema. None for a non-object itemSchema.
12
+ */
13
+ export declare function sseEventsOf(itemSchema: unknown, follow: (value: unknown) => Json | undefined): IRSseEvent[] | undefined;
14
+ /** The rich `x-websocket` object's message schemas, each direction only when it is an object; none for any other value. */
15
+ export declare function websocketMessagesOf(raw: unknown): IRWebSocketMessages | undefined;
16
+ export {};
@@ -0,0 +1,40 @@
1
+ import { schemaToIR } from "./schema.js";
2
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3
+ /**
4
+ * The events an SSE `itemSchema` declares, in order: one event object, or a `oneOf`/`anyOf` of them, each
5
+ * followed through `follow`. A member is named by its `event` const, `message` when it has none; its data
6
+ * is its `data`'s `contentSchema` when it has one, else the `data` schema. None for a non-object itemSchema.
7
+ */
8
+ export function sseEventsOf(itemSchema, follow) {
9
+ const root = follow(itemSchema);
10
+ if (!isObject(root))
11
+ return undefined;
12
+ const union = root.oneOf ?? root.anyOf;
13
+ const members = Array.isArray(union) ? union.map(follow) : [root];
14
+ return members.flatMap((member) => {
15
+ if (!isObject(member))
16
+ return [];
17
+ const properties = isObject(member.properties) ? member.properties : {};
18
+ const event = isObject(properties.event) ? properties.event.const : undefined;
19
+ if (event !== undefined && typeof event !== "string")
20
+ return [];
21
+ return [{ data: dataOf(properties.data), name: event ?? "message" }];
22
+ });
23
+ }
24
+ /* an event's data: what `contentSchema` encodes when it is there, else the schema itself */
25
+ function dataOf(data) {
26
+ if (!isObject(data))
27
+ return { kind: "unknown" };
28
+ return schemaToIR(isObject(data.contentSchema) ? data.contentSchema : data);
29
+ }
30
+ /** The rich `x-websocket` object's message schemas, each direction only when it is an object; none for any other value. */
31
+ export function websocketMessagesOf(raw) {
32
+ if (!isObject(raw))
33
+ return undefined;
34
+ const out = {};
35
+ if (isObject(raw.receive))
36
+ out.receive = schemaToIR(raw.receive);
37
+ if (isObject(raw.send))
38
+ out.send = schemaToIR(raw.send);
39
+ return out;
40
+ }