@contello/client 2.2.1 → 2.2.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
@@ -89,11 +89,11 @@ async function* asyncKeepalive(factory, signal) {
89
89
  attempt = 0;
90
90
  }
91
91
  attempt = 0;
92
- } catch (err) {
92
+ } catch (error) {
93
93
  if (signal?.aborted) {
94
94
  return;
95
95
  }
96
- void err;
96
+ void error;
97
97
  await exponentialBackoffWithSignal(attempt, signal);
98
98
  attempt++;
99
99
  }
@@ -155,6 +155,32 @@ function decorateMessage(message) {
155
155
 
156
156
  // src/http.ts
157
157
  import { Agent, request as undiciRequest } from "undici";
158
+ var SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
159
+ var FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
160
+ "content-type",
161
+ "content-length",
162
+ "content-range",
163
+ "content-encoding",
164
+ "accept-ranges",
165
+ "cache-control",
166
+ "etag",
167
+ "last-modified",
168
+ "expires",
169
+ "age"
170
+ ]);
171
+ function assertSafeSegment(segment, kind) {
172
+ if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") {
173
+ throw new Error(`invalid ${kind}`);
174
+ }
175
+ }
176
+ function assertSafeAssetPath(path, kind) {
177
+ if (path === "") {
178
+ throw new Error(`invalid ${kind}`);
179
+ }
180
+ for (const segment of path.split("/")) {
181
+ assertSafeSegment(segment, kind);
182
+ }
183
+ }
158
184
  function createHttpAgent(options) {
159
185
  return new Agent({
160
186
  pipelining: options?.pipelining ?? 10,
@@ -166,6 +192,7 @@ function createHttpAgent(options) {
166
192
  });
167
193
  }
168
194
  async function downloadFile(agent, url, token, fileId) {
195
+ assertSafeSegment(fileId, "file id");
169
196
  const response = await undiciRequest(`${url}/api/v1/assets/files/${fileId}`, {
170
197
  headers: { token },
171
198
  dispatcher: agent
@@ -184,6 +211,7 @@ async function downloadFile(agent, url, token, fileId) {
184
211
  };
185
212
  }
186
213
  async function proxyHls(agent, url, token, path, signal) {
214
+ assertSafeAssetPath(path, "hls path");
187
215
  const response = await undiciRequest(`${url}/api/v1/assets/video/hls/${path}`, {
188
216
  headers: { token },
189
217
  dispatcher: agent,
@@ -194,9 +222,12 @@ async function proxyHls(agent, url, token, path, signal) {
194
222
  function buildProxyResult(response, signal) {
195
223
  const headers = new Headers();
196
224
  for (const [key, value] of Object.entries(response.headers)) {
225
+ if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {
226
+ continue;
227
+ }
197
228
  if (Array.isArray(value)) {
198
229
  for (const v of value) headers.append(key, v);
199
- } else if (value != null) {
230
+ } else if (value !== null && value !== void 0) {
200
231
  headers.set(key, String(value));
201
232
  }
202
233
  }
@@ -280,42 +311,66 @@ async function ping(execute) {
280
311
  }
281
312
 
282
313
  // src/pool.ts
314
+ var DEFAULT_CONNECT_TIMEOUT = 1e4;
283
315
  var ConnectionPool = class {
284
- constructor(createClient2, poolSize) {
285
- this.createClient = createClient2;
286
- this.poolSize = poolSize;
316
+ constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
317
+ this._createClient = _createClient;
318
+ this._poolSize = _poolSize;
319
+ this._connectTimeout = _connectTimeout;
287
320
  }
288
- clients = [];
289
- currentIndex = 0;
321
+ _clients = [];
322
+ _connected = [];
323
+ _currentIndex = 0;
290
324
  async connect() {
291
- const connected = [];
292
- for (let i = 0; i < this.poolSize; i++) {
293
- const client = this.createClient(`${i + 1}`);
294
- this.clients.push(client);
295
- connected.push(
325
+ const ready = [];
326
+ for (let i = 0; i < this._poolSize; i++) {
327
+ const index = i;
328
+ const client = this._createClient(`${i + 1}`);
329
+ this._clients.push(client);
330
+ this._connected.push(false);
331
+ client.on("connected", () => {
332
+ this._connected[index] = true;
333
+ });
334
+ client.on("closed", () => {
335
+ this._connected[index] = false;
336
+ });
337
+ ready.push(
296
338
  new Promise((resolve) => {
297
- const unsubscribe = client.on("connected", () => {
298
- unsubscribe();
339
+ let settled = false;
340
+ const done = () => {
341
+ if (settled) {
342
+ return;
343
+ }
344
+ settled = true;
345
+ offConnected();
346
+ clearTimeout(timer);
299
347
  resolve();
300
- });
348
+ };
349
+ const offConnected = client.on("connected", done);
350
+ const timer = setTimeout(done, this._connectTimeout);
351
+ timer.unref?.();
301
352
  })
302
353
  );
303
354
  }
304
- await Promise.all(connected);
355
+ await Promise.all(ready);
305
356
  }
306
357
  get() {
307
- if (this.clients.length === 0) {
358
+ if (this._clients.length === 0) {
308
359
  throw new Error("@contello/client: connection pool is empty \u2014 call client.init() first");
309
360
  }
310
- const client = this.clients[this.currentIndex];
311
- this.currentIndex = (this.currentIndex + 1) % this.poolSize;
312
- if (!client) {
313
- throw new Error("No available WebSocket client");
361
+ for (let i = 0; i < this._clients.length; i++) {
362
+ const index = (this._currentIndex + i) % this._clients.length;
363
+ if (this._connected[index]) {
364
+ this._currentIndex = (index + 1) % this._clients.length;
365
+ return this._clients[index];
366
+ }
314
367
  }
368
+ const client = this._clients[this._currentIndex];
369
+ this._currentIndex = (this._currentIndex + 1) % this._clients.length;
315
370
  return client;
316
371
  }
317
372
  async disconnect() {
318
- const closed = this.clients.map(
373
+ const closed = this._clients.map(
319
374
  (client) => new Promise((resolve) => {
320
375
  const unsubscribe = client.on("closed", () => {
321
376
  unsubscribe();
@@ -324,7 +379,9 @@ var ConnectionPool = class {
324
379
  client.dispose();
325
380
  })
326
381
  );
327
- this.clients = [];
382
+ this._clients = [];
383
+ this._connected = [];
384
+ this._currentIndex = 0;
328
385
  await Promise.all(closed);
329
386
  }
330
387
  };
@@ -427,11 +484,7 @@ function transformVariables(value) {
427
484
  function buildRpc(operations, subscribe) {
428
485
  const rpc = {};
429
486
  for (const [name, def] of Object.entries(operations)) {
430
- if (def.kind === "subscription") {
431
- rpc[name] = (variables) => subscribe(def.document, transformVariables(variables));
432
- } else {
433
- rpc[name] = (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
434
- }
487
+ rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
435
488
  }
436
489
  return rpc;
437
490
  }
@@ -441,16 +494,21 @@ var cache = /* @__PURE__ */ new WeakMap();
441
494
  function createSelection(source) {
442
495
  const spread = `{ ...${source.fragment} }`;
443
496
  switch (source.__cardinality) {
444
- case "singleton":
497
+ case "singleton": {
445
498
  return `subscription { source: ${source.subscription} ${spread} }`;
446
- case "entity":
499
+ }
500
+ case "entity": {
447
501
  return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
448
- case "route":
502
+ }
503
+ case "route": {
449
504
  return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
450
- case "asset":
505
+ }
506
+ case "asset": {
451
507
  return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
452
- case "i18nMessage":
508
+ }
509
+ case "i18nMessage": {
453
510
  return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
511
+ }
454
512
  }
455
513
  }
456
514
  function createSourceSubscription(source) {
@@ -471,12 +529,13 @@ function createSources(sources, subscribe) {
471
529
  const def = source;
472
530
  const doc = createSourceSubscription(def);
473
531
  switch (def.__cardinality) {
474
- case "singleton":
532
+ case "singleton": {
475
533
  out[name] = {
476
534
  fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
477
535
  };
478
536
  break;
479
- case "entity":
537
+ }
538
+ case "entity": {
480
539
  out[name] = {
481
540
  fetch: (vars) => wrap(
482
541
  `source:${name}`,
@@ -489,7 +548,8 @@ function createSources(sources, subscribe) {
489
548
  )
490
549
  };
491
550
  break;
492
- case "route":
551
+ }
552
+ case "route": {
493
553
  out[name] = {
494
554
  fetch: (vars) => wrap(
495
555
  `source:${name}`,
@@ -502,7 +562,8 @@ function createSources(sources, subscribe) {
502
562
  )
503
563
  };
504
564
  break;
505
- case "asset":
565
+ }
566
+ case "asset": {
506
567
  out[name] = {
507
568
  fetch: (vars) => wrap(
508
569
  `source:${name}`,
@@ -515,7 +576,8 @@ function createSources(sources, subscribe) {
515
576
  )
516
577
  };
517
578
  break;
518
- case "i18nMessage":
579
+ }
580
+ case "i18nMessage": {
519
581
  out[name] = {
520
582
  fetch: (vars) => wrap(
521
583
  `source:${name}`,
@@ -531,6 +593,7 @@ function createSources(sources, subscribe) {
531
593
  )
532
594
  };
533
595
  break;
596
+ }
534
597
  }
535
598
  }
536
599
  return out;
@@ -563,16 +626,24 @@ function deriveModel(typename) {
563
626
  return void 0;
564
627
  }
565
628
  function transformResponse(data) {
566
- if (data === null || data === void 0 || typeof data !== "object") {
567
- return data;
629
+ transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
630
+ return data;
631
+ }
632
+ function transformNode(value, flatMap, seen) {
633
+ if (!value || typeof value !== "object") {
634
+ return;
635
+ }
636
+ if (seen.has(value)) {
637
+ return;
568
638
  }
569
- if (Array.isArray(data)) {
570
- for (const item of data) {
571
- transformResponse(item);
639
+ seen.add(value);
640
+ if (Array.isArray(value)) {
641
+ for (const item of value) {
642
+ transformNode(item, flatMap, seen);
572
643
  }
573
- return data;
644
+ return;
574
645
  }
575
- const obj = data;
646
+ const obj = value;
576
647
  const typename = obj["__typename"];
577
648
  if (typeof typename === "string") {
578
649
  const model = deriveModel(typename);
@@ -580,77 +651,56 @@ function transformResponse(data) {
580
651
  obj["__model"] = model;
581
652
  }
582
653
  }
583
- const flatKeys = Object.keys(obj).filter((k) => k.startsWith(FLAT_PREFIX));
584
- for (const flatKey of flatKeys) {
585
- const fieldKey = flatKey.slice(FLAT_PREFIX.length);
586
- const flatArray = obj[flatKey];
587
- const refArray = obj[fieldKey];
588
- if (!flatArray || !refArray) {
654
+ let ownMap;
655
+ for (const key of Object.keys(obj)) {
656
+ if (!key.startsWith(FLAT_PREFIX)) {
657
+ continue;
658
+ }
659
+ const flatArray = obj[key];
660
+ delete obj[key];
661
+ if (!flatArray) {
589
662
  continue;
590
663
  }
591
- const flatMap = /* @__PURE__ */ new Map();
664
+ if (!ownMap) {
665
+ ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
666
+ }
592
667
  for (const component of flatArray) {
593
668
  if (component._flatId) {
594
- flatMap.set(component._flatId, component);
669
+ ownMap.set(component._flatId, component);
595
670
  }
596
671
  }
597
- obj[fieldKey] = resolveRefs(refArray, flatMap);
598
- delete obj[flatKey];
599
672
  }
673
+ const resolveMap = ownMap ?? flatMap;
600
674
  for (const key of Object.keys(obj)) {
601
675
  if (key.startsWith(LDT_PREFIX)) {
602
- const original = key.slice(LDT_PREFIX.length);
603
- obj[original] = decodeValue(obj[key], decodeLocalDateTime);
676
+ obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);
604
677
  delete obj[key];
605
- } else if (key.startsWith(LD_PREFIX)) {
606
- const original = key.slice(LD_PREFIX.length);
607
- obj[original] = decodeValue(obj[key], decodeLocalDate);
678
+ continue;
679
+ }
680
+ if (key.startsWith(LD_PREFIX)) {
681
+ obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);
608
682
  delete obj[key];
683
+ continue;
609
684
  }
610
- }
611
- for (const key of Object.keys(obj)) {
612
- const value = obj[key];
613
- if (value && typeof value === "object") {
614
- if (Array.isArray(value)) {
615
- for (const item of value) {
616
- if (item && typeof item === "object") {
617
- transformResponse(item);
618
- }
619
- }
620
- } else {
621
- transformResponse(value);
622
- }
685
+ const inner = obj[key];
686
+ if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
687
+ obj[key] = resolveRefs(inner, resolveMap);
623
688
  }
689
+ transformNode(obj[key], resolveMap, seen);
624
690
  }
625
- return data;
626
691
  }
627
692
  function resolveRefs(refs, flatMap) {
628
- return refs.flatMap((ref) => {
629
- if (!ref._flatId) return [];
630
- const component = flatMap.get(ref._flatId);
631
- if (!component) return [];
632
- resolveNestedRefs(component, flatMap);
633
- transformResponse(component);
634
- return [component];
635
- });
636
- }
637
- function resolveNestedRefs(value, flatMap) {
638
- if (!value || typeof value !== "object") return;
639
- if (Array.isArray(value)) {
640
- for (const item of value) {
641
- resolveNestedRefs(item, flatMap);
693
+ const resolved = [];
694
+ for (const ref of refs) {
695
+ if (!ref._flatId) {
696
+ continue;
642
697
  }
643
- return;
644
- }
645
- const obj = value;
646
- for (const key of Object.keys(obj)) {
647
- const inner = obj[key];
648
- if (Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
649
- obj[key] = resolveRefs(inner, flatMap);
650
- } else if (inner && typeof inner === "object") {
651
- resolveNestedRefs(inner, flatMap);
698
+ const component = flatMap.get(ref._flatId);
699
+ if (component) {
700
+ resolved.push(component);
652
701
  }
653
702
  }
703
+ return resolved;
654
704
  }
655
705
 
656
706
  // src/upload.ts
@@ -684,24 +734,42 @@ function upload(url, project, token, data, meta, options) {
684
734
  }
685
735
  ws.send(JSON.stringify({ type: "done" }));
686
736
  }
737
+ const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
738
+ function waitForBufferedDrain() {
739
+ return new Promise((resolveDrain, rejectDrain) => {
740
+ const check = () => {
741
+ if (options?.abort?.aborted) {
742
+ rejectDrain(new Error("upload aborted"));
743
+ return;
744
+ }
745
+ if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
746
+ resolveDrain();
747
+ return;
748
+ }
749
+ setTimeout(check, 50);
750
+ };
751
+ check();
752
+ });
753
+ }
687
754
  async function sendStream(stream) {
688
755
  const reader = stream.getReader();
689
756
  try {
690
757
  while (true) {
691
758
  const { done: streamDone, value } = await reader.read();
692
759
  if (streamDone) break;
760
+ await waitForBufferedDrain();
693
761
  ws.send(value);
694
762
  }
695
763
  ws.send(JSON.stringify({ type: "done" }));
696
- } catch (err) {
697
- reject(err);
764
+ } catch (error) {
765
+ reject(error);
698
766
  ws.close();
699
767
  }
700
768
  }
701
769
  ws.addEventListener("open", () => {
702
770
  const initFrame = {
703
771
  type: "init",
704
- metadata: { ...meta, ...size !== void 0 ? { size } : {}, projectRef: project },
772
+ metadata: { ...meta, ...size === void 0 ? {} : { size }, projectRef: project },
705
773
  token
706
774
  };
707
775
  ws.send(JSON.stringify(initFrame));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contello/client",
3
- "version": "2.2.1",
3
+ "version": "2.2.2",
4
4
  "description": "GraphQL client for Contello CMS with WebSocket transport, connection pooling, and built-in codegen",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "scripts": {
36
36
  "build": "tsup",
37
- "lint": "eslint .",
37
+ "lint": "eslint . --cache",
38
38
  "lint:fix": "eslint . --fix",
39
39
  "typecheck": "tsc --noEmit"
40
40
  }