@contello/client 1.2.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,13 +31,120 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  ContelloClient: () => ContelloClient,
34
- createContelloClient: () => createContelloClient
34
+ asyncKeepalive: () => asyncKeepalive,
35
+ collectAsync: () => collectAsync,
36
+ createAsyncIterableSubject: () => createAsyncIterableSubject,
37
+ createContelloClient: () => createContelloClient,
38
+ createSourceSubscription: () => createSourceSubscription,
39
+ exponentialBackoff: () => exponentialBackoff,
40
+ filterAsync: () => filterAsync,
41
+ firstAsync: () => firstAsync,
42
+ mapAsync: () => mapAsync,
43
+ runWithBackoff: () => runWithBackoff
35
44
  });
36
45
  module.exports = __toCommonJS(index_exports);
37
46
 
38
47
  // src/client.ts
39
48
  var import_graphql_ws = require("graphql-ws");
40
- var import_rxjs2 = require("rxjs");
49
+
50
+ // src/async-iterable-utils.ts
51
+ var MAX_BACKOFF_MS = 3e4;
52
+ var JITTER_MIN_MS = 300;
53
+ var JITTER_MAX_MS = 3e3;
54
+ async function firstAsync(iter) {
55
+ const it = iter[Symbol.asyncIterator]();
56
+ try {
57
+ const result = await it.next();
58
+ if (result.done) {
59
+ throw new Error("firstAsync: async iterable completed without yielding a value");
60
+ }
61
+ return result.value;
62
+ } finally {
63
+ await it.return?.();
64
+ }
65
+ }
66
+ async function* mapAsync(iter, fn) {
67
+ for await (const value of iter) {
68
+ yield fn(value);
69
+ }
70
+ }
71
+ async function* filterAsync(iter, predicate) {
72
+ for await (const value of iter) {
73
+ if (predicate(value)) {
74
+ yield value;
75
+ }
76
+ }
77
+ }
78
+ async function collectAsync(iter) {
79
+ const out = [];
80
+ for await (const chunk of iter) {
81
+ out.push(...chunk);
82
+ }
83
+ return out;
84
+ }
85
+ function exponentialBackoff(attempt) {
86
+ const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
87
+ const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
88
+ return delay(base + jitter);
89
+ }
90
+ function delay(ms, signal) {
91
+ if (signal?.aborted) {
92
+ return Promise.reject(signal.reason);
93
+ }
94
+ return new Promise((resolve, reject) => {
95
+ const timer = setTimeout(() => {
96
+ signal?.removeEventListener("abort", onAbort);
97
+ resolve();
98
+ }, ms);
99
+ const onAbort = () => {
100
+ clearTimeout(timer);
101
+ reject(signal.reason);
102
+ };
103
+ signal?.addEventListener("abort", onAbort, { once: true });
104
+ });
105
+ }
106
+ async function runWithBackoff(fn, signal) {
107
+ let attempt = 0;
108
+ for (; ; ) {
109
+ if (signal?.aborted) {
110
+ throw signal.reason;
111
+ }
112
+ try {
113
+ await fn();
114
+ return;
115
+ } catch {
116
+ await exponentialBackoffWithSignal(attempt, signal);
117
+ attempt++;
118
+ }
119
+ }
120
+ }
121
+ function exponentialBackoffWithSignal(attempt, signal) {
122
+ const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
123
+ const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
124
+ return delay(base + jitter, signal);
125
+ }
126
+ async function* asyncKeepalive(factory, signal) {
127
+ let attempt = 0;
128
+ while (!signal?.aborted) {
129
+ try {
130
+ for await (const value of factory()) {
131
+ if (signal?.aborted) {
132
+ return;
133
+ }
134
+ yield value;
135
+ attempt = 0;
136
+ }
137
+ attempt = 0;
138
+ } catch (err) {
139
+ if (signal?.aborted) {
140
+ return;
141
+ }
142
+ void err;
143
+ await exponentialBackoffWithSignal(attempt, signal);
144
+ attempt++;
145
+ }
146
+ }
147
+ }
41
148
 
42
149
  // src/diagnostics.ts
43
150
  var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
@@ -268,9 +375,6 @@ var ConnectionPool = class {
268
375
  }
269
376
  };
270
377
 
271
- // src/rpc.ts
272
- var import_rxjs = require("rxjs");
273
-
274
378
  // src/transform-response.ts
275
379
  var FLAT_PREFIX = "_flat_";
276
380
  var MODEL_SUFFIXES = ["Entity", "Component"];
@@ -364,21 +468,86 @@ function resolveNestedRefs(value, flatMap) {
364
468
  }
365
469
 
366
470
  // src/rpc.ts
367
- function buildRpc(operations, client) {
471
+ function buildRpc(operations, subscribe) {
368
472
  const rpc = {};
369
473
  for (const [name, def] of Object.entries(operations)) {
370
474
  if (def.kind === "subscription") {
371
- rpc[name] = (variables) => client.subscribe(def.document, variables).pipe((0, import_rxjs.map)(transformResponse));
475
+ rpc[name] = (variables) => mapAsync(subscribe(def.document, variables), transformResponse);
372
476
  } else {
373
- rpc[name] = (variables) => wrap(
374
- `rpc:${name}`,
375
- () => (0, import_rxjs.firstValueFrom)(client.subscribe(def.document, variables).pipe((0, import_rxjs.map)(transformResponse)))
376
- );
477
+ rpc[name] = (variables) => wrap(`rpc:${name}`, () => firstAsync(mapAsync(subscribe(def.document, variables), transformResponse)));
377
478
  }
378
479
  }
379
480
  return rpc;
380
481
  }
381
482
 
483
+ // src/source-subscription.ts
484
+ var cache = /* @__PURE__ */ new WeakMap();
485
+ function createSelection(source) {
486
+ const spread = `{ ...${source.fragment} }`;
487
+ switch (source.__cardinality) {
488
+ case "singleton":
489
+ return `subscription { source: ${source.subscription} ${spread} }`;
490
+ case "entity":
491
+ return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
492
+ case "route":
493
+ case "asset":
494
+ return `subscription { source: ${source.subscription} ${spread} }`;
495
+ case "i18nMessage":
496
+ return `subscription($collection: String!) { source: ${source.subscription}(collectionReferenceName: $collection) ${spread} }`;
497
+ }
498
+ }
499
+ function createSourceSubscription(source) {
500
+ const cached = cache.get(source);
501
+ if (cached !== void 0) {
502
+ return cached;
503
+ }
504
+ const doc = `${source.document}
505
+ ${createSelection(source)}`;
506
+ cache.set(source, doc);
507
+ return doc;
508
+ }
509
+
510
+ // src/sources.ts
511
+ function createSources(sources, subscribe) {
512
+ const out = {};
513
+ for (const [name, source] of Object.entries(sources)) {
514
+ const def = source;
515
+ const doc = createSourceSubscription(def);
516
+ switch (def.__cardinality) {
517
+ case "singleton":
518
+ out[name] = {
519
+ fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
520
+ };
521
+ break;
522
+ case "entity":
523
+ out[name] = {
524
+ fetch: (vars) => wrap(
525
+ `source:${name}`,
526
+ () => firstAsync(mapAsync(subscribe(doc, { ids: vars?.ids }), (r) => r.source))
527
+ )
528
+ };
529
+ break;
530
+ case "route":
531
+ case "asset":
532
+ out[name] = {
533
+ fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
534
+ };
535
+ break;
536
+ case "i18nMessage":
537
+ out[name] = {
538
+ fetch: (vars) => wrap(
539
+ `source:${name}`,
540
+ () => firstAsync(
541
+ mapAsync(subscribe(doc, { collection: vars.collection }), (r) => r.source)
542
+ )
543
+ )
544
+ };
545
+ break;
546
+ }
547
+ }
548
+ return out;
549
+ }
550
+
382
551
  // src/upload.ts
383
552
  var DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
384
553
  function isUint8Array(data) {
@@ -464,23 +633,24 @@ function upload(url, project, token, data, meta, options) {
464
633
 
465
634
  // src/utils.ts
466
635
  var MAX_DELAY_MS = 3e4;
467
- var JITTER_MIN_MS = 300;
468
- var JITTER_MAX_MS = 3e3;
469
- function exponentialBackoff(retries) {
470
- const delay = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
471
- return new Promise((resolve) => setTimeout(resolve, delay));
636
+ var JITTER_MIN_MS2 = 300;
637
+ var JITTER_MAX_MS2 = 3e3;
638
+ function wsRetryWait(retries) {
639
+ const delay2 = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS2 - JITTER_MIN_MS2) + JITTER_MIN_MS2);
640
+ return new Promise((resolve) => setTimeout(resolve, delay2));
472
641
  }
473
642
 
474
643
  // src/client.ts
475
644
  var ContelloClient = class {
476
645
  _pool;
477
646
  _rpc;
647
+ _sources;
478
648
  _url;
479
649
  _project;
480
650
  _token;
481
651
  _agent;
482
652
  constructor(options) {
483
- const { url, project, token, operations, connections = 1, connectionEvents } = options;
653
+ const { url, project, token, schema, connections = 1, connectionEvents } = options;
484
654
  this._url = url;
485
655
  this._project = project;
486
656
  this._token = token;
@@ -512,7 +682,7 @@ var ContelloClient = class {
512
682
  lazy: false,
513
683
  keepAlive: 3e4,
514
684
  retryAttempts: Infinity,
515
- retryWait: exponentialBackoff,
685
+ retryWait: wsRetryWait,
516
686
  shouldRetry: () => true,
517
687
  jsonMessageReplacer: (key, value) => {
518
688
  if (!key) {
@@ -542,14 +712,21 @@ var ContelloClient = class {
542
712
  }
543
713
  });
544
714
  }, connections);
545
- this._rpc = operations ? buildRpc(operations, this) : void 0;
715
+ this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
716
+ this._sources = schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : void 0;
546
717
  }
547
718
  get rpc() {
548
719
  if (!this._rpc) {
549
- throw new Error("@contello/client: .rpc accessed without operations");
720
+ throw new Error("@contello/client: .rpc accessed without a schema containing operations");
550
721
  }
551
722
  return this._rpc;
552
723
  }
724
+ get sources() {
725
+ if (!this._sources) {
726
+ throw new Error("@contello/client: .sources accessed without a schema containing sources");
727
+ }
728
+ return this._sources;
729
+ }
553
730
  async init() {
554
731
  await this._pool.connect();
555
732
  }
@@ -558,13 +735,83 @@ var ContelloClient = class {
558
735
  await this._agent.close();
559
736
  }
560
737
  async ping() {
561
- return ping((query) => (0, import_rxjs2.firstValueFrom)(this.subscribe(query)));
738
+ return ping((query) => firstAsync(this.subscribe(query)));
562
739
  }
740
+ /**
741
+ * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
742
+ * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
743
+ * down when the iterator is returned (`break`, error, or explicit stop).
744
+ */
563
745
  subscribe(query, variables) {
564
- const wsClient = this._pool.get();
565
- return new import_rxjs2.Observable((obs) => wsClient.subscribe({ query, variables }, obs)).pipe(
566
- (0, import_rxjs2.map)((r) => r.data)
567
- );
746
+ const pool = this._pool;
747
+ return {
748
+ [Symbol.asyncIterator]() {
749
+ const wsClient = pool.get();
750
+ const queue = [];
751
+ let pending;
752
+ let done = false;
753
+ let error;
754
+ const unsubscribe = wsClient.subscribe(
755
+ { query, variables },
756
+ {
757
+ next(msg) {
758
+ const value = msg.data;
759
+ if (value === void 0 || value === null) {
760
+ return;
761
+ }
762
+ if (pending) {
763
+ const p = pending;
764
+ pending = void 0;
765
+ p.resolve({ value, done: false });
766
+ } else {
767
+ queue.push(value);
768
+ }
769
+ },
770
+ error(err) {
771
+ done = true;
772
+ error = err;
773
+ if (pending) {
774
+ const p = pending;
775
+ pending = void 0;
776
+ p.reject(err);
777
+ }
778
+ },
779
+ complete() {
780
+ done = true;
781
+ if (pending) {
782
+ const p = pending;
783
+ pending = void 0;
784
+ p.resolve({ value: void 0, done: true });
785
+ }
786
+ }
787
+ }
788
+ );
789
+ return {
790
+ next() {
791
+ if (queue.length > 0) {
792
+ return Promise.resolve({ value: queue.shift(), done: false });
793
+ }
794
+ if (error !== void 0) {
795
+ return Promise.reject(error);
796
+ }
797
+ if (done) {
798
+ return Promise.resolve({ value: void 0, done: true });
799
+ }
800
+ return new Promise((resolve, reject) => {
801
+ pending = { resolve, reject };
802
+ });
803
+ },
804
+ return() {
805
+ unsubscribe();
806
+ return Promise.resolve({ value: void 0, done: true });
807
+ },
808
+ throw(err) {
809
+ unsubscribe();
810
+ return Promise.reject(err);
811
+ }
812
+ };
813
+ }
814
+ };
568
815
  }
569
816
  download(fileId) {
570
817
  return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
@@ -579,14 +826,138 @@ var ContelloClient = class {
579
826
  );
580
827
  }
581
828
  execute(query, variables) {
582
- return wrap("@contello/client:execute", () => (0, import_rxjs2.firstValueFrom)(this.subscribe(query, variables)));
829
+ return wrap("@contello/client:execute", () => firstAsync(this.subscribe(query, variables)));
583
830
  }
584
831
  };
585
832
  function createContelloClient(options) {
586
833
  return new ContelloClient(options);
587
834
  }
835
+
836
+ // src/async-iterable-subject.ts
837
+ function createAsyncIterableSubject() {
838
+ const consumers = /* @__PURE__ */ new Set();
839
+ let status = { state: "open" };
840
+ const next = (value) => {
841
+ if (status.state !== "open") {
842
+ return;
843
+ }
844
+ for (const consumer of consumers) {
845
+ if (consumer.kind === "listener") {
846
+ consumer.next?.(value);
847
+ } else if (consumer.pending) {
848
+ const p = consumer.pending;
849
+ consumer.pending = void 0;
850
+ p.resolve({ value, done: false });
851
+ } else {
852
+ consumer.queue.push(value);
853
+ }
854
+ }
855
+ };
856
+ const error = (err) => {
857
+ if (status.state !== "open") {
858
+ return;
859
+ }
860
+ status = { state: "errored", err };
861
+ for (const consumer of consumers) {
862
+ if (consumer.kind === "listener") {
863
+ consumer.error?.(err);
864
+ } else if (consumer.pending) {
865
+ const p = consumer.pending;
866
+ consumer.pending = void 0;
867
+ p.reject(err);
868
+ }
869
+ }
870
+ consumers.clear();
871
+ };
872
+ const complete = () => {
873
+ if (status.state !== "open") {
874
+ return;
875
+ }
876
+ status = { state: "completed" };
877
+ for (const consumer of consumers) {
878
+ if (consumer.kind === "listener") {
879
+ consumer.complete?.();
880
+ } else if (consumer.pending) {
881
+ const p = consumer.pending;
882
+ consumer.pending = void 0;
883
+ p.resolve({ value: void 0, done: true });
884
+ }
885
+ }
886
+ consumers.clear();
887
+ };
888
+ const subscribe = (observerOrNext) => {
889
+ if (status.state !== "open") {
890
+ return () => {
891
+ };
892
+ }
893
+ const observer = typeof observerOrNext === "function" ? { next: observerOrNext } : observerOrNext;
894
+ const consumer = { kind: "listener", ...observer };
895
+ consumers.add(consumer);
896
+ return () => {
897
+ consumers.delete(consumer);
898
+ };
899
+ };
900
+ const iterable = {
901
+ [Symbol.asyncIterator]() {
902
+ if (status.state === "errored") {
903
+ const err = status.err;
904
+ return {
905
+ next: () => Promise.reject(err),
906
+ return: () => Promise.resolve({ value: void 0, done: true })
907
+ };
908
+ }
909
+ if (status.state === "completed") {
910
+ return {
911
+ next: () => Promise.resolve({ value: void 0, done: true }),
912
+ return: () => Promise.resolve({ value: void 0, done: true })
913
+ };
914
+ }
915
+ const consumer = { kind: "iterator", queue: [] };
916
+ consumers.add(consumer);
917
+ return {
918
+ next() {
919
+ if (consumer.queue.length > 0) {
920
+ return Promise.resolve({ value: consumer.queue.shift(), done: false });
921
+ }
922
+ if (status.state === "errored") {
923
+ return Promise.reject(status.err);
924
+ }
925
+ if (status.state === "completed") {
926
+ return Promise.resolve({ value: void 0, done: true });
927
+ }
928
+ return new Promise((resolve, reject) => {
929
+ consumer.pending = { resolve, reject };
930
+ });
931
+ },
932
+ return() {
933
+ consumers.delete(consumer);
934
+ if (consumer.pending) {
935
+ const p = consumer.pending;
936
+ consumer.pending = void 0;
937
+ p.resolve({ value: void 0, done: true });
938
+ }
939
+ return Promise.resolve({ value: void 0, done: true });
940
+ },
941
+ throw(err) {
942
+ consumers.delete(consumer);
943
+ return Promise.reject(err);
944
+ }
945
+ };
946
+ }
947
+ };
948
+ return Object.assign(iterable, { next, error, complete, subscribe });
949
+ }
588
950
  // Annotate the CommonJS export names for ESM import in node:
589
951
  0 && (module.exports = {
590
952
  ContelloClient,
591
- createContelloClient
953
+ asyncKeepalive,
954
+ collectAsync,
955
+ createAsyncIterableSubject,
956
+ createContelloClient,
957
+ createSourceSubscription,
958
+ exponentialBackoff,
959
+ filterAsync,
960
+ firstAsync,
961
+ mapAsync,
962
+ runWithBackoff
592
963
  });
package/dist/index.d.cts CHANGED
@@ -1,4 +1,3 @@
1
- import { Observable } from 'rxjs';
2
1
  import { ReadableStream as ReadableStream$1 } from 'node:stream/web';
3
2
 
4
3
  type HttpAgentOptions = {
@@ -31,10 +30,54 @@ type OperationDef<TResult = unknown, TVariables = Record<string, unknown>, TKind
31
30
  type OperationMap = Record<string, OperationDef>;
32
31
  type InferResult<T extends OperationDef> = NonNullable<T['__result']>;
33
32
  type InferVariables<T extends OperationDef> = NonNullable<T['__variables']>;
34
- type RpcMethod<T extends OperationDef> = T['kind'] extends 'subscription' ? InferVariables<T> extends Record<string, never> ? () => Observable<InferResult<T>> : (variables: InferVariables<T>) => Observable<InferResult<T>> : InferVariables<T> extends Record<string, never> ? () => Promise<InferResult<T>> : (variables: InferVariables<T>) => Promise<InferResult<T>>;
33
+ type RpcMethod<T extends OperationDef> = T['kind'] extends 'subscription' ? InferVariables<T> extends Record<string, never> ? () => AsyncIterable<InferResult<T>> : (variables: InferVariables<T>) => AsyncIterable<InferResult<T>> : InferVariables<T> extends Record<string, never> ? () => Promise<InferResult<T>> : (variables: InferVariables<T>) => Promise<InferResult<T>>;
35
34
  type Rpc<T extends OperationMap> = {
36
35
  [K in keyof T]: RpcMethod<T[K]>;
37
36
  };
37
+ /**
38
+ * Discriminator for how a SourceDef binds to a Subscription field:
39
+ * - `entity` — a Contello entity model collection (`categoriesBatch` etc.), accepts optional `{ ids }` filter
40
+ * - `singleton` — a single Contello entity (`config` etc.), no args
41
+ * - `route` — built-in: `contelloRoutesBatch`, no args
42
+ * - `asset` — built-in: `contelloAssetsBatch`, no args
43
+ * - `i18nMessage` — built-in: `contelloI18nMessagesBatch`, requires `{ collection }`
44
+ */
45
+ type SourceCardinality = 'entity' | 'singleton' | 'route' | 'asset' | 'i18nMessage';
46
+ type SourceDef<TModel extends string = string, TCardinality extends SourceCardinality = SourceCardinality, TResult = unknown> = {
47
+ /** the GQL fragment text — bundled with transitive deps if any */
48
+ document: string;
49
+ /** the fragment name to spread inside the source subscription — e.g. `Category` */
50
+ fragment: string;
51
+ /** the subscription field this fragment is bound to — `categoriesBatch`, `config`, etc */
52
+ subscription: string;
53
+ __model: TModel;
54
+ __cardinality: TCardinality;
55
+ /** phantom type — exists only at the type level */
56
+ __result?: TResult | undefined;
57
+ };
58
+ type SourceMap = Record<string, SourceDef>;
59
+ /**
60
+ * The bundle emitted by `contello-client generate`. Pass to `createContelloClient({ schema })`
61
+ * (and to `createStore`, `createContello`). Each layer reads what it needs:
62
+ * - client uses `operations` (for `client.rpc.*`) and `sources` (for `client.sources.*`).
63
+ * - store uses `models` (for the dependency resolver) on top of what client uses.
64
+ */
65
+ type Schema<TOps extends OperationMap = OperationMap, TSources extends SourceMap = SourceMap, TModels extends string = string> = {
66
+ operations: TOps;
67
+ sources: TSources;
68
+ models: Record<TModels, string>;
69
+ };
70
+ type SourceFetcherFor<S> = S extends SourceDef<string, 'singleton', infer R> ? () => Promise<R> : S extends SourceDef<string, 'entity', infer R> ? (vars?: {
71
+ ids?: string[];
72
+ }) => Promise<R[]> : S extends SourceDef<string, 'route', infer R> ? () => Promise<R[]> : S extends SourceDef<string, 'asset', infer R> ? () => Promise<R[]> : S extends SourceDef<string, 'i18nMessage', infer R> ? (vars: {
73
+ collection: string;
74
+ }) => Promise<R[]> : never;
75
+ /** Per-source runtime accessor: `client.sources.category.fetch()` → `Promise<CategoryFragment[]>` etc. */
76
+ type SourceAccessors<TSources extends SourceMap> = {
77
+ [K in keyof TSources]: {
78
+ fetch: SourceFetcherFor<TSources[K]>;
79
+ };
80
+ };
38
81
 
39
82
  type UploadMetadata = {
40
83
  name: string;
@@ -62,11 +105,11 @@ type ConnectionEvents = {
62
105
  onClosed?: ((context: ConnectionContext) => void) | undefined;
63
106
  onError?: ((context: ConnectionContext, error: unknown) => void) | undefined;
64
107
  };
65
- type ContelloClientOptions<T extends OperationMap | undefined = undefined> = {
108
+ type ContelloClientOptions<TSchema extends Schema | undefined = undefined> = {
66
109
  url: string;
67
110
  project: string;
68
111
  token: string;
69
- operations?: T | undefined;
112
+ schema?: TSchema | undefined;
70
113
  connections?: number | undefined;
71
114
  http?: HttpAgentOptions | undefined;
72
115
  onConnected?: (() => void) | undefined;
@@ -74,24 +117,95 @@ type ContelloClientOptions<T extends OperationMap | undefined = undefined> = {
74
117
  onError?: ((error: unknown) => void) | undefined;
75
118
  connectionEvents?: ConnectionEvents | undefined;
76
119
  };
77
- declare class ContelloClient<T extends OperationMap | undefined = undefined> {
120
+ declare class ContelloClient<TSchema extends Schema | undefined = undefined> {
78
121
  private _pool;
79
122
  private _rpc;
123
+ private _sources;
80
124
  private _url;
81
125
  private _project;
82
126
  private _token;
83
127
  private _agent;
84
- constructor(options: ContelloClientOptions<T>);
85
- get rpc(): T extends OperationMap ? Rpc<T> : never;
128
+ constructor(options: ContelloClientOptions<TSchema>);
129
+ get rpc(): TSchema extends Schema<infer TOps, any, any> ? Rpc<TOps> : never;
130
+ get sources(): TSchema extends Schema<any, infer TSources, any> ? SourceAccessors<TSources> : never;
86
131
  init(): Promise<void>;
87
132
  destroy(): Promise<void>;
88
133
  ping(): Promise<void>;
89
- subscribe<TData>(query: string, variables?: Record<string, unknown> | undefined): Observable<TData>;
134
+ /**
135
+ * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
136
+ * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
137
+ * down when the iterator is returned (`break`, error, or explicit stop).
138
+ */
139
+ subscribe<TData>(query: string, variables?: Record<string, unknown> | undefined): AsyncIterable<TData>;
90
140
  download(fileId: string): Promise<DownloadResult>;
91
141
  proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;
92
142
  upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;
93
143
  execute<TData>(query: string, variables?: Record<string, unknown> | undefined): Promise<TData>;
94
144
  }
95
- declare function createContelloClient<T extends OperationMap | undefined = undefined>(options: ContelloClientOptions<T>): ContelloClient<T>;
145
+ declare function createContelloClient<TSchema extends Schema | undefined = undefined>(options: ContelloClientOptions<TSchema>): ContelloClient<TSchema>;
146
+
147
+ declare function createSourceSubscription(source: SourceDef): string;
148
+
149
+ /**
150
+ * Returns the first value yielded by `iter`, then disposes the iterator. Throws if the iterable
151
+ * completes without yielding. Equivalent of rxjs's `firstValueFrom` for AsyncIterables.
152
+ */
153
+ declare function firstAsync<T>(iter: AsyncIterable<T>): Promise<T>;
154
+ /** Lazy map over an async iterable. Cleanup propagates: breaking the outer iter disposes the inner. */
155
+ declare function mapAsync<T, R>(iter: AsyncIterable<T>, fn: (value: T) => R): AsyncIterable<R>;
156
+ /** Lazy filter over an async iterable. */
157
+ declare function filterAsync<T>(iter: AsyncIterable<T>, predicate: (value: T) => boolean): AsyncIterable<T>;
158
+ /**
159
+ * Concatenates all elements of all arrays yielded by `iter` into a single array. Used to support
160
+ * subscriptions that emit chunks of items before completing.
161
+ */
162
+ declare function collectAsync<T>(iter: AsyncIterable<T[]>): Promise<T[]>;
163
+ /**
164
+ * Exponential backoff with jitter. `attempt` starts at 0 → ~1s+jitter, 1 → ~2s+jitter, etc.,
165
+ * capped at 30s. Returns a Promise that resolves after the delay.
166
+ */
167
+ declare function exponentialBackoff(attempt: number): Promise<void>;
168
+ /**
169
+ * Runs `fn` with exponential-backoff retry on rejection. Returns once `fn` resolves successfully.
170
+ * `signal` aborts both the in-flight `fn` (if it observes the signal) and the backoff wait.
171
+ */
172
+ declare function runWithBackoff(fn: () => Promise<unknown>, signal?: AbortSignal | undefined): Promise<void>;
173
+ /**
174
+ * Long-running stream wrapper: subscribes via `factory()`, yields every value, and on error or
175
+ * unexpected completion re-subscribes with exponential backoff. Stops only when `signal` aborts.
176
+ * Designed for subscriptions that should stay open across reconnects (e.g. the watcher).
177
+ */
178
+ declare function asyncKeepalive<T>(factory: () => AsyncIterable<T>, signal?: AbortSignal | undefined): AsyncIterable<T>;
179
+
180
+ /**
181
+ * Multicast event source with `next` / `error` / `complete` (Subject semantics) plus an
182
+ * `AsyncIterable` view. Two consumption modes that fan out from the same source:
183
+ *
184
+ * - `for await (const v of subject)` — iteration. Each `[Symbol.asyncIterator]()` call returns
185
+ * a fresh per-iterator queue. Stop by `break`ing the loop. On `.error(err)` the iterator's
186
+ * pending `next()` rejects, propagating into the for-await as a thrown exception.
187
+ *
188
+ * - `subject.subscribe(observerOrNext)` — observer style. Pass either a full/partial observer
189
+ * `{ next?, error?, complete? }` or just an `(value) => …` function as the `next`-only shortcut.
190
+ * Returns an unsubscribe function. Missing handlers default to no-ops.
191
+ *
192
+ * Producer side: call `.next(value)` to emit, `.error(err)` to fail the subject (all consumers
193
+ * see the error and are detached), `.complete()` to close cleanly (all consumers see done and
194
+ * are detached). After either `error` or `complete`, further `.next()` calls are dropped and
195
+ * new `.subscribe(...)` calls register a no-op unsubscribe.
196
+ *
197
+ * Backpressure: unbounded queue per pending iterator. Intended for low-frequency events.
198
+ */
199
+ type AsyncIterableSubject<T> = AsyncIterable<T> & {
200
+ next: (value: T) => void;
201
+ error: (err: unknown) => void;
202
+ complete: () => void;
203
+ subscribe: (observerOrNext: {
204
+ next?: (value: T) => void;
205
+ error?: (err: unknown) => void;
206
+ complete?: () => void;
207
+ } | ((value: T) => void)) => () => void;
208
+ };
209
+ declare function createAsyncIterableSubject<T>(): AsyncIterableSubject<T>;
96
210
 
97
- export { type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type UploadData, type UploadMetadata, type UploadOptions, createContelloClient };
211
+ export { type AsyncIterableSubject, type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type Schema, type SourceAccessors, type SourceCardinality, type SourceDef, type SourceMap, type UploadData, type UploadMetadata, type UploadOptions, asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, exponentialBackoff, filterAsync, firstAsync, mapAsync, runWithBackoff };