@contello/sdk-client 8.21.0 → 8.21.2

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/dist/index.js CHANGED
@@ -1,1009 +1,156 @@
1
- function k(e) {
2
- return e === null ? "null" : Array.isArray(e) ? "array" : typeof e;
3
- }
4
- function R(e) {
5
- return k(e) === "object";
6
- }
7
- function be(e) {
8
- return Array.isArray(e) && // must be at least one error
9
- e.length > 0 && // error has at least a message
10
- e.every((t) => "message" in t);
11
- }
12
- function re(e, t) {
13
- return e.length < 124 ? e : t;
14
- }
15
- const me = "graphql-transport-ws";
16
- var _ = /* @__PURE__ */ ((e) => (e[e.InternalServerError = 4500] = "InternalServerError", e[e.InternalClientError = 4005] = "InternalClientError", e[e.BadRequest = 4400] = "BadRequest", e[e.BadResponse = 4004] = "BadResponse", e[e.Unauthorized = 4401] = "Unauthorized", e[e.Forbidden = 4403] = "Forbidden", e[e.SubprotocolNotAcceptable = 4406] = "SubprotocolNotAcceptable", e[e.ConnectionInitialisationTimeout = 4408] = "ConnectionInitialisationTimeout", e[e.ConnectionAcknowledgementTimeout = 4504] = "ConnectionAcknowledgementTimeout", e[e.SubscriberAlreadyExists = 4409] = "SubscriberAlreadyExists", e[e.TooManyInitialisationRequests = 4429] = "TooManyInitialisationRequests", e))(_ || {}), O = /* @__PURE__ */ ((e) => (e.ConnectionInit = "connection_init", e.ConnectionAck = "connection_ack", e.Ping = "ping", e.Pong = "pong", e.Subscribe = "subscribe", e.Next = "next", e.Error = "error", e.Complete = "complete", e))(O || {});
17
- function ue(e) {
18
- if (!R(e))
19
- throw new Error(
20
- `Message is expected to be an object, but got ${k(e)}`
21
- );
22
- if (!e.type)
23
- throw new Error("Message is missing the 'type' property");
24
- if (typeof e.type != "string")
25
- throw new Error(
26
- `Message is expects the 'type' property to be a string, but got ${k(
27
- e.type
28
- )}`
29
- );
30
- switch (e.type) {
31
- case "connection_init":
32
- case "connection_ack":
33
- case "ping":
34
- case "pong": {
35
- if (e.payload != null && !R(e.payload))
36
- throw new Error(
37
- `"${e.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${e.payload}"`
38
- );
39
- break;
40
- }
41
- case "subscribe": {
42
- if (typeof e.id != "string")
43
- throw new Error(
44
- `"${e.type}" message expects the 'id' property to be a string, but got ${k(
45
- e.id
46
- )}`
47
- );
48
- if (!e.id)
49
- throw new Error(
50
- `"${e.type}" message requires a non-empty 'id' property`
51
- );
52
- if (!R(e.payload))
53
- throw new Error(
54
- `"${e.type}" message expects the 'payload' property to be an object, but got ${k(
55
- e.payload
56
- )}`
57
- );
58
- if (typeof e.payload.query != "string")
59
- throw new Error(
60
- `"${e.type}" message payload expects the 'query' property to be a string, but got ${k(
61
- e.payload.query
62
- )}`
63
- );
64
- if (e.payload.variables != null && !R(e.payload.variables))
65
- throw new Error(
66
- `"${e.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${k(
67
- e.payload.variables
68
- )}`
69
- );
70
- if (e.payload.operationName != null && k(e.payload.operationName) !== "string")
71
- throw new Error(
72
- `"${e.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${k(
73
- e.payload.operationName
74
- )}`
75
- );
76
- if (e.payload.extensions != null && !R(e.payload.extensions))
77
- throw new Error(
78
- `"${e.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${k(
79
- e.payload.extensions
80
- )}`
81
- );
82
- break;
83
- }
84
- case "next": {
85
- if (typeof e.id != "string")
86
- throw new Error(
87
- `"${e.type}" message expects the 'id' property to be a string, but got ${k(
88
- e.id
89
- )}`
90
- );
91
- if (!e.id)
92
- throw new Error(
93
- `"${e.type}" message requires a non-empty 'id' property`
94
- );
95
- if (!R(e.payload))
96
- throw new Error(
97
- `"${e.type}" message expects the 'payload' property to be an object, but got ${k(
98
- e.payload
99
- )}`
100
- );
101
- break;
102
- }
103
- case "error": {
104
- if (typeof e.id != "string")
105
- throw new Error(
106
- `"${e.type}" message expects the 'id' property to be a string, but got ${k(
107
- e.id
108
- )}`
109
- );
110
- if (!e.id)
111
- throw new Error(
112
- `"${e.type}" message requires a non-empty 'id' property`
113
- );
114
- if (!be(e.payload))
115
- throw new Error(
116
- `"${e.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(
117
- e.payload
118
- )}`
119
- );
120
- break;
121
- }
122
- case "complete": {
123
- if (typeof e.id != "string")
124
- throw new Error(
125
- `"${e.type}" message expects the 'id' property to be a string, but got ${k(
126
- e.id
127
- )}`
128
- );
129
- if (!e.id)
130
- throw new Error(
131
- `"${e.type}" message requires a non-empty 'id' property`
132
- );
133
- break;
134
- }
135
- default:
136
- throw new Error(`Invalid message 'type' property "${e.type}"`);
137
- }
138
- return e;
139
- }
140
- function ge(e, t) {
141
- return ue(
142
- typeof e == "string" ? JSON.parse(e, t) : e
143
- );
144
- }
145
- function F(e, t) {
146
- return ue(e), JSON.stringify(e, t);
147
- }
148
- function we(e) {
149
- const {
150
- url: t,
151
- connectionParams: r,
152
- lazy: n = !0,
153
- onNonLazyError: s = console.error,
154
- lazyCloseTimeout: i = 0,
155
- keepAlive: o = 0,
156
- disablePong: h,
157
- connectionAckWaitTimeout: b = 0,
158
- retryAttempts: A = 5,
159
- retryWait: w = async function(f) {
160
- const c = Math.pow(2, f);
161
- await new Promise(
162
- (u) => setTimeout(
163
- u,
164
- c * 1e3 + // add random timeout from 300ms to 3s
165
- Math.floor(Math.random() * 2700 + 300)
166
- )
167
- );
168
- },
169
- shouldRetry: E = G,
170
- on: l,
171
- webSocketImpl: y,
172
- /**
173
- * Generates a v4 UUID to be used as the ID using `Math`
174
- * as the random number generator. Supply your own generator
175
- * in case you need more uniqueness.
176
- *
177
- * Reference: https://gist.github.com/jed/982883
178
- */
179
- generateID: P = function() {
180
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (f) => {
181
- const c = Math.random() * 16 | 0;
182
- return (f == "x" ? c : c & 3 | 8).toString(16);
183
- });
184
- },
185
- jsonMessageReplacer: m,
186
- jsonMessageReviver: de
187
- } = e;
188
- let N;
189
- if (y) {
190
- if (!xe(y))
191
- throw new Error("Invalid WebSocket implementation provided");
192
- N = y;
193
- } else typeof WebSocket < "u" ? N = WebSocket : typeof global < "u" ? N = global.WebSocket || // @ts-expect-error: Support more browsers
194
- global.MozWebSocket : typeof window < "u" && (N = window.WebSocket || // @ts-expect-error: Support more browsers
195
- window.MozWebSocket);
196
- if (!N)
197
- throw new Error(
198
- "WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`"
199
- );
200
- const q = N, x = (() => {
201
- const a = /* @__PURE__ */ (() => {
202
- const c = {};
203
- return {
204
- on(u, d) {
205
- return c[u] = d, () => {
206
- delete c[u];
207
- };
208
- },
209
- emit(u) {
210
- "id" in u && c[u.id]?.(u);
211
- }
212
- };
213
- })(), f = {
214
- connecting: l?.connecting ? [l.connecting] : [],
215
- opened: l?.opened ? [l.opened] : [],
216
- connected: l?.connected ? [l.connected] : [],
217
- ping: l?.ping ? [l.ping] : [],
218
- pong: l?.pong ? [l.pong] : [],
219
- message: l?.message ? [a.emit, l.message] : [a.emit],
220
- closed: l?.closed ? [l.closed] : [],
221
- error: l?.error ? [l.error] : []
222
- };
223
- return {
224
- onMessage: a.on,
225
- on(c, u) {
226
- const d = f[c];
227
- return d.push(u), () => {
228
- d.splice(d.indexOf(u), 1);
229
- };
230
- },
231
- emit(c, ...u) {
232
- for (const d of [...f[c]])
233
- d(...u);
234
- }
235
- };
236
- })();
237
- function H(a) {
238
- const f = [
239
- // errors are fatal and more critical than close events, throw them first
240
- x.on("error", (c) => {
241
- f.forEach((u) => u()), a(c);
242
- }),
243
- // closes can be graceful and not fatal, throw them second (if error didnt throw)
244
- x.on("closed", (c) => {
245
- f.forEach((u) => u()), a(c);
246
- })
247
- ];
248
- }
249
- let $, I = 0, K, W = !1, B = 0, X = !1;
250
- async function Z() {
251
- clearTimeout(K);
252
- const [a, f] = await ($ ?? ($ = new Promise(
253
- (d, v) => (async () => {
254
- if (W) {
255
- if (await w(B), !I)
256
- return $ = void 0, v({ code: 1e3, reason: "All Subscriptions Gone" });
257
- B++;
258
- }
259
- x.emit("connecting", W);
260
- const p = new q(
261
- typeof t == "function" ? await t() : t,
262
- me
263
- );
264
- let M, z;
265
- function U() {
266
- isFinite(o) && o > 0 && (clearTimeout(z), z = setTimeout(() => {
267
- p.readyState === q.OPEN && (p.send(F({ type: O.Ping })), x.emit("ping", !1, void 0));
268
- }, o));
269
- }
270
- H((S) => {
271
- $ = void 0, clearTimeout(M), clearTimeout(z), v(S), S instanceof ne && (p.close(4499, "Terminated"), p.onerror = null, p.onclose = null);
272
- }), p.onerror = (S) => x.emit("error", S), p.onclose = (S) => x.emit("closed", S), p.onopen = async () => {
273
- try {
274
- x.emit("opened", p);
275
- const S = typeof r == "function" ? await r() : r;
276
- if (p.readyState !== q.OPEN) return;
277
- p.send(
278
- F(
279
- S ? {
280
- type: O.ConnectionInit,
281
- payload: S
282
- } : {
283
- type: O.ConnectionInit
284
- // payload is completely absent if not provided
285
- },
286
- m
287
- )
288
- ), isFinite(b) && b > 0 && (M = setTimeout(() => {
289
- p.close(
290
- _.ConnectionAcknowledgementTimeout,
291
- "Connection acknowledgement timeout"
292
- );
293
- }, b)), U();
294
- } catch (S) {
295
- x.emit("error", S), p.close(
296
- _.InternalClientError,
297
- re(
298
- S instanceof Error ? S.message : String(S),
299
- "Internal client error"
300
- )
301
- );
302
- }
303
- };
304
- let j = !1;
305
- p.onmessage = ({ data: S }) => {
306
- try {
307
- const g = ge(S, de);
308
- if (x.emit("message", g), g.type === "ping" || g.type === "pong") {
309
- x.emit(g.type, !0, g.payload), g.type === "pong" ? U() : h || (p.send(
310
- F(
311
- g.payload ? {
312
- type: O.Pong,
313
- payload: g.payload
314
- } : {
315
- type: O.Pong
316
- // payload is completely absent if not provided
317
- }
318
- )
319
- ), x.emit("pong", !1, g.payload));
320
- return;
321
- }
322
- if (j) return;
323
- if (g.type !== O.ConnectionAck)
324
- throw new Error(
325
- `First message cannot be of type ${g.type}`
326
- );
327
- clearTimeout(M), j = !0, x.emit("connected", p, g.payload, W), W = !1, B = 0, d([
328
- p,
329
- new Promise((Fe, he) => H(he))
330
- ]);
331
- } catch (g) {
332
- p.onmessage = null, x.emit("error", g), p.close(
333
- _.BadResponse,
334
- re(
335
- g instanceof Error ? g.message : String(g),
336
- "Bad response"
337
- )
338
- );
339
- }
340
- };
341
- })()
342
- )));
343
- a.readyState === q.CLOSING && await f;
344
- let c = () => {
345
- };
346
- const u = new Promise((d) => c = d);
347
- return [
348
- a,
349
- c,
350
- Promise.race([
351
- // wait for
352
- u.then(() => {
353
- if (!I) {
354
- const d = () => a.close(1e3, "Normal Closure");
355
- isFinite(i) && i > 0 ? K = setTimeout(() => {
356
- a.readyState === q.OPEN && d();
357
- }, i) : d();
358
- }
359
- }),
360
- // or
361
- f
362
- ])
363
- ];
1
+ // src/client.ts
2
+ import { createClient } from "graphql-ws";
3
+
4
+ // src/pool.ts
5
+ var ConnectionPool = class {
6
+ constructor(createClient2, poolSize) {
7
+ this.createClient = createClient2;
8
+ this.poolSize = poolSize;
364
9
  }
365
- function ee(a) {
366
- if (G(a) && (Ee(a.code) || [
367
- _.InternalServerError,
368
- _.InternalClientError,
369
- _.BadRequest,
370
- _.BadResponse,
371
- _.Unauthorized,
372
- // CloseCode.Forbidden, might grant access out after retry
373
- _.SubprotocolNotAcceptable,
374
- // CloseCode.ConnectionInitialisationTimeout, might not time out after retry
375
- // CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry
376
- _.SubscriberAlreadyExists,
377
- _.TooManyInitialisationRequests
378
- // 4499, // Terminated, probably because the socket froze, we want to retry
379
- ].includes(a.code)))
380
- throw a;
381
- if (X) return !1;
382
- if (G(a) && a.code === 1e3)
383
- return I > 0;
384
- if (!A || B >= A || !E(a)) throw a;
385
- return W = !0;
386
- }
387
- n || (async () => {
388
- for (I++; ; )
389
- try {
390
- const [, , a] = await Z();
391
- await a;
392
- } catch (a) {
393
- try {
394
- if (!ee(a)) return;
395
- } catch (f) {
396
- return s?.(f);
397
- }
398
- }
399
- })();
400
- function te(a, f) {
401
- const c = P(a);
402
- let u = !1, d = !1, v = () => {
403
- I--, u = !0;
404
- };
405
- return (async () => {
406
- for (I++; ; )
407
- try {
408
- const [p, M, z] = await Z();
409
- if (u) return M();
410
- const U = x.onMessage(c, (j) => {
411
- switch (j.type) {
412
- case O.Next: {
413
- f.next(j.payload);
414
- return;
415
- }
416
- case O.Error: {
417
- d = !0, u = !0, f.error(j.payload), v();
418
- return;
419
- }
420
- case O.Complete: {
421
- u = !0, v();
422
- return;
423
- }
424
- }
10
+ clients = [];
11
+ currentIndex = 0;
12
+ async connect() {
13
+ const connected = [];
14
+ for (let i = 0; i < this.poolSize; i++) {
15
+ const client = this.createClient(`${i + 1}`);
16
+ this.clients.push(client);
17
+ connected.push(
18
+ new Promise((resolve) => {
19
+ const unsubscribe = client.on("connected", () => {
20
+ unsubscribe();
21
+ resolve();
425
22
  });
426
- p.send(
427
- F(
428
- {
429
- id: c,
430
- type: O.Subscribe,
431
- payload: a
432
- },
433
- m
434
- )
435
- ), v = () => {
436
- !u && p.readyState === q.OPEN && p.send(
437
- F(
438
- {
439
- id: c,
440
- type: O.Complete
441
- },
442
- m
443
- )
444
- ), I--, u = !0, M();
445
- }, await z.finally(U);
446
- return;
447
- } catch (p) {
448
- if (!ee(p)) return;
449
- }
450
- })().then(() => {
451
- d || f.complete();
452
- }).catch((p) => {
453
- f.error(p);
454
- }), () => {
455
- u || v();
456
- };
457
- }
458
- return {
459
- on: x.on,
460
- subscribe: te,
461
- iterate(a) {
462
- const f = [], c = {
463
- done: !1,
464
- error: null,
465
- resolve: () => {
466
- }
467
- }, u = te(a, {
468
- next(v) {
469
- f.push(v), c.resolve();
470
- },
471
- error(v) {
472
- c.done = !0, c.error = v, c.resolve();
473
- },
474
- complete() {
475
- c.done = !0, c.resolve();
476
- }
477
- }), d = (async function* () {
478
- for (; ; ) {
479
- for (f.length || await new Promise((p) => c.resolve = p); f.length; )
480
- yield f.shift();
481
- if (c.error)
482
- throw c.error;
483
- if (c.done)
484
- return;
485
- }
486
- })();
487
- return d.throw = async (v) => (c.done || (c.done = !0, c.error = v, c.resolve()), { done: !0, value: void 0 }), d.return = async () => (u(), { done: !0, value: void 0 }), d;
488
- },
489
- async dispose() {
490
- if (X = !0, $) {
491
- const [a] = await $;
492
- a.close(1e3, "Normal Closure");
493
- }
494
- },
495
- terminate() {
496
- $ && x.emit("closed", new ne());
23
+ })
24
+ );
497
25
  }
498
- };
499
- }
500
- class ne extends Error {
501
- name = "TerminatedCloseEvent";
502
- message = "4499: Terminated";
503
- code = 4499;
504
- reason = "Terminated";
505
- wasClean = !1;
506
- }
507
- function G(e) {
508
- return R(e) && "code" in e && "reason" in e;
509
- }
510
- function Ee(e) {
511
- return [
512
- 1e3,
513
- // Normal Closure is not an erroneous close code
514
- 1001,
515
- // Going Away
516
- 1006,
517
- // Abnormal Closure
518
- 1005,
519
- // No Status Received
520
- 1012,
521
- // Service Restart
522
- 1013,
523
- // Try Again Later
524
- 1014
525
- // Bad Gateway
526
- ].includes(e) ? !1 : e >= 1e3 && e <= 1999;
527
- }
528
- function xe(e) {
529
- return typeof e == "function" && "constructor" in e && "CLOSED" in e && "CLOSING" in e && "CONNECTING" in e && "OPEN" in e;
530
- }
531
- var J = function(e, t) {
532
- return J = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(r, n) {
533
- r.__proto__ = n;
534
- } || function(r, n) {
535
- for (var s in n) Object.prototype.hasOwnProperty.call(n, s) && (r[s] = n[s]);
536
- }, J(e, t);
537
- };
538
- function pe(e, t) {
539
- if (typeof t != "function" && t !== null)
540
- throw new TypeError("Class extends value " + String(t) + " is not a constructor or null");
541
- J(e, t);
542
- function r() {
543
- this.constructor = e;
26
+ await Promise.all(connected);
544
27
  }
545
- e.prototype = t === null ? Object.create(t) : (r.prototype = t.prototype, new r());
546
- }
547
- function oe(e) {
548
- var t = typeof Symbol == "function" && Symbol.iterator, r = t && e[t], n = 0;
549
- if (r) return r.call(e);
550
- if (e && typeof e.length == "number") return {
551
- next: function() {
552
- return e && n >= e.length && (e = void 0), { value: e && e[n++], done: !e };
28
+ get() {
29
+ if (this.clients.length === 0) {
30
+ throw new Error("Connection pool is empty. Please call connect() first.");
553
31
  }
554
- };
555
- throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.");
556
- }
557
- function Q(e, t) {
558
- var r = typeof Symbol == "function" && e[Symbol.iterator];
559
- if (!r) return e;
560
- var n = r.call(e), s, i = [], o;
561
- try {
562
- for (; (t === void 0 || t-- > 0) && !(s = n.next()).done; ) i.push(s.value);
563
- } catch (h) {
564
- o = { error: h };
565
- } finally {
566
- try {
567
- s && !s.done && (r = n.return) && r.call(n);
568
- } finally {
569
- if (o) throw o.error;
32
+ const client = this.clients[this.currentIndex];
33
+ this.currentIndex = (this.currentIndex + 1) % this.poolSize;
34
+ if (!client) {
35
+ throw new Error("No available WebSocket client");
570
36
  }
37
+ return client;
571
38
  }
572
- return i;
573
- }
574
- function V(e, t, r) {
575
- if (r || arguments.length === 2) for (var n = 0, s = t.length, i; n < s; n++)
576
- (i || !(n in t)) && (i || (i = Array.prototype.slice.call(t, 0, n)), i[n] = t[n]);
577
- return e.concat(i || Array.prototype.slice.call(t));
578
- }
579
- function T(e) {
580
- return typeof e == "function";
581
- }
582
- function le(e) {
583
- var t = function(n) {
584
- Error.call(n), n.stack = new Error().stack;
585
- }, r = e(t);
586
- return r.prototype = Object.create(Error.prototype), r.prototype.constructor = r, r;
587
- }
588
- var D = le(function(e) {
589
- return function(r) {
590
- e(this), this.message = r ? r.length + ` errors occurred during unsubscription:
591
- ` + r.map(function(n, s) {
592
- return s + 1 + ") " + n.toString();
593
- }).join(`
594
- `) : "", this.name = "UnsubscriptionError", this.errors = r;
595
- };
596
- });
597
- function ie(e, t) {
598
- if (e) {
599
- var r = e.indexOf(t);
600
- 0 <= r && e.splice(r, 1);
601
- }
602
- }
603
- var Y = (function() {
604
- function e(t) {
605
- this.initialTeardown = t, this.closed = !1, this._parentage = null, this._finalizers = null;
39
+ async disconnect() {
40
+ const closed = this.clients.map(
41
+ (client) => new Promise((resolve) => {
42
+ const unsubscribe = client.on("closed", () => {
43
+ unsubscribe();
44
+ resolve();
45
+ });
46
+ client.dispose();
47
+ })
48
+ );
49
+ this.clients = [];
50
+ await Promise.all(closed);
606
51
  }
607
- return e.prototype.unsubscribe = function() {
608
- var t, r, n, s, i;
609
- if (!this.closed) {
610
- this.closed = !0;
611
- var o = this._parentage;
612
- if (o)
613
- if (this._parentage = null, Array.isArray(o))
614
- try {
615
- for (var h = oe(o), b = h.next(); !b.done; b = h.next()) {
616
- var A = b.value;
617
- A.remove(this);
618
- }
619
- } catch (m) {
620
- t = { error: m };
621
- } finally {
622
- try {
623
- b && !b.done && (r = h.return) && r.call(h);
624
- } finally {
625
- if (t) throw t.error;
626
- }
627
- }
628
- else
629
- o.remove(this);
630
- var w = this.initialTeardown;
631
- if (T(w))
632
- try {
633
- w();
634
- } catch (m) {
635
- i = m instanceof D ? m.errors : [m];
636
- }
637
- var E = this._finalizers;
638
- if (E) {
639
- this._finalizers = null;
640
- try {
641
- for (var l = oe(E), y = l.next(); !y.done; y = l.next()) {
642
- var P = y.value;
643
- try {
644
- se(P);
645
- } catch (m) {
646
- i = i ?? [], m instanceof D ? i = V(V([], Q(i)), Q(m.errors)) : i.push(m);
647
- }
648
- }
649
- } catch (m) {
650
- n = { error: m };
651
- } finally {
652
- try {
653
- y && !y.done && (s = l.return) && s.call(l);
654
- } finally {
655
- if (n) throw n.error;
656
- }
657
- }
658
- }
659
- if (i)
660
- throw new D(i);
661
- }
662
- }, e.prototype.add = function(t) {
663
- var r;
664
- if (t && t !== this)
665
- if (this.closed)
666
- se(t);
667
- else {
668
- if (t instanceof e) {
669
- if (t.closed || t._hasParent(this))
670
- return;
671
- t._addParent(this);
672
- }
673
- (this._finalizers = (r = this._finalizers) !== null && r !== void 0 ? r : []).push(t);
674
- }
675
- }, e.prototype._hasParent = function(t) {
676
- var r = this._parentage;
677
- return r === t || Array.isArray(r) && r.includes(t);
678
- }, e.prototype._addParent = function(t) {
679
- var r = this._parentage;
680
- this._parentage = Array.isArray(r) ? (r.push(t), r) : r ? [r, t] : t;
681
- }, e.prototype._removeParent = function(t) {
682
- var r = this._parentage;
683
- r === t ? this._parentage = null : Array.isArray(r) && ie(r, t);
684
- }, e.prototype.remove = function(t) {
685
- var r = this._finalizers;
686
- r && ie(r, t), t instanceof e && t._removeParent(this);
687
- }, e.EMPTY = (function() {
688
- var t = new e();
689
- return t.closed = !0, t;
690
- })(), e;
691
- })();
692
- Y.EMPTY;
693
- function fe(e) {
694
- return e instanceof Y || e && "closed" in e && T(e.remove) && T(e.add) && T(e.unsubscribe);
695
- }
696
- function se(e) {
697
- T(e) ? e() : e.unsubscribe();
698
- }
699
- var Se = {
700
- Promise: void 0
701
- }, ve = {
702
- setTimeout: function(e, t) {
703
- for (var r = [], n = 2; n < arguments.length; n++)
704
- r[n - 2] = arguments[n];
705
- return setTimeout.apply(void 0, V([e, t], Q(r)));
706
- },
707
- clearTimeout: function(e) {
708
- return clearTimeout(e);
709
- },
710
- delegate: void 0
711
52
  };
712
- function ke(e) {
713
- ve.setTimeout(function() {
714
- throw e;
715
- });
716
- }
717
- function ce() {
718
- }
719
- function Pe(e) {
720
- e();
721
- }
722
- var ye = (function(e) {
723
- pe(t, e);
724
- function t(r) {
725
- var n = e.call(this) || this;
726
- return n.isStopped = !1, r ? (n.destination = r, fe(r) && r.add(n)) : n.destination = Te, n;
727
- }
728
- return t.create = function(r, n, s) {
729
- return new C(r, n, s);
730
- }, t.prototype.next = function(r) {
731
- this.isStopped || this._next(r);
732
- }, t.prototype.error = function(r) {
733
- this.isStopped || (this.isStopped = !0, this._error(r));
734
- }, t.prototype.complete = function() {
735
- this.isStopped || (this.isStopped = !0, this._complete());
736
- }, t.prototype.unsubscribe = function() {
737
- this.closed || (this.isStopped = !0, e.prototype.unsubscribe.call(this), this.destination = null);
738
- }, t.prototype._next = function(r) {
739
- this.destination.next(r);
740
- }, t.prototype._error = function(r) {
741
- try {
742
- this.destination.error(r);
743
- } finally {
744
- this.unsubscribe();
53
+
54
+ // src/sdk.ts
55
+ import { Observable, firstValueFrom } from "rxjs";
56
+ var createSdk = (client, middlewares, getSdk) => {
57
+ return getSdk((doc, vars, options) => {
58
+ if (options) {
59
+ console.warn("options are not supported yet");
745
60
  }
746
- }, t.prototype._complete = function() {
747
- try {
748
- this.destination.complete();
749
- } finally {
750
- this.unsubscribe();
61
+ const query = doc.loc?.source.body;
62
+ if (!query) {
63
+ throw new Error("No query provided");
751
64
  }
752
- }, t;
753
- })(Y), _e = (function() {
754
- function e(t) {
755
- this.partialObserver = t;
756
- }
757
- return e.prototype.next = function(t) {
758
- var r = this.partialObserver;
759
- if (r.next)
760
- try {
761
- r.next(t);
762
- } catch (n) {
763
- L(n);
764
- }
765
- }, e.prototype.error = function(t) {
766
- var r = this.partialObserver;
767
- if (r.error)
768
- try {
769
- r.error(t);
770
- } catch (n) {
771
- L(n);
772
- }
773
- else
774
- L(t);
775
- }, e.prototype.complete = function() {
776
- var t = this.partialObserver;
777
- if (t.complete)
778
- try {
779
- t.complete();
780
- } catch (r) {
781
- L(r);
782
- }
783
- }, e;
784
- })(), C = (function(e) {
785
- pe(t, e);
786
- function t(r, n, s) {
787
- var i = e.call(this) || this, o;
788
- return T(r) || !r ? o = {
789
- next: r ?? void 0,
790
- error: n ?? void 0,
791
- complete: s ?? void 0
792
- } : o = r, i.destination = new _e(o), i;
793
- }
794
- return t;
795
- })(ye);
796
- function L(e) {
797
- ke(e);
798
- }
799
- function Oe(e) {
800
- throw e;
801
- }
802
- var Te = {
803
- closed: !0,
804
- next: ce,
805
- error: Oe,
806
- complete: ce
807
- }, Ae = (function() {
808
- return typeof Symbol == "function" && Symbol.observable || "@@observable";
809
- })();
810
- function $e(e) {
811
- return e;
812
- }
813
- function Ie(e) {
814
- return e.length === 0 ? $e : e.length === 1 ? e[0] : function(r) {
815
- return e.reduce(function(n, s) {
816
- return s(n);
817
- }, r);
818
- };
819
- }
820
- var Re = (function() {
821
- function e(t) {
822
- t && (this._subscribe = t);
823
- }
824
- return e.prototype.lift = function(t) {
825
- var r = new e();
826
- return r.source = this, r.operator = t, r;
827
- }, e.prototype.subscribe = function(t, r, n) {
828
- var s = this, i = qe(t) ? t : new C(t, r, n);
829
- return Pe(function() {
830
- var o = s, h = o.operator, b = o.source;
831
- i.add(h ? h.call(i, b) : b ? s._subscribe(i) : s._trySubscribe(i));
832
- }), i;
833
- }, e.prototype._trySubscribe = function(t) {
834
- try {
835
- return this._subscribe(t);
836
- } catch (r) {
837
- t.error(r);
65
+ if (vars && typeof vars !== "object") {
66
+ throw new Error("Variables must be an object");
838
67
  }
839
- }, e.prototype.forEach = function(t, r) {
840
- var n = this;
841
- return r = ae(r), new r(function(s, i) {
842
- var o = new C({
843
- next: function(h) {
844
- try {
845
- t(h);
846
- } catch (b) {
847
- i(b), o.unsubscribe();
848
- }
849
- },
850
- error: i,
851
- complete: s
852
- });
853
- n.subscribe(o);
854
- });
855
- }, e.prototype._subscribe = function(t) {
856
- var r;
857
- return (r = this.source) === null || r === void 0 ? void 0 : r.subscribe(t);
858
- }, e.prototype[Ae] = function() {
859
- return this;
860
- }, e.prototype.pipe = function() {
861
- for (var t = [], r = 0; r < arguments.length; r++)
862
- t[r] = arguments[r];
863
- return Ie(t)(this);
864
- }, e.prototype.toPromise = function(t) {
865
- var r = this;
866
- return t = ae(t), new t(function(n, s) {
867
- var i;
868
- r.subscribe(function(o) {
869
- return i = o;
870
- }, function(o) {
871
- return s(o);
872
- }, function() {
873
- return n(i);
874
- });
875
- });
876
- }, e.create = function(t) {
877
- return new e(t);
878
- }, e;
879
- })();
880
- function ae(e) {
881
- var t;
882
- return (t = e ?? Se.Promise) !== null && t !== void 0 ? t : Promise;
883
- }
884
- function Ne(e) {
885
- return e && T(e.next) && T(e.error) && T(e.complete);
886
- }
887
- function qe(e) {
888
- return e && e instanceof ye || Ne(e) && fe(e);
889
- }
890
- var Me = le(function(e) {
891
- return function() {
892
- e(this), this.name = "EmptyError", this.message = "no elements in sequence";
893
- };
894
- });
895
- function je(e, t) {
896
- return new Promise(function(r, n) {
897
- var s = new C({
898
- next: function(i) {
899
- r(i), s.unsubscribe();
900
- },
901
- error: n,
902
- complete: function() {
903
- n(new Me());
68
+ const operationDef = doc.definitions.find((def) => def.kind === "OperationDefinition");
69
+ if (!operationDef) {
70
+ throw new Error("No operation definition found");
71
+ }
72
+ const kind = operationDef.operation;
73
+ const executeRequest = () => {
74
+ const wsClient = client();
75
+ return new Observable((obs) => wsClient.subscribe({ query, variables: vars }, obs));
76
+ };
77
+ const request = {
78
+ kind,
79
+ operationName: operationDef.name?.value ?? "",
80
+ query,
81
+ variables: vars || {}
82
+ };
83
+ const executeWithMiddlewares = (middlewares2, index) => {
84
+ if (index >= middlewares2.length) {
85
+ return executeRequest();
904
86
  }
905
- });
906
- e.subscribe(s);
87
+ const middleware = middlewares2[index];
88
+ if (middleware?.onRequest) {
89
+ return middleware.onRequest(request, () => executeWithMiddlewares(middlewares2, index + 1));
90
+ }
91
+ return executeWithMiddlewares(middlewares2, index + 1);
92
+ };
93
+ const res = executeWithMiddlewares(middlewares, 0);
94
+ return kind !== "subscription" ? firstValueFrom(res) : res;
907
95
  });
908
- }
909
- class We {
910
- constructor(t, r) {
911
- this.createClient = t, this.poolSize = r;
912
- }
913
- clients = [];
914
- currentIndex = 0;
915
- connect() {
916
- for (let t = 0; t < this.poolSize; t++)
917
- this.clients.push(this.createClient(`${t + 1}`));
918
- }
919
- get() {
920
- if (this.clients.length === 0)
921
- throw new Error("Connection pool is empty. Please call connect() first.");
922
- const t = this.clients[this.currentIndex];
923
- if (this.currentIndex = (this.currentIndex + 1) % this.poolSize, !t)
924
- throw new Error("No available WebSocket client");
925
- return t;
926
- }
927
- disconnect() {
928
- this.clients.forEach((t) => t.dispose()), this.clients = [];
929
- }
930
- }
931
- const ze = (e, t, r) => r((n, s, i) => {
932
- i && console.warn("options are not supported yet");
933
- const o = n.loc?.source.body;
934
- if (!o)
935
- throw new Error("No query provided");
936
- if (s && typeof s != "object")
937
- throw new Error("Variables must be an object");
938
- const h = n.definitions.find((y) => y.kind === "OperationDefinition");
939
- if (!h)
940
- throw new Error("No operation definition found");
941
- const b = h.operation, A = () => {
942
- const y = e();
943
- return new Re((P) => y.subscribe({ query: o, variables: s }, P));
944
- }, w = {
945
- kind: b,
946
- operationName: h.name?.value ?? "",
947
- query: o,
948
- variables: s || {}
949
- }, E = (y, P) => {
950
- if (P >= y.length)
951
- return A();
952
- const m = y[P];
953
- return m?.onRequest ? m.onRequest(w, () => E(y, P + 1)) : E(y, P + 1);
954
- }, l = E(t, 0);
955
- return b !== "subscription" ? je(l) : l;
956
- });
957
- class Be {
96
+ };
97
+
98
+ // src/client.ts
99
+ var ContelloSdkClient = class {
958
100
  _pool;
959
101
  _sdk;
960
- constructor(t, r) {
961
- const { url: n, project: s, token: i, client: o, pooling: h } = r, b = `${n}/graphql/projects/${s}`.replace(/^http/i, "ws");
962
- this._pool = new We(
963
- (A) => {
964
- const w = Object.freeze({ connectionId: A, websocketUrl: b });
965
- return we({
966
- url: b,
967
- connectionParams: { authorization: `Bearer ${i}` },
968
- lazy: !1,
102
+ constructor(getSdk, params) {
103
+ const { url, project, token, client, pooling } = params;
104
+ const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
105
+ this._pool = new ConnectionPool(
106
+ (id) => {
107
+ const context = Object.freeze({ connectionId: id, websocketUrl });
108
+ return createClient({
109
+ url: websocketUrl,
110
+ connectionParams: { authorization: `Bearer ${token}` },
111
+ lazy: false,
969
112
  keepAlive: 3e4,
970
- retryAttempts: o?.retryAttempts ?? 3,
971
- shouldRetry: () => !0,
972
- jsonMessageReplacer: (E, l) => {
973
- if (!E) {
974
- let y = l;
975
- for (const P of r.middlewares ?? [])
976
- P.onOutgoingMessage && (y = P.onOutgoingMessage(y));
977
- return y;
113
+ retryAttempts: client?.retryAttempts ?? 3,
114
+ shouldRetry: () => true,
115
+ jsonMessageReplacer: (key, value) => {
116
+ if (!key) {
117
+ let message = value;
118
+ for (const middleware of params.middlewares ?? []) {
119
+ if (middleware.onOutgoingMessage) {
120
+ message = middleware.onOutgoingMessage(message);
121
+ }
122
+ }
123
+ return message;
978
124
  }
979
- return l;
125
+ return value;
980
126
  },
981
- ...o?.onError ? { onNonLazyError: (E) => o.onError(w, E) } : {},
127
+ ...client?.onError ? { onNonLazyError: (e) => client.onError(context, e) } : {},
982
128
  on: {
983
- ...o?.onError ? { error: (E) => o.onError(w, E) } : {},
984
- ...o?.onConnected ? { connected: () => o.onConnected(w) } : {},
985
- ...o?.onClosed ? { closed: () => o.onClosed(w) } : {},
986
- ...o?.onConnecting ? { connecting: () => o.onConnecting(w) } : {},
987
- ...o?.onOpened ? { opened: () => o.onOpened(w) } : {},
988
- ...o?.onMessage ? { message: (E) => o.onMessage(w, E) } : {},
989
- ...o?.onPing ? { ping: () => o.onPing(w) } : {},
990
- ...o?.onPong ? { pong: () => o.onPong(w) } : {}
129
+ ...client?.onError ? { error: (e) => client.onError(context, e) } : {},
130
+ ...client?.onConnected ? { connected: () => client.onConnected(context) } : {},
131
+ ...client?.onClosed ? { closed: () => client.onClosed(context) } : {},
132
+ ...client?.onConnecting ? { connecting: () => client.onConnecting(context) } : {},
133
+ ...client?.onOpened ? { opened: () => client.onOpened(context) } : {},
134
+ ...client?.onMessage ? { message: (m) => client.onMessage(context, m) } : {},
135
+ ...client?.onPing ? { ping: () => client.onPing(context) } : {},
136
+ ...client?.onPong ? { pong: () => client.onPong(context) } : {}
991
137
  }
992
138
  });
993
139
  },
994
- h?.enabled === !1 ? 1 : h?.size ?? 5
995
- ), this._sdk = { sdk: ze(() => this._pool.get(), r.middlewares ?? [], t) };
140
+ pooling?.enabled === false ? 1 : pooling?.size ?? 5
141
+ );
142
+ this._sdk = { sdk: createSdk(() => this._pool.get(), params.middlewares ?? [], getSdk) };
996
143
  }
997
144
  get sdk() {
998
145
  return this._sdk.sdk;
999
146
  }
1000
147
  async connect() {
1001
- this._pool.connect();
148
+ await this._pool.connect();
1002
149
  }
1003
150
  async disconnect() {
1004
- this._pool.disconnect();
151
+ await this._pool.disconnect();
1005
152
  }
1006
- }
153
+ };
1007
154
  export {
1008
- Be as ContelloSdkClient
155
+ ContelloSdkClient
1009
156
  };