@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.cjs CHANGED
@@ -135,11 +135,11 @@ async function* asyncKeepalive(factory, signal) {
135
135
  attempt = 0;
136
136
  }
137
137
  attempt = 0;
138
- } catch (err) {
138
+ } catch (error) {
139
139
  if (signal?.aborted) {
140
140
  return;
141
141
  }
142
- void err;
142
+ void error;
143
143
  await exponentialBackoffWithSignal(attempt, signal);
144
144
  attempt++;
145
145
  }
@@ -201,6 +201,32 @@ function decorateMessage(message) {
201
201
 
202
202
  // src/http.ts
203
203
  var import_undici = require("undici");
204
+ var SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
205
+ var FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
206
+ "content-type",
207
+ "content-length",
208
+ "content-range",
209
+ "content-encoding",
210
+ "accept-ranges",
211
+ "cache-control",
212
+ "etag",
213
+ "last-modified",
214
+ "expires",
215
+ "age"
216
+ ]);
217
+ function assertSafeSegment(segment, kind) {
218
+ if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") {
219
+ throw new Error(`invalid ${kind}`);
220
+ }
221
+ }
222
+ function assertSafeAssetPath(path, kind) {
223
+ if (path === "") {
224
+ throw new Error(`invalid ${kind}`);
225
+ }
226
+ for (const segment of path.split("/")) {
227
+ assertSafeSegment(segment, kind);
228
+ }
229
+ }
204
230
  function createHttpAgent(options) {
205
231
  return new import_undici.Agent({
206
232
  pipelining: options?.pipelining ?? 10,
@@ -212,6 +238,7 @@ function createHttpAgent(options) {
212
238
  });
213
239
  }
214
240
  async function downloadFile(agent, url, token, fileId) {
241
+ assertSafeSegment(fileId, "file id");
215
242
  const response = await (0, import_undici.request)(`${url}/api/v1/assets/files/${fileId}`, {
216
243
  headers: { token },
217
244
  dispatcher: agent
@@ -230,6 +257,7 @@ async function downloadFile(agent, url, token, fileId) {
230
257
  };
231
258
  }
232
259
  async function proxyHls(agent, url, token, path, signal) {
260
+ assertSafeAssetPath(path, "hls path");
233
261
  const response = await (0, import_undici.request)(`${url}/api/v1/assets/video/hls/${path}`, {
234
262
  headers: { token },
235
263
  dispatcher: agent,
@@ -240,9 +268,12 @@ async function proxyHls(agent, url, token, path, signal) {
240
268
  function buildProxyResult(response, signal) {
241
269
  const headers = new Headers();
242
270
  for (const [key, value] of Object.entries(response.headers)) {
271
+ if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {
272
+ continue;
273
+ }
243
274
  if (Array.isArray(value)) {
244
275
  for (const v of value) headers.append(key, v);
245
- } else if (value != null) {
276
+ } else if (value !== null && value !== void 0) {
246
277
  headers.set(key, String(value));
247
278
  }
248
279
  }
@@ -326,42 +357,66 @@ async function ping(execute) {
326
357
  }
327
358
 
328
359
  // src/pool.ts
360
+ var DEFAULT_CONNECT_TIMEOUT = 1e4;
329
361
  var ConnectionPool = class {
330
- constructor(createClient2, poolSize) {
331
- this.createClient = createClient2;
332
- this.poolSize = poolSize;
362
+ constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
363
+ this._createClient = _createClient;
364
+ this._poolSize = _poolSize;
365
+ this._connectTimeout = _connectTimeout;
333
366
  }
334
- clients = [];
335
- currentIndex = 0;
367
+ _clients = [];
368
+ _connected = [];
369
+ _currentIndex = 0;
336
370
  async connect() {
337
- const connected = [];
338
- for (let i = 0; i < this.poolSize; i++) {
339
- const client = this.createClient(`${i + 1}`);
340
- this.clients.push(client);
341
- connected.push(
371
+ const ready = [];
372
+ for (let i = 0; i < this._poolSize; i++) {
373
+ const index = i;
374
+ const client = this._createClient(`${i + 1}`);
375
+ this._clients.push(client);
376
+ this._connected.push(false);
377
+ client.on("connected", () => {
378
+ this._connected[index] = true;
379
+ });
380
+ client.on("closed", () => {
381
+ this._connected[index] = false;
382
+ });
383
+ ready.push(
342
384
  new Promise((resolve) => {
343
- const unsubscribe = client.on("connected", () => {
344
- unsubscribe();
385
+ let settled = false;
386
+ const done = () => {
387
+ if (settled) {
388
+ return;
389
+ }
390
+ settled = true;
391
+ offConnected();
392
+ clearTimeout(timer);
345
393
  resolve();
346
- });
394
+ };
395
+ const offConnected = client.on("connected", done);
396
+ const timer = setTimeout(done, this._connectTimeout);
397
+ timer.unref?.();
347
398
  })
348
399
  );
349
400
  }
350
- await Promise.all(connected);
401
+ await Promise.all(ready);
351
402
  }
352
403
  get() {
353
- if (this.clients.length === 0) {
404
+ if (this._clients.length === 0) {
354
405
  throw new Error("@contello/client: connection pool is empty \u2014 call client.init() first");
355
406
  }
356
- const client = this.clients[this.currentIndex];
357
- this.currentIndex = (this.currentIndex + 1) % this.poolSize;
358
- if (!client) {
359
- throw new Error("No available WebSocket client");
407
+ for (let i = 0; i < this._clients.length; i++) {
408
+ const index = (this._currentIndex + i) % this._clients.length;
409
+ if (this._connected[index]) {
410
+ this._currentIndex = (index + 1) % this._clients.length;
411
+ return this._clients[index];
412
+ }
360
413
  }
414
+ const client = this._clients[this._currentIndex];
415
+ this._currentIndex = (this._currentIndex + 1) % this._clients.length;
361
416
  return client;
362
417
  }
363
418
  async disconnect() {
364
- const closed = this.clients.map(
419
+ const closed = this._clients.map(
365
420
  (client) => new Promise((resolve) => {
366
421
  const unsubscribe = client.on("closed", () => {
367
422
  unsubscribe();
@@ -370,7 +425,9 @@ var ConnectionPool = class {
370
425
  client.dispose();
371
426
  })
372
427
  );
373
- this.clients = [];
428
+ this._clients = [];
429
+ this._connected = [];
430
+ this._currentIndex = 0;
374
431
  await Promise.all(closed);
375
432
  }
376
433
  };
@@ -473,11 +530,7 @@ function transformVariables(value) {
473
530
  function buildRpc(operations, subscribe) {
474
531
  const rpc = {};
475
532
  for (const [name, def] of Object.entries(operations)) {
476
- if (def.kind === "subscription") {
477
- rpc[name] = (variables) => subscribe(def.document, transformVariables(variables));
478
- } else {
479
- rpc[name] = (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
480
- }
533
+ rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
481
534
  }
482
535
  return rpc;
483
536
  }
@@ -487,16 +540,21 @@ var cache = /* @__PURE__ */ new WeakMap();
487
540
  function createSelection(source) {
488
541
  const spread = `{ ...${source.fragment} }`;
489
542
  switch (source.__cardinality) {
490
- case "singleton":
543
+ case "singleton": {
491
544
  return `subscription { source: ${source.subscription} ${spread} }`;
492
- case "entity":
545
+ }
546
+ case "entity": {
493
547
  return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
494
- case "route":
548
+ }
549
+ case "route": {
495
550
  return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
496
- case "asset":
551
+ }
552
+ case "asset": {
497
553
  return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
498
- case "i18nMessage":
554
+ }
555
+ case "i18nMessage": {
499
556
  return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
557
+ }
500
558
  }
501
559
  }
502
560
  function createSourceSubscription(source) {
@@ -517,12 +575,13 @@ function createSources(sources, subscribe) {
517
575
  const def = source;
518
576
  const doc = createSourceSubscription(def);
519
577
  switch (def.__cardinality) {
520
- case "singleton":
578
+ case "singleton": {
521
579
  out[name] = {
522
580
  fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
523
581
  };
524
582
  break;
525
- case "entity":
583
+ }
584
+ case "entity": {
526
585
  out[name] = {
527
586
  fetch: (vars) => wrap(
528
587
  `source:${name}`,
@@ -535,7 +594,8 @@ function createSources(sources, subscribe) {
535
594
  )
536
595
  };
537
596
  break;
538
- case "route":
597
+ }
598
+ case "route": {
539
599
  out[name] = {
540
600
  fetch: (vars) => wrap(
541
601
  `source:${name}`,
@@ -548,7 +608,8 @@ function createSources(sources, subscribe) {
548
608
  )
549
609
  };
550
610
  break;
551
- case "asset":
611
+ }
612
+ case "asset": {
552
613
  out[name] = {
553
614
  fetch: (vars) => wrap(
554
615
  `source:${name}`,
@@ -561,7 +622,8 @@ function createSources(sources, subscribe) {
561
622
  )
562
623
  };
563
624
  break;
564
- case "i18nMessage":
625
+ }
626
+ case "i18nMessage": {
565
627
  out[name] = {
566
628
  fetch: (vars) => wrap(
567
629
  `source:${name}`,
@@ -577,6 +639,7 @@ function createSources(sources, subscribe) {
577
639
  )
578
640
  };
579
641
  break;
642
+ }
580
643
  }
581
644
  }
582
645
  return out;
@@ -609,16 +672,24 @@ function deriveModel(typename) {
609
672
  return void 0;
610
673
  }
611
674
  function transformResponse(data) {
612
- if (data === null || data === void 0 || typeof data !== "object") {
613
- return data;
675
+ transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
676
+ return data;
677
+ }
678
+ function transformNode(value, flatMap, seen) {
679
+ if (!value || typeof value !== "object") {
680
+ return;
681
+ }
682
+ if (seen.has(value)) {
683
+ return;
614
684
  }
615
- if (Array.isArray(data)) {
616
- for (const item of data) {
617
- transformResponse(item);
685
+ seen.add(value);
686
+ if (Array.isArray(value)) {
687
+ for (const item of value) {
688
+ transformNode(item, flatMap, seen);
618
689
  }
619
- return data;
690
+ return;
620
691
  }
621
- const obj = data;
692
+ const obj = value;
622
693
  const typename = obj["__typename"];
623
694
  if (typeof typename === "string") {
624
695
  const model = deriveModel(typename);
@@ -626,77 +697,56 @@ function transformResponse(data) {
626
697
  obj["__model"] = model;
627
698
  }
628
699
  }
629
- const flatKeys = Object.keys(obj).filter((k) => k.startsWith(FLAT_PREFIX));
630
- for (const flatKey of flatKeys) {
631
- const fieldKey = flatKey.slice(FLAT_PREFIX.length);
632
- const flatArray = obj[flatKey];
633
- const refArray = obj[fieldKey];
634
- if (!flatArray || !refArray) {
700
+ let ownMap;
701
+ for (const key of Object.keys(obj)) {
702
+ if (!key.startsWith(FLAT_PREFIX)) {
703
+ continue;
704
+ }
705
+ const flatArray = obj[key];
706
+ delete obj[key];
707
+ if (!flatArray) {
635
708
  continue;
636
709
  }
637
- const flatMap = /* @__PURE__ */ new Map();
710
+ if (!ownMap) {
711
+ ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
712
+ }
638
713
  for (const component of flatArray) {
639
714
  if (component._flatId) {
640
- flatMap.set(component._flatId, component);
715
+ ownMap.set(component._flatId, component);
641
716
  }
642
717
  }
643
- obj[fieldKey] = resolveRefs(refArray, flatMap);
644
- delete obj[flatKey];
645
718
  }
719
+ const resolveMap = ownMap ?? flatMap;
646
720
  for (const key of Object.keys(obj)) {
647
721
  if (key.startsWith(LDT_PREFIX)) {
648
- const original = key.slice(LDT_PREFIX.length);
649
- obj[original] = decodeValue(obj[key], decodeLocalDateTime);
722
+ obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);
650
723
  delete obj[key];
651
- } else if (key.startsWith(LD_PREFIX)) {
652
- const original = key.slice(LD_PREFIX.length);
653
- obj[original] = decodeValue(obj[key], decodeLocalDate);
724
+ continue;
725
+ }
726
+ if (key.startsWith(LD_PREFIX)) {
727
+ obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);
654
728
  delete obj[key];
729
+ continue;
655
730
  }
656
- }
657
- for (const key of Object.keys(obj)) {
658
- const value = obj[key];
659
- if (value && typeof value === "object") {
660
- if (Array.isArray(value)) {
661
- for (const item of value) {
662
- if (item && typeof item === "object") {
663
- transformResponse(item);
664
- }
665
- }
666
- } else {
667
- transformResponse(value);
668
- }
731
+ const inner = obj[key];
732
+ if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
733
+ obj[key] = resolveRefs(inner, resolveMap);
669
734
  }
735
+ transformNode(obj[key], resolveMap, seen);
670
736
  }
671
- return data;
672
737
  }
673
738
  function resolveRefs(refs, flatMap) {
674
- return refs.flatMap((ref) => {
675
- if (!ref._flatId) return [];
676
- const component = flatMap.get(ref._flatId);
677
- if (!component) return [];
678
- resolveNestedRefs(component, flatMap);
679
- transformResponse(component);
680
- return [component];
681
- });
682
- }
683
- function resolveNestedRefs(value, flatMap) {
684
- if (!value || typeof value !== "object") return;
685
- if (Array.isArray(value)) {
686
- for (const item of value) {
687
- resolveNestedRefs(item, flatMap);
739
+ const resolved = [];
740
+ for (const ref of refs) {
741
+ if (!ref._flatId) {
742
+ continue;
688
743
  }
689
- return;
690
- }
691
- const obj = value;
692
- for (const key of Object.keys(obj)) {
693
- const inner = obj[key];
694
- if (Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
695
- obj[key] = resolveRefs(inner, flatMap);
696
- } else if (inner && typeof inner === "object") {
697
- resolveNestedRefs(inner, flatMap);
744
+ const component = flatMap.get(ref._flatId);
745
+ if (component) {
746
+ resolved.push(component);
698
747
  }
699
748
  }
749
+ return resolved;
700
750
  }
701
751
 
702
752
  // src/upload.ts
@@ -730,24 +780,42 @@ function upload(url, project, token, data, meta, options) {
730
780
  }
731
781
  ws.send(JSON.stringify({ type: "done" }));
732
782
  }
783
+ const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
784
+ function waitForBufferedDrain() {
785
+ return new Promise((resolveDrain, rejectDrain) => {
786
+ const check = () => {
787
+ if (options?.abort?.aborted) {
788
+ rejectDrain(new Error("upload aborted"));
789
+ return;
790
+ }
791
+ if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
792
+ resolveDrain();
793
+ return;
794
+ }
795
+ setTimeout(check, 50);
796
+ };
797
+ check();
798
+ });
799
+ }
733
800
  async function sendStream(stream) {
734
801
  const reader = stream.getReader();
735
802
  try {
736
803
  while (true) {
737
804
  const { done: streamDone, value } = await reader.read();
738
805
  if (streamDone) break;
806
+ await waitForBufferedDrain();
739
807
  ws.send(value);
740
808
  }
741
809
  ws.send(JSON.stringify({ type: "done" }));
742
- } catch (err) {
743
- reject(err);
810
+ } catch (error) {
811
+ reject(error);
744
812
  ws.close();
745
813
  }
746
814
  }
747
815
  ws.addEventListener("open", () => {
748
816
  const initFrame = {
749
817
  type: "init",
750
- metadata: { ...meta, ...size !== void 0 ? { size } : {}, projectRef: project },
818
+ metadata: { ...meta, ...size === void 0 ? {} : { size }, projectRef: project },
751
819
  token
752
820
  };
753
821
  ws.send(JSON.stringify(initFrame));