@kitman-sh/cli 0.0.0-stage → 0.7.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.
@@ -0,0 +1,1178 @@
1
+ // @bun
2
+ import {
3
+ dual,
4
+ identity,
5
+ constVoid,
6
+ flow,
7
+ hasProperty,
8
+ assignProperty,
9
+ isNone,
10
+ isSome,
11
+ map,
12
+ Service,
13
+ empty,
14
+ add,
15
+ getOrUndefinedUnsafe,
16
+ getUnsafe,
17
+ get,
18
+ merge,
19
+ Reference,
20
+ isSuccess,
21
+ toMillis,
22
+ squash,
23
+ findError,
24
+ hasInterrupts,
25
+ interruptors,
26
+ failCause,
27
+ fail2,
28
+ die2,
29
+ interrupt,
30
+ isFailure2,
31
+ Scope,
32
+ provide,
33
+ addFinalizerExit,
34
+ addFinalizer,
35
+ succeed4,
36
+ effect,
37
+ Clock,
38
+ min,
39
+ exponential,
40
+ spaced,
41
+ forEach,
42
+ whileLoop,
43
+ succeed5,
44
+ suspend,
45
+ sync,
46
+ void_2,
47
+ callback,
48
+ never,
49
+ gen,
50
+ fail4,
51
+ withFiber,
52
+ flatMap,
53
+ andThen,
54
+ map3,
55
+ catchCause,
56
+ catchCauseIf,
57
+ orDie,
58
+ tapCause,
59
+ retryOrElse,
60
+ ignore,
61
+ ignoreCause,
62
+ timeout,
63
+ timeoutOrElse,
64
+ delay,
65
+ raceFirst,
66
+ matchCauseEffect,
67
+ context,
68
+ contextWith,
69
+ provideContext,
70
+ serviceOption,
71
+ updateContext,
72
+ updateService,
73
+ scope,
74
+ scoped,
75
+ acquireRelease,
76
+ ensuring,
77
+ onError,
78
+ onExit,
79
+ interrupt2,
80
+ interruptible,
81
+ onInterrupt,
82
+ uninterruptibleMask,
83
+ forever,
84
+ makeSpanScoped,
85
+ useSpan,
86
+ withParentSpan,
87
+ forkIn,
88
+ forkScoped,
89
+ runForkWith,
90
+ fnUntraced,
91
+ logError,
92
+ annotateLogs,
93
+ interrupt3,
94
+ getCurrent,
95
+ makeUnsafe3,
96
+ bounded,
97
+ offerAll,
98
+ failCause3,
99
+ end,
100
+ shutdownUnsafe,
101
+ fromQueue,
102
+ unwrap,
103
+ empty3,
104
+ fromInput,
105
+ merge3,
106
+ decodeUnknownEffect,
107
+ decodeSync,
108
+ encodeEffect,
109
+ optional,
110
+ String2,
111
+ NonEmptyArray,
112
+ Union,
113
+ Literals,
114
+ tag,
115
+ Int,
116
+ Defect,
117
+ Error2,
118
+ TaggedError2,
119
+ toCodecJson,
120
+ HttpClientErrorSchema,
121
+ isStreamSchema,
122
+ getStreamSchemas,
123
+ exitSchema
124
+ } from "./chunk-704ws2q7.js";
125
+
126
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/socket/Socket.js
127
+ var TypeId = "~effect/socket/Socket";
128
+ var Socket = /* @__PURE__ */ Service("effect/socket/Socket");
129
+ var make4 = (options) => Socket.of({
130
+ [TypeId]: TypeId,
131
+ reader: options.reader,
132
+ writer: options.writer
133
+ });
134
+ var encoder = /* @__PURE__ */ new TextEncoder;
135
+ var readerString = (self, encoding) => map3(self.reader, ({
136
+ pull
137
+ }) => {
138
+ const decoder = new TextDecoder(encoding);
139
+ return map3(pull, (chunk) => {
140
+ const out = new Array(chunk.length);
141
+ for (let i = 0;i < chunk.length; i++) {
142
+ const item = chunk[i];
143
+ out[i] = typeof item === "string" ? item : decoder.decode(item);
144
+ }
145
+ return out;
146
+ });
147
+ });
148
+ var CloseEventTypeId = "~effect/socket/Socket/CloseEvent";
149
+ var isCloseEvent = (u) => hasProperty(u, CloseEventTypeId);
150
+ var SocketErrorTypeId = "~effect/socket/Socket/SocketError";
151
+ var isSocketError = (u) => hasProperty(u, SocketErrorTypeId);
152
+
153
+ class SocketReadError extends (/* @__PURE__ */ Error2("effect/socket/Socket/SocketReadError")({
154
+ _tag: /* @__PURE__ */ tag("SocketReadError"),
155
+ cause: /* @__PURE__ */ Defect()
156
+ })) {
157
+ message = `An error occurred during Read`;
158
+ }
159
+
160
+ class SocketWriteError extends (/* @__PURE__ */ Error2("effect/socket/Socket/SocketWriteError")({
161
+ _tag: /* @__PURE__ */ tag("SocketWriteError"),
162
+ cause: /* @__PURE__ */ Defect()
163
+ })) {
164
+ message = `An error occurred during Write`;
165
+ }
166
+
167
+ class SocketOpenError extends (/* @__PURE__ */ Error2("effect/socket/Socket/SocketOpenError")({
168
+ _tag: /* @__PURE__ */ tag("SocketOpenError"),
169
+ kind: /* @__PURE__ */ Literals(["Unknown", "Timeout"]),
170
+ cause: /* @__PURE__ */ Defect()
171
+ })) {
172
+ get message() {
173
+ return this.kind === "Timeout" ? `timeout waiting for "open"` : `An error occurred during Open`;
174
+ }
175
+ }
176
+
177
+ class SocketUpgradeError extends (/* @__PURE__ */ Error2("effect/socket/Socket/SocketUpgradeError")({
178
+ _tag: /* @__PURE__ */ tag("SocketUpgradeError"),
179
+ cause: /* @__PURE__ */ optional(/* @__PURE__ */ Defect())
180
+ })) {
181
+ static unsupported = () => fail4(new SocketError({
182
+ reason: new SocketUpgradeError({})
183
+ }));
184
+ get message() {
185
+ return this.cause === undefined ? `Socket does not support TLS upgrade` : `An error occurred during TLS upgrade`;
186
+ }
187
+ }
188
+
189
+ class SocketCloseError extends (/* @__PURE__ */ Error2("effect/socket/Socket/SocketCloseError")({
190
+ _tag: /* @__PURE__ */ tag("SocketCloseError"),
191
+ code: Int,
192
+ closeReason: /* @__PURE__ */ optional(String2)
193
+ })) {
194
+ get message() {
195
+ if (this.closeReason) {
196
+ return `${this.code}: ${this.closeReason}`;
197
+ }
198
+ return `${this.code}`;
199
+ }
200
+ }
201
+ var SocketErrorReason = /* @__PURE__ */ Union([SocketReadError, SocketWriteError, SocketOpenError, SocketUpgradeError, SocketCloseError]);
202
+
203
+ class SocketError extends (/* @__PURE__ */ TaggedError2(SocketErrorTypeId)("SocketError", {
204
+ _tag: /* @__PURE__ */ tag("SocketError"),
205
+ reason: SocketErrorReason
206
+ })) {
207
+ constructor(props) {
208
+ if ("cause" in props.reason) {
209
+ super({
210
+ ...props,
211
+ cause: props.reason.cause
212
+ });
213
+ } else {
214
+ super(props);
215
+ }
216
+ }
217
+ [SocketErrorTypeId] = SocketErrorTypeId;
218
+ static is(u) {
219
+ return isSocketError(u);
220
+ }
221
+ message = this.reason.message;
222
+ }
223
+ var closeError = (code, closeReason) => new SocketError({
224
+ reason: new SocketCloseError({
225
+ code,
226
+ closeReason
227
+ })
228
+ });
229
+ class WebSocketConstructor extends (/* @__PURE__ */ Service()("@effect/platform/Socket/WebSocketConstructor")) {
230
+ }
231
+ var layerWebSocketConstructorGlobal = /* @__PURE__ */ succeed4(WebSocketConstructor)((url, options) => {
232
+ if (options !== undefined && typeof options !== "string" && !Array.isArray(options)) {
233
+ throw new TypeError("WebSocket client options are not supported by the global WebSocket constructor");
234
+ }
235
+ return new globalThis.WebSocket(url, options);
236
+ });
237
+ var makeWebSocket = (url, options) => WebSocketConstructor.use((makeWs) => fromWebSocket(acquireRelease((typeof url === "string" ? succeed5(url) : url).pipe(map3((url) => makeWs(url, options?.headers === undefined ? options?.protocols : {
238
+ protocols: options.protocols,
239
+ headers: options.headers
240
+ }))), (ws) => sync(() => ws.close(1000))), options));
241
+ var isPausable = (ws) => ("pause" in ws) && typeof ws.pause === "function";
242
+ var fromWebSocket = (acquire, options) => withFiber((fiber) => {
243
+ let currentWS;
244
+ const latch = makeUnsafe3(false);
245
+ const acquireContext = fiber.context;
246
+ const reader = gen(function* () {
247
+ const scope2 = yield* scope;
248
+ const ws = yield* provide(acquire, scope2);
249
+ if ("binaryType" in ws) {
250
+ ws.binaryType = "arraybuffer";
251
+ }
252
+ const pausable = isPausable(ws);
253
+ const highWaterMark = options?.highWaterMark ?? (pausable ? defaultHighWaterMark : undefined);
254
+ let open = ws.readyState === 1;
255
+ let paused = pausable && "isPaused" in ws && ws.isPaused === true;
256
+ let buffer = [];
257
+ let bufferSize = 0;
258
+ let error;
259
+ let waiter;
260
+ let openWaiter;
261
+ function pauseWebSocket() {
262
+ if (!pausable || paused)
263
+ return;
264
+ ws.pause();
265
+ paused = true;
266
+ }
267
+ function resumeWebSocket() {
268
+ if (!pausable || !paused)
269
+ return;
270
+ ws.resume();
271
+ paused = false;
272
+ }
273
+ function takeBuffer() {
274
+ const chunk = buffer;
275
+ buffer = [];
276
+ bufferSize = 0;
277
+ if (error === undefined)
278
+ resumeWebSocket();
279
+ return chunk;
280
+ }
281
+ function deliver() {
282
+ if (waiter === undefined || buffer.length === 0)
283
+ return;
284
+ const resume = waiter;
285
+ waiter = undefined;
286
+ resume(succeed5(takeBuffer()));
287
+ }
288
+ function push(data) {
289
+ buffer.push(data);
290
+ if (highWaterMark !== undefined) {
291
+ bufferSize += typeof data === "string" ? encoder.encode(data).byteLength : data.byteLength;
292
+ }
293
+ if (waiter !== undefined)
294
+ deliver();
295
+ if (pausable && bufferSize >= highWaterMark) {
296
+ pauseWebSocket();
297
+ } else if (!pausable && !waiter && highWaterMark !== undefined && bufferSize > highWaterMark) {
298
+ fail(new SocketError({
299
+ reason: new SocketReadError({
300
+ cause: new Error(`Socket highWaterMark of ${highWaterMark} bytes exceeded`)
301
+ })
302
+ }));
303
+ }
304
+ }
305
+ function fail(err) {
306
+ if (error === undefined)
307
+ error = err;
308
+ if (openWaiter !== undefined) {
309
+ const {
310
+ cleanup,
311
+ resume
312
+ } = openWaiter;
313
+ openWaiter = undefined;
314
+ cleanup();
315
+ resume(fail4(error));
316
+ }
317
+ if (waiter !== undefined) {
318
+ const resume = waiter;
319
+ waiter = undefined;
320
+ resume(buffer.length > 0 ? succeed5(takeBuffer()) : fail4(error));
321
+ }
322
+ }
323
+ function onMessage(event) {
324
+ const data = event.data;
325
+ if (typeof Blob !== "undefined" && data instanceof Blob) {
326
+ data.arrayBuffer().then((buf) => push(new Uint8Array(buf)), (cause) => {
327
+ fail(new SocketError({
328
+ reason: new SocketReadError({
329
+ cause
330
+ })
331
+ }));
332
+ });
333
+ return;
334
+ }
335
+ push(data instanceof ArrayBuffer ? new Uint8Array(data) : data);
336
+ }
337
+ function onError(event) {
338
+ fail(new SocketError({
339
+ reason: open ? new SocketReadError({
340
+ cause: event
341
+ }) : new SocketOpenError({
342
+ kind: "Unknown",
343
+ cause: event
344
+ })
345
+ }));
346
+ }
347
+ function onClose(event) {
348
+ fail(closeError(typeof event.code === "number" ? event.code : 1006, event.reason));
349
+ }
350
+ ws.addEventListener("message", onMessage);
351
+ ws.addEventListener("error", onError, {
352
+ once: true
353
+ });
354
+ ws.addEventListener("close", onClose, {
355
+ once: true
356
+ });
357
+ yield* addFinalizer(scope2, sync(() => {
358
+ fail(closeError(1006));
359
+ ws.removeEventListener("message", onMessage);
360
+ ws.removeEventListener("error", onError);
361
+ ws.removeEventListener("close", onClose);
362
+ if (pausable) {
363
+ try {
364
+ resumeWebSocket();
365
+ } catch {}
366
+ }
367
+ latch.closeUnsafe();
368
+ currentWS = undefined;
369
+ }));
370
+ if (ws.readyState >= 2) {
371
+ return yield* fail4(error ?? closeError(1006));
372
+ }
373
+ if (!open) {
374
+ yield* callback((resume) => {
375
+ const onOpen = () => {
376
+ if (openWaiter?.resume !== resume)
377
+ return;
378
+ openWaiter = undefined;
379
+ ws.removeEventListener("open", onOpen);
380
+ resume(void_2);
381
+ };
382
+ const cleanup = () => ws.removeEventListener("open", onOpen);
383
+ openWaiter = {
384
+ resume,
385
+ cleanup
386
+ };
387
+ ws.addEventListener("open", onOpen, {
388
+ once: true
389
+ });
390
+ return sync(() => {
391
+ if (openWaiter?.resume === resume)
392
+ openWaiter = undefined;
393
+ cleanup();
394
+ });
395
+ }).pipe(timeoutOrElse({
396
+ duration: options?.openTimeout ?? 1e4,
397
+ orElse: () => fail4(new SocketError({
398
+ reason: new SocketOpenError({
399
+ kind: "Timeout",
400
+ cause: new Error('timeout waiting for "open"')
401
+ })
402
+ }))
403
+ }));
404
+ open = true;
405
+ }
406
+ if (error === undefined && bufferSize < highWaterMark)
407
+ resumeWebSocket();
408
+ currentWS = ws;
409
+ latch.openUnsafe();
410
+ return {
411
+ pull: callback((resume) => {
412
+ if (buffer.length > 0)
413
+ return resume(succeed5(takeBuffer()));
414
+ if (error !== undefined)
415
+ return resume(fail4(error));
416
+ waiter = resume;
417
+ return sync(() => {
418
+ if (waiter === resume)
419
+ waiter = undefined;
420
+ });
421
+ }),
422
+ upgrade: SocketUpgradeError.unsupported
423
+ };
424
+ }).pipe(updateContext((input) => merge(acquireContext, input)));
425
+ const write = (chunk) => suspend(() => {
426
+ const ws = currentWS;
427
+ if (ws === undefined)
428
+ return latch.whenOpen(write(chunk));
429
+ try {
430
+ if (isCloseEvent(chunk)) {
431
+ ws.close(chunk.code, chunk.reason);
432
+ } else {
433
+ ws.send(chunk);
434
+ }
435
+ return void_2;
436
+ } catch (cause) {
437
+ return fail4(new SocketError({
438
+ reason: new SocketWriteError({
439
+ cause
440
+ })
441
+ }));
442
+ }
443
+ });
444
+ const writeAll = (chunks) => suspend(() => {
445
+ const ws = currentWS;
446
+ if (ws === undefined)
447
+ return latch.whenOpen(writeAll(chunks));
448
+ try {
449
+ for (let i = 0;i < chunks.length; i++) {
450
+ ws.send(chunks[i]);
451
+ }
452
+ return void_2;
453
+ } catch (cause) {
454
+ return fail4(new SocketError({
455
+ reason: new SocketWriteError({
456
+ cause
457
+ })
458
+ }));
459
+ }
460
+ });
461
+ const writer = succeed5({
462
+ write,
463
+ writeAll
464
+ });
465
+ return succeed5(make4({
466
+ reader,
467
+ writer
468
+ }));
469
+ });
470
+ var defaultHighWaterMark = 64 * 1024;
471
+ var layerWebSocket = /* @__PURE__ */ flow(makeWebSocket, /* @__PURE__ */ effect(Socket));
472
+
473
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/workers/Transferable.js
474
+ class Collector extends (/* @__PURE__ */ Service()("effect/workers/Transferable/Collector")) {
475
+ }
476
+ var makeCollectorUnsafe = () => {
477
+ let tranferables = [];
478
+ const unsafeAddAll = (transfers) => {
479
+ tranferables.push(...transfers);
480
+ };
481
+ const unsafeRead = () => tranferables;
482
+ const unsafeClear = () => {
483
+ const prev = tranferables;
484
+ tranferables = [];
485
+ return prev;
486
+ };
487
+ return Collector.of({
488
+ addAllUnsafe: unsafeAddAll,
489
+ addAll: (transferables) => sync(() => unsafeAddAll(transferables)),
490
+ readUnsafe: unsafeRead,
491
+ read: sync(unsafeRead),
492
+ clearUnsafe: unsafeClear,
493
+ clear: sync(unsafeClear)
494
+ });
495
+ };
496
+
497
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/workers/WorkerError.js
498
+ class WorkerSpawnError extends (/* @__PURE__ */ Error2("effect/workers/WorkerError/WorkerSpawnError")({
499
+ _tag: /* @__PURE__ */ tag("WorkerSpawnError"),
500
+ message: String2,
501
+ cause: /* @__PURE__ */ optional(/* @__PURE__ */ Defect())
502
+ })) {
503
+ }
504
+
505
+ class WorkerSendError extends (/* @__PURE__ */ Error2("effect/workers/WorkerError/WorkerSendError")({
506
+ _tag: /* @__PURE__ */ tag("WorkerSendError"),
507
+ message: String2,
508
+ cause: /* @__PURE__ */ optional(/* @__PURE__ */ Defect())
509
+ })) {
510
+ }
511
+
512
+ class WorkerReceiveError extends (/* @__PURE__ */ Error2("effect/workers/WorkerError/WorkerReceiveError")({
513
+ _tag: /* @__PURE__ */ tag("WorkerReceiveError"),
514
+ message: String2,
515
+ cause: /* @__PURE__ */ optional(/* @__PURE__ */ Defect())
516
+ })) {
517
+ }
518
+
519
+ class WorkerUnknownError extends (/* @__PURE__ */ Error2("effect/workers/WorkerError/WorkerUnknownError")({
520
+ _tag: /* @__PURE__ */ tag("WorkerUnknownError"),
521
+ message: String2,
522
+ cause: /* @__PURE__ */ optional(/* @__PURE__ */ Defect())
523
+ })) {
524
+ }
525
+ var WorkerErrorReason = /* @__PURE__ */ Union([WorkerSpawnError, WorkerSendError, WorkerReceiveError, WorkerUnknownError]);
526
+
527
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/rpc/internal/tracing.js
528
+ var spanName = (spanPrefix, tag) => spanPrefix === undefined ? tag : `${spanPrefix}.${tag}`;
529
+ var spanAttributes = (tag, attributes) => ({
530
+ "rpc.system.name": "effect_rpc",
531
+ "rpc.method": tag,
532
+ ...attributes
533
+ });
534
+
535
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/rpc/RpcClientError.js
536
+ var TypeId2 = "~effect/rpc/RpcClientError";
537
+
538
+ class RpcClientDefect extends (/* @__PURE__ */ Error2("effect/rpc/RpcClientError/RpcClientDefect")({
539
+ _tag: /* @__PURE__ */ tag("RpcClientDefect"),
540
+ message: String2,
541
+ cause: /* @__PURE__ */ Defect()
542
+ })) {
543
+ }
544
+
545
+ class RpcClientError extends (/* @__PURE__ */ Error2(TypeId2)({
546
+ _tag: /* @__PURE__ */ tag("RpcClientError"),
547
+ reason: /* @__PURE__ */ Union([WorkerErrorReason, SocketErrorReason, HttpClientErrorSchema, RpcClientDefect])
548
+ })) {
549
+ [TypeId2] = TypeId2;
550
+ get message() {
551
+ return `${this.reason._tag}: ${this.reason.message}`;
552
+ }
553
+ }
554
+
555
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/rpc/RpcMessage.js
556
+ var RequestId = (id) => id;
557
+ var constPing = {
558
+ _tag: "Ping"
559
+ };
560
+
561
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/rpc/RpcSerialization.js
562
+ var codecForJson = toCodecJson;
563
+ var sharedTextDecoder;
564
+ var decodeText = (bytes) => (sharedTextDecoder ??= new TextDecoder).decode(bytes);
565
+
566
+ class RpcSerialization extends (/* @__PURE__ */ Service()("effect/rpc/RpcSerialization")) {
567
+ }
568
+ var defaultMaxBufferSize = 16 * 1024 * 1024;
569
+ var json = /* @__PURE__ */ RpcSerialization.of({
570
+ contentType: "application/json",
571
+ includesFraming: false,
572
+ codecFor: codecForJson,
573
+ makeUnsafe: () => ({
574
+ decode: (bytes) => {
575
+ const decoded = JSON.parse(typeof bytes === "string" ? bytes : decodeText(bytes));
576
+ return Array.isArray(decoded) ? decoded : [decoded];
577
+ },
578
+ encode: (response) => JSON.stringify(response)
579
+ })
580
+ });
581
+ var defaultSchemaBinaryMaxFrameSize = 16 * 1024 * 1024;
582
+ var layerJson = /* @__PURE__ */ succeed4(RpcSerialization)(json);
583
+
584
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/rpc/Utils.js
585
+ var withRunClient = (f) => suspend(() => {
586
+ const clientIds = new Set;
587
+ const clientBuffers = new Map;
588
+ const clientWrites = new Map;
589
+ let write = (clientId, data) => contextWith((context) => {
590
+ let buffer = clientBuffers.get(clientId);
591
+ if (!buffer) {
592
+ buffer = [];
593
+ clientBuffers.set(clientId, buffer);
594
+ }
595
+ buffer.push([data, context]);
596
+ return void_2;
597
+ });
598
+ return map3(f((clientId, data) => {
599
+ const clientWrite = clientWrites.get(clientId);
600
+ if (clientWrite) {
601
+ return clientWrite(data);
602
+ }
603
+ return write(clientId, data);
604
+ }, clientIds), (a) => ({
605
+ ...a,
606
+ run(clientId, f) {
607
+ return gen(function* () {
608
+ clientIds.add(clientId);
609
+ clientWrites.set(clientId, f);
610
+ const buffer = clientBuffers.get(clientId);
611
+ if (buffer) {
612
+ clientBuffers.delete(clientId);
613
+ for (const [args, context] of buffer) {
614
+ yield* provideContext(suspend(() => f(args)), context);
615
+ }
616
+ }
617
+ return yield* onExit(never, () => {
618
+ clientIds.delete(clientId);
619
+ clientWrites.delete(clientId);
620
+ return void_2;
621
+ });
622
+ });
623
+ }
624
+ }));
625
+ });
626
+
627
+ // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/rpc/RpcClient.js
628
+ var requestIdCounter = 0;
629
+ var makeNoSerialization = /* @__PURE__ */ fnUntraced(function* (group, options) {
630
+ const spanPrefix = options.spanPrefix;
631
+ const supportsAck = options?.supportsAck ?? true;
632
+ const disableTracing = options?.disableTracing ?? false;
633
+ const generateRequestId = options?.generateRequestId ?? (() => requestIdCounter++);
634
+ const services = yield* context();
635
+ const scope = get(services, Scope);
636
+ const entries = new Map;
637
+ let isShutdown = false;
638
+ yield* addFinalizer(scope, withFiber((parent) => {
639
+ isShutdown = true;
640
+ return clearEntries(interrupt(parent.id));
641
+ }));
642
+ const clearEntries = fnUntraced(function* (exit) {
643
+ for (const [id, entry] of entries) {
644
+ entries.delete(id);
645
+ if (entry._tag === "Queue") {
646
+ yield* exit._tag === "Success" ? end(entry.queue) : failCause3(entry.queue, exit.cause);
647
+ } else {
648
+ entry.resume(exit);
649
+ }
650
+ }
651
+ });
652
+ const onRequest = (rpc) => {
653
+ const isStream = isStreamSchema(rpc.successSchema);
654
+ const middleware = getRpcClientMiddleware(rpc);
655
+ return (payload, opts) => {
656
+ const headers = opts?.headers ? fromInput(opts.headers) : empty3;
657
+ const context = opts?.context ?? empty();
658
+ if (!isStream) {
659
+ const onRequest = (span) => onEffectRequest(rpc, middleware, span, rpc.payloadSchema.make(payload), headers, context, opts?.discard ?? false);
660
+ return disableTracing ? onRequest(undefined) : useSpan(spanName(spanPrefix, rpc._tag), {
661
+ kind: "client",
662
+ attributes: spanAttributes(rpc._tag, options.spanAttributes)
663
+ }, onRequest);
664
+ }
665
+ const queue = onStreamRequest(rpc, middleware, rpc.payloadSchema.make(payload), headers, opts?.streamBufferSize ?? 16, context);
666
+ if (opts?.asQueue)
667
+ return queue;
668
+ return unwrap(map3(queue, fromQueue));
669
+ };
670
+ };
671
+ const onEffectRequest = (rpc, middleware, span, payload, headers, context, discard) => withFiber((parentFiber) => {
672
+ if (isShutdown) {
673
+ return interrupt2;
674
+ }
675
+ const id = generateRequestId();
676
+ const send = middleware((message) => options.onFromClient({
677
+ message,
678
+ context,
679
+ discard
680
+ }), {
681
+ _tag: "Request",
682
+ id,
683
+ tag: rpc._tag,
684
+ payload,
685
+ ...span ? {
686
+ traceId: span.traceId,
687
+ spanId: span.spanId,
688
+ sampled: span.sampled
689
+ } : {},
690
+ headers: merge3(parentFiber.getRef(CurrentHeaders), headers)
691
+ });
692
+ if (discard) {
693
+ return send;
694
+ }
695
+ let fiber;
696
+ return onInterrupt(callback((resume) => {
697
+ const entry = {
698
+ _tag: "Effect",
699
+ rpc,
700
+ context,
701
+ resume(exit) {
702
+ resume(exit);
703
+ if (fiber && !fiber.pollUnsafe()) {
704
+ parentFiber.currentDispatcher.scheduleTask(() => {
705
+ fiber.interruptUnsafe(parentFiber.id);
706
+ }, 0);
707
+ }
708
+ }
709
+ };
710
+ entries.set(id, entry);
711
+ fiber = send.pipe(span ? withParentSpan(span, {
712
+ captureStackTrace: false
713
+ }) : identity, runForkWith(parentFiber.context));
714
+ fiber.addObserver((exit) => {
715
+ if (exit._tag === "Failure") {
716
+ return resume(exit);
717
+ }
718
+ });
719
+ }), (interruptors) => {
720
+ entries.delete(id);
721
+ return andThen(interrupt3(fiber), sendInterrupt(id, Array.from(interruptors), context));
722
+ });
723
+ });
724
+ const onStreamRequest = fnUntraced(function* (rpc, middleware, payload, headers, streamBufferSize, context) {
725
+ if (isShutdown) {
726
+ return yield* interrupt2;
727
+ }
728
+ const span = disableTracing ? undefined : yield* makeSpanScoped(spanName(spanPrefix, rpc._tag), {
729
+ kind: "client",
730
+ attributes: spanAttributes(rpc._tag, options.spanAttributes)
731
+ });
732
+ const fiber = getCurrent();
733
+ const id = generateRequestId();
734
+ const scope = getUnsafe(fiber.context, Scope);
735
+ const queue = yield* bounded(streamBufferSize);
736
+ yield* addFinalizerExit(scope, (exit) => {
737
+ shutdownUnsafe(queue);
738
+ if (!entries.has(id))
739
+ return void_2;
740
+ entries.delete(id);
741
+ return sendInterrupt(id, isFailure2(exit) ? Array.from(interruptors(exit.cause)) : [], context);
742
+ });
743
+ entries.set(id, {
744
+ _tag: "Queue",
745
+ rpc,
746
+ queue,
747
+ scope,
748
+ context
749
+ });
750
+ yield* middleware((message) => options.onFromClient({
751
+ message,
752
+ context,
753
+ discard: false
754
+ }), {
755
+ _tag: "Request",
756
+ id,
757
+ tag: rpc._tag,
758
+ payload,
759
+ ...span ? {
760
+ traceId: span.traceId,
761
+ spanId: span.spanId,
762
+ sampled: span.sampled
763
+ } : {},
764
+ headers: merge3(fiber.getRef(CurrentHeaders), headers)
765
+ }).pipe(span ? withParentSpan(span, {
766
+ captureStackTrace: false
767
+ }) : identity, onError((cause) => failCause3(queue, cause)), interruptible, forkIn(scope, {
768
+ startImmediately: true
769
+ }));
770
+ return queue;
771
+ });
772
+ const getRpcClientMiddleware = (rpc) => {
773
+ const middlewares = [];
774
+ for (const tag of rpc.middlewares.values()) {
775
+ const middleware = getOrUndefinedUnsafe(services, `${tag.key}/Client`);
776
+ if (!middleware)
777
+ continue;
778
+ middlewares.push(middleware);
779
+ }
780
+ if (middlewares.length === 0) {
781
+ return (send, request) => send(request);
782
+ }
783
+ return function loop(send, request, index = middlewares.length - 1) {
784
+ if (index === -1) {
785
+ return send(request);
786
+ }
787
+ return middlewares[index]({
788
+ rpc,
789
+ request,
790
+ next(request) {
791
+ return loop(send, request, index - 1);
792
+ }
793
+ });
794
+ };
795
+ };
796
+ const sendInterrupt = (requestId, interruptors, context) => callback((resume) => {
797
+ const parentFiber = getCurrent();
798
+ const fiber = options.onFromClient({
799
+ message: {
800
+ _tag: "Interrupt",
801
+ requestId,
802
+ interruptors
803
+ },
804
+ context,
805
+ discard: false
806
+ }).pipe(timeout(1000), runForkWith(parentFiber.context));
807
+ fiber.addObserver(() => {
808
+ resume(void_2);
809
+ });
810
+ });
811
+ const write = (message) => {
812
+ switch (message._tag) {
813
+ case "Chunk": {
814
+ const requestId = message.requestId;
815
+ const entry = entries.get(requestId);
816
+ if (!entry || entry._tag !== "Queue")
817
+ return void_2;
818
+ return offerAll(entry.queue, message.values).pipe(supportsAck ? flatMap(() => options.onFromClient({
819
+ message: {
820
+ _tag: "Ack",
821
+ requestId: message.requestId
822
+ },
823
+ context: entry.context,
824
+ discard: false
825
+ })) : identity, catchCause((cause) => failCause3(entry.queue, cause)));
826
+ }
827
+ case "Exit": {
828
+ const requestId = message.requestId;
829
+ const entry = entries.get(requestId);
830
+ if (!entry)
831
+ return void_2;
832
+ entries.delete(requestId);
833
+ if (entry._tag === "Effect") {
834
+ entry.resume(message.exit);
835
+ return void_2;
836
+ }
837
+ return message.exit._tag === "Success" ? end(entry.queue) : failCause3(entry.queue, message.exit.cause);
838
+ }
839
+ case "Defect": {
840
+ return clearEntries(die2(message.defect));
841
+ }
842
+ case "ClientEnd": {
843
+ return void_2;
844
+ }
845
+ }
846
+ };
847
+ let client;
848
+ if (options.flatten) {
849
+ const fns = new Map;
850
+ client = function client(tag, payload, options) {
851
+ let fn = fns.get(tag);
852
+ if (!fn) {
853
+ fn = onRequest(group.requests.get(tag));
854
+ fns.set(tag, fn);
855
+ }
856
+ return fn(payload, options);
857
+ };
858
+ } else {
859
+ client = {};
860
+ group.requests.forEach((rpc) => {
861
+ assignProperty(client, rpc._tag, onRequest(rpc));
862
+ });
863
+ }
864
+ return {
865
+ client,
866
+ write
867
+ };
868
+ });
869
+ var clientIdCounter = 0;
870
+ var make5 = /* @__PURE__ */ fnUntraced(function* (group, options) {
871
+ const clientId = clientIdCounter++;
872
+ const {
873
+ codecFor,
874
+ run,
875
+ send,
876
+ supportsAck,
877
+ supportsTransferables
878
+ } = yield* Protocol;
879
+ const rpcSchemas = makeRpcSchemas(codecFor);
880
+ const decodeDefect = decodeSync(codecFor(Defect()));
881
+ const entries = new Map;
882
+ const interruptRequest = (requestId) => {
883
+ if (!entries.has(requestId))
884
+ return void_2;
885
+ entries.delete(requestId);
886
+ return send(clientId, {
887
+ _tag: "Interrupt",
888
+ requestId
889
+ });
890
+ };
891
+ const {
892
+ client,
893
+ write
894
+ } = yield* makeNoSerialization(group, {
895
+ ...options,
896
+ supportsAck,
897
+ onFromClient({
898
+ message
899
+ }) {
900
+ switch (message._tag) {
901
+ case "Request": {
902
+ const rpc = group.requests.get(message.tag);
903
+ const collector = supportsTransferables ? makeCollectorUnsafe() : undefined;
904
+ const fiber = getCurrent();
905
+ const entry = {
906
+ rpc,
907
+ context: collector ? add(fiber.context, Collector, collector) : fiber.context,
908
+ schemas: rpcSchemas(rpc)
909
+ };
910
+ entries.set(message.id, entry);
911
+ return entry.schemas.encodePayload(message.payload).pipe(provideContext(entry.context), orDie, flatMap((payload) => send(clientId, {
912
+ ...message,
913
+ id: message.id,
914
+ payload,
915
+ headers: Object.entries(message.headers)
916
+ }, collector && collector.readUnsafe())));
917
+ }
918
+ case "Ack": {
919
+ const entry = entries.get(message.requestId);
920
+ if (!entry)
921
+ return void_2;
922
+ return send(clientId, {
923
+ _tag: "Ack",
924
+ requestId: message.requestId
925
+ });
926
+ }
927
+ case "Interrupt": {
928
+ return interruptRequest(message.requestId);
929
+ }
930
+ case "Eof": {
931
+ return void_2;
932
+ }
933
+ }
934
+ }
935
+ });
936
+ yield* run(clientId, (message) => {
937
+ switch (message._tag) {
938
+ case "Chunk": {
939
+ const requestId = RequestId(message.requestId);
940
+ const entry = entries.get(requestId);
941
+ if (!entry || isNone(entry.schemas.decodeChunk))
942
+ return void_2;
943
+ const decodeChunk = entry.schemas.decodeChunk.value;
944
+ return uninterruptibleMask((restore) => restore(decodeChunk(message.values).pipe(provideContext(entry.context), orDie, flatMap((chunk) => write({
945
+ _tag: "Chunk",
946
+ clientId: 0,
947
+ requestId,
948
+ values: chunk
949
+ })))).pipe(onError((cause) => write({
950
+ _tag: "Exit",
951
+ clientId: 0,
952
+ requestId,
953
+ exit: failCause(cause)
954
+ }).pipe(andThen(hasInterrupts(cause) ? void_2 : ignore(interruptRequest(requestId))))), catchCauseIf((cause) => !hasInterrupts(cause), () => void_2)));
955
+ }
956
+ case "Exit": {
957
+ const requestId = RequestId(message.requestId);
958
+ const entry = entries.get(requestId);
959
+ if (!entry)
960
+ return void_2;
961
+ entries.delete(requestId);
962
+ return entry.schemas.decodeExit(message.exit).pipe(provideContext(entry.context), orDie, matchCauseEffect({
963
+ onSuccess: (exit) => write({
964
+ _tag: "Exit",
965
+ clientId: 0,
966
+ requestId,
967
+ exit
968
+ }),
969
+ onFailure: (cause) => write({
970
+ _tag: "Exit",
971
+ clientId: 0,
972
+ requestId,
973
+ exit: failCause(cause)
974
+ })
975
+ }));
976
+ }
977
+ case "Defect": {
978
+ return write({
979
+ _tag: "Defect",
980
+ clientId: 0,
981
+ defect: decodeDefect(message.defect)
982
+ });
983
+ }
984
+ case "ClientProtocolError": {
985
+ const exit = fail2(message.error);
986
+ return forEach(Array.from(entries.keys()), (requestId) => write({
987
+ _tag: "Exit",
988
+ clientId: 0,
989
+ requestId,
990
+ exit
991
+ }));
992
+ }
993
+ default: {
994
+ return void_2;
995
+ }
996
+ }
997
+ }).pipe(catchCause(logError), interruptible, forkScoped);
998
+ return client;
999
+ });
1000
+ var makeRpcSchemas = (codecFor) => {
1001
+ const cache = new WeakMap;
1002
+ return (rpc) => {
1003
+ let entry = cache.get(rpc);
1004
+ if (entry !== undefined) {
1005
+ return entry;
1006
+ }
1007
+ const streamSchemas = getStreamSchemas(rpc.successSchema);
1008
+ entry = {
1009
+ decodeChunk: map(streamSchemas, (streamSchemas) => decodeUnknownEffect(codecFor(NonEmptyArray(streamSchemas.success)))),
1010
+ encodePayload: encodeEffect(codecFor(rpc.payloadSchema)),
1011
+ decodeExit: decodeUnknownEffect(codecFor(exitSchema(rpc)))
1012
+ };
1013
+ cache.set(rpc, entry);
1014
+ return entry;
1015
+ };
1016
+ };
1017
+ var CurrentHeaders = /* @__PURE__ */ Reference("effect/rpc/RpcClient/CurrentHeaders", {
1018
+ defaultValue: () => empty3
1019
+ });
1020
+ var withHeaders = /* @__PURE__ */ dual(2, (effect, headers) => updateService(effect, CurrentHeaders, merge3(fromInput(headers))));
1021
+
1022
+ class Protocol extends (/* @__PURE__ */ Service()("effect/rpc/RpcClient/Protocol")) {
1023
+ static make = withRunClient;
1024
+ }
1025
+ var makeProtocolSocket = (options) => Protocol.make(fnUntraced(function* (writeResponse, clientIds) {
1026
+ const socket = yield* Socket;
1027
+ const serialization = yield* RpcSerialization;
1028
+ const hooks = yield* serviceOption(ConnectionHooks);
1029
+ const requestClientMap = new Map;
1030
+ const writer = yield* socket.writer;
1031
+ let parser = serialization.makeUnsafe();
1032
+ const pinger = yield* makePinger(suspend(() => writer.write(parser.encode(constPing))), options);
1033
+ const onPingTimeout = ignoreCause(options?.onPingTimeout ?? void_2, {
1034
+ log: true,
1035
+ message: "RpcClient onPingTimeout hook failed"
1036
+ });
1037
+ let currentError;
1038
+ const broadcast = (response) => forEach(clientIds, (clientId) => writeResponse(clientId, response));
1039
+ const broadcastError = (error) => {
1040
+ currentError = error;
1041
+ return broadcast({
1042
+ _tag: "ClientProtocolError",
1043
+ error
1044
+ });
1045
+ };
1046
+ const processData = (data) => {
1047
+ try {
1048
+ const responses = parser.decode(data);
1049
+ if (responses.length === 0)
1050
+ return void_2;
1051
+ pinger.onFrame();
1052
+ let i = 0;
1053
+ return whileLoop({
1054
+ while: () => i < responses.length,
1055
+ body: () => {
1056
+ const response = responses[i++];
1057
+ if (response._tag === "Pong")
1058
+ return void_2;
1059
+ if (Object.hasOwn(response, "requestId")) {
1060
+ const requestId = response.requestId;
1061
+ const clientId = requestClientMap.get(requestId);
1062
+ if (clientId !== undefined) {
1063
+ if (response._tag === "Exit") {
1064
+ requestClientMap.delete(requestId);
1065
+ }
1066
+ return writeResponse(clientId, response);
1067
+ }
1068
+ }
1069
+ return broadcast(response);
1070
+ },
1071
+ step: constVoid
1072
+ });
1073
+ } catch (defect) {
1074
+ return broadcast({
1075
+ _tag: "ClientProtocolError",
1076
+ error: new RpcClientError({
1077
+ reason: new RpcClientDefect({
1078
+ message: "Error decoding message",
1079
+ cause: defect
1080
+ })
1081
+ })
1082
+ });
1083
+ }
1084
+ };
1085
+ yield* suspend(() => {
1086
+ parser = serialization.makeUnsafe();
1087
+ pinger.reset();
1088
+ let connected = false;
1089
+ return gen(function* () {
1090
+ const {
1091
+ pull
1092
+ } = yield* socket.reader;
1093
+ currentError = undefined;
1094
+ connected = true;
1095
+ if (isSome(hooks)) {
1096
+ yield* hooks.value.onConnect;
1097
+ }
1098
+ while (true) {
1099
+ const frames = yield* pull;
1100
+ for (let i = 0;i < frames.length; i++) {
1101
+ yield* processData(frames[i]);
1102
+ }
1103
+ }
1104
+ }).pipe(scoped, raceFirst(pinger.timeout), andThen(() => connected ? onPingTimeout : void_2), andThen(() => fail4(new SocketError({
1105
+ reason: new SocketReadError({
1106
+ cause: new Error("ping timeout")
1107
+ })
1108
+ }))));
1109
+ }).pipe(isSome(hooks) ? ensuring(hooks.value.onDisconnect) : identity, tapCause((cause) => {
1110
+ const error = findError(cause);
1111
+ const hasError = isSuccess(error);
1112
+ const rpcError = new RpcClientError({
1113
+ reason: hasError ? error.success.reason : new RpcClientDefect({
1114
+ message: "Unknown socket error",
1115
+ cause: squash(cause)
1116
+ })
1117
+ });
1118
+ if (options?.retryTransientErrors && hasError && error.success.reason._tag === "SocketOpenError") {
1119
+ return (options.onTransientError?.(rpcError) ?? void_2).pipe(ignoreCause({
1120
+ log: true,
1121
+ message: "RpcClient onTransientError hook failed"
1122
+ }));
1123
+ }
1124
+ return broadcastError(rpcError);
1125
+ }), retryOrElse(options?.retryPolicy ?? defaultRetryPolicy, (error) => broadcastError(new RpcClientError({
1126
+ reason: error.reason
1127
+ }))), annotateLogs({
1128
+ module: "RpcClient",
1129
+ method: "makeProtocolSocket"
1130
+ }), forkScoped);
1131
+ return {
1132
+ send(clientId, request) {
1133
+ if (currentError) {
1134
+ return fail4(currentError);
1135
+ }
1136
+ if (request._tag === "Request") {
1137
+ requestClientMap.set(request.id, clientId);
1138
+ }
1139
+ const encoded = parser.encode(request);
1140
+ if (encoded === undefined)
1141
+ return void_2;
1142
+ return orDie(writer.write(encoded));
1143
+ },
1144
+ supportsAck: true,
1145
+ supportsTransferables: false,
1146
+ codecFor: serialization.codecFor
1147
+ };
1148
+ }));
1149
+ var defaultRetryPolicy = /* @__PURE__ */ min([/* @__PURE__ */ exponential(500, 1.5), /* @__PURE__ */ spaced(5000)]);
1150
+ var makePinger = /* @__PURE__ */ fnUntraced(function* (writePing, options) {
1151
+ const clock = yield* Clock;
1152
+ const interval = options?.pingInterval ?? "5 seconds";
1153
+ const timeoutMillis = toMillis(options?.pingTimeout ?? interval);
1154
+ let lastSeen = clock.currentTimeMillisUnsafe();
1155
+ const latch = makeUnsafe3();
1156
+ const onFrame = () => {
1157
+ lastSeen = clock.currentTimeMillisUnsafe();
1158
+ };
1159
+ const reset = () => {
1160
+ onFrame();
1161
+ latch.closeUnsafe();
1162
+ };
1163
+ yield* suspend(() => {
1164
+ if (clock.currentTimeMillisUnsafe() - lastSeen > timeoutMillis)
1165
+ return latch.open;
1166
+ return writePing;
1167
+ }).pipe(delay(interval), ignore, forever, interruptible, forkScoped);
1168
+ return {
1169
+ timeout: latch.await,
1170
+ reset,
1171
+ onFrame
1172
+ };
1173
+ });
1174
+ var layerProtocolSocket = (options) => effect(Protocol)(makeProtocolSocket(options));
1175
+ class ConnectionHooks extends (/* @__PURE__ */ Service()("effect/rpc/RpcClient/ConnectionHooks")) {
1176
+ }
1177
+
1178
+ export { make4, readerString, isCloseEvent, SocketReadError, SocketWriteError, SocketOpenError, SocketUpgradeError, SocketCloseError, SocketError, WebSocketConstructor, layerWebSocketConstructorGlobal, layerWebSocket, layerJson, make5, withHeaders, layerProtocolSocket, ConnectionHooks };