@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.
- package/README.md +30 -7
- package/dist/emit/cli/commands.js +25 -5
- package/dist/emit/cli/flags.js +7 -3
- package/dist/emit/cli/skills.js +5 -1
- package/dist/emit/csharp/realtime.d.ts +1 -8
- package/dist/emit/csharp/realtime.js +25 -25
- package/dist/emit/csharp/sdk-answer.d.ts +10 -2
- package/dist/emit/csharp/sdk-method.js +9 -2
- package/dist/emit/csharp/sse.d.ts +0 -11
- package/dist/emit/csharp/sse.js +91 -10
- package/dist/emit/csharp/transport.js +3 -3
- package/dist/emit/csharp/types-messages.d.ts +47 -0
- package/dist/emit/csharp/types-messages.js +172 -0
- package/dist/emit/csharp/types-names.js +3 -2
- package/dist/emit/csharp/ws.d.ts +0 -15
- package/dist/emit/csharp/ws.js +26 -5
- package/dist/emit/go/sdk-answer.d.ts +24 -1
- package/dist/emit/go/sdk-method.d.ts +3 -0
- package/dist/emit/go/sdk-method.js +16 -10
- package/dist/emit/go/sse.d.ts +2 -10
- package/dist/emit/go/sse.js +87 -12
- package/dist/emit/go/types-union.d.ts +3 -2
- package/dist/emit/go/types-union.js +2 -0
- package/dist/emit/go/types.d.ts +6 -0
- package/dist/emit/go/types.js +12 -1
- package/dist/emit/go/ws.d.ts +4 -11
- package/dist/emit/go/ws.js +214 -58
- package/dist/emit/java/json.d.ts +3 -0
- package/dist/emit/java/layout-ast.d.ts +4 -1
- package/dist/emit/java/layout-types.js +1 -1
- package/dist/emit/java/models-names.d.ts +2 -0
- package/dist/emit/java/models-names.js +1 -0
- package/dist/emit/java/models-union.d.ts +12 -1
- package/dist/emit/java/models-union.js +11 -5
- package/dist/emit/java/models.d.ts +5 -0
- package/dist/emit/java/models.js +22 -7
- package/dist/emit/java/realtime.d.ts +29 -9
- package/dist/emit/java/realtime.js +45 -10
- package/dist/emit/java/sdk-mirror.js +6 -5
- package/dist/emit/java/sdk-op.js +1 -1
- package/dist/emit/java/sse.d.ts +11 -10
- package/dist/emit/java/sse.js +104 -5
- package/dist/emit/java/ws.d.ts +46 -7
- package/dist/emit/java/ws.js +89 -4
- package/dist/emit/mcp/output-schema.d.ts +4 -2
- package/dist/emit/mcp/output-schema.js +56 -12
- package/dist/emit/python/realtime.d.ts +9 -6
- package/dist/emit/python/realtime.js +21 -19
- package/dist/emit/python/sdk-answer.d.ts +5 -1
- package/dist/emit/python/sdk-method.d.ts +1 -1
- package/dist/emit/python/sdk-method.js +33 -6
- package/dist/emit/python/sdk.js +22 -2
- package/dist/emit/python/sse.d.ts +0 -5
- package/dist/emit/python/sse.js +35 -5
- package/dist/emit/python/types.d.ts +7 -0
- package/dist/emit/python/types.js +20 -3
- package/dist/emit/python/ws.d.ts +20 -6
- package/dist/emit/python/ws.js +67 -1
- package/dist/emit/rust/realtime.d.ts +7 -5
- package/dist/emit/rust/realtime.js +14 -17
- package/dist/emit/rust/sdk-method.js +1 -1
- package/dist/emit/rust/sse.d.ts +11 -7
- package/dist/emit/rust/sse.js +52 -6
- package/dist/emit/rust/types-union.d.ts +9 -1
- package/dist/emit/rust/types-union.js +4 -0
- package/dist/emit/rust/types.d.ts +9 -0
- package/dist/emit/rust/types.js +13 -7
- package/dist/emit/rust/ws.d.ts +22 -4
- package/dist/emit/rust/ws.js +57 -7
- package/dist/emit/ts/sdk-types-preamble.js +4 -0
- package/dist/emit/ts/sdk-types.js +49 -10
- package/dist/emit/ts/sdk.js +2 -2
- package/dist/emit/ts/service-map.d.ts +8 -2
- package/dist/emit/ts/service-map.js +30 -2
- package/dist/emit/ts/type-gen.js +6 -4
- package/dist/ir/build.js +4 -0
- package/dist/ir/model.d.ts +14 -0
- package/dist/ir/sdk-model.d.ts +25 -1
- package/dist/ir/sdk-model.js +35 -5
- package/dist/ir/slots.d.ts +1 -1
- package/dist/ir/slots.js +9 -3
- package/dist/ir/streams.d.ts +16 -0
- package/dist/ir/streams.js +40 -0
- package/dist/runtime/cli/socket.go +107 -13
- package/dist/runtime/cli/stream.go +18 -11
- package/dist/runtime/csharp/Adapters.cs +12 -11
- package/dist/runtime/csharp/Events.cs +22 -17
- package/dist/runtime/csharp/Realtime.cs +50 -23
- package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
- package/dist/runtime/csharp/TransportSse.cs +3 -3
- package/dist/runtime/csharp/Ws.cs +1 -1
- package/dist/runtime/csharp/WsDial.cs +19 -1
- package/dist/runtime/csharp/WsTyped.cs +109 -0
- package/dist/runtime/go/realtime.go +125 -41
- package/dist/runtime/go/realtime_loop.go +21 -18
- package/dist/runtime/go/result.go +2 -1
- package/dist/runtime/go/sse.go +11 -0
- package/dist/runtime/go/stream.go +29 -13
- package/dist/runtime/go/transport.go +15 -21
- package/dist/runtime/go/transport_longpoll.go +3 -4
- package/dist/runtime/go/transport_sse.go +6 -6
- package/dist/runtime/go/ws.go +157 -61
- package/dist/runtime/java/EventStream.java +47 -29
- package/dist/runtime/java/Exchange.java +5 -5
- package/dist/runtime/java/Flight.java +3 -3
- package/dist/runtime/java/Realtime.java +45 -11
- package/dist/runtime/java/ResumableConnection.java +77 -32
- package/dist/runtime/java/Socket.java +8 -4
- package/dist/runtime/java/SseAdapter.java +1 -1
- package/dist/runtime/java/TypedWebSocket.java +81 -24
- package/dist/runtime/java/WsAdapter.java +4 -2
- package/dist/runtime/java/WsDial.java +12 -5
- package/dist/runtime/python/events.py +25 -11
- package/dist/runtime/python/operation.py +6 -1
- package/dist/runtime/python/realtime.py +47 -33
- package/dist/runtime/python/send_async.py +1 -0
- package/dist/runtime/python/transport_sse.py +2 -2
- package/dist/runtime/python/transport_ws.py +1 -1
- package/dist/runtime/python/ws.py +100 -39
- package/dist/runtime/rust/events.rs +64 -41
- package/dist/runtime/rust/realtime.rs +80 -34
- package/dist/runtime/rust/realtime_loop.rs +37 -12
- package/dist/runtime/rust/sse.rs +3 -2
- package/dist/runtime/rust/transport_sse.rs +1 -1
- package/dist/runtime/rust/transport_ws.rs +3 -2
- package/dist/runtime/rust/ws.rs +122 -50
- package/dist/runtime/ts/realtime-connection.ts +22 -0
- package/dist/runtime/ts/realtime-transports.ts +13 -4
- package/dist/runtime/ts/realtime.ts +27 -3
- package/dist/runtime/ts/sdk-realtime.ts +1 -1
- package/dist/runtime/ts/sdk-sse.ts +31 -14
- package/dist/runtime/ts/sdk-ws.ts +2 -1
- package/dist/runtime/ts/sdk.ts +9 -2
- package/dist/runtime/ts/sse.ts +8 -0
- package/dist/runtime/ts/ws.ts +88 -50
- package/package.json +3 -34
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
} from "./realtime.ts"
|
|
18
18
|
|
|
19
19
|
type QueueEntry = { type: "done" } | { error: unknown; type: "error" } | { type: "value"; value: unknown }
|
|
20
|
+
type MessageHandler = (data: never) => void
|
|
20
21
|
|
|
21
22
|
/**
|
|
22
23
|
* One logical stream over reconnecting transports: messages arrive in order through the async
|
|
@@ -41,6 +42,8 @@ export class Resumable implements ResumableConnection {
|
|
|
41
42
|
readonly #timers = new Set<ReturnType<typeof setTimeout>>()
|
|
42
43
|
/** the transport being dialed, closed with the connection */
|
|
43
44
|
#dialing: TransportConnection | null = null
|
|
45
|
+
/** `on`'s handlers by event: `"message"`, and the values of the dispatch key */
|
|
46
|
+
readonly #handlers = new Map<string, Set<MessageHandler>>()
|
|
44
47
|
|
|
45
48
|
constructor(opts: ResumableConnectionOpts, refresh?: () => Promise<boolean>) {
|
|
46
49
|
this.#opts = opts
|
|
@@ -125,6 +128,7 @@ export class Resumable implements ResumableConnection {
|
|
|
125
128
|
this.#lastEventId = frame.id ?? this.#lastEventId
|
|
126
129
|
this.#reconnectToken = frame.reconnectToken || this.#reconnectToken
|
|
127
130
|
this.#enqueue({ type: "value", value: frame.data })
|
|
131
|
+
this.#hear(frame.data)
|
|
128
132
|
} else if (frame.t === "ready") this.#reconnectToken = frame.reconnectToken || this.#reconnectToken
|
|
129
133
|
else if (frame.t === "pong") this.#keepalive?.onPong()
|
|
130
134
|
else {
|
|
@@ -250,6 +254,24 @@ export class Resumable implements ResumableConnection {
|
|
|
250
254
|
this.#later(() => void this.#connect(), this.#opts.reconnectDelayMs ?? 1000)
|
|
251
255
|
}
|
|
252
256
|
|
|
257
|
+
/** `data` to `on("message")`, then to `on(value)` by the dispatch key's value. */
|
|
258
|
+
#hear(data: unknown): void {
|
|
259
|
+
const key = this.#opts.dispatch
|
|
260
|
+
const value = key === undefined || typeof data !== "object" || data === null ? undefined : Reflect.get(data, key)
|
|
261
|
+
const events = typeof value === "string" && value !== "message" ? ["message", value] : ["message"]
|
|
262
|
+
for (const event of events)
|
|
263
|
+
for (const handler of this.#handlers.get(event) ?? []) safely(() => (handler as (data: unknown) => void)(data))
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
on(event: string, handler: MessageHandler): void {
|
|
267
|
+
const handlers = this.#handlers.get(event) ?? new Set()
|
|
268
|
+
this.#handlers.set(event, handlers.add(handler))
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
off(event: string, handler: MessageHandler): void {
|
|
272
|
+
this.#handlers.get(event)?.delete(handler)
|
|
273
|
+
}
|
|
274
|
+
|
|
253
275
|
send(data: unknown): Promise<void> {
|
|
254
276
|
return this.sendText(JSON.stringify(data))
|
|
255
277
|
}
|
|
@@ -14,7 +14,7 @@ import { createTypedWebSocket, wsUrl } from "./ws.ts"
|
|
|
14
14
|
|
|
15
15
|
type Target = { http: HTTPClient; opts: RequestOptions; path: string }
|
|
16
16
|
|
|
17
|
-
export type RealtimeOptions = Omit<ResumableConnectionOpts, "headers" | "signal" | "transports" | "url">
|
|
17
|
+
export type RealtimeOptions = Omit<ResumableConnectionOpts, "dispatch" | "headers" | "signal" | "transports" | "url">
|
|
18
18
|
|
|
19
19
|
/** A payload's JSON when it parses, else its text. */
|
|
20
20
|
function payloadOf(text: string): unknown {
|
|
@@ -140,10 +140,19 @@ function pollAdapter(at: Target): TransportAdapter {
|
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
142
|
|
|
143
|
-
/**
|
|
144
|
-
|
|
143
|
+
/**
|
|
144
|
+
* An x-realtime op's chain, as Go's: WebSocket, SSE, long-poll; no JSON keepalive unless set. `dispatch` is the field
|
|
145
|
+
* its declared messages are keyed on.
|
|
146
|
+
*/
|
|
147
|
+
export function realtimeConnection(
|
|
148
|
+
http: HTTPClient,
|
|
149
|
+
path: string,
|
|
150
|
+
input: RequestOptions & RealtimeOptions,
|
|
151
|
+
dispatch?: string,
|
|
152
|
+
): Resumable {
|
|
145
153
|
const { baseURL, cookies, headers, params, search, signal, ...opts } = input
|
|
146
154
|
const at = { http, opts: { baseURL, cookies, headers, params, search }, path }
|
|
147
155
|
const transports = [wsAdapter(at), sseAdapter(at), pollAdapter(at)]
|
|
148
|
-
|
|
156
|
+
const resumable = { keepaliveInterval: 0, ...opts, dispatch, signal, transports, url: path }
|
|
157
|
+
return new Resumable(resumable, () => http[REFRESH_AUTH]())
|
|
149
158
|
}
|
|
@@ -270,6 +270,8 @@ export type ResumableConnectionOpts = {
|
|
|
270
270
|
/** Ping every this many ms (WebSocket 20 s, SSE none, unless set; 0: none); one unanswered as long reconnects. */
|
|
271
271
|
keepaliveInterval?: number | undefined
|
|
272
272
|
lastEventId?: string | undefined
|
|
273
|
+
/** The field each message is handed to `on(value)` by: the operation's declared messages are keyed on it. */
|
|
274
|
+
dispatch?: string | undefined
|
|
273
275
|
/** Reconnects after a drop before the stream ends; 0 retries forever. Default 5. */
|
|
274
276
|
maxReconnectAttempts?: number | undefined
|
|
275
277
|
onReconnected?: (() => void) | undefined
|
|
@@ -281,13 +283,35 @@ export type ResumableConnectionOpts = {
|
|
|
281
283
|
url: string
|
|
282
284
|
}
|
|
283
285
|
|
|
284
|
-
|
|
286
|
+
/** The values of `T`'s field `K`, `"message"` left out: `on("message")` hears every message. */
|
|
287
|
+
type MessageKey<T, K extends string> = Exclude<
|
|
288
|
+
T extends { readonly [P in K]: infer V extends string } ? V : never,
|
|
289
|
+
"message"
|
|
290
|
+
>
|
|
291
|
+
|
|
292
|
+
/** `on(value)` and `off(value)` for a connection whose messages are keyed on `K`; nothing for an unkeyed one. */
|
|
293
|
+
type KeyedMessages<T, K extends string> = [K] extends [never]
|
|
294
|
+
? unknown
|
|
295
|
+
: {
|
|
296
|
+
off(event: MessageKey<T, K>, handler: (...args: never[]) => void): void
|
|
297
|
+
/** The messages whose `K` is `event`, after `"message"` hears them. */
|
|
298
|
+
on<V extends MessageKey<T, K>>(event: V, handler: (data: Extract<T, { readonly [P in K]: V }>) => void): void
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* One logical stream of `T` that sends `In`. Iterating it opens it; `on("message")` and, when `T` is a union keyed on
|
|
303
|
+
* `K`, `on(value)` (D9) hear each message as it arrives, beside the iterator, which still yields every one.
|
|
304
|
+
*/
|
|
305
|
+
export type ResumableConnection<T = unknown, In = unknown, K extends string = never> = {
|
|
285
306
|
close(reason?: string): void
|
|
307
|
+
off(event: "message", handler: (...args: never[]) => void): void
|
|
308
|
+
/** Every message as it arrives; a handler that throws is skipped, and the stream carries on. */
|
|
309
|
+
on(event: "message", handler: (data: T) => void): void
|
|
286
310
|
readonly provenTransport: Transport | null
|
|
287
311
|
/** Resolves once sent; over SSE and long-poll a POST, rejecting with its error. */
|
|
288
|
-
send(data:
|
|
312
|
+
send(data: In): Promise<void>
|
|
289
313
|
/** `send`'s raw form: `text` as it is, a text frame or a POSTed text/plain body. */
|
|
290
314
|
sendText(text: string): Promise<void>
|
|
291
315
|
readonly state: ConnectionState
|
|
292
316
|
[Symbol.asyncIterator](): AsyncIterableIterator<T>
|
|
293
|
-
}
|
|
317
|
+
} & KeyedMessages<T, K>
|
|
@@ -7,4 +7,4 @@ import { type OperationCall, templateOf } from "./sdk.ts"
|
|
|
7
7
|
export const realtimeOp: OperationCall =
|
|
8
8
|
(core, entry) =>
|
|
9
9
|
(input: RequestOptions & RealtimeOptions = {}): ResumableConnection =>
|
|
10
|
-
realtimeConnection(core.http, templateOf(entry), input)
|
|
10
|
+
realtimeConnection(core.http, templateOf(entry), input, entry.dispatch)
|
|
@@ -7,21 +7,38 @@ import { type OperationCall, optionsFor, type SdkCore, type ServiceEntry, templa
|
|
|
7
7
|
import type { SSEEvent } from "./sse.ts"
|
|
8
8
|
import { later, openStream } from "./stream.ts"
|
|
9
9
|
|
|
10
|
-
/**
|
|
11
|
-
function
|
|
10
|
+
/** `event` with its `data` parsed as JSON; data that does not parse fails the stream, naming the event. */
|
|
11
|
+
function parsed(event: SSEEvent): SSEEvent<unknown> {
|
|
12
|
+
try {
|
|
13
|
+
return { ...event, data: JSON.parse(event.data) }
|
|
14
|
+
} catch (e) {
|
|
15
|
+
const name = event.id === undefined ? "an event" : `event ${JSON.stringify(event.id)}`
|
|
16
|
+
const message = `SSE ${name} is not valid JSON: ${e instanceof Error ? e.message : String(e)}`
|
|
17
|
+
throw new ClientError({ body: event.data, message, response: Response.error(), status: 0 })
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The events of `events` as `entry` reads them: each parsed (`"json"`); or, for a stream that names its events, each
|
|
23
|
+
* named `message` when it has no name and parsed when `sse` holds its name; else as they came.
|
|
24
|
+
*/
|
|
25
|
+
function eventsOf(events: AsyncIterable<SSEEvent>, sse: ServiceEntry["sse"]): AsyncIterable<SSEEvent<unknown>> {
|
|
26
|
+
if (sse === "json") return mapEvents(events, parsed)
|
|
27
|
+
if (typeof sse !== "object") return events
|
|
28
|
+
return mapEvents(events, (raw) => {
|
|
29
|
+
const event = { ...raw, event: raw.event ?? "message" }
|
|
30
|
+
return sse.includes(event.event) ? parsed(event) : event
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** `events`, each through `map`. */
|
|
35
|
+
function mapEvents(
|
|
36
|
+
events: AsyncIterable<SSEEvent>,
|
|
37
|
+
map: (event: SSEEvent) => SSEEvent<unknown>,
|
|
38
|
+
): AsyncIterable<SSEEvent<unknown>> {
|
|
12
39
|
return {
|
|
13
40
|
async *[Symbol.asyncIterator]() {
|
|
14
|
-
for await (const event of events)
|
|
15
|
-
let data: unknown
|
|
16
|
-
try {
|
|
17
|
-
data = JSON.parse(event.data)
|
|
18
|
-
} catch (e) {
|
|
19
|
-
const name = event.id === undefined ? "an event" : `event ${JSON.stringify(event.id)}`
|
|
20
|
-
const message = `SSE ${name} is not valid JSON: ${e instanceof Error ? e.message : String(e)}`
|
|
21
|
-
throw new ClientError({ body: event.data, message, response: Response.error(), status: 0 })
|
|
22
|
-
}
|
|
23
|
-
yield { ...event, data }
|
|
24
|
-
}
|
|
41
|
+
for await (const event of events) yield map(event)
|
|
25
42
|
},
|
|
26
43
|
}
|
|
27
44
|
}
|
|
@@ -43,7 +60,7 @@ async function open(core: SdkCore, entry: ServiceEntry, input: RequestOptions):
|
|
|
43
60
|
if (selector !== undefined) core.mark(entry, input.params, selector)
|
|
44
61
|
}
|
|
45
62
|
const { data, response } = await openStream(core.http, { meta, method: entry.method, onOpen, opts, path: template })
|
|
46
|
-
return { data: entry.sse
|
|
63
|
+
return { data: eventsOf(data, entry.sse), response }
|
|
47
64
|
}
|
|
48
65
|
|
|
49
66
|
/** An event stream: sent when iterated, or opened into a Result by the safe twin. */
|
|
@@ -12,7 +12,8 @@ export const wsOp: OperationCall =
|
|
|
12
12
|
(input: WsInput = {}): TypedWebSocket => {
|
|
13
13
|
const url = new URL(wsUrl(core.http, templateOf(entry), { params: input.params, search: input.search }))
|
|
14
14
|
if (input.reconnectToken) url.searchParams.append("reconnect_token", input.reconnectToken)
|
|
15
|
-
const
|
|
15
|
+
const { decode, dispatch, encode } = entry
|
|
16
|
+
const socket = createTypedWebSocket(url.toString(), { decode, dispatch, encode, protocols: input.protocols })
|
|
16
17
|
if (entry.invalidate?.length) {
|
|
17
18
|
const selector = `WS ${interpolatePath(templateOf(entry), input.params)}`
|
|
18
19
|
socket.on("open", () => core.mark(entry, input.params, selector))
|
package/dist/runtime/ts/sdk.ts
CHANGED
|
@@ -21,11 +21,18 @@ export type ServiceEntry = {
|
|
|
21
21
|
/** the OpenAPI path template, `{param}` kept */
|
|
22
22
|
path: string
|
|
23
23
|
realtime?: boolean
|
|
24
|
-
/** an event stream; `"json"` when its events carry JSON `data` the client parses
|
|
25
|
-
|
|
24
|
+
/** an event stream; `"json"` when its events carry JSON `data` the client parses, or the names of the events that
|
|
25
|
+
do when the operation names its events (an unnamed one is `message`) */
|
|
26
|
+
sse?: boolean | "json" | readonly string[]
|
|
26
27
|
/** the param that spans segments (`x-backend-wildcard`) */
|
|
27
28
|
wildcard?: string
|
|
28
29
|
ws?: boolean
|
|
30
|
+
/** a socket whose server declares what it sends: each text frame is parsed as JSON */
|
|
31
|
+
decode?: boolean
|
|
32
|
+
/** the field a socket's parsed message is handed to `on(value)` by (D9) */
|
|
33
|
+
dispatch?: string
|
|
34
|
+
/** a socket whose server declares what it receives: every send is JSON */
|
|
35
|
+
encode?: boolean
|
|
29
36
|
/** how a stream, WebSocket or realtime operation is called; a REST one has none */
|
|
30
37
|
call?: OperationCall
|
|
31
38
|
}
|
package/dist/runtime/ts/sse.ts
CHANGED
|
@@ -7,6 +7,14 @@ export type SSEEvent<T = string> = {
|
|
|
7
7
|
retry?: number
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* One event of a stream that names its events (an OpenAPI 3.2 `itemSchema`), `M` mapping each name to its `data`:
|
|
12
|
+
* narrowing on `event` types `data`. An unnamed event is `message`, as `EventSource` names it.
|
|
13
|
+
*/
|
|
14
|
+
export type SSEEventOf<M> = {
|
|
15
|
+
[K in keyof M & string]: { data: M[K]; event: K; id?: string; retry?: number }
|
|
16
|
+
}[keyof M & string]
|
|
17
|
+
|
|
10
18
|
/* the siblings' caps, in UTF-8 bytes */
|
|
11
19
|
const MAX_LINE = 1 << 20
|
|
12
20
|
const MAX_EVENT = 8 << 20
|
package/dist/runtime/ts/ws.ts
CHANGED
|
@@ -3,28 +3,61 @@
|
|
|
3
3
|
* with no onAuthExpired refresh. The platform WebSocket exposes no ping and no message cap, so this socket has neither.
|
|
4
4
|
*/
|
|
5
5
|
import type { HTTPClient } from "./http.ts"
|
|
6
|
+
import { ClientError } from "./error.ts"
|
|
6
7
|
import type { RequestOptions } from "./request.ts"
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
/** What an untyped socket sends: strings, bytes and `Blob` as they are, any other value as JSON. */
|
|
10
|
+
export type WsFrame = ArrayBuffer | ArrayBufferView | Blob | object | string
|
|
11
|
+
|
|
12
|
+
/** The events every socket has; a message whose key is one of these names gets no `on(value)` of its own. */
|
|
13
|
+
type SocketEvent = "binary" | "close" | "error" | "message" | "open"
|
|
14
|
+
|
|
15
|
+
/** The values of `Out`'s field `K`, the lifecycle names left out. */
|
|
16
|
+
type KeyOf<Out, K extends string> = Exclude<
|
|
17
|
+
Out extends { readonly [P in K]: infer V extends string } ? V : never,
|
|
18
|
+
SocketEvent
|
|
19
|
+
>
|
|
20
|
+
|
|
21
|
+
/** `on(value)` and `off(value)` for a socket whose messages are keyed on `K`; nothing for an unkeyed one. */
|
|
22
|
+
type Keyed<Out, K extends string> = [K] extends [never]
|
|
23
|
+
? unknown
|
|
24
|
+
: {
|
|
25
|
+
off(event: KeyOf<Out, K>, handler: (...args: never[]) => void): void
|
|
26
|
+
/** The messages whose `K` is `event`, after `"message"` hears them. */
|
|
27
|
+
on<V extends KeyOf<Out, K>>(event: V, handler: (data: Extract<Out, { readonly [P in K]: V }>) => void): void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A WebSocket typed both ways: `send` takes `In`, `on("message")` gets `Out`, and when `Out` is a union keyed on `K`,
|
|
32
|
+
* `on(value)` gets the member whose `K` is `value` (D9). Untyped, it sends `WsFrame` and hears text.
|
|
33
|
+
*/
|
|
34
|
+
export type TypedWebSocket<In = WsFrame, Out = string, K extends string = never> = {
|
|
9
35
|
close(code?: number, reason?: string): void
|
|
10
|
-
off(event:
|
|
36
|
+
off(event: SocketEvent, handler: (...args: never[]) => void): void
|
|
11
37
|
/** Binary frames, as `ArrayBuffer`. Text frames go to `"message"`. */
|
|
12
38
|
on(event: "binary", handler: (data: ArrayBuffer) => void): void
|
|
13
39
|
on(event: "close", handler: (code: number, reason: string) => void): void
|
|
40
|
+
/** A socket error; for a socket with declared messages, also a text frame that is no JSON, as a `ClientError`. */
|
|
14
41
|
on(event: "error", handler: (error: unknown) => void): void
|
|
15
|
-
/** Text frames. */
|
|
16
|
-
on(event: "message", handler: (data:
|
|
42
|
+
/** Text frames: as text, or parsed as JSON for a socket with declared messages. */
|
|
43
|
+
on(event: "message", handler: (data: Out) => void): void
|
|
17
44
|
on(event: "open", handler: () => void): void
|
|
18
45
|
readonly readyState: number
|
|
19
46
|
/**
|
|
20
|
-
*
|
|
21
|
-
* Sends before the socket opens are queued; after it closes they are dropped.
|
|
47
|
+
* Untyped, strings, `ArrayBuffer`, typed arrays and `Blob` are sent as-is and any other value is JSON-encoded; with
|
|
48
|
+
* declared messages every value is JSON. Sends before the socket opens are queued; after it closes they are dropped.
|
|
22
49
|
*/
|
|
23
|
-
send(data:
|
|
24
|
-
}
|
|
50
|
+
send(data: In): void
|
|
51
|
+
} & Keyed<Out, K>
|
|
25
52
|
|
|
26
53
|
export type WSOptions = {
|
|
27
54
|
protocols?: string | string[] | undefined
|
|
55
|
+
/** Parse each text frame as JSON: the operation declares what the server sends. */
|
|
56
|
+
decode?: boolean | undefined
|
|
57
|
+
/** The field a parsed message is handed to `on(value)` by. */
|
|
58
|
+
dispatch?: string | undefined
|
|
59
|
+
/** Send every value as JSON: the operation declares what the server receives. */
|
|
60
|
+
encode?: boolean | undefined
|
|
28
61
|
}
|
|
29
62
|
|
|
30
63
|
type Payload = Blob | string | Uint8Array<ArrayBuffer>
|
|
@@ -32,28 +65,8 @@ type Handler = (...args: never[]) => void
|
|
|
32
65
|
|
|
33
66
|
const WS_EVENTS: readonly string[] = ["binary", "close", "error", "message", "open"]
|
|
34
67
|
|
|
35
|
-
/** The DOM listener that hands `event` to `handler` in its typed shape. */
|
|
36
|
-
function wrapListener(event: string, handler: Handler): EventListener {
|
|
37
|
-
const call = handler as (...args: unknown[]) => void
|
|
38
|
-
if (event === "message") {
|
|
39
|
-
return (e) => {
|
|
40
|
-
const data = (e as MessageEvent).data
|
|
41
|
-
if (typeof data === "string") call(data)
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
if (event === "binary") {
|
|
45
|
-
return (e) => {
|
|
46
|
-
const data = (e as MessageEvent).data
|
|
47
|
-
if (data instanceof ArrayBuffer) call(data)
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
if (event === "open") return () => call()
|
|
51
|
-
if (event === "close") return (e) => call((e as CloseEvent).code, (e as CloseEvent).reason)
|
|
52
|
-
return (e) => call(e)
|
|
53
|
-
}
|
|
54
|
-
|
|
55
68
|
/** `data` as a frame: text and Blobs as they are, bytes copied, anything else as JSON. */
|
|
56
|
-
function toPayload(data:
|
|
69
|
+
function toPayload(data: WsFrame): Payload {
|
|
57
70
|
if (typeof data === "string") return data
|
|
58
71
|
if (typeof Blob !== "undefined" && data instanceof Blob) return data
|
|
59
72
|
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
|
@@ -66,32 +79,66 @@ function toPayload(data: ArrayBuffer | ArrayBufferView | Blob | object | string)
|
|
|
66
79
|
return JSON.stringify(data)
|
|
67
80
|
}
|
|
68
81
|
|
|
82
|
+
/** The error a text frame that is no JSON raises on a socket with declared messages. */
|
|
83
|
+
function notJson(frame: string, error: unknown): ClientError {
|
|
84
|
+
const message = `WebSocket frame is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
85
|
+
return new ClientError({ body: frame, message, response: Response.error(), status: 0 })
|
|
86
|
+
}
|
|
87
|
+
|
|
69
88
|
/** A WebSocket with typed events, a send queue until it opens, and nothing sent once it closes. */
|
|
70
89
|
class TypedSocket {
|
|
71
90
|
readonly #ws: WebSocket
|
|
72
|
-
|
|
73
|
-
readonly #
|
|
91
|
+
readonly #opts: WSOptions
|
|
92
|
+
readonly #handlers = new Map<string, Set<Handler>>()
|
|
74
93
|
readonly #queue: Payload[] = []
|
|
75
94
|
#state: "closed" | "connecting" | "open" = "connecting"
|
|
76
95
|
|
|
77
|
-
constructor(ws: WebSocket) {
|
|
96
|
+
constructor(ws: WebSocket, opts: WSOptions) {
|
|
78
97
|
this.#ws = ws
|
|
98
|
+
this.#opts = opts
|
|
79
99
|
ws.binaryType = "arraybuffer"
|
|
80
100
|
ws.addEventListener("open", () => {
|
|
81
101
|
this.#state = "open"
|
|
82
102
|
for (const msg of this.#queue) ws.send(msg)
|
|
83
103
|
this.#queue.length = 0
|
|
104
|
+
this.#emit("open")
|
|
84
105
|
})
|
|
85
|
-
ws.addEventListener("close", () => {
|
|
106
|
+
ws.addEventListener("close", (e) => {
|
|
86
107
|
this.#state = "closed"
|
|
87
108
|
this.#queue.length = 0
|
|
109
|
+
this.#emit("close", (e as CloseEvent).code, (e as CloseEvent).reason)
|
|
88
110
|
})
|
|
111
|
+
ws.addEventListener("error", (e) => this.#emit("error", e))
|
|
112
|
+
ws.addEventListener("message", (e) => this.#frame((e as MessageEvent).data))
|
|
89
113
|
}
|
|
90
114
|
|
|
91
115
|
get readyState(): number {
|
|
92
116
|
return this.#ws.readyState
|
|
93
117
|
}
|
|
94
118
|
|
|
119
|
+
#emit(event: string, ...args: unknown[]): void {
|
|
120
|
+
const handlers = this.#handlers.get(event)
|
|
121
|
+
if (handlers === undefined) return
|
|
122
|
+
for (const handler of handlers) (handler as (...args: unknown[]) => void)(...args)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** One frame from the server: bytes to `"binary"`, text to `"message"`, parsed and dispatched when typed. */
|
|
126
|
+
#frame(data: unknown): void {
|
|
127
|
+
if (data instanceof ArrayBuffer) return this.#emit("binary", data)
|
|
128
|
+
if (typeof data !== "string") return
|
|
129
|
+
if (this.#opts.decode !== true) return this.#emit("message", data)
|
|
130
|
+
let value: unknown
|
|
131
|
+
try {
|
|
132
|
+
value = JSON.parse(data)
|
|
133
|
+
} catch (error) {
|
|
134
|
+
return this.#emit("error", notJson(data, error))
|
|
135
|
+
}
|
|
136
|
+
this.#emit("message", value)
|
|
137
|
+
const { dispatch } = this.#opts
|
|
138
|
+
const key = dispatch !== undefined && typeof value === "object" && value !== null ? value[dispatch as never] : null
|
|
139
|
+
if (typeof key === "string" && !WS_EVENTS.includes(key)) this.#emit(key, value)
|
|
140
|
+
}
|
|
141
|
+
|
|
95
142
|
close(code?: number, reason?: string): void {
|
|
96
143
|
this.#state = "closed"
|
|
97
144
|
this.#queue.length = 0
|
|
@@ -99,28 +146,19 @@ class TypedSocket {
|
|
|
99
146
|
}
|
|
100
147
|
|
|
101
148
|
on(event: string, handler: Handler): void {
|
|
102
|
-
if (!WS_EVENTS.includes(event)) return
|
|
103
|
-
const
|
|
104
|
-
this.#
|
|
105
|
-
|
|
106
|
-
const previous = byHandler.get(handler)
|
|
107
|
-
if (previous) this.#ws.removeEventListener(target, previous)
|
|
108
|
-
const wrapped = wrapListener(event, handler)
|
|
109
|
-
byHandler.set(handler, wrapped)
|
|
110
|
-
this.#ws.addEventListener(target, wrapped)
|
|
149
|
+
if (!WS_EVENTS.includes(event) && this.#opts.dispatch === undefined) return
|
|
150
|
+
const handlers = this.#handlers.get(event) ?? new Set<Handler>()
|
|
151
|
+
this.#handlers.set(event, handlers)
|
|
152
|
+
handlers.add(handler)
|
|
111
153
|
}
|
|
112
154
|
|
|
113
155
|
off(event: string, handler: Handler): void {
|
|
114
|
-
|
|
115
|
-
const wrapped = byHandler?.get(handler)
|
|
116
|
-
if (!wrapped) return
|
|
117
|
-
this.#ws.removeEventListener(event === "binary" ? "message" : event, wrapped)
|
|
118
|
-
byHandler?.delete(handler)
|
|
156
|
+
this.#handlers.get(event)?.delete(handler)
|
|
119
157
|
}
|
|
120
158
|
|
|
121
|
-
send(data:
|
|
159
|
+
send(data: WsFrame): void {
|
|
122
160
|
if (this.#state === "closed") return
|
|
123
|
-
const payload = toPayload(data)
|
|
161
|
+
const payload = this.#opts.encode === true ? JSON.stringify(data) : toPayload(data)
|
|
124
162
|
if (this.#state === "connecting") this.#queue.push(payload)
|
|
125
163
|
else this.#ws.send(payload)
|
|
126
164
|
}
|
|
@@ -140,7 +178,7 @@ export function createTypedWebSocket(
|
|
|
140
178
|
WebSocketImpl: typeof WebSocket = WebSocket,
|
|
141
179
|
): TypedWebSocket {
|
|
142
180
|
const ws = opts?.protocols ? new WebSocketImpl(url, opts.protocols) : new WebSocketImpl(url)
|
|
143
|
-
const socket = new TypedSocket(ws)
|
|
181
|
+
const socket = new TypedSocket(ws, opts ?? {})
|
|
144
182
|
const typed: TypedWebSocket = {
|
|
145
183
|
close: (code, reason) => socket.close(code, reason),
|
|
146
184
|
off: (event, handler) => socket.off(event, handler),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@workerstack/clients",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.29",
|
|
4
4
|
"description": "Generates SDKs (TypeScript, Go, Rust, Python, C#, Java), a CLI and an MCP server from any OpenAPI 3.x document.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"codegen",
|
|
@@ -55,27 +55,9 @@
|
|
|
55
55
|
"scripts": {
|
|
56
56
|
"fmt": "oxfmt",
|
|
57
57
|
"fmt:check": "oxfmt --check",
|
|
58
|
-
"grunt:antigravity": "antigravity --dangerously-skip-permissions",
|
|
59
|
-
"grunt:claude": "claude --dangerously-skip-permissions",
|
|
60
|
-
"grunt:clean": "node ./.rulesync/scripts/clean.mjs",
|
|
61
|
-
"grunt:codex": "codex --dangerously-bypass-approvals-and-sandbox",
|
|
62
|
-
"grunt:doctor": "node ./.rulesync/scripts/doctor.mjs",
|
|
63
|
-
"grunt:gemini": "gemini --yolo",
|
|
64
|
-
"grunt:grok": "grok --yolo",
|
|
65
|
-
"grunt:hooks:check": "node .rulesync/scripts/hooks-union.mjs --check",
|
|
66
|
-
"grunt:hooks:union": "node .rulesync/scripts/hooks-union.mjs",
|
|
67
|
-
"grunt:purge:global-mcps": "node .rulesync/scripts/purge-global-mcps.mjs",
|
|
68
|
-
"grunt:purge:global-mcps:apply": "node .rulesync/scripts/purge-global-mcps.mjs --apply",
|
|
69
|
-
"grunt:rulesync:check": "node ./.rulesync/scripts/guarded-roots.mjs check",
|
|
70
|
-
"grunt:rulesync:doctor": "rulesync doctor",
|
|
71
|
-
"grunt:rulesync:generate": "node ./.rulesync/scripts/guarded-roots.mjs generate",
|
|
72
|
-
"grunt:rulesync:watch": "node ./.rulesync/scripts/guarded-roots.mjs watch",
|
|
73
|
-
"grunt:setup": "node ./.rulesync/scripts/setup.mjs",
|
|
74
|
-
"grunt:sync:globals": "node .rulesync/scripts/sync-global-settings.mjs",
|
|
75
|
-
"grunt:sync:globals:apply": "node .rulesync/scripts/sync-global-settings.mjs --apply",
|
|
76
|
-
"grunt:sync:globals:check": "node .rulesync/scripts/check-globals.mjs",
|
|
77
58
|
"lint": "oxlint",
|
|
78
59
|
"lint:fix": "oxlint --fix",
|
|
60
|
+
"postinstall": "repo sync --postinstall",
|
|
79
61
|
"prepack": "bun scripts/build.ts",
|
|
80
62
|
"prepare": "lefthook install --reset-hooks-path",
|
|
81
63
|
"test": "vitest run --coverage",
|
|
@@ -102,18 +84,5 @@
|
|
|
102
84
|
"engines": {
|
|
103
85
|
"node": ">=22.12.0"
|
|
104
86
|
},
|
|
105
|
-
"packageManager": "bun@1.4.4"
|
|
106
|
-
"standards": {
|
|
107
|
-
"repo": "clients",
|
|
108
|
-
"gates": [
|
|
109
|
-
"test:harness"
|
|
110
|
-
],
|
|
111
|
-
"ci": [
|
|
112
|
-
"fmt:check",
|
|
113
|
-
"lint",
|
|
114
|
-
"typecheck",
|
|
115
|
-
"test",
|
|
116
|
-
"test:harness"
|
|
117
|
-
]
|
|
118
|
-
}
|
|
87
|
+
"packageManager": "bun@1.4.4"
|
|
119
88
|
}
|