@cmodjs/core 6.3.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/docs/commands.md +123 -65
  2. package/docs/dependencies.md +189 -4
  3. package/docs/index.md +56 -12
  4. package/docs/install-steps.md +20 -17
  5. package/docs/jobs.md +43 -16
  6. package/docs/mod.md +43 -27
  7. package/docs/options.md +2 -2
  8. package/docs/session.md +58 -32
  9. package/docs/testing.md +88 -24
  10. package/docs/ui.md +128 -58
  11. package/installer.d.ts +2 -2
  12. package/jobs/context.js +1 -1
  13. package/jobs/program.d.ts +4 -1
  14. package/jobs/program.d.ts.map +1 -1
  15. package/jobs/program.js +79 -20
  16. package/mod.d.ts +59 -9
  17. package/mod.d.ts.map +1 -1
  18. package/mod.js +5 -3
  19. package/package.json +1 -1
  20. package/records.d.ts +15 -2
  21. package/records.d.ts.map +1 -1
  22. package/records.js +24 -10
  23. package/register.d.ts.map +1 -1
  24. package/register.js +7 -4
  25. package/rpc.d.ts +7 -0
  26. package/rpc.d.ts.map +1 -0
  27. package/rpc.js +59 -0
  28. package/runtime/bound.d.ts +1 -0
  29. package/runtime/bound.d.ts.map +1 -1
  30. package/runtime/bound.js +10 -0
  31. package/runtime/bun.d.ts +20 -0
  32. package/runtime/bun.d.ts.map +1 -0
  33. package/runtime/bun.js +20 -0
  34. package/runtime/claude.d.ts +1 -0
  35. package/runtime/claude.d.ts.map +1 -1
  36. package/runtime/conversations.d.ts +12 -1
  37. package/runtime/conversations.d.ts.map +1 -1
  38. package/runtime/conversations.js +472 -362
  39. package/runtime/deadline.d.ts +4 -3
  40. package/runtime/deadline.d.ts.map +1 -1
  41. package/runtime/deadline.js +10 -4
  42. package/runtime/engine.d.ts +5 -4
  43. package/runtime/engine.d.ts.map +1 -1
  44. package/runtime/installer.d.ts +3 -3
  45. package/runtime/installer.d.ts.map +1 -1
  46. package/runtime/installer.js +10 -9
  47. package/runtime/interfaces.d.ts +262 -0
  48. package/runtime/interfaces.d.ts.map +1 -0
  49. package/runtime/interfaces.js +935 -0
  50. package/runtime/lifecycle.d.ts +3 -3
  51. package/runtime/lifecycle.d.ts.map +1 -1
  52. package/runtime/lifecycle.js +83 -52
  53. package/runtime/options.d.ts.map +1 -1
  54. package/runtime/options.js +2 -6
  55. package/runtime/parts.d.ts +64 -1
  56. package/runtime/parts.d.ts.map +1 -1
  57. package/runtime/parts.js +311 -4
  58. package/runtime/programs.d.ts +1 -0
  59. package/runtime/programs.d.ts.map +1 -1
  60. package/runtime/programs.js +5 -3
  61. package/runtime/rpc.d.ts +111 -0
  62. package/runtime/rpc.d.ts.map +1 -0
  63. package/runtime/rpc.js +387 -0
  64. package/runtime/sessions.d.ts +6 -4
  65. package/runtime/sessions.d.ts.map +1 -1
  66. package/runtime/sessions.js +59 -80
  67. package/runtime/toaster.js +1 -1
  68. package/runtime/ui.d.ts +23 -10
  69. package/runtime/ui.d.ts.map +1 -1
  70. package/runtime/ui.js +63 -52
  71. package/runtime/web.d.ts +0 -73
  72. package/runtime/web.d.ts.map +1 -1
  73. package/runtime/web.js +9 -5
  74. package/runtime/widgets.d.ts +4 -2
  75. package/runtime/widgets.d.ts.map +1 -1
  76. package/runtime/widgets.js +17 -16
  77. package/session/conversation.d.ts +7 -1
  78. package/session/conversation.d.ts.map +1 -1
  79. package/session/session.d.ts +31 -7
  80. package/session/session.d.ts.map +1 -1
  81. package/session/session.js +1 -0
  82. package/src/installer.ts +2 -2
  83. package/src/jobs/context.ts +1 -1
  84. package/src/jobs/program.ts +76 -21
  85. package/src/mod.ts +51 -10
  86. package/src/records.ts +33 -9
  87. package/src/register.ts +7 -4
  88. package/src/rpc.ts +67 -0
  89. package/src/runtime/bound.ts +10 -0
  90. package/src/runtime/bun.ts +40 -0
  91. package/src/runtime/claude.ts +1 -0
  92. package/src/runtime/conversations.ts +470 -352
  93. package/src/runtime/deadline.ts +13 -6
  94. package/src/runtime/engine.ts +5 -4
  95. package/src/runtime/installer.ts +13 -12
  96. package/src/runtime/interfaces.ts +1161 -0
  97. package/src/runtime/lifecycle.ts +102 -59
  98. package/src/runtime/options.ts +2 -5
  99. package/src/runtime/parts.ts +364 -5
  100. package/src/runtime/programs.ts +6 -3
  101. package/src/runtime/rpc.ts +457 -0
  102. package/src/runtime/sessions.ts +63 -83
  103. package/src/runtime/toaster.ts +1 -1
  104. package/src/runtime/ui.ts +82 -61
  105. package/src/runtime/web.ts +10 -39
  106. package/src/runtime/widgets.ts +20 -18
  107. package/src/session/conversation.ts +7 -1
  108. package/src/session/session.ts +22 -7
  109. package/src/testing/fake-claude.ts +38 -7
  110. package/src/testing/fake-serve.ts +144 -0
  111. package/src/testing/fake-sessions.ts +21 -6
  112. package/src/testing.ts +156 -68
  113. package/src/ui/areas.ts +2 -2
  114. package/src/ui/elements.ts +21 -16
  115. package/src/ui/panes.ts +14 -7
  116. package/testing/fake-claude.d.ts +6 -0
  117. package/testing/fake-claude.d.ts.map +1 -1
  118. package/testing/fake-claude.js +34 -7
  119. package/testing/fake-serve.d.ts +39 -0
  120. package/testing/fake-serve.d.ts.map +1 -0
  121. package/testing/fake-serve.js +110 -0
  122. package/testing/fake-sessions.d.ts.map +1 -1
  123. package/testing/fake-sessions.js +22 -6
  124. package/testing.d.ts +21 -4
  125. package/testing.d.ts.map +1 -1
  126. package/testing.js +138 -56
  127. package/ui/areas.d.ts +3 -1
  128. package/ui/areas.d.ts.map +1 -1
  129. package/ui/elements.d.ts +18 -9
  130. package/ui/elements.d.ts.map +1 -1
  131. package/ui/elements.js +9 -8
  132. package/ui/panes.d.ts +10 -6
  133. package/ui/panes.d.ts.map +1 -1
  134. package/ui/panes.js +5 -3
  135. package/runtime/pages.d.ts +0 -32
  136. package/runtime/pages.d.ts.map +0 -1
  137. package/runtime/pages.js +0 -142
  138. package/src/runtime/pages.ts +0 -183
@@ -0,0 +1,457 @@
1
+ export type RpcId = number | string
2
+
3
+ export type RpcErrorData = { readonly code: number; readonly message: string; readonly data?: unknown }
4
+
5
+ export type RpcMessage =
6
+ | { readonly jsonrpc: '2.0'; readonly id: RpcId; readonly method: string; readonly params?: unknown }
7
+ | { readonly jsonrpc: '2.0'; readonly method: string; readonly params?: unknown }
8
+ | { readonly jsonrpc: '2.0'; readonly id: RpcId; readonly result: unknown }
9
+ | { readonly jsonrpc: '2.0'; readonly id: RpcId; readonly error: RpcErrorData }
10
+
11
+ export const rpcCodes = {
12
+ methodNotFound: -32601,
13
+ invalidParams: -32602,
14
+ internal: -32603,
15
+ closed: -32099,
16
+ notHeld: -32098,
17
+ cancelled: -32800,
18
+ } as const
19
+
20
+ export class RpcError extends Error {
21
+ readonly code: number
22
+ readonly data: unknown
23
+
24
+ constructor(code: number, message: string, data?: unknown) {
25
+ super(message)
26
+ this.code = code
27
+ this.data = data
28
+ }
29
+ }
30
+
31
+ export type RpcHandler = (method: string, params: unknown, signal: AbortSignal) => unknown
32
+
33
+ export type Peer = {
34
+ request<Result>(method: string, params?: unknown, signal?: AbortSignal): Promise<Result>
35
+ notify(method: string, params?: unknown): void
36
+ receive(message: unknown): void
37
+ close(reason: Error): void
38
+ readonly signal: AbortSignal
39
+ }
40
+
41
+ const cancelMethod = '$/cancelRequest'
42
+
43
+ type Waiting = { resolve(value: unknown): void; reject(error: Error): void }
44
+
45
+ export function createPeer({ send, handle }: { readonly send: (message: RpcMessage) => void; readonly handle: RpcHandler }): Peer {
46
+ const closing = new AbortController()
47
+ const waiting = new Map<RpcId, Waiting>()
48
+ const running = new Map<RpcId, AbortController>()
49
+ let nextId = 0
50
+
51
+ const reply = (id: RpcId, run: (signal: AbortSignal) => unknown) => {
52
+ const cancel = new AbortController()
53
+ running.set(id, cancel)
54
+ void (async () => run(cancel.signal))()
55
+ .then(
56
+ (result) => ({ jsonrpc: '2.0' as const, id, result: result ?? null }),
57
+ (error: unknown) => ({ jsonrpc: '2.0' as const, id, error: errorDataOf(cancel.signal.aborted ? new RpcError(rpcCodes.cancelled, 'The caller cancelled the request.') : error) }),
58
+ )
59
+ .then((answer) => {
60
+ running.delete(id)
61
+ if (!closing.signal.aborted) send(answer)
62
+ })
63
+ }
64
+
65
+ const receiveOne = (message: unknown) => {
66
+ if (typeof message !== 'object' || message === null) return
67
+ const fields = message as Record<string, unknown>
68
+ const id = fields['id']
69
+ const isId = typeof id === 'number' || typeof id === 'string'
70
+ if (typeof fields['method'] === 'string') {
71
+ const method = fields['method']
72
+ if (method === cancelMethod) {
73
+ const cancelled = (fields['params'] as { readonly id?: RpcId } | undefined)?.id
74
+ if (cancelled !== undefined) running.get(cancelled)?.abort()
75
+ return
76
+ }
77
+ if (!isId) {
78
+ void (async () => handle(method, fields['params'], closing.signal))().catch(() => undefined)
79
+ return
80
+ }
81
+ reply(id, (signal) => handle(method, fields['params'], signal))
82
+ return
83
+ }
84
+ if (!isId) return
85
+ const waiter = waiting.get(id)
86
+ if (waiter === undefined) return
87
+ waiting.delete(id)
88
+ const error = fields['error'] as RpcErrorData | undefined
89
+ if (error !== undefined) waiter.reject(new RpcError(error.code, error.message, error.data))
90
+ else waiter.resolve(fields['result'])
91
+ }
92
+
93
+ return {
94
+ signal: closing.signal,
95
+ request<Result>(method: string, params?: unknown, signal?: AbortSignal) {
96
+ if (closing.signal.aborted) return Promise.reject(closedError(closing.signal.reason))
97
+ const id = (nextId += 1)
98
+ return new Promise<Result>((resolve, reject) => {
99
+ const cancel = () => {
100
+ if (!waiting.delete(id)) return
101
+ send({ jsonrpc: '2.0', method: cancelMethod, params: { id } })
102
+ reject(new RpcError(rpcCodes.cancelled, `${method} was cancelled.`))
103
+ }
104
+ waiting.set(id, {
105
+ resolve: (value) => {
106
+ signal?.removeEventListener('abort', cancel)
107
+ resolve(value as Result)
108
+ },
109
+ reject: (error) => {
110
+ signal?.removeEventListener('abort', cancel)
111
+ reject(error)
112
+ },
113
+ })
114
+ if (signal?.aborted === true) return cancel()
115
+ signal?.addEventListener('abort', cancel, { once: true })
116
+ send({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) })
117
+ })
118
+ },
119
+ notify(method, params) {
120
+ if (!closing.signal.aborted) send({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) })
121
+ },
122
+ receive(message) {
123
+ if (Array.isArray(message)) for (const each of message) receiveOne(each)
124
+ else receiveOne(message)
125
+ },
126
+ close(reason) {
127
+ if (closing.signal.aborted) return
128
+ closing.abort(reason)
129
+ for (const cancel of running.values()) cancel.abort()
130
+ running.clear()
131
+ for (const waiter of waiting.values()) waiter.reject(closedError(reason))
132
+ waiting.clear()
133
+ },
134
+ }
135
+ }
136
+
137
+ export function closedError(reason: unknown): RpcError {
138
+ return new RpcError(rpcCodes.closed, `The connection closed: ${reason instanceof Error ? reason.message : String(reason)}`)
139
+ }
140
+
141
+ function errorDataOf(error: unknown): RpcErrorData {
142
+ if (error instanceof RpcError) return { code: error.code, message: error.message, ...(error.data === undefined ? {} : { data: error.data }) }
143
+ return { code: rpcCodes.internal, message: error instanceof Error ? error.message : String(error) }
144
+ }
145
+
146
+ export const rpcPath = '/rpc'
147
+
148
+ export type RpcConnection = Peer & { readonly id: string }
149
+
150
+ type Held = {
151
+ readonly connection: RpcConnection
152
+ readonly outbox: RpcMessage[]
153
+ poll: ((messages: RpcMessage[]) => void) | undefined
154
+ seenAt: number
155
+ }
156
+
157
+ export type RpcHttpRequest = { readonly method: string; readonly path: string; readonly signal: AbortSignal; json(): Promise<unknown> }
158
+
159
+ export type RpcHttpAnswer = { readonly status: number; readonly json?: unknown }
160
+
161
+ export type RpcRoutes = {
162
+ route(request: RpcHttpRequest): Promise<RpcHttpAnswer> | undefined
163
+ channel(send: (message: RpcMessage) => void): RpcConnection
164
+ connections(): RpcConnection[]
165
+ close(): void
166
+ }
167
+
168
+ const timers = globalThis as unknown as { setTimeout(run: () => void, ms: number): unknown; clearTimeout(timer: unknown): void }
169
+
170
+ export function rpcRoutes({
171
+ handle,
172
+ onClose,
173
+ now,
174
+ pollMs = 8000,
175
+ liveMs = 30_000,
176
+ }: {
177
+ readonly handle: (connection: RpcConnection) => RpcHandler
178
+ readonly onClose?: (connection: RpcConnection) => void
179
+ readonly now: () => number
180
+ readonly pollMs?: number
181
+ readonly liveMs?: number
182
+ }): RpcRoutes {
183
+ const held = new Map<string, Held>()
184
+
185
+ const drop = (id: string, reason: string) => {
186
+ const each = held.get(id)
187
+ if (each === undefined) return
188
+ held.delete(id)
189
+ each.poll?.([])
190
+ each.connection.close(new Error(reason))
191
+ onClose?.(each.connection)
192
+ }
193
+
194
+ const open = (): Held => {
195
+ const id = crypto.randomUUID()
196
+ const outbox: RpcMessage[] = []
197
+ let entry: Held | undefined
198
+ const peer = createPeer({
199
+ send: (message) => {
200
+ if (entry === undefined) return
201
+ if (entry.poll === undefined) return void outbox.push(message)
202
+ const poll = entry.poll
203
+ entry.poll = undefined
204
+ poll([...outbox.splice(0), message])
205
+ },
206
+ handle: (method, params, signal) => handler(method, params, signal),
207
+ })
208
+ const connection: RpcConnection = Object.assign(peer, { id })
209
+ const handler = handle(connection)
210
+ entry = { connection, outbox, poll: undefined, seenAt: now() }
211
+ held.set(id, entry)
212
+ return entry
213
+ }
214
+
215
+ const sweep = () => {
216
+ for (const [id, each] of held) if (each.poll === undefined && now() - each.seenAt > liveMs) drop(id, `no poll for ${liveMs / 1000} s`)
217
+ }
218
+
219
+ const known = (id: string) => {
220
+ const each = held.get(id)
221
+ if (each === undefined) throw new GoneError(id)
222
+ each.seenAt = now()
223
+ return each
224
+ }
225
+
226
+ const poll = (each: Held, signal: AbortSignal) =>
227
+ new Promise<RpcMessage[]>((resolve) => {
228
+ each.poll?.([])
229
+ if (each.outbox.length > 0) return resolve(each.outbox.splice(0))
230
+ const timer = timers.setTimeout(() => answer([]), pollMs)
231
+ const answer = (messages: RpcMessage[]) => {
232
+ timers.clearTimeout(timer)
233
+ if (each.poll === answer) each.poll = undefined
234
+ each.seenAt = now()
235
+ resolve(messages)
236
+ }
237
+ each.poll = answer
238
+ signal.addEventListener('abort', () => {
239
+ if (each.poll !== answer) return
240
+ each.poll = undefined
241
+ timers.clearTimeout(timer)
242
+ resolve([])
243
+ drop(each.connection.id, 'the client left its poll')
244
+ })
245
+ })
246
+
247
+ const route = async (request: RpcHttpRequest): Promise<RpcHttpAnswer> => {
248
+ sweep()
249
+ const [, id] = /^\/rpc\/([\w-]{1,64})$/.exec(request.path) ?? []
250
+ try {
251
+ if (request.path === `${rpcPath}/connect` && request.method === 'POST') return { status: 200, json: { connection: open().connection.id } }
252
+ if (id === undefined) return { status: 404, json: { error: `cmod has no ${request.method} ${request.path}.` } }
253
+ if (request.method === 'DELETE') {
254
+ drop(id, 'the client closed it')
255
+ return { status: 204 }
256
+ }
257
+ const each = known(id)
258
+ if (request.method === 'GET') return { status: 200, json: await poll(each, request.signal) }
259
+ if (request.method === 'POST') {
260
+ each.connection.receive(await request.json())
261
+ return { status: 204 }
262
+ }
263
+ return { status: 405, json: { error: `cmod has no ${request.method} ${request.path}.` } }
264
+ } catch (error) {
265
+ if (error instanceof GoneError) return { status: 410, json: { error: error.message } }
266
+ throw error
267
+ }
268
+ }
269
+
270
+ const channels = new Map<string, RpcConnection>()
271
+
272
+ const channel = (send: (message: RpcMessage) => void): RpcConnection => {
273
+ const id = crypto.randomUUID()
274
+ const peer = createPeer({ send, handle: (method, params, signal) => handler(method, params, signal) })
275
+ const connection: RpcConnection = {
276
+ ...peer,
277
+ id,
278
+ close(reason) {
279
+ if (!channels.delete(id)) return
280
+ peer.close(reason)
281
+ onClose?.(connection)
282
+ },
283
+ }
284
+ const handler = handle(connection)
285
+ channels.set(id, connection)
286
+ return connection
287
+ }
288
+
289
+ return {
290
+ route: (request) => (request.path.startsWith(rpcPath) ? route(request) : undefined),
291
+ channel,
292
+ connections: () => [...[...held.values()].map((each) => each.connection), ...channels.values()],
293
+ close() {
294
+ for (const id of held.keys()) drop(id, 'the server stopped')
295
+ for (const each of channels.values()) each.close(new Error('the server stopped'))
296
+ },
297
+ }
298
+ }
299
+
300
+ export class RpcUnreached extends Error {}
301
+
302
+ export function isConnectionGone(error: unknown): boolean {
303
+ return error instanceof RpcUnreached || (error instanceof RpcError && error.code === rpcCodes.closed)
304
+ }
305
+
306
+ class GoneError extends Error {
307
+ constructor(id: string) {
308
+ super(`cmod has no connection ${id}: it closed, or the server started again. Connect again.`)
309
+ }
310
+ }
311
+
312
+ export type HttpCall = (path: string, init: { readonly method: 'GET' | 'POST' | 'DELETE'; readonly body?: string }) => Promise<{ readonly status: number; readonly text: string }>
313
+
314
+ export type HttpFetch = (url: string, init: { readonly method: string; readonly body?: string; readonly headers?: Readonly<Record<string, string>>; readonly socketPath?: string }) => Promise<{ readonly status: number; readonly text: string }>
315
+
316
+ export function addressCall(fetch: HttpFetch, address: string): HttpCall {
317
+ const socketPath = address.startsWith('unix:') ? address.slice('unix:'.length) : address.startsWith('/') ? address : undefined
318
+ const base = socketPath !== undefined ? 'http://localhost' : /^https?:\/\//.test(address) ? address.replace(/\/+$/, '') : `http://${address}`
319
+ return async (path, init) => {
320
+ const answer = await fetch(`${base}${path}`, { method: init.method, ...(init.body === undefined ? {} : { body: init.body, headers: { 'content-type': 'application/json' } }), ...(socketPath === undefined ? {} : { socketPath }) })
321
+ return { status: answer.status, text: answer.text }
322
+ }
323
+ }
324
+
325
+ export type RpcClient = Pick<Peer, 'request' | 'notify'> & {
326
+ readonly isConnected: boolean
327
+ close(): Promise<void>
328
+ }
329
+
330
+ export function connectRpc({
331
+ call,
332
+ handle,
333
+ onConnect,
334
+ onError,
335
+ wait,
336
+ retryMs = 2000,
337
+ keepsConnecting = false,
338
+ }: {
339
+ readonly call: HttpCall
340
+ readonly handle: RpcHandler
341
+ readonly onConnect?: (client: RpcClient) => unknown
342
+ readonly onError?: (error: unknown) => void
343
+ readonly wait: (ms: number) => Promise<void>
344
+ readonly retryMs?: number
345
+ readonly keepsConnecting?: boolean
346
+ }): RpcClient {
347
+ let current: { readonly id: string; readonly peer: Peer } | undefined
348
+ let connecting: Promise<{ readonly id: string; readonly peer: Peer }> | undefined
349
+ let isClosed = false
350
+ let queued: RpcMessage[] = []
351
+ let flushing: Promise<void> | undefined
352
+
353
+ const flush = (id: string, peer: Peer) => {
354
+ flushing ??= (async () => {
355
+ await Promise.resolve()
356
+ while (queued.length > 0 && current?.id === id) {
357
+ const batch = queued
358
+ queued = []
359
+ const answer = await call(`${rpcPath}/${id}`, { method: 'POST', body: JSON.stringify(batch) }).catch((error: unknown) => ({ status: 0, text: String(error) }))
360
+ if (answer.status !== 204) {
361
+ lose(id, peer, new RpcUnreached(`cmod serve answered ${answer.status}: ${answer.text}`))
362
+ return
363
+ }
364
+ }
365
+ })().finally(() => {
366
+ flushing = undefined
367
+ if (queued.length > 0 && current?.id === id) flush(id, peer)
368
+ })
369
+ }
370
+
371
+ const lose = (id: string, peer: Peer, reason: Error) => {
372
+ if (current?.id !== id) return
373
+ current = undefined
374
+ queued = []
375
+ peer.close(reason)
376
+ reconnect()
377
+ }
378
+
379
+ const isCurrent = (id: string) => current?.id === id
380
+
381
+ const pollLoop = async (id: string, peer: Peer) => {
382
+ while (isCurrent(id) && !isClosed) {
383
+ const answer = await call(`${rpcPath}/${id}`, { method: 'GET' }).catch((error: unknown) => ({ status: 0, text: String(error) }))
384
+ if (!isCurrent(id)) return
385
+ if (answer.status !== 200) return lose(id, peer, new RpcUnreached(`cmod serve answered the poll with ${answer.status}: ${answer.text}`))
386
+ peer.receive(JSON.parse(answer.text))
387
+ }
388
+ }
389
+
390
+ let hasConnected = false
391
+
392
+ const reconnect = () => {
393
+ if (isClosed || !(keepsConnecting || hasConnected)) return
394
+ void wait(retryMs).then(async () => {
395
+ await Promise.allSettled([connecting])
396
+ if (!isClosed && current === undefined) void connection().catch(() => undefined)
397
+ })
398
+ }
399
+
400
+ const open = async () => {
401
+ if (isClosed) throw new Error('The connection is closed.')
402
+ try {
403
+ const answer = await call(`${rpcPath}/connect`, { method: 'POST' })
404
+ if (answer.status !== 200) throw new Error(`cmod serve answered the connect with ${answer.status}: ${answer.text}`)
405
+ const { connection: id } = JSON.parse(answer.text) as { readonly connection: string }
406
+ const peer: Peer = createPeer({
407
+ send: (message) => {
408
+ queued.push(message)
409
+ flush(id, peer)
410
+ },
411
+ handle,
412
+ })
413
+ current = { id, peer }
414
+ hasConnected = true
415
+ void pollLoop(id, peer)
416
+ void (async () => onConnect?.(client))().catch((error: unknown) => onError?.(error))
417
+ return current
418
+ } catch (error) {
419
+ onError?.(error)
420
+ reconnect()
421
+ throw new RpcUnreached(error instanceof Error ? error.message : String(error), { cause: error })
422
+ }
423
+ }
424
+
425
+ const connection = () => {
426
+ if (current !== undefined) return Promise.resolve(current)
427
+ connecting ??= open().finally(() => {
428
+ connecting = undefined
429
+ })
430
+ return connecting
431
+ }
432
+
433
+ const client: RpcClient = {
434
+ get isConnected() {
435
+ return current !== undefined
436
+ },
437
+ async request<Result>(method: string, params?: unknown, signal?: AbortSignal) {
438
+ const { peer } = await connection()
439
+ return peer.request<Result>(method, params, signal)
440
+ },
441
+ notify(method, params) {
442
+ void connection()
443
+ .then(({ peer }) => peer.notify(method, params))
444
+ .catch(() => undefined)
445
+ },
446
+ async close() {
447
+ isClosed = true
448
+ const was = current
449
+ current = undefined
450
+ if (was === undefined) return
451
+ was.peer.close(new Error('the client closed it'))
452
+ void call(`${rpcPath}/${was.id}`, { method: 'DELETE' }).catch(() => undefined)
453
+ },
454
+ }
455
+ if (keepsConnecting) void connection().catch(() => undefined)
456
+ return client
457
+ }