@adaptic/lumic-utils 1.0.8 → 1.0.10

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.
Files changed (87) hide show
  1. package/dist/{index-Cstek604.js → index-CcXQeJz8.js} +22 -182
  2. package/dist/index-CcXQeJz8.js.map +1 -0
  3. package/dist/{index-DZZCd-1T.js → index-CcgbRft2.js} +22 -182
  4. package/dist/index-CcgbRft2.js.map +1 -0
  5. package/dist/index.cjs +11417 -122
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.mjs +11399 -39
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/test.cjs +7 -24
  10. package/dist/test.cjs.map +1 -1
  11. package/dist/test.mjs +7 -24
  12. package/dist/test.mjs.map +1 -1
  13. package/dist/types/aws-types.ts +1 -1
  14. package/dist/types/functions/aws-lambda.d.ts +1 -1
  15. package/dist/types/functions/aws-s3-utils.d.ts +2 -2
  16. package/dist/types/functions/google-sheets.d.ts +4 -4
  17. package/dist/types/functions/json-llm-tools.d.ts +3 -25
  18. package/dist/types/functions/llm-call.d.ts +2 -2
  19. package/dist/types/functions/llm-deepseek.d.ts +1 -1
  20. package/dist/types/functions/llm-openai.d.ts +2 -3
  21. package/dist/types/functions/llm-utils.d.ts +1 -24
  22. package/dist/types/functions/slack-utils.d.ts +4 -3
  23. package/dist/types/functions/utils.d.ts +14 -2
  24. package/dist/types/functions/zip-utils.d.ts +10 -12
  25. package/dist/types/google-types.ts +3 -6
  26. package/dist/types/index.d.ts +0 -30
  27. package/dist/types/index.ts +1 -1
  28. package/dist/types/openai-types.ts +6 -165
  29. package/dist/types/types/aws-types.d.ts +1 -1
  30. package/dist/types/types/google-types.d.ts +3 -5
  31. package/dist/types/types/index.d.ts +1 -1
  32. package/dist/types/types/openai-types.d.ts +3 -149
  33. package/dist/types/utils/aws-initialise.d.ts +1 -6
  34. package/package.json +3 -2
  35. package/dist/apollo-client.client-DE7JUXjy.js +0 -3693
  36. package/dist/apollo-client.client-DE7JUXjy.js.map +0 -1
  37. package/dist/apollo-client.client-DlG4HsFm.js +0 -3704
  38. package/dist/apollo-client.client-DlG4HsFm.js.map +0 -1
  39. package/dist/apollo-client.server-D1QJea5_.js +0 -16319
  40. package/dist/apollo-client.server-D1QJea5_.js.map +0 -1
  41. package/dist/apollo-client.server-uqalq3yp.js +0 -16321
  42. package/dist/apollo-client.server-uqalq3yp.js.map +0 -1
  43. package/dist/index-Bd84zcTQ.js +0 -74944
  44. package/dist/index-Bd84zcTQ.js.map +0 -1
  45. package/dist/index-CZKOqrJ4.js +0 -75137
  46. package/dist/index-CZKOqrJ4.js.map +0 -1
  47. package/dist/index-CsKfs4nG.js +0 -12108
  48. package/dist/index-CsKfs4nG.js.map +0 -1
  49. package/dist/index-Cstek604.js.map +0 -1
  50. package/dist/index-DZZCd-1T.js.map +0 -1
  51. package/dist/index-aP9ow8_W.js +0 -12271
  52. package/dist/index-aP9ow8_W.js.map +0 -1
  53. package/dist/types/config/__tests__/secrets.test.d.ts +0 -1
  54. package/dist/types/config/secrets.d.ts +0 -186
  55. package/dist/types/errors/__tests__/errors.test.d.ts +0 -1
  56. package/dist/types/errors/index.d.ts +0 -77
  57. package/dist/types/functions/__tests__/aws-lambda.test.d.ts +0 -1
  58. package/dist/types/functions/__tests__/aws-s3-utils.test.d.ts +0 -1
  59. package/dist/types/functions/__tests__/json-llm-tools.test.d.ts +0 -1
  60. package/dist/types/functions/__tests__/json-tools.test.d.ts +0 -1
  61. package/dist/types/functions/__tests__/slack-utils.test.d.ts +0 -1
  62. package/dist/types/schemas/aws-schemas.d.ts +0 -210
  63. package/dist/types/schemas/google-sheets-schemas.d.ts +0 -32
  64. package/dist/types/schemas/index.d.ts +0 -17
  65. package/dist/types/schemas/openai-schemas.d.ts +0 -834
  66. package/dist/types/schemas/perplexity-schemas.d.ts +0 -338
  67. package/dist/types/schemas/validation-helpers.d.ts +0 -33
  68. package/dist/types/utils/__tests__/circuit-breaker.test.d.ts +0 -1
  69. package/dist/types/utils/__tests__/correlation.test.d.ts +0 -1
  70. package/dist/types/utils/__tests__/input-validator.test.d.ts +0 -1
  71. package/dist/types/utils/__tests__/llm-cost-tracker.test.d.ts +0 -1
  72. package/dist/types/utils/__tests__/logger.test.d.ts +0 -1
  73. package/dist/types/utils/__tests__/metrics.test.d.ts +0 -1
  74. package/dist/types/utils/__tests__/retry.test.d.ts +0 -1
  75. package/dist/types/utils/__tests__/sanitizer.test.d.ts +0 -1
  76. package/dist/types/utils/__tests__/timeouts.test.d.ts +0 -1
  77. package/dist/types/utils/circuit-breaker.d.ts +0 -99
  78. package/dist/types/utils/correlation.d.ts +0 -43
  79. package/dist/types/utils/health-check.d.ts +0 -50
  80. package/dist/types/utils/input-validator.d.ts +0 -51
  81. package/dist/types/utils/llm-cost-tracker.d.ts +0 -174
  82. package/dist/types/utils/logger.d.ts +0 -8
  83. package/dist/types/utils/metrics.d.ts +0 -61
  84. package/dist/types/utils/rate-limiter.d.ts +0 -85
  85. package/dist/types/utils/retry.d.ts +0 -58
  86. package/dist/types/utils/sanitizer.d.ts +0 -30
  87. package/dist/types/utils/timeouts.d.ts +0 -44
@@ -1,3693 +0,0 @@
1
- import { bv as __extends, z as __assign, y as getOperationDefinition, bw as warnDeprecated, v as invariant, bx as muteDeprecations, by as equal, bz as equalByQuery, ag as getQueryDefinition, bA as warnRemovedOption, a2 as compact, a1 as cloneDeep, aH as preventUnhandledRejection, aA as iterateObserversSafely, bB as Slot, O as Observable, bC as isApolloError, bD as ApolloError, a4 as fixObservableSubclass, aj as graphQLResultHasError, Y as canUseWeakMap, H as DeepMerger, ax as isNonEmptyArray, aF as mergeIncrementalData, F as AutoCleanedWeakCache, R as cacheSizes, bE as Trie, J as DocumentTransform, x as newInvariantError, bF as __awaiter, bG as __generator, P as asyncMap, ac as getGraphQLErrorsFromResult, ar as isExecutionPatchIncrementalResult, af as getOperationName, at as isExecutionPatchResult, a5 as getDefaultValues, aM as removeDirectivesFromDocument, K as addNonReactiveToNamedFragments, an as hasDirectives, am as hasClientExports, aq as isDocumentNode, aI as print, ay as isNonNullObject, aC as makeUniqueId, $ as canonicalStringify, G as Concast, a_ as execute, av as isFullyUnmaskedOperation, be as maskOperation, bd as maskFragment, bH as graphQLResultHasProtocolErrors, bI as PROTOCOL_ERRORS_SYMBOL, A as mergeDeep, aK as removeClientSetsFromDocument, Q as buildQueryFromSelectionSet, ae as getMainDefinition, a8 as getFragmentDefinitions, a3 as createFragmentMap, aE as mergeDeepArray, aP as shouldInclude, au as isField, aO as resultKeyNameFromField, aw as isInlineFragment, bm as cacheSlot, N as argumentsObjectFromField, m as isSelectionNode, aG as mergeOptions, b0 as HttpLink, aZ as ApolloLink, bJ as version, bK as getApolloClientMemoryInternals, B as __rest } from './index-CsKfs4nG.js';
2
- export { bj as InMemoryCache, bL as gql, a$ as split } from './index-CsKfs4nG.js';
3
- import { W as visit, a8 as BREAK } from './index-Bd84zcTQ.js';
4
- import 'openai';
5
- import 'zod';
6
- import '@aws-sdk/client-s3';
7
- import '@aws-sdk/client-lambda';
8
- import 'axios';
9
- import 'fs';
10
- import 'path';
11
- import 'os';
12
- import 'adm-zip';
13
- import 'stream';
14
- import 'fs/promises';
15
- import 'crypto';
16
- import 'stream/promises';
17
- import 'node:path';
18
- import 'node:fs';
19
- import 'node:fs/promises';
20
- import 'graphql-fields';
21
- import 'date-fns';
22
- import 'date-fns-tz';
23
- import 'ms';
24
- import 'events';
25
- import 'https';
26
- import 'http';
27
- import 'net';
28
- import 'tls';
29
- import 'url';
30
- import 'zlib';
31
- import 'buffer';
32
- import 'readline';
33
- import 'assert';
34
- import 'tty';
35
- import 'util';
36
- import 'pdfkit';
37
- import 'marked';
38
- import 'google-auth-library';
39
- import 'http2';
40
- import 'process';
41
- import 'node:async_hooks';
42
-
43
- /**
44
- * The current status of a query’s execution in our system.
45
- */
46
- var NetworkStatus;
47
- (function (NetworkStatus) {
48
- /**
49
- * The query has never been run before and the query is now currently running. A query will still
50
- * have this network status even if a partial data result was returned from the cache, but a
51
- * query was dispatched anyway.
52
- */
53
- NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
54
- /**
55
- * If `setVariables` was called and a query was fired because of that then the network status
56
- * will be `setVariables` until the result of that query comes back.
57
- */
58
- NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
59
- /**
60
- * Indicates that `fetchMore` was called on this query and that the query created is currently in
61
- * flight.
62
- */
63
- NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
64
- /**
65
- * Similar to the `setVariables` network status. It means that `refetch` was called on a query
66
- * and the refetch request is currently in flight.
67
- */
68
- NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
69
- /**
70
- * Indicates that a polling query is currently in flight. So for example if you are polling a
71
- * query every 10 seconds then the network status will switch to `poll` every 10 seconds whenever
72
- * a poll request has been sent but not resolved.
73
- */
74
- NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
75
- /**
76
- * No request is in flight for this query, and no errors happened. Everything is OK.
77
- */
78
- NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
79
- /**
80
- * No request is in flight for this query, but one or more errors were detected.
81
- */
82
- NetworkStatus[NetworkStatus["error"] = 8] = "error";
83
- })(NetworkStatus || (NetworkStatus = {}));
84
- /**
85
- * Returns true if there is currently a network request in flight according to a given network
86
- * status.
87
- */
88
- function isNetworkRequestInFlight(networkStatus) {
89
- return networkStatus ? networkStatus < 7 : false;
90
- }
91
-
92
- var assign = Object.assign, hasOwnProperty$1 = Object.hasOwnProperty;
93
- var ObservableQuery = /** @class */ (function (_super) {
94
- __extends(ObservableQuery, _super);
95
- function ObservableQuery(_a) {
96
- var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
97
- var _this = this;
98
- var startedInactive = ObservableQuery.inactiveOnCreation.getValue();
99
- _this = _super.call(this, function (observer) {
100
- _this._getOrCreateQuery();
101
- // Zen Observable has its own error function, so in order to log correctly
102
- // we need to provide a custom error callback.
103
- try {
104
- var subObserver = observer._subscription._observer;
105
- if (subObserver && !subObserver.error) {
106
- subObserver.error = defaultSubscriptionObserverErrorCallback;
107
- }
108
- }
109
- catch (_a) { }
110
- var first = !_this.observers.size;
111
- _this.observers.add(observer);
112
- // Deliver most recent error or result.
113
- var last = _this.last;
114
- if (last && last.error) {
115
- observer.error && observer.error(last.error);
116
- }
117
- else if (last && last.result) {
118
- observer.next && observer.next(_this.maskResult(last.result));
119
- }
120
- // Initiate observation of this query if it hasn't been reported to
121
- // the QueryManager yet.
122
- if (first) {
123
- // Blindly catching here prevents unhandled promise rejections,
124
- // and is safe because the ObservableQuery handles this error with
125
- // this.observer.error, so we're not just swallowing the error by
126
- // ignoring it here.
127
- _this.reobserve().catch(function () { });
128
- }
129
- return function () {
130
- if (_this.observers.delete(observer) && !_this.observers.size) {
131
- _this.tearDownQuery();
132
- }
133
- };
134
- }) || this;
135
- _this.observers = new Set();
136
- _this.subscriptions = new Set();
137
- _this.dirty = false;
138
- _this._getOrCreateQuery = function () {
139
- if (startedInactive) {
140
- queryManager["queries"].set(_this.queryId, queryInfo);
141
- startedInactive = false;
142
- }
143
- return _this.queryManager.getOrCreateQuery(_this.queryId);
144
- };
145
- // related classes
146
- _this.queryInfo = queryInfo;
147
- _this.queryManager = queryManager;
148
- // active state
149
- _this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);
150
- _this.isTornDown = false;
151
- _this.subscribeToMore = _this.subscribeToMore.bind(_this);
152
- _this.maskResult = _this.maskResult.bind(_this);
153
- var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? "cache-first" : _d;
154
- var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e,
155
- // Make sure we don't store "standby" as the initialFetchPolicy.
156
- _f = options.initialFetchPolicy,
157
- // Make sure we don't store "standby" as the initialFetchPolicy.
158
- initialFetchPolicy = _f === void 0 ? fetchPolicy === "standby" ? defaultFetchPolicy : (fetchPolicy) : _f;
159
- _this.options = __assign(__assign({}, options), {
160
- // Remember the initial options.fetchPolicy so we can revert back to this
161
- // policy when variables change. This information can also be specified
162
- // (or overridden) by providing options.initialFetchPolicy explicitly.
163
- initialFetchPolicy: initialFetchPolicy,
164
- // This ensures this.options.fetchPolicy always has a string value, in
165
- // case options.fetchPolicy was not provided.
166
- fetchPolicy: fetchPolicy });
167
- _this.queryId = queryInfo.queryId || queryManager.generateQueryId();
168
- var opDef = getOperationDefinition(_this.query);
169
- _this.queryName = opDef && opDef.name && opDef.name.value;
170
- return _this;
171
- }
172
- Object.defineProperty(ObservableQuery.prototype, "query", {
173
- // The `query` computed property will always reflect the document transformed
174
- // by the last run query. `this.options.query` will always reflect the raw
175
- // untransformed query to ensure document transforms with runtime conditionals
176
- // are run on the original document.
177
- get: function () {
178
- return this.lastQuery || this.options.query;
179
- },
180
- enumerable: false,
181
- configurable: true
182
- });
183
- Object.defineProperty(ObservableQuery.prototype, "variables", {
184
- // Computed shorthand for this.options.variables, preserved for
185
- // backwards compatibility.
186
- /**
187
- * An object containing the variables that were provided for the query.
188
- */
189
- get: function () {
190
- return this.options.variables;
191
- },
192
- enumerable: false,
193
- configurable: true
194
- });
195
- /**
196
- * @deprecated `result` will be removed in Apollo Client 4.0.
197
- *
198
- * **Recommended now**
199
- *
200
- * If you continue to need this functionality, subscribe to `ObservableQuery`
201
- * to get the first value emitted from the observable, then immediately unsubscribe.
202
- *
203
- * **When upgrading**
204
- *
205
- * Use RxJS's [`firstResultFrom`](https://rxjs.dev/api/index/function/firstValueFrom) function to mimic this functionality.
206
- *
207
- * ```ts
208
- * const result = await firstValueFrom(from(observableQuery));
209
- * ```
210
- */
211
- ObservableQuery.prototype.result = function () {
212
- var _this = this;
213
- if (globalThis.__DEV__ !== false) {
214
- warnDeprecated("observableQuery.result", function () {
215
- globalThis.__DEV__ !== false && invariant.warn(23);
216
- });
217
- }
218
- return new Promise(function (resolve, reject) {
219
- // TODO: this code doesn’t actually make sense insofar as the observer
220
- // will never exist in this.observers due how zen-observable wraps observables.
221
- // https://github.com/zenparsing/zen-observable/blob/master/src/Observable.js#L169
222
- var observer = {
223
- next: function (result) {
224
- resolve(result);
225
- // Stop the query within the QueryManager if we can before
226
- // this function returns.
227
- //
228
- // We do this in order to prevent observers piling up within
229
- // the QueryManager. Notice that we only fully unsubscribe
230
- // from the subscription in a setTimeout(..., 0) call. This call can
231
- // actually be handled by the browser at a much later time. If queries
232
- // are fired in the meantime, observers that should have been removed
233
- // from the QueryManager will continue to fire, causing an unnecessary
234
- // performance hit.
235
- _this.observers.delete(observer);
236
- if (!_this.observers.size) {
237
- _this.queryManager.removeQuery(_this.queryId);
238
- }
239
- setTimeout(function () {
240
- subscription.unsubscribe();
241
- }, 0);
242
- },
243
- error: reject,
244
- };
245
- var subscription = _this.subscribe(observer);
246
- });
247
- };
248
- /** @internal */
249
- ObservableQuery.prototype.resetDiff = function () {
250
- this.queryInfo.resetDiff();
251
- };
252
- ObservableQuery.prototype.getCurrentFullResult = function (saveAsLastResult) {
253
- var _this = this;
254
- if (saveAsLastResult === void 0) { saveAsLastResult = true; }
255
- // Use the last result as long as the variables match this.variables.
256
- var lastResult = muteDeprecations("getLastResult", function () {
257
- return _this.getLastResult(true);
258
- });
259
- var networkStatus = this.queryInfo.networkStatus ||
260
- (lastResult && lastResult.networkStatus) ||
261
- NetworkStatus.ready;
262
- var result = __assign(__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
263
- var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a;
264
- if (
265
- // These fetch policies should never deliver data from the cache, unless
266
- // redelivering a previously delivered result.
267
- skipCacheDataFor(fetchPolicy) ||
268
- // If this.options.query has @client(always: true) fields, we cannot
269
- // trust diff.result, since it was read from the cache without running
270
- // local resolvers (and it's too late to run resolvers now, since we must
271
- // return a result synchronously).
272
- this.queryManager.getDocumentInfo(this.query).hasForcedResolvers) ;
273
- else if (this.waitForOwnResult) {
274
- // This would usually be a part of `QueryInfo.getDiff()`.
275
- // which we skip in the waitForOwnResult case since we are not
276
- // interested in the diff.
277
- this.queryInfo["updateWatch"]();
278
- }
279
- else {
280
- var diff = this.queryInfo.getDiff();
281
- if (diff.complete || this.options.returnPartialData) {
282
- result.data = diff.result;
283
- }
284
- if (equal(result.data, {})) {
285
- result.data = void 0;
286
- }
287
- if (diff.complete) {
288
- // Similar to setting result.partial to false, but taking advantage of the
289
- // falsiness of missing fields.
290
- delete result.partial;
291
- // If the diff is complete, and we're using a FetchPolicy that
292
- // terminates after a complete cache read, we can assume the next result
293
- // we receive will have NetworkStatus.ready and !loading.
294
- if (diff.complete &&
295
- result.networkStatus === NetworkStatus.loading &&
296
- (fetchPolicy === "cache-first" || fetchPolicy === "cache-only")) {
297
- result.networkStatus = NetworkStatus.ready;
298
- result.loading = false;
299
- }
300
- }
301
- else {
302
- result.partial = true;
303
- }
304
- // We need to check for both both `error` and `errors` field because there
305
- // are cases where sometimes `error` is set, but not `errors` and
306
- // vice-versa. This will be updated in the next major version when
307
- // `errors` is deprecated in favor of `error`.
308
- if (result.networkStatus === NetworkStatus.ready &&
309
- (result.error || result.errors)) {
310
- result.networkStatus = NetworkStatus.error;
311
- }
312
- if (globalThis.__DEV__ !== false &&
313
- !diff.complete &&
314
- !this.options.partialRefetch &&
315
- !result.loading &&
316
- !result.data &&
317
- !result.error) {
318
- logMissingFieldErrors(diff.missing);
319
- }
320
- }
321
- if (saveAsLastResult) {
322
- this.updateLastResult(result);
323
- }
324
- return result;
325
- };
326
- ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
327
- if (saveAsLastResult === void 0) { saveAsLastResult = true; }
328
- return this.maskResult(this.getCurrentFullResult(saveAsLastResult));
329
- };
330
- // Compares newResult to the snapshot we took of this.lastResult when it was
331
- // first received.
332
- ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
333
- if (!this.last) {
334
- return true;
335
- }
336
- var documentInfo = this.queryManager.getDocumentInfo(this.query);
337
- var dataMasking = this.queryManager.dataMasking;
338
- var query = dataMasking ? documentInfo.nonReactiveQuery : this.query;
339
- var resultIsDifferent = dataMasking || documentInfo.hasNonreactiveDirective ?
340
- !equalByQuery(query, this.last.result, newResult, this.variables)
341
- : !equal(this.last.result, newResult);
342
- return (resultIsDifferent || (variables && !equal(this.last.variables, variables)));
343
- };
344
- ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
345
- var last = this.last;
346
- if (last &&
347
- last[key] &&
348
- (!variablesMustMatch || equal(last.variables, this.variables))) {
349
- return last[key];
350
- }
351
- };
352
- /**
353
- * @deprecated `getLastResult` will be removed in Apollo Client 4.0. Please
354
- * discontinue using this method.
355
- */
356
- ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {
357
- if (globalThis.__DEV__ !== false) {
358
- warnDeprecated("getLastResult", function () {
359
- globalThis.__DEV__ !== false && invariant.warn(24);
360
- });
361
- }
362
- return this.getLast("result", variablesMustMatch);
363
- };
364
- /**
365
- * @deprecated `getLastError` will be removed in Apollo Client 4.0. Please
366
- * discontinue using this method.
367
- */
368
- ObservableQuery.prototype.getLastError = function (variablesMustMatch) {
369
- if (globalThis.__DEV__ !== false) {
370
- warnDeprecated("getLastError", function () {
371
- globalThis.__DEV__ !== false && invariant.warn(25);
372
- });
373
- }
374
- return this.getLast("error", variablesMustMatch);
375
- };
376
- /**
377
- * @deprecated `resetLastResults` will be removed in Apollo Client 4.0. Please
378
- * discontinue using this method.
379
- */
380
- ObservableQuery.prototype.resetLastResults = function () {
381
- if (globalThis.__DEV__ !== false) {
382
- warnDeprecated("resetLastResults", function () {
383
- globalThis.__DEV__ !== false && invariant.warn(26);
384
- });
385
- }
386
- delete this.last;
387
- this.isTornDown = false;
388
- };
389
- /**
390
- * @deprecated `resetQueryStoreErrors` will be removed in Apollo Client 4.0.
391
- * Please discontinue using this method.
392
- */
393
- ObservableQuery.prototype.resetQueryStoreErrors = function () {
394
- if (globalThis.__DEV__ !== false) {
395
- globalThis.__DEV__ !== false && invariant.warn(27);
396
- }
397
- this.queryManager.resetErrors(this.queryId);
398
- };
399
- /**
400
- * Update the variables of this observable query, and fetch the new results.
401
- * This method should be preferred over `setVariables` in most use cases.
402
- *
403
- * @param variables - The new set of variables. If there are missing variables,
404
- * the previous values of those variables will be used.
405
- */
406
- ObservableQuery.prototype.refetch = function (variables) {
407
- var _a;
408
- var reobserveOptions = {
409
- // Always disable polling for refetches.
410
- pollInterval: 0,
411
- };
412
- // Unless the provided fetchPolicy always consults the network
413
- // (no-cache, network-only, or cache-and-network), override it with
414
- // network-only to force the refetch for this fetchQuery call.
415
- var fetchPolicy = this.options.fetchPolicy;
416
- if (fetchPolicy === "no-cache") {
417
- reobserveOptions.fetchPolicy = "no-cache";
418
- }
419
- else {
420
- reobserveOptions.fetchPolicy = "network-only";
421
- }
422
- if (globalThis.__DEV__ !== false && variables && hasOwnProperty$1.call(variables, "variables")) {
423
- var queryDef = getQueryDefinition(this.query);
424
- var vars = queryDef.variableDefinitions;
425
- if (!vars || !vars.some(function (v) { return v.variable.name.value === "variables"; })) {
426
- globalThis.__DEV__ !== false && invariant.warn(
427
- 28,
428
- variables,
429
- ((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || queryDef
430
- );
431
- }
432
- }
433
- if (variables && !equal(this.options.variables, variables)) {
434
- // Update the existing options with new variables
435
- reobserveOptions.variables = this.options.variables = __assign(__assign({}, this.options.variables), variables);
436
- }
437
- this.queryInfo.resetLastWrite();
438
- return this.reobserve(reobserveOptions, NetworkStatus.refetch);
439
- };
440
- /**
441
- * A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
442
- */
443
- ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
444
- var _this = this;
445
- var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : (__assign(__assign(__assign(__assign({}, this.options), { query: this.options.query }), fetchMoreOptions), { variables: __assign(__assign({}, this.options.variables), fetchMoreOptions.variables) })))), {
446
- // The fetchMore request goes immediately to the network and does
447
- // not automatically write its result to the cache (hence no-cache
448
- // instead of network-only), because we allow the caller of
449
- // fetchMore to provide an updateQuery callback that determines how
450
- // the data gets written to the cache.
451
- fetchPolicy: "no-cache" });
452
- combinedOptions.query = this.transformDocument(combinedOptions.query);
453
- var qid = this.queryManager.generateQueryId();
454
- // If a temporary query is passed to `fetchMore`, we don't want to store
455
- // it as the last query result since it may be an optimized query for
456
- // pagination. We will however run the transforms on the original document
457
- // as well as the document passed in `fetchMoreOptions` to ensure the cache
458
- // uses the most up-to-date document which may rely on runtime conditionals.
459
- this.lastQuery =
460
- fetchMoreOptions.query ?
461
- this.transformDocument(this.options.query)
462
- : combinedOptions.query;
463
- // Simulate a loading result for the original query with
464
- // result.networkStatus === NetworkStatus.fetchMore.
465
- var queryInfo = this.queryInfo;
466
- var originalNetworkStatus = queryInfo.networkStatus;
467
- queryInfo.networkStatus = NetworkStatus.fetchMore;
468
- if (combinedOptions.notifyOnNetworkStatusChange) {
469
- this.observe();
470
- }
471
- var updatedQuerySet = new Set();
472
- var updateQuery = fetchMoreOptions === null || fetchMoreOptions === void 0 ? void 0 : fetchMoreOptions.updateQuery;
473
- var isCached = this.options.fetchPolicy !== "no-cache";
474
- if (!isCached) {
475
- invariant(updateQuery, 29);
476
- }
477
- return this.queryManager
478
- .fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore)
479
- .then(function (fetchMoreResult) {
480
- _this.queryManager.removeQuery(qid);
481
- if (queryInfo.networkStatus === NetworkStatus.fetchMore) {
482
- queryInfo.networkStatus = originalNetworkStatus;
483
- }
484
- if (isCached) {
485
- // Performing this cache update inside a cache.batch transaction ensures
486
- // any affected cache.watch watchers are notified at most once about any
487
- // updates. Most watchers will be using the QueryInfo class, which
488
- // responds to notifications by calling reobserveCacheFirst to deliver
489
- // fetchMore cache results back to this ObservableQuery.
490
- _this.queryManager.cache.batch({
491
- update: function (cache) {
492
- var updateQuery = fetchMoreOptions.updateQuery;
493
- if (updateQuery) {
494
- cache.updateQuery({
495
- query: _this.query,
496
- variables: _this.variables,
497
- returnPartialData: true,
498
- optimistic: false,
499
- }, function (previous) {
500
- return updateQuery(previous, {
501
- fetchMoreResult: fetchMoreResult.data,
502
- variables: combinedOptions.variables,
503
- });
504
- });
505
- }
506
- else {
507
- // If we're using a field policy instead of updateQuery, the only
508
- // thing we need to do is write the new data to the cache using
509
- // combinedOptions.variables (instead of this.variables, which is
510
- // what this.updateQuery uses, because it works by abusing the
511
- // original field value, keyed by the original variables).
512
- cache.writeQuery({
513
- query: combinedOptions.query,
514
- variables: combinedOptions.variables,
515
- data: fetchMoreResult.data,
516
- });
517
- }
518
- },
519
- onWatchUpdated: function (watch) {
520
- // Record the DocumentNode associated with any watched query whose
521
- // data were updated by the cache writes above.
522
- updatedQuerySet.add(watch.query);
523
- },
524
- });
525
- }
526
- else {
527
- // There is a possibility `lastResult` may not be set when
528
- // `fetchMore` is called which would cause this to crash. This should
529
- // only happen if we haven't previously reported a result. We don't
530
- // quite know what the right behavior should be here since this block
531
- // of code runs after the fetch result has executed on the network.
532
- // We plan to let it crash in the meantime.
533
- //
534
- // If we get bug reports due to the `data` property access on
535
- // undefined, this should give us a real-world scenario that we can
536
- // use to test against and determine the right behavior. If we do end
537
- // up changing this behavior, this may require, for example, an
538
- // adjustment to the types on `updateQuery` since that function
539
- // expects that the first argument always contains previous result
540
- // data, but not `undefined`.
541
- var lastResult = _this.getLast("result");
542
- var data = updateQuery(lastResult.data, {
543
- fetchMoreResult: fetchMoreResult.data,
544
- variables: combinedOptions.variables,
545
- });
546
- _this.reportResult(__assign(__assign({}, lastResult), { networkStatus: originalNetworkStatus, loading: isNetworkRequestInFlight(originalNetworkStatus), data: data }), _this.variables);
547
- }
548
- return _this.maskResult(fetchMoreResult);
549
- })
550
- .finally(function () {
551
- // In case the cache writes above did not generate a broadcast
552
- // notification (which would have been intercepted by onWatchUpdated),
553
- // likely because the written data were the same as what was already in
554
- // the cache, we still want fetchMore to deliver its final loading:false
555
- // result with the unchanged data.
556
- if (isCached && !updatedQuerySet.has(_this.query)) {
557
- _this.reobserveCacheFirst();
558
- }
559
- });
560
- };
561
- // XXX the subscription variables are separate from the query variables.
562
- // if you want to update subscription variables, right now you have to do that separately,
563
- // and you can only do it by stopping the subscription and then subscribing again with new variables.
564
- /**
565
- * A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), usually to subscribe to specific fields that were included in the query.
566
- *
567
- * This function returns _another_ function that you can call to terminate the subscription.
568
- */
569
- ObservableQuery.prototype.subscribeToMore = function (options) {
570
- var _this = this;
571
- var subscription = this.queryManager
572
- .startGraphQLSubscription({
573
- query: options.document,
574
- variables: options.variables,
575
- context: options.context,
576
- })
577
- .subscribe({
578
- next: function (subscriptionData) {
579
- var updateQuery = options.updateQuery;
580
- if (updateQuery) {
581
- _this.updateQuery(function (previous, updateOptions) {
582
- return updateQuery(previous, __assign({ subscriptionData: subscriptionData }, updateOptions));
583
- });
584
- }
585
- },
586
- error: function (err) {
587
- if (options.onError) {
588
- options.onError(err);
589
- return;
590
- }
591
- globalThis.__DEV__ !== false && invariant.error(30, err);
592
- },
593
- });
594
- this.subscriptions.add(subscription);
595
- return function () {
596
- if (_this.subscriptions.delete(subscription)) {
597
- subscription.unsubscribe();
598
- }
599
- };
600
- };
601
- /**
602
- * @deprecated `setOptions` will be removed in Apollo Client 4.0. Please use
603
- * `observableQuery.reobserve(newOptions)` instead.
604
- */
605
- ObservableQuery.prototype.setOptions = function (newOptions) {
606
- if (globalThis.__DEV__ !== false) {
607
- warnRemovedOption(newOptions, "canonizeResults", "setOptions");
608
- warnDeprecated("setOptions", function () {
609
- globalThis.__DEV__ !== false && invariant.warn(31);
610
- });
611
- }
612
- return this.reobserve(newOptions);
613
- };
614
- ObservableQuery.prototype.silentSetOptions = function (newOptions) {
615
- var mergedOptions = compact(this.options, newOptions || {});
616
- assign(this.options, mergedOptions);
617
- };
618
- /**
619
- * Update the variables of this observable query, and fetch the new results
620
- * if they've changed. Most users should prefer `refetch` instead of
621
- * `setVariables` in order to to be properly notified of results even when
622
- * they come from the cache.
623
- *
624
- * Note: the `next` callback will *not* fire if the variables have not changed
625
- * or if the result is coming from cache.
626
- *
627
- * Note: the promise will return the old results immediately if the variables
628
- * have not changed.
629
- *
630
- * Note: the promise will return null immediately if the query is not active
631
- * (there are no subscribers).
632
- *
633
- * @param variables - The new set of variables. If there are missing variables,
634
- * the previous values of those variables will be used.
635
- */
636
- ObservableQuery.prototype.setVariables = function (variables) {
637
- var _this = this;
638
- if (equal(this.variables, variables)) {
639
- // If we have no observers, then we don't actually want to make a network
640
- // request. As soon as someone observes the query, the request will kick
641
- // off. For now, we just store any changes. (See #1077)
642
- return this.observers.size ?
643
- muteDeprecations("observableQuery.result", function () { return _this.result(); })
644
- : Promise.resolve();
645
- }
646
- this.options.variables = variables;
647
- // See comment above
648
- if (!this.observers.size) {
649
- return Promise.resolve();
650
- }
651
- return this.reobserve({
652
- // Reset options.fetchPolicy to its original value.
653
- fetchPolicy: this.options.initialFetchPolicy,
654
- variables: variables,
655
- }, NetworkStatus.setVariables);
656
- };
657
- /**
658
- * A function that enables you to update the query's cached result without executing a followup GraphQL operation.
659
- *
660
- * See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.
661
- */
662
- ObservableQuery.prototype.updateQuery = function (mapFn) {
663
- var queryManager = this.queryManager;
664
- var _a = queryManager.cache.diff({
665
- query: this.options.query,
666
- variables: this.variables,
667
- returnPartialData: true,
668
- optimistic: false,
669
- }), result = _a.result, complete = _a.complete;
670
- var newResult = mapFn(result, {
671
- variables: this.variables,
672
- complete: !!complete,
673
- previousData: result,
674
- });
675
- if (newResult) {
676
- queryManager.cache.writeQuery({
677
- query: this.options.query,
678
- data: newResult,
679
- variables: this.variables,
680
- });
681
- queryManager.broadcastQueries();
682
- }
683
- };
684
- /**
685
- * A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
686
- */
687
- ObservableQuery.prototype.startPolling = function (pollInterval) {
688
- this.options.pollInterval = pollInterval;
689
- this.updatePolling();
690
- };
691
- /**
692
- * A function that instructs the query to stop polling after a previous call to `startPolling`.
693
- */
694
- ObservableQuery.prototype.stopPolling = function () {
695
- this.options.pollInterval = 0;
696
- this.updatePolling();
697
- };
698
- // Update options.fetchPolicy according to options.nextFetchPolicy.
699
- ObservableQuery.prototype.applyNextFetchPolicy = function (reason,
700
- // It's possible to use this method to apply options.nextFetchPolicy to
701
- // options.fetchPolicy even if options !== this.options, though that happens
702
- // most often when the options are temporary, used for only one request and
703
- // then thrown away, so nextFetchPolicy may not end up mattering.
704
- options) {
705
- if (options.nextFetchPolicy) {
706
- var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;
707
- if (fetchPolicy === "standby") ;
708
- else if (typeof options.nextFetchPolicy === "function") {
709
- // When someone chooses "cache-and-network" or "network-only" as their
710
- // initial FetchPolicy, they often do not want future cache updates to
711
- // trigger unconditional network requests, which is what repeatedly
712
- // applying the "cache-and-network" or "network-only" policies would
713
- // seem to imply. Instead, when the cache reports an update after the
714
- // initial network request, it may be desirable for subsequent network
715
- // requests to be triggered only if the cache result is incomplete. To
716
- // that end, the options.nextFetchPolicy option provides an easy way to
717
- // update options.fetchPolicy after the initial network request, without
718
- // having to call observableQuery.setOptions.
719
- options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {
720
- reason: reason,
721
- options: options,
722
- observable: this,
723
- initialFetchPolicy: initialFetchPolicy,
724
- });
725
- }
726
- else if (reason === "variables-changed") {
727
- options.fetchPolicy = initialFetchPolicy;
728
- }
729
- else {
730
- options.fetchPolicy = options.nextFetchPolicy;
731
- }
732
- }
733
- return options.fetchPolicy;
734
- };
735
- ObservableQuery.prototype.fetch = function (options, newNetworkStatus, query) {
736
- // TODO Make sure we update the networkStatus (and infer fetchVariables)
737
- // before actually committing to the fetch.
738
- var queryInfo = this._getOrCreateQuery();
739
- queryInfo.setObservableQuery(this);
740
- return this.queryManager["fetchConcastWithInfo"](queryInfo, options, newNetworkStatus, query);
741
- };
742
- // Turns polling on or off based on this.options.pollInterval.
743
- ObservableQuery.prototype.updatePolling = function () {
744
- var _this = this;
745
- // Avoid polling in SSR mode
746
- if (this.queryManager.ssrMode) {
747
- return;
748
- }
749
- var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
750
- if (!pollInterval || !this.hasObservers()) {
751
- if (pollingInfo) {
752
- clearTimeout(pollingInfo.timeout);
753
- delete this.pollingInfo;
754
- }
755
- return;
756
- }
757
- if (pollingInfo && pollingInfo.interval === pollInterval) {
758
- return;
759
- }
760
- invariant(pollInterval, 32);
761
- var info = pollingInfo || (this.pollingInfo = {});
762
- info.interval = pollInterval;
763
- var maybeFetch = function () {
764
- var _a, _b;
765
- if (_this.pollingInfo) {
766
- if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus) &&
767
- !((_b = (_a = _this.options).skipPollAttempt) === null || _b === void 0 ? void 0 : _b.call(_a))) {
768
- _this.reobserve({
769
- // Most fetchPolicy options don't make sense to use in a polling context, as
770
- // users wouldn't want to be polling the cache directly. However, network-only and
771
- // no-cache are both useful for when the user wants to control whether or not the
772
- // polled results are written to the cache.
773
- fetchPolicy: _this.options.initialFetchPolicy === "no-cache" ?
774
- "no-cache"
775
- : "network-only",
776
- }, NetworkStatus.poll).then(poll, poll);
777
- }
778
- else {
779
- poll();
780
- }
781
- }
782
- };
783
- var poll = function () {
784
- var info = _this.pollingInfo;
785
- if (info) {
786
- clearTimeout(info.timeout);
787
- info.timeout = setTimeout(maybeFetch, info.interval);
788
- }
789
- };
790
- poll();
791
- };
792
- ObservableQuery.prototype.updateLastResult = function (newResult, variables) {
793
- var _this = this;
794
- if (variables === void 0) { variables = this.variables; }
795
- var error = muteDeprecations("getLastError", function () {
796
- return _this.getLastError();
797
- });
798
- // Preserve this.last.error unless the variables have changed.
799
- if (error && this.last && !equal(variables, this.last.variables)) {
800
- error = void 0;
801
- }
802
- return (this.last = __assign({ result: this.queryManager.assumeImmutableResults ?
803
- newResult
804
- : cloneDeep(newResult), variables: variables }, (error ? { error: error } : null)));
805
- };
806
- ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {
807
- var _this = this;
808
- this.isTornDown = false;
809
- var useDisposableConcast =
810
- // Refetching uses a disposable Concast to allow refetches using different
811
- // options/variables, without permanently altering the options of the
812
- // original ObservableQuery.
813
- newNetworkStatus === NetworkStatus.refetch ||
814
- // The fetchMore method does not actually call the reobserve method, but,
815
- // if it did, it would definitely use a disposable Concast.
816
- newNetworkStatus === NetworkStatus.fetchMore ||
817
- // Polling uses a disposable Concast so the polling options (which force
818
- // fetchPolicy to be "network-only" or "no-cache") won't override the original options.
819
- newNetworkStatus === NetworkStatus.poll;
820
- // Save the old variables, since Object.assign may modify them below.
821
- var oldVariables = this.options.variables;
822
- var oldFetchPolicy = this.options.fetchPolicy;
823
- var mergedOptions = compact(this.options, newOptions || {});
824
- var options = useDisposableConcast ?
825
- // Disposable Concast fetches receive a shallow copy of this.options
826
- // (merged with newOptions), leaving this.options unmodified.
827
- mergedOptions
828
- : assign(this.options, mergedOptions);
829
- // Don't update options.query with the transformed query to avoid
830
- // overwriting this.options.query when we aren't using a disposable concast.
831
- // We want to ensure we can re-run the custom document transforms the next
832
- // time a request is made against the original query.
833
- var query = this.transformDocument(options.query);
834
- this.lastQuery = query;
835
- if (!useDisposableConcast) {
836
- // We can skip calling updatePolling if we're not changing this.options.
837
- this.updatePolling();
838
- // Reset options.fetchPolicy to its original value when variables change,
839
- // unless a new fetchPolicy was provided by newOptions.
840
- if (newOptions &&
841
- newOptions.variables &&
842
- !equal(newOptions.variables, oldVariables) &&
843
- // Don't mess with the fetchPolicy if it's currently "standby".
844
- options.fetchPolicy !== "standby" &&
845
- // If we're changing the fetchPolicy anyway, don't try to change it here
846
- // using applyNextFetchPolicy. The explicit options.fetchPolicy wins.
847
- (options.fetchPolicy === oldFetchPolicy ||
848
- // A `nextFetchPolicy` function has even higher priority, though,
849
- // so in that case `applyNextFetchPolicy` must be called.
850
- typeof options.nextFetchPolicy === "function")) {
851
- this.applyNextFetchPolicy("variables-changed", options);
852
- if (newNetworkStatus === void 0) {
853
- newNetworkStatus = NetworkStatus.setVariables;
854
- }
855
- }
856
- }
857
- this.waitForOwnResult && (this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy));
858
- var finishWaitingForOwnResult = function () {
859
- if (_this.concast === concast) {
860
- _this.waitForOwnResult = false;
861
- }
862
- };
863
- var variables = options.variables && __assign({}, options.variables);
864
- var _a = this.fetch(options, newNetworkStatus, query), concast = _a.concast, fromLink = _a.fromLink;
865
- var observer = {
866
- next: function (result) {
867
- if (equal(_this.variables, variables)) {
868
- finishWaitingForOwnResult();
869
- _this.reportResult(result, variables);
870
- }
871
- },
872
- error: function (error) {
873
- if (equal(_this.variables, variables)) {
874
- // Coming from `getResultsFromLink`, `error` here should always be an `ApolloError`.
875
- // However, calling `concast.cancel` can inject another type of error, so we have to
876
- // wrap it again here.
877
- if (!isApolloError(error)) {
878
- error = new ApolloError({ networkError: error });
879
- }
880
- finishWaitingForOwnResult();
881
- _this.reportError(error, variables);
882
- }
883
- },
884
- };
885
- if (!useDisposableConcast && (fromLink || !this.concast)) {
886
- // We use the {add,remove}Observer methods directly to avoid wrapping
887
- // observer with an unnecessary SubscriptionObserver object.
888
- if (this.concast && this.observer) {
889
- this.concast.removeObserver(this.observer);
890
- }
891
- this.concast = concast;
892
- this.observer = observer;
893
- }
894
- concast.addObserver(observer);
895
- return concast;
896
- };
897
- ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
898
- return preventUnhandledRejection(this.reobserveAsConcast(newOptions, newNetworkStatus).promise.then(this.maskResult));
899
- };
900
- ObservableQuery.prototype.resubscribeAfterError = function () {
901
- var _this = this;
902
- var args = [];
903
- for (var _i = 0; _i < arguments.length; _i++) {
904
- args[_i] = arguments[_i];
905
- }
906
- // If `lastError` is set in the current when the subscription is re-created,
907
- // the subscription will immediately receive the error, which will
908
- // cause it to terminate again. To avoid this, we first clear
909
- // the last error/result from the `observableQuery` before re-starting
910
- // the subscription, and restore the last value afterwards so that the
911
- // subscription has a chance to stay open.
912
- var last = this.last;
913
- muteDeprecations("resetLastResults", function () { return _this.resetLastResults(); });
914
- var subscription = this.subscribe.apply(this, args);
915
- this.last = last;
916
- return subscription;
917
- };
918
- // (Re)deliver the current result to this.observers without applying fetch
919
- // policies or making network requests.
920
- ObservableQuery.prototype.observe = function () {
921
- this.reportResult(
922
- // Passing false is important so that this.getCurrentResult doesn't
923
- // save the fetchMore result as this.lastResult, causing it to be
924
- // ignored due to the this.isDifferentFromLastResult check in
925
- // this.reportResult.
926
- this.getCurrentFullResult(false), this.variables);
927
- };
928
- ObservableQuery.prototype.reportResult = function (result, variables) {
929
- var _this = this;
930
- var lastError = muteDeprecations("getLastError", function () {
931
- return _this.getLastError();
932
- });
933
- var isDifferent = this.isDifferentFromLastResult(result, variables);
934
- // Update the last result even when isDifferentFromLastResult returns false,
935
- // because the query may be using the @nonreactive directive, and we want to
936
- // save the the latest version of any nonreactive subtrees (in case
937
- // getCurrentResult is called), even though we skip broadcasting changes.
938
- if (lastError || !result.partial || this.options.returnPartialData) {
939
- this.updateLastResult(result, variables);
940
- }
941
- if (lastError || isDifferent) {
942
- iterateObserversSafely(this.observers, "next", this.maskResult(result));
943
- }
944
- };
945
- ObservableQuery.prototype.reportError = function (error, variables) {
946
- var _this = this;
947
- // Since we don't get the current result on errors, only the error, we
948
- // must mirror the updates that occur in QueryStore.markQueryError here
949
- var errorResult = __assign(__assign({}, muteDeprecations("getLastResult", function () { return _this.getLastResult(); })), { error: error, errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false });
950
- this.updateLastResult(errorResult, variables);
951
- iterateObserversSafely(this.observers, "error", (this.last.error = error));
952
- };
953
- ObservableQuery.prototype.hasObservers = function () {
954
- return this.observers.size > 0;
955
- };
956
- ObservableQuery.prototype.tearDownQuery = function () {
957
- if (this.isTornDown)
958
- return;
959
- if (this.concast && this.observer) {
960
- this.concast.removeObserver(this.observer);
961
- delete this.concast;
962
- delete this.observer;
963
- }
964
- this.stopPolling();
965
- // stop all active GraphQL subscriptions
966
- this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
967
- this.subscriptions.clear();
968
- this.queryManager.stopQuery(this.queryId);
969
- this.observers.clear();
970
- this.isTornDown = true;
971
- };
972
- ObservableQuery.prototype.transformDocument = function (document) {
973
- return this.queryManager.transform(document);
974
- };
975
- ObservableQuery.prototype.maskResult = function (result) {
976
- return result && "data" in result ? __assign(__assign({}, result), { data: this.queryManager.maskOperation({
977
- document: this.query,
978
- data: result.data,
979
- fetchPolicy: this.options.fetchPolicy,
980
- id: this.queryId,
981
- }) }) : result;
982
- };
983
- /** @internal */
984
- ObservableQuery.prototype.resetNotifications = function () {
985
- this.cancelNotifyTimeout();
986
- this.dirty = false;
987
- };
988
- ObservableQuery.prototype.cancelNotifyTimeout = function () {
989
- if (this.notifyTimeout) {
990
- clearTimeout(this.notifyTimeout);
991
- this.notifyTimeout = void 0;
992
- }
993
- };
994
- /** @internal */
995
- ObservableQuery.prototype.scheduleNotify = function () {
996
- var _this = this;
997
- if (this.dirty)
998
- return;
999
- this.dirty = true;
1000
- if (!this.notifyTimeout) {
1001
- this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
1002
- }
1003
- };
1004
- /** @internal */
1005
- ObservableQuery.prototype.notify = function () {
1006
- this.cancelNotifyTimeout();
1007
- if (this.dirty) {
1008
- if (this.options.fetchPolicy == "cache-only" ||
1009
- this.options.fetchPolicy == "cache-and-network" ||
1010
- !isNetworkRequestInFlight(this.queryInfo.networkStatus)) {
1011
- var diff = this.queryInfo.getDiff();
1012
- if (diff.fromOptimisticTransaction) {
1013
- // If this diff came from an optimistic transaction, deliver the
1014
- // current cache data to the ObservableQuery, but don't perform a
1015
- // reobservation, since oq.reobserveCacheFirst might make a network
1016
- // request, and we never want to trigger network requests in the
1017
- // middle of optimistic updates.
1018
- this.observe();
1019
- }
1020
- else {
1021
- // Otherwise, make the ObservableQuery "reobserve" the latest data
1022
- // using a temporary fetch policy of "cache-first", so complete cache
1023
- // results have a chance to be delivered without triggering additional
1024
- // network requests, even when options.fetchPolicy is "network-only"
1025
- // or "cache-and-network". All other fetch policies are preserved by
1026
- // this method, and are handled by calling oq.reobserve(). If this
1027
- // reobservation is spurious, isDifferentFromLastResult still has a
1028
- // chance to catch it before delivery to ObservableQuery subscribers.
1029
- this.reobserveCacheFirst();
1030
- }
1031
- }
1032
- }
1033
- this.dirty = false;
1034
- };
1035
- // Reobserve with fetchPolicy effectively set to "cache-first", triggering
1036
- // delivery of any new data from the cache, possibly falling back to the network
1037
- // if any cache data are missing. This allows _complete_ cache results to be
1038
- // delivered without also kicking off unnecessary network requests when
1039
- // this.options.fetchPolicy is "cache-and-network" or "network-only". When
1040
- // this.options.fetchPolicy is any other policy ("cache-first", "cache-only",
1041
- // "standby", or "no-cache"), we call this.reobserve() as usual.
1042
- ObservableQuery.prototype.reobserveCacheFirst = function () {
1043
- var _a = this.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;
1044
- if (fetchPolicy === "cache-and-network" || fetchPolicy === "network-only") {
1045
- return this.reobserve({
1046
- fetchPolicy: "cache-first",
1047
- // Use a temporary nextFetchPolicy function that replaces itself with the
1048
- // previous nextFetchPolicy value and returns the original fetchPolicy.
1049
- nextFetchPolicy: function (currentFetchPolicy, context) {
1050
- // Replace this nextFetchPolicy function in the options object with the
1051
- // original this.options.nextFetchPolicy value.
1052
- this.nextFetchPolicy = nextFetchPolicy;
1053
- // If the original nextFetchPolicy value was a function, give it a
1054
- // chance to decide what happens here.
1055
- if (typeof this.nextFetchPolicy === "function") {
1056
- return this.nextFetchPolicy(currentFetchPolicy, context);
1057
- }
1058
- // Otherwise go back to the original this.options.fetchPolicy.
1059
- return fetchPolicy;
1060
- },
1061
- });
1062
- }
1063
- return this.reobserve();
1064
- };
1065
- /**
1066
- * @internal
1067
- * A slot used by the `useQuery` hook to indicate that `client.watchQuery`
1068
- * should not register the query immediately, but instead wait for the query to
1069
- * be started registered with the `QueryManager` when `useSyncExternalStore`
1070
- * actively subscribes to it.
1071
- */
1072
- ObservableQuery.inactiveOnCreation = new Slot();
1073
- return ObservableQuery;
1074
- }(Observable));
1075
- // Necessary because the ObservableQuery constructor has a different
1076
- // signature than the Observable constructor.
1077
- fixObservableSubclass(ObservableQuery);
1078
- function defaultSubscriptionObserverErrorCallback(error) {
1079
- globalThis.__DEV__ !== false && invariant.error(33, error.message, error.stack);
1080
- }
1081
- function logMissingFieldErrors(missing) {
1082
- if (globalThis.__DEV__ !== false && missing) {
1083
- globalThis.__DEV__ !== false && invariant.debug(34, missing);
1084
- }
1085
- }
1086
- function skipCacheDataFor(fetchPolicy /* `undefined` would mean `"cache-first"` */) {
1087
- return (fetchPolicy === "network-only" ||
1088
- fetchPolicy === "no-cache" ||
1089
- fetchPolicy === "standby");
1090
- }
1091
-
1092
- var destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)();
1093
- function wrapDestructiveCacheMethod(cache, methodName) {
1094
- var original = cache[methodName];
1095
- if (typeof original === "function") {
1096
- // @ts-expect-error this is just too generic to be typed correctly
1097
- cache[methodName] = function () {
1098
- destructiveMethodCounts.set(cache,
1099
- // The %1e15 allows the count to wrap around to 0 safely every
1100
- // quadrillion evictions, so there's no risk of overflow. To be
1101
- // clear, this is more of a pedantic principle than something
1102
- // that matters in any conceivable practical scenario.
1103
- (destructiveMethodCounts.get(cache) + 1) % 1e15);
1104
- // @ts-expect-error this is just too generic to be typed correctly
1105
- return original.apply(this, arguments);
1106
- };
1107
- }
1108
- }
1109
- // A QueryInfo object represents a single query managed by the
1110
- // QueryManager, which tracks all QueryInfo objects by queryId in its
1111
- // this.queries Map. QueryInfo objects store the latest results and errors
1112
- // for the given query, and are responsible for reporting those results to
1113
- // the corresponding ObservableQuery, via the QueryInfo.notify method.
1114
- // Results are reported asynchronously whenever setDiff marks the
1115
- // QueryInfo object as dirty, though a call to the QueryManager's
1116
- // broadcastQueries method may trigger the notification before it happens
1117
- // automatically. This class used to be a simple interface type without
1118
- // any field privacy or meaningful methods, which is why it still has so
1119
- // many public fields. The effort to lock down and simplify the QueryInfo
1120
- // interface is ongoing, and further improvements are welcome.
1121
- var QueryInfo = /** @class */ (function () {
1122
- function QueryInfo(queryManager, queryId) {
1123
- if (queryId === void 0) { queryId = queryManager.generateQueryId(); }
1124
- this.queryId = queryId;
1125
- this.document = null;
1126
- this.lastRequestId = 1;
1127
- this.stopped = false;
1128
- this.observableQuery = null;
1129
- var cache = (this.cache = queryManager.cache);
1130
- // Track how often cache.evict is called, since we want eviction to
1131
- // override the feud-stopping logic in the markResult method, by
1132
- // causing shouldWrite to return true. Wrapping the cache.evict method
1133
- // is a bit of a hack, but it saves us from having to make eviction
1134
- // counting an official part of the ApolloCache API.
1135
- if (!destructiveMethodCounts.has(cache)) {
1136
- destructiveMethodCounts.set(cache, 0);
1137
- wrapDestructiveCacheMethod(cache, "evict");
1138
- wrapDestructiveCacheMethod(cache, "modify");
1139
- wrapDestructiveCacheMethod(cache, "reset");
1140
- }
1141
- }
1142
- QueryInfo.prototype.init = function (query) {
1143
- var networkStatus = query.networkStatus || NetworkStatus.loading;
1144
- if (this.variables &&
1145
- this.networkStatus !== NetworkStatus.loading &&
1146
- !equal(this.variables, query.variables)) {
1147
- networkStatus = NetworkStatus.setVariables;
1148
- }
1149
- if (!equal(query.variables, this.variables)) {
1150
- this.lastDiff = void 0;
1151
- // Ensure we don't continue to receive cache updates for old variables
1152
- this.cancel();
1153
- }
1154
- Object.assign(this, {
1155
- document: query.document,
1156
- variables: query.variables,
1157
- networkError: null,
1158
- graphQLErrors: this.graphQLErrors || [],
1159
- networkStatus: networkStatus,
1160
- });
1161
- if (query.observableQuery) {
1162
- this.setObservableQuery(query.observableQuery);
1163
- }
1164
- if (query.lastRequestId) {
1165
- this.lastRequestId = query.lastRequestId;
1166
- }
1167
- return this;
1168
- };
1169
- QueryInfo.prototype.resetDiff = function () {
1170
- this.lastDiff = void 0;
1171
- };
1172
- QueryInfo.prototype.getDiff = function () {
1173
- var _this = this;
1174
- var options = this.getDiffOptions();
1175
- if (this.lastDiff && equal(options, this.lastDiff.options)) {
1176
- return this.lastDiff.diff;
1177
- }
1178
- this.updateWatch(this.variables);
1179
- var oq = this.observableQuery;
1180
- if (oq && oq.options.fetchPolicy === "no-cache") {
1181
- return { complete: false };
1182
- }
1183
- var diff = muteDeprecations("canonizeResults", function () {
1184
- return _this.cache.diff(options);
1185
- });
1186
- this.updateLastDiff(diff, options);
1187
- return diff;
1188
- };
1189
- QueryInfo.prototype.updateLastDiff = function (diff, options) {
1190
- this.lastDiff =
1191
- diff ?
1192
- {
1193
- diff: diff,
1194
- options: options || this.getDiffOptions(),
1195
- }
1196
- : void 0;
1197
- };
1198
- QueryInfo.prototype.getDiffOptions = function (variables) {
1199
- var _a;
1200
- if (variables === void 0) { variables = this.variables; }
1201
- return {
1202
- query: this.document,
1203
- variables: variables,
1204
- returnPartialData: true,
1205
- optimistic: true,
1206
- canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,
1207
- };
1208
- };
1209
- QueryInfo.prototype.setDiff = function (diff) {
1210
- var _this = this;
1211
- var _a;
1212
- var oldDiff = this.lastDiff && this.lastDiff.diff;
1213
- // If we are trying to deliver an incomplete cache result, we avoid
1214
- // reporting it if the query has errored, otherwise we let the broadcast try
1215
- // and repair the partial result by refetching the query. This check avoids
1216
- // a situation where a query that errors and another succeeds with
1217
- // overlapping data does not report the partial data result to the errored
1218
- // query.
1219
- //
1220
- // See https://github.com/apollographql/apollo-client/issues/11400 for more
1221
- // information on this issue.
1222
- if (diff &&
1223
- !diff.complete &&
1224
- muteDeprecations("getLastError", function () { var _a; return (_a = _this.observableQuery) === null || _a === void 0 ? void 0 : _a.getLastError(); })) {
1225
- return;
1226
- }
1227
- this.updateLastDiff(diff);
1228
- if (!equal(oldDiff && oldDiff.result, diff && diff.result)) {
1229
- (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["scheduleNotify"]();
1230
- }
1231
- };
1232
- QueryInfo.prototype.setObservableQuery = function (oq) {
1233
- if (oq === this.observableQuery)
1234
- return;
1235
- this.observableQuery = oq;
1236
- if (oq) {
1237
- oq["queryInfo"] = this;
1238
- }
1239
- };
1240
- QueryInfo.prototype.stop = function () {
1241
- var _a;
1242
- if (!this.stopped) {
1243
- this.stopped = true;
1244
- // Cancel the pending notify timeout
1245
- (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["resetNotifications"]();
1246
- this.cancel();
1247
- var oq = this.observableQuery;
1248
- if (oq)
1249
- oq.stopPolling();
1250
- }
1251
- };
1252
- QueryInfo.prototype.cancel = function () {
1253
- var _a;
1254
- (_a = this.cancelWatch) === null || _a === void 0 ? void 0 : _a.call(this);
1255
- this.cancelWatch = void 0;
1256
- };
1257
- QueryInfo.prototype.updateWatch = function (variables) {
1258
- var _this = this;
1259
- if (variables === void 0) { variables = this.variables; }
1260
- var oq = this.observableQuery;
1261
- if (oq && oq.options.fetchPolicy === "no-cache") {
1262
- return;
1263
- }
1264
- var watchOptions = __assign(__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });
1265
- if (!this.lastWatch || !equal(watchOptions, this.lastWatch)) {
1266
- this.cancel();
1267
- this.cancelWatch = this.cache.watch((this.lastWatch = watchOptions));
1268
- }
1269
- };
1270
- QueryInfo.prototype.resetLastWrite = function () {
1271
- this.lastWrite = void 0;
1272
- };
1273
- QueryInfo.prototype.shouldWrite = function (result, variables) {
1274
- var lastWrite = this.lastWrite;
1275
- return !(lastWrite &&
1276
- // If cache.evict has been called since the last time we wrote this
1277
- // data into the cache, there's a chance writing this result into
1278
- // the cache will repair what was evicted.
1279
- lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
1280
- equal(variables, lastWrite.variables) &&
1281
- equal(result.data, lastWrite.result.data));
1282
- };
1283
- QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {
1284
- var _this = this;
1285
- var _a;
1286
- var merger = new DeepMerger();
1287
- var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];
1288
- // Cancel the pending notify timeout (if it exists) to prevent extraneous network
1289
- // requests. To allow future notify timeouts, diff and dirty are reset as well.
1290
- (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["resetNotifications"]();
1291
- if ("incremental" in result && isNonEmptyArray(result.incremental)) {
1292
- var mergedData = mergeIncrementalData(this.getDiff().result, result);
1293
- result.data = mergedData;
1294
- // Detect the first chunk of a deferred query and merge it with existing
1295
- // cache data. This ensures a `cache-first` fetch policy that returns
1296
- // partial cache data or a `cache-and-network` fetch policy that already
1297
- // has full data in the cache does not complain when trying to merge the
1298
- // initial deferred server data with existing cache data.
1299
- }
1300
- else if ("hasNext" in result && result.hasNext) {
1301
- var diff = this.getDiff();
1302
- result.data = merger.merge(diff.result, result.data);
1303
- }
1304
- this.graphQLErrors = graphQLErrors;
1305
- if (options.fetchPolicy === "no-cache") {
1306
- this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));
1307
- }
1308
- else if (cacheWriteBehavior !== 0 /* CacheWriteBehavior.FORBID */) {
1309
- if (shouldWriteResult(result, options.errorPolicy)) {
1310
- // Using a transaction here so we have a chance to read the result
1311
- // back from the cache before the watch callback fires as a result
1312
- // of writeQuery, so we can store the new diff quietly and ignore
1313
- // it when we receive it redundantly from the watch callback.
1314
- this.cache.performTransaction(function (cache) {
1315
- if (_this.shouldWrite(result, options.variables)) {
1316
- cache.writeQuery({
1317
- query: document,
1318
- data: result.data,
1319
- variables: options.variables,
1320
- overwrite: cacheWriteBehavior === 1 /* CacheWriteBehavior.OVERWRITE */,
1321
- });
1322
- _this.lastWrite = {
1323
- result: result,
1324
- variables: options.variables,
1325
- dmCount: destructiveMethodCounts.get(_this.cache),
1326
- };
1327
- }
1328
- else {
1329
- // If result is the same as the last result we received from
1330
- // the network (and the variables match too), avoid writing
1331
- // result into the cache again. The wisdom of skipping this
1332
- // cache write is far from obvious, since any cache write
1333
- // could be the one that puts the cache back into a desired
1334
- // state, fixing corruption or missing data. However, if we
1335
- // always write every network result into the cache, we enable
1336
- // feuds between queries competing to update the same data in
1337
- // incompatible ways, which can lead to an endless cycle of
1338
- // cache broadcasts and useless network requests. As with any
1339
- // feud, eventually one side must step back from the brink,
1340
- // letting the other side(s) have the last word(s). There may
1341
- // be other points where we could break this cycle, such as
1342
- // silencing the broadcast for cache.writeQuery (not a good
1343
- // idea, since it just delays the feud a bit) or somehow
1344
- // avoiding the network request that just happened (also bad,
1345
- // because the server could return useful new data). All
1346
- // options considered, skipping this cache write seems to be
1347
- // the least damaging place to break the cycle, because it
1348
- // reflects the intuition that we recently wrote this exact
1349
- // result into the cache, so the cache *should* already/still
1350
- // contain this data. If some other query has clobbered that
1351
- // data in the meantime, that's too bad, but there will be no
1352
- // winners if every query blindly reverts to its own version
1353
- // of the data. This approach also gives the network a chance
1354
- // to return new data, which will be written into the cache as
1355
- // usual, notifying only those queries that are directly
1356
- // affected by the cache updates, as usual. In the future, an
1357
- // even more sophisticated cache could perhaps prevent or
1358
- // mitigate the clobbering somehow, but that would make this
1359
- // particular cache write even less important, and thus
1360
- // skipping it would be even safer than it is today.
1361
- if (_this.lastDiff && _this.lastDiff.diff.complete) {
1362
- // Reuse data from the last good (complete) diff that we
1363
- // received, when possible.
1364
- result.data = _this.lastDiff.diff.result;
1365
- return;
1366
- }
1367
- // If the previous this.diff was incomplete, fall through to
1368
- // re-reading the latest data with cache.diff, below.
1369
- }
1370
- var diffOptions = _this.getDiffOptions(options.variables);
1371
- var diff = muteDeprecations("canonizeResults", function () {
1372
- return cache.diff(diffOptions);
1373
- });
1374
- // In case the QueryManager stops this QueryInfo before its
1375
- // results are delivered, it's important to avoid restarting the
1376
- // cache watch when markResult is called. We also avoid updating
1377
- // the watch if we are writing a result that doesn't match the current
1378
- // variables to avoid race conditions from broadcasting the wrong
1379
- // result.
1380
- if (!_this.stopped && equal(_this.variables, options.variables)) {
1381
- // Any time we're about to update this.diff, we need to make
1382
- // sure we've started watching the cache.
1383
- _this.updateWatch(options.variables);
1384
- }
1385
- // If we're allowed to write to the cache, and we can read a
1386
- // complete result from the cache, update result.data to be the
1387
- // result from the cache, rather than the raw network result.
1388
- // Set without setDiff to avoid triggering a notify call, since
1389
- // we have other ways of notifying for this result.
1390
- _this.updateLastDiff(diff, diffOptions);
1391
- if (diff.complete) {
1392
- result.data = diff.result;
1393
- }
1394
- });
1395
- }
1396
- else {
1397
- this.lastWrite = void 0;
1398
- }
1399
- }
1400
- };
1401
- QueryInfo.prototype.markReady = function () {
1402
- this.networkError = null;
1403
- return (this.networkStatus = NetworkStatus.ready);
1404
- };
1405
- QueryInfo.prototype.markError = function (error) {
1406
- var _a;
1407
- this.networkStatus = NetworkStatus.error;
1408
- this.lastWrite = void 0;
1409
- (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["resetNotifications"]();
1410
- if (error.graphQLErrors) {
1411
- this.graphQLErrors = error.graphQLErrors;
1412
- }
1413
- if (error.networkError) {
1414
- this.networkError = error.networkError;
1415
- }
1416
- return error;
1417
- };
1418
- return QueryInfo;
1419
- }());
1420
- function shouldWriteResult(result, errorPolicy) {
1421
- if (errorPolicy === void 0) { errorPolicy = "none"; }
1422
- var ignoreErrors = errorPolicy === "ignore" || errorPolicy === "all";
1423
- var writeWithErrors = !graphQLResultHasError(result);
1424
- if (!writeWithErrors && ignoreErrors && result.data) {
1425
- writeWithErrors = true;
1426
- }
1427
- return writeWithErrors;
1428
- }
1429
-
1430
- var hasOwnProperty = Object.prototype.hasOwnProperty;
1431
- var IGNORE = Object.create(null);
1432
- var QueryManager = /** @class */ (function () {
1433
- function QueryManager(options) {
1434
- var _this = this;
1435
- this.clientAwareness = {};
1436
- // All the queries that the QueryManager is currently managing (not
1437
- // including mutations and subscriptions).
1438
- this.queries = new Map();
1439
- // Maps from queryId strings to Promise rejection functions for
1440
- // currently active queries and fetches.
1441
- // Use protected instead of private field so
1442
- // @apollo/experimental-nextjs-app-support can access type info.
1443
- this.fetchCancelFns = new Map();
1444
- this.transformCache = new AutoCleanedWeakCache(cacheSizes["queryManager.getDocumentInfo"] ||
1445
- 2000 /* defaultCacheSizes["queryManager.getDocumentInfo"] */);
1446
- this.queryIdCounter = 1;
1447
- this.requestIdCounter = 1;
1448
- this.mutationIdCounter = 1;
1449
- // Use protected instead of private field so
1450
- // @apollo/experimental-nextjs-app-support can access type info.
1451
- this.inFlightLinkObservables = new Trie(false);
1452
- this.noCacheWarningsByQueryId = new Set();
1453
- var defaultDocumentTransform = new DocumentTransform(function (document) { return _this.cache.transformDocument(document); },
1454
- // Allow the apollo cache to manage its own transform caches
1455
- { cache: false });
1456
- this.cache = options.cache;
1457
- this.link = options.link;
1458
- this.defaultOptions = options.defaultOptions;
1459
- this.queryDeduplication = options.queryDeduplication;
1460
- this.clientAwareness = options.clientAwareness;
1461
- this.localState = options.localState;
1462
- this.ssrMode = options.ssrMode;
1463
- this.assumeImmutableResults = options.assumeImmutableResults;
1464
- this.dataMasking = options.dataMasking;
1465
- var documentTransform = options.documentTransform;
1466
- this.documentTransform =
1467
- documentTransform ?
1468
- defaultDocumentTransform
1469
- .concat(documentTransform)
1470
- // The custom document transform may add new fragment spreads or new
1471
- // field selections, so we want to give the cache a chance to run
1472
- // again. For example, the InMemoryCache adds __typename to field
1473
- // selections and fragments from the fragment registry.
1474
- .concat(defaultDocumentTransform)
1475
- : defaultDocumentTransform;
1476
- this.defaultContext = options.defaultContext || Object.create(null);
1477
- if ((this.onBroadcast = options.onBroadcast)) {
1478
- this.mutationStore = Object.create(null);
1479
- }
1480
- }
1481
- /**
1482
- * Call this method to terminate any active query processes, making it safe
1483
- * to dispose of this QueryManager instance.
1484
- */
1485
- QueryManager.prototype.stop = function () {
1486
- var _this = this;
1487
- this.queries.forEach(function (_info, queryId) {
1488
- _this.stopQueryNoBroadcast(queryId);
1489
- });
1490
- this.cancelPendingFetches(newInvariantError(35));
1491
- };
1492
- QueryManager.prototype.cancelPendingFetches = function (error) {
1493
- this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
1494
- this.fetchCancelFns.clear();
1495
- };
1496
- QueryManager.prototype.mutate = function (_a) {
1497
- return __awaiter(this, arguments, void 0, function (_b) {
1498
- var mutationId, hasClientExports, mutationStoreValue, isOptimistic, self;
1499
- var _c, _d;
1500
- var mutation = _b.mutation, variables = _b.variables, optimisticResponse = _b.optimisticResponse, updateQueries = _b.updateQueries, _e = _b.refetchQueries, refetchQueries = _e === void 0 ? [] : _e, _f = _b.awaitRefetchQueries, awaitRefetchQueries = _f === void 0 ? false : _f, updateWithProxyFn = _b.update, onQueryUpdated = _b.onQueryUpdated, _g = _b.fetchPolicy, fetchPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.fetchPolicy) || "network-only" : _g, _h = _b.errorPolicy, errorPolicy = _h === void 0 ? ((_d = this.defaultOptions.mutate) === null || _d === void 0 ? void 0 : _d.errorPolicy) || "none" : _h, keepRootFields = _b.keepRootFields, context = _b.context;
1501
- return __generator(this, function (_j) {
1502
- switch (_j.label) {
1503
- case 0:
1504
- invariant(mutation, 36);
1505
- invariant(fetchPolicy === "network-only" || fetchPolicy === "no-cache", 37);
1506
- mutationId = this.generateMutationId();
1507
- mutation = this.cache.transformForLink(this.transform(mutation));
1508
- hasClientExports = this.getDocumentInfo(mutation).hasClientExports;
1509
- variables = this.getVariables(mutation, variables);
1510
- if (!hasClientExports) return [3 /*break*/, 2];
1511
- return [4 /*yield*/, this.localState.addExportedVariables(mutation, variables, context)];
1512
- case 1:
1513
- variables = (_j.sent());
1514
- _j.label = 2;
1515
- case 2:
1516
- mutationStoreValue = this.mutationStore &&
1517
- (this.mutationStore[mutationId] = {
1518
- mutation: mutation,
1519
- variables: variables,
1520
- loading: true,
1521
- error: null,
1522
- });
1523
- isOptimistic = optimisticResponse &&
1524
- this.markMutationOptimistic(optimisticResponse, {
1525
- mutationId: mutationId,
1526
- document: mutation,
1527
- variables: variables,
1528
- fetchPolicy: fetchPolicy,
1529
- errorPolicy: errorPolicy,
1530
- context: context,
1531
- updateQueries: updateQueries,
1532
- update: updateWithProxyFn,
1533
- keepRootFields: keepRootFields,
1534
- });
1535
- this.broadcastQueries();
1536
- self = this;
1537
- return [2 /*return*/, new Promise(function (resolve, reject) {
1538
- return asyncMap(self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: isOptimistic ? optimisticResponse : void 0 }), variables, {}, false), function (result) {
1539
- if (graphQLResultHasError(result) && errorPolicy === "none") {
1540
- throw new ApolloError({
1541
- graphQLErrors: getGraphQLErrorsFromResult(result),
1542
- });
1543
- }
1544
- if (mutationStoreValue) {
1545
- mutationStoreValue.loading = false;
1546
- mutationStoreValue.error = null;
1547
- }
1548
- var storeResult = __assign({}, result);
1549
- if (typeof refetchQueries === "function") {
1550
- refetchQueries = refetchQueries(storeResult);
1551
- }
1552
- if (errorPolicy === "ignore" && graphQLResultHasError(storeResult)) {
1553
- delete storeResult.errors;
1554
- }
1555
- return self.markMutationResult({
1556
- mutationId: mutationId,
1557
- result: storeResult,
1558
- document: mutation,
1559
- variables: variables,
1560
- fetchPolicy: fetchPolicy,
1561
- errorPolicy: errorPolicy,
1562
- context: context,
1563
- update: updateWithProxyFn,
1564
- updateQueries: updateQueries,
1565
- awaitRefetchQueries: awaitRefetchQueries,
1566
- refetchQueries: refetchQueries,
1567
- removeOptimistic: isOptimistic ? mutationId : void 0,
1568
- onQueryUpdated: onQueryUpdated,
1569
- keepRootFields: keepRootFields,
1570
- });
1571
- }).subscribe({
1572
- next: function (storeResult) {
1573
- self.broadcastQueries();
1574
- // Since mutations might receive multiple payloads from the
1575
- // ApolloLink chain (e.g. when used with @defer),
1576
- // we resolve with a SingleExecutionResult or after the final
1577
- // ExecutionPatchResult has arrived and we have assembled the
1578
- // multipart response into a single result.
1579
- if (!("hasNext" in storeResult) || storeResult.hasNext === false) {
1580
- resolve(__assign(__assign({}, storeResult), { data: self.maskOperation({
1581
- document: mutation,
1582
- data: storeResult.data,
1583
- fetchPolicy: fetchPolicy,
1584
- id: mutationId,
1585
- }) }));
1586
- }
1587
- },
1588
- error: function (err) {
1589
- if (mutationStoreValue) {
1590
- mutationStoreValue.loading = false;
1591
- mutationStoreValue.error = err;
1592
- }
1593
- if (isOptimistic) {
1594
- self.cache.removeOptimistic(mutationId);
1595
- }
1596
- self.broadcastQueries();
1597
- reject(err instanceof ApolloError ? err : (new ApolloError({
1598
- networkError: err,
1599
- })));
1600
- },
1601
- });
1602
- })];
1603
- }
1604
- });
1605
- });
1606
- };
1607
- QueryManager.prototype.markMutationResult = function (mutation, cache) {
1608
- var _this = this;
1609
- if (cache === void 0) { cache = this.cache; }
1610
- var result = mutation.result;
1611
- var cacheWrites = [];
1612
- var skipCache = mutation.fetchPolicy === "no-cache";
1613
- if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
1614
- if (!isExecutionPatchIncrementalResult(result)) {
1615
- cacheWrites.push({
1616
- result: result.data,
1617
- dataId: "ROOT_MUTATION",
1618
- query: mutation.document,
1619
- variables: mutation.variables,
1620
- });
1621
- }
1622
- if (isExecutionPatchIncrementalResult(result) &&
1623
- isNonEmptyArray(result.incremental)) {
1624
- var diff = cache.diff({
1625
- id: "ROOT_MUTATION",
1626
- // The cache complains if passed a mutation where it expects a
1627
- // query, so we transform mutations and subscriptions to queries
1628
- // (only once, thanks to this.transformCache).
1629
- query: this.getDocumentInfo(mutation.document).asQuery,
1630
- variables: mutation.variables,
1631
- optimistic: false,
1632
- returnPartialData: true,
1633
- });
1634
- var mergedData = void 0;
1635
- if (diff.result) {
1636
- mergedData = mergeIncrementalData(diff.result, result);
1637
- }
1638
- if (typeof mergedData !== "undefined") {
1639
- // cast the ExecutionPatchResult to FetchResult here since
1640
- // ExecutionPatchResult never has `data` when returned from the server
1641
- result.data = mergedData;
1642
- cacheWrites.push({
1643
- result: mergedData,
1644
- dataId: "ROOT_MUTATION",
1645
- query: mutation.document,
1646
- variables: mutation.variables,
1647
- });
1648
- }
1649
- }
1650
- var updateQueries_1 = mutation.updateQueries;
1651
- if (updateQueries_1) {
1652
- this.queries.forEach(function (_a, queryId) {
1653
- var observableQuery = _a.observableQuery;
1654
- var queryName = observableQuery && observableQuery.queryName;
1655
- if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {
1656
- return;
1657
- }
1658
- var updater = updateQueries_1[queryName];
1659
- var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
1660
- // Read the current query result from the store.
1661
- var _c = cache.diff({
1662
- query: document,
1663
- variables: variables,
1664
- returnPartialData: true,
1665
- optimistic: false,
1666
- }), currentQueryResult = _c.result, complete = _c.complete;
1667
- if (complete && currentQueryResult) {
1668
- // Run our reducer using the current query result and the mutation result.
1669
- var nextQueryResult = updater(currentQueryResult, {
1670
- mutationResult: result,
1671
- queryName: (document && getOperationName(document)) || void 0,
1672
- queryVariables: variables,
1673
- });
1674
- // Write the modified result back into the store if we got a new result.
1675
- if (nextQueryResult) {
1676
- cacheWrites.push({
1677
- result: nextQueryResult,
1678
- dataId: "ROOT_QUERY",
1679
- query: document,
1680
- variables: variables,
1681
- });
1682
- }
1683
- }
1684
- });
1685
- }
1686
- }
1687
- if (cacheWrites.length > 0 ||
1688
- (mutation.refetchQueries || "").length > 0 ||
1689
- mutation.update ||
1690
- mutation.onQueryUpdated ||
1691
- mutation.removeOptimistic) {
1692
- var results_1 = [];
1693
- this.refetchQueries({
1694
- updateCache: function (cache) {
1695
- if (!skipCache) {
1696
- cacheWrites.forEach(function (write) { return cache.write(write); });
1697
- }
1698
- // If the mutation has some writes associated with it then we need to
1699
- // apply those writes to the store by running this reducer again with
1700
- // a write action.
1701
- var update = mutation.update;
1702
- // Determine whether result is a SingleExecutionResult,
1703
- // or the final ExecutionPatchResult.
1704
- var isFinalResult = !isExecutionPatchResult(result) ||
1705
- (isExecutionPatchIncrementalResult(result) && !result.hasNext);
1706
- if (update) {
1707
- if (!skipCache) {
1708
- // Re-read the ROOT_MUTATION data we just wrote into the cache
1709
- // (the first cache.write call in the cacheWrites.forEach loop
1710
- // above), so field read functions have a chance to run for
1711
- // fields within mutation result objects.
1712
- var diff = cache.diff({
1713
- id: "ROOT_MUTATION",
1714
- // The cache complains if passed a mutation where it expects a
1715
- // query, so we transform mutations and subscriptions to queries
1716
- // (only once, thanks to this.transformCache).
1717
- query: _this.getDocumentInfo(mutation.document).asQuery,
1718
- variables: mutation.variables,
1719
- optimistic: false,
1720
- returnPartialData: true,
1721
- });
1722
- if (diff.complete) {
1723
- result = __assign(__assign({}, result), { data: diff.result });
1724
- if ("incremental" in result) {
1725
- delete result.incremental;
1726
- }
1727
- if ("hasNext" in result) {
1728
- delete result.hasNext;
1729
- }
1730
- }
1731
- }
1732
- // If we've received the whole response,
1733
- // either a SingleExecutionResult or the final ExecutionPatchResult,
1734
- // call the update function.
1735
- if (isFinalResult) {
1736
- update(cache, result, {
1737
- context: mutation.context,
1738
- variables: mutation.variables,
1739
- });
1740
- }
1741
- }
1742
- // TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it
1743
- // shallow to allow rolling back optimistic evictions.
1744
- if (!skipCache && !mutation.keepRootFields && isFinalResult) {
1745
- cache.modify({
1746
- id: "ROOT_MUTATION",
1747
- fields: function (value, _a) {
1748
- var fieldName = _a.fieldName, DELETE = _a.DELETE;
1749
- return fieldName === "__typename" ? value : DELETE;
1750
- },
1751
- });
1752
- }
1753
- },
1754
- include: mutation.refetchQueries,
1755
- // Write the final mutation.result to the root layer of the cache.
1756
- optimistic: false,
1757
- // Remove the corresponding optimistic layer at the same time as we
1758
- // write the final non-optimistic result.
1759
- removeOptimistic: mutation.removeOptimistic,
1760
- // Let the caller of client.mutate optionally determine the refetching
1761
- // behavior for watched queries after the mutation.update function runs.
1762
- // If no onQueryUpdated function was provided for this mutation, pass
1763
- // null instead of undefined to disable the default refetching behavior.
1764
- onQueryUpdated: mutation.onQueryUpdated || null,
1765
- }).forEach(function (result) { return results_1.push(result); });
1766
- if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
1767
- // Returning a promise here makes the mutation await that promise, so we
1768
- // include results in that promise's work if awaitRefetchQueries or an
1769
- // onQueryUpdated function was specified.
1770
- return Promise.all(results_1).then(function () { return result; });
1771
- }
1772
- }
1773
- return Promise.resolve(result);
1774
- };
1775
- QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
1776
- var _this = this;
1777
- var data = typeof optimisticResponse === "function" ?
1778
- optimisticResponse(mutation.variables, { IGNORE: IGNORE })
1779
- : optimisticResponse;
1780
- if (data === IGNORE) {
1781
- return false;
1782
- }
1783
- this.cache.recordOptimisticTransaction(function (cache) {
1784
- try {
1785
- _this.markMutationResult(__assign(__assign({}, mutation), { result: { data: data } }), cache);
1786
- }
1787
- catch (error) {
1788
- globalThis.__DEV__ !== false && invariant.error(error);
1789
- }
1790
- }, mutation.mutationId);
1791
- return true;
1792
- };
1793
- QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
1794
- return this.fetchConcastWithInfo(this.getOrCreateQuery(queryId), options, networkStatus).concast.promise;
1795
- };
1796
- QueryManager.prototype.getQueryStore = function () {
1797
- var store = Object.create(null);
1798
- this.queries.forEach(function (info, queryId) {
1799
- store[queryId] = {
1800
- variables: info.variables,
1801
- networkStatus: info.networkStatus,
1802
- networkError: info.networkError,
1803
- graphQLErrors: info.graphQLErrors,
1804
- };
1805
- });
1806
- return store;
1807
- };
1808
- QueryManager.prototype.resetErrors = function (queryId) {
1809
- var queryInfo = this.queries.get(queryId);
1810
- if (queryInfo) {
1811
- queryInfo.networkError = undefined;
1812
- queryInfo.graphQLErrors = [];
1813
- }
1814
- };
1815
- QueryManager.prototype.transform = function (document) {
1816
- return this.documentTransform.transformDocument(document);
1817
- };
1818
- QueryManager.prototype.getDocumentInfo = function (document) {
1819
- var transformCache = this.transformCache;
1820
- if (!transformCache.has(document)) {
1821
- var cacheEntry = {
1822
- // TODO These three calls (hasClientExports, shouldForceResolvers, and
1823
- // usesNonreactiveDirective) are performing independent full traversals
1824
- // of the transformed document. We should consider merging these
1825
- // traversals into a single pass in the future, though the work is
1826
- // cached after the first time.
1827
- hasClientExports: hasClientExports(document),
1828
- hasForcedResolvers: this.localState.shouldForceResolvers(document),
1829
- hasNonreactiveDirective: hasDirectives(["nonreactive"], document),
1830
- nonReactiveQuery: addNonReactiveToNamedFragments(document),
1831
- clientQuery: this.localState.clientQuery(document),
1832
- serverQuery: removeDirectivesFromDocument([
1833
- { name: "client", remove: true },
1834
- { name: "connection" },
1835
- { name: "nonreactive" },
1836
- { name: "unmask" },
1837
- ], document),
1838
- defaultVars: getDefaultValues(getOperationDefinition(document)),
1839
- // Transform any mutation or subscription operations to query operations
1840
- // so we can read/write them from/to the cache.
1841
- asQuery: __assign(__assign({}, document), { definitions: document.definitions.map(function (def) {
1842
- if (def.kind === "OperationDefinition" &&
1843
- def.operation !== "query") {
1844
- return __assign(__assign({}, def), { operation: "query" });
1845
- }
1846
- return def;
1847
- }) }),
1848
- };
1849
- transformCache.set(document, cacheEntry);
1850
- }
1851
- return transformCache.get(document);
1852
- };
1853
- QueryManager.prototype.getVariables = function (document, variables) {
1854
- return __assign(__assign({}, this.getDocumentInfo(document).defaultVars), variables);
1855
- };
1856
- QueryManager.prototype.watchQuery = function (options) {
1857
- var query = this.transform(options.query);
1858
- // assign variable default values if supplied
1859
- // NOTE: We don't modify options.query here with the transformed query to
1860
- // ensure observable.options.query is set to the raw untransformed query.
1861
- options = __assign(__assign({}, options), { variables: this.getVariables(query, options.variables) });
1862
- if (typeof options.notifyOnNetworkStatusChange === "undefined") {
1863
- options.notifyOnNetworkStatusChange = false;
1864
- }
1865
- var queryInfo = new QueryInfo(this);
1866
- var observable = new ObservableQuery({
1867
- queryManager: this,
1868
- queryInfo: queryInfo,
1869
- options: options,
1870
- });
1871
- observable["lastQuery"] = query;
1872
- if (!ObservableQuery["inactiveOnCreation"].getValue()) {
1873
- this.queries.set(observable.queryId, queryInfo);
1874
- }
1875
- // We give queryInfo the transformed query to ensure the first cache diff
1876
- // uses the transformed query instead of the raw query
1877
- queryInfo.init({
1878
- document: query,
1879
- observableQuery: observable,
1880
- variables: observable.variables,
1881
- });
1882
- return observable;
1883
- };
1884
- QueryManager.prototype.query = function (options, queryId) {
1885
- var _this = this;
1886
- if (queryId === void 0) { queryId = this.generateQueryId(); }
1887
- invariant(options.query, 38);
1888
- invariant(options.query.kind === "Document", 39);
1889
- invariant(!options.returnPartialData, 40);
1890
- invariant(!options.pollInterval, 41);
1891
- var query = this.transform(options.query);
1892
- return this.fetchQuery(queryId, __assign(__assign({}, options), { query: query }))
1893
- .then(function (result) {
1894
- return result && __assign(__assign({}, result), { data: _this.maskOperation({
1895
- document: query,
1896
- data: result.data,
1897
- fetchPolicy: options.fetchPolicy,
1898
- id: queryId,
1899
- }) });
1900
- })
1901
- .finally(function () { return _this.stopQuery(queryId); });
1902
- };
1903
- QueryManager.prototype.generateQueryId = function () {
1904
- return String(this.queryIdCounter++);
1905
- };
1906
- QueryManager.prototype.generateRequestId = function () {
1907
- return this.requestIdCounter++;
1908
- };
1909
- QueryManager.prototype.generateMutationId = function () {
1910
- return String(this.mutationIdCounter++);
1911
- };
1912
- QueryManager.prototype.stopQueryInStore = function (queryId) {
1913
- this.stopQueryInStoreNoBroadcast(queryId);
1914
- this.broadcastQueries();
1915
- };
1916
- QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
1917
- var queryInfo = this.queries.get(queryId);
1918
- if (queryInfo)
1919
- queryInfo.stop();
1920
- };
1921
- QueryManager.prototype.clearStore = function (options) {
1922
- if (options === void 0) { options = {
1923
- discardWatches: true,
1924
- }; }
1925
- // Before we have sent the reset action to the store, we can no longer
1926
- // rely on the results returned by in-flight requests since these may
1927
- // depend on values that previously existed in the data portion of the
1928
- // store. So, we cancel the promises and observers that we have issued
1929
- // so far and not yet resolved (in the case of queries).
1930
- this.cancelPendingFetches(newInvariantError(42));
1931
- this.queries.forEach(function (queryInfo) {
1932
- if (queryInfo.observableQuery) {
1933
- // Set loading to true so listeners don't trigger unless they want
1934
- // results with partial data.
1935
- queryInfo.networkStatus = NetworkStatus.loading;
1936
- }
1937
- else {
1938
- queryInfo.stop();
1939
- }
1940
- });
1941
- if (this.mutationStore) {
1942
- this.mutationStore = Object.create(null);
1943
- }
1944
- // begin removing data from the store
1945
- return this.cache.reset(options);
1946
- };
1947
- QueryManager.prototype.getObservableQueries = function (include) {
1948
- var _this = this;
1949
- if (include === void 0) { include = "active"; }
1950
- var queries = new Map();
1951
- var queryNames = new Map();
1952
- var queryNamesAndQueryStrings = new Map();
1953
- var legacyQueryOptions = new Set();
1954
- if (Array.isArray(include)) {
1955
- include.forEach(function (desc) {
1956
- if (typeof desc === "string") {
1957
- queryNames.set(desc, desc);
1958
- queryNamesAndQueryStrings.set(desc, false);
1959
- }
1960
- else if (isDocumentNode(desc)) {
1961
- var queryString = print(_this.transform(desc));
1962
- queryNames.set(queryString, getOperationName(desc));
1963
- queryNamesAndQueryStrings.set(queryString, false);
1964
- }
1965
- else if (isNonNullObject(desc) && desc.query) {
1966
- legacyQueryOptions.add(desc);
1967
- }
1968
- });
1969
- }
1970
- this.queries.forEach(function (_a, queryId) {
1971
- var oq = _a.observableQuery, document = _a.document;
1972
- if (oq) {
1973
- if (include === "all") {
1974
- queries.set(queryId, oq);
1975
- return;
1976
- }
1977
- var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
1978
- if (fetchPolicy === "standby" ||
1979
- (include === "active" && !oq.hasObservers())) {
1980
- return;
1981
- }
1982
- if (include === "active" ||
1983
- (queryName && queryNamesAndQueryStrings.has(queryName)) ||
1984
- (document && queryNamesAndQueryStrings.has(print(document)))) {
1985
- queries.set(queryId, oq);
1986
- if (queryName)
1987
- queryNamesAndQueryStrings.set(queryName, true);
1988
- if (document)
1989
- queryNamesAndQueryStrings.set(print(document), true);
1990
- }
1991
- }
1992
- });
1993
- if (legacyQueryOptions.size) {
1994
- legacyQueryOptions.forEach(function (options) {
1995
- // We will be issuing a fresh network request for this query, so we
1996
- // pre-allocate a new query ID here, using a special prefix to enable
1997
- // cleaning up these temporary queries later, after fetching.
1998
- var queryId = makeUniqueId("legacyOneTimeQuery");
1999
- var queryInfo = _this.getOrCreateQuery(queryId).init({
2000
- document: options.query,
2001
- variables: options.variables,
2002
- });
2003
- var oq = new ObservableQuery({
2004
- queryManager: _this,
2005
- queryInfo: queryInfo,
2006
- options: __assign(__assign({}, options), { fetchPolicy: "network-only" }),
2007
- });
2008
- invariant(oq.queryId === queryId);
2009
- queryInfo.setObservableQuery(oq);
2010
- queries.set(queryId, oq);
2011
- });
2012
- }
2013
- if (globalThis.__DEV__ !== false && queryNamesAndQueryStrings.size) {
2014
- queryNamesAndQueryStrings.forEach(function (included, nameOrQueryString) {
2015
- if (!included) {
2016
- var queryName = queryNames.get(nameOrQueryString);
2017
- if (queryName) {
2018
- globalThis.__DEV__ !== false && invariant.warn(43, queryName);
2019
- }
2020
- else {
2021
- globalThis.__DEV__ !== false && invariant.warn(44);
2022
- }
2023
- }
2024
- });
2025
- }
2026
- return queries;
2027
- };
2028
- QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
2029
- var _this = this;
2030
- if (includeStandby === void 0) { includeStandby = false; }
2031
- var observableQueryPromises = [];
2032
- this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
2033
- var fetchPolicy = observableQuery.options.fetchPolicy;
2034
- muteDeprecations("resetLastResults", function () {
2035
- return observableQuery.resetLastResults();
2036
- });
2037
- if (includeStandby ||
2038
- (fetchPolicy !== "standby" && fetchPolicy !== "cache-only")) {
2039
- observableQueryPromises.push(observableQuery.refetch());
2040
- }
2041
- (_this.queries.get(queryId) || observableQuery["queryInfo"]).setDiff(null);
2042
- });
2043
- this.broadcastQueries();
2044
- return Promise.all(observableQueryPromises);
2045
- };
2046
- QueryManager.prototype.startGraphQLSubscription = function (options) {
2047
- var _this = this;
2048
- var query = options.query, variables = options.variables;
2049
- var fetchPolicy = options.fetchPolicy, _a = options.errorPolicy, errorPolicy = _a === void 0 ? "none" : _a, _b = options.context, context = _b === void 0 ? {} : _b, _c = options.extensions, extensions = _c === void 0 ? {} : _c;
2050
- query = this.transform(query);
2051
- variables = this.getVariables(query, variables);
2052
- var makeObservable = function (variables) {
2053
- return _this.getObservableFromLink(query, context, variables, extensions).map(function (result) {
2054
- if (fetchPolicy !== "no-cache") {
2055
- // the subscription interface should handle not sending us results we no longer subscribe to.
2056
- // XXX I don't think we ever send in an object with errors, but we might in the future...
2057
- if (shouldWriteResult(result, errorPolicy)) {
2058
- _this.cache.write({
2059
- query: query,
2060
- result: result.data,
2061
- dataId: "ROOT_SUBSCRIPTION",
2062
- variables: variables,
2063
- });
2064
- }
2065
- _this.broadcastQueries();
2066
- }
2067
- var hasErrors = graphQLResultHasError(result);
2068
- var hasProtocolErrors = graphQLResultHasProtocolErrors(result);
2069
- if (hasErrors || hasProtocolErrors) {
2070
- var errors = {};
2071
- if (hasErrors) {
2072
- errors.graphQLErrors = result.errors;
2073
- }
2074
- if (hasProtocolErrors) {
2075
- errors.protocolErrors = result.extensions[PROTOCOL_ERRORS_SYMBOL];
2076
- }
2077
- // `errorPolicy` is a mechanism for handling GraphQL errors, according
2078
- // to our documentation, so we throw protocol errors regardless of the
2079
- // set error policy.
2080
- if (errorPolicy === "none" || hasProtocolErrors) {
2081
- throw new ApolloError(errors);
2082
- }
2083
- }
2084
- if (errorPolicy === "ignore") {
2085
- delete result.errors;
2086
- }
2087
- return result;
2088
- });
2089
- };
2090
- if (this.getDocumentInfo(query).hasClientExports) {
2091
- var observablePromise_1 = this.localState
2092
- .addExportedVariables(query, variables, context)
2093
- .then(makeObservable);
2094
- return new Observable(function (observer) {
2095
- var sub = null;
2096
- observablePromise_1.then(function (observable) { return (sub = observable.subscribe(observer)); }, observer.error);
2097
- return function () { return sub && sub.unsubscribe(); };
2098
- });
2099
- }
2100
- return makeObservable(variables);
2101
- };
2102
- QueryManager.prototype.stopQuery = function (queryId) {
2103
- this.stopQueryNoBroadcast(queryId);
2104
- this.broadcastQueries();
2105
- };
2106
- QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
2107
- this.stopQueryInStoreNoBroadcast(queryId);
2108
- this.removeQuery(queryId);
2109
- };
2110
- QueryManager.prototype.removeQuery = function (queryId) {
2111
- var _a;
2112
- // teardown all links
2113
- // Both `QueryManager.fetchRequest` and `QueryManager.query` create separate promises
2114
- // that each add their reject functions to fetchCancelFns.
2115
- // A query created with `QueryManager.query()` could trigger a `QueryManager.fetchRequest`.
2116
- // The same queryId could have two rejection fns for two promises
2117
- this.fetchCancelFns.delete(queryId);
2118
- if (this.queries.has(queryId)) {
2119
- (_a = this.queries.get(queryId)) === null || _a === void 0 ? void 0 : _a.stop();
2120
- this.queries.delete(queryId);
2121
- }
2122
- };
2123
- QueryManager.prototype.broadcastQueries = function () {
2124
- if (this.onBroadcast)
2125
- this.onBroadcast();
2126
- this.queries.forEach(function (info) { var _a; return (_a = info.observableQuery) === null || _a === void 0 ? void 0 : _a["notify"](); });
2127
- };
2128
- QueryManager.prototype.getLocalState = function () {
2129
- return this.localState;
2130
- };
2131
- QueryManager.prototype.getObservableFromLink = function (query, context, variables, extensions,
2132
- // Prefer context.queryDeduplication if specified.
2133
- deduplication) {
2134
- var _this = this;
2135
- var _a;
2136
- if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
2137
- var observable;
2138
- var _b = this.getDocumentInfo(query), serverQuery = _b.serverQuery, clientQuery = _b.clientQuery;
2139
- if (serverQuery) {
2140
- var _c = this, inFlightLinkObservables_1 = _c.inFlightLinkObservables, link = _c.link;
2141
- var operation = {
2142
- query: serverQuery,
2143
- variables: variables,
2144
- operationName: getOperationName(serverQuery) || void 0,
2145
- context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),
2146
- extensions: extensions,
2147
- };
2148
- context = operation.context;
2149
- if (deduplication) {
2150
- var printedServerQuery_1 = print(serverQuery);
2151
- var varJson_1 = canonicalStringify(variables);
2152
- var entry = inFlightLinkObservables_1.lookup(printedServerQuery_1, varJson_1);
2153
- observable = entry.observable;
2154
- if (!observable) {
2155
- var concast_1 = new Concast([
2156
- execute(link, operation),
2157
- ]);
2158
- observable = entry.observable = concast_1;
2159
- concast_1.beforeNext(function cb(method, arg) {
2160
- if (method === "next" && "hasNext" in arg && arg.hasNext) {
2161
- concast_1.beforeNext(cb);
2162
- }
2163
- else {
2164
- inFlightLinkObservables_1.remove(printedServerQuery_1, varJson_1);
2165
- }
2166
- });
2167
- }
2168
- }
2169
- else {
2170
- observable = new Concast([
2171
- execute(link, operation),
2172
- ]);
2173
- }
2174
- }
2175
- else {
2176
- observable = new Concast([Observable.of({ data: {} })]);
2177
- context = this.prepareContext(context);
2178
- }
2179
- if (clientQuery) {
2180
- observable = asyncMap(observable, function (result) {
2181
- return _this.localState.runResolvers({
2182
- document: clientQuery,
2183
- remoteResult: result,
2184
- context: context,
2185
- variables: variables,
2186
- });
2187
- });
2188
- }
2189
- return observable;
2190
- };
2191
- QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
2192
- var requestId = (queryInfo.lastRequestId = this.generateRequestId());
2193
- // Performing transformForLink here gives this.cache a chance to fill in
2194
- // missing fragment definitions (for example) before sending this document
2195
- // through the link chain.
2196
- var linkDocument = this.cache.transformForLink(options.query);
2197
- return asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
2198
- var graphQLErrors = getGraphQLErrorsFromResult(result);
2199
- var hasErrors = graphQLErrors.length > 0;
2200
- var errorPolicy = options.errorPolicy;
2201
- // If we interrupted this request by calling getResultsFromLink again
2202
- // with the same QueryInfo object, we ignore the old results.
2203
- if (requestId >= queryInfo.lastRequestId) {
2204
- if (hasErrors && errorPolicy === "none") {
2205
- // Throwing here effectively calls observer.error.
2206
- throw queryInfo.markError(new ApolloError({
2207
- graphQLErrors: graphQLErrors,
2208
- }));
2209
- }
2210
- // Use linkDocument rather than queryInfo.document so the
2211
- // operation/fragments used to write the result are the same as the
2212
- // ones used to obtain it from the link.
2213
- queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
2214
- queryInfo.markReady();
2215
- }
2216
- var aqr = {
2217
- data: result.data,
2218
- loading: false,
2219
- networkStatus: NetworkStatus.ready,
2220
- };
2221
- // In the case we start multiple network requests simulatenously, we
2222
- // want to ensure we properly set `data` if we're reporting on an old
2223
- // result which will not be caught by the conditional above that ends up
2224
- // throwing the markError result.
2225
- if (hasErrors && errorPolicy === "none") {
2226
- aqr.data = void 0;
2227
- }
2228
- if (hasErrors && errorPolicy !== "ignore") {
2229
- aqr.errors = graphQLErrors;
2230
- aqr.networkStatus = NetworkStatus.error;
2231
- }
2232
- return aqr;
2233
- }, function (networkError) {
2234
- var error = isApolloError(networkError) ? networkError : (new ApolloError({ networkError: networkError }));
2235
- // Avoid storing errors from older interrupted queries.
2236
- if (requestId >= queryInfo.lastRequestId) {
2237
- queryInfo.markError(error);
2238
- }
2239
- throw error;
2240
- });
2241
- };
2242
- QueryManager.prototype.fetchConcastWithInfo = function (queryInfo, options,
2243
- // The initial networkStatus for this fetch, most often
2244
- // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
2245
- // or setVariables.
2246
- networkStatus, query) {
2247
- var _this = this;
2248
- if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }
2249
- if (query === void 0) { query = options.query; }
2250
- var variables = this.getVariables(query, options.variables);
2251
- var defaults = this.defaultOptions.watchQuery;
2252
- var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? (defaults && defaults.fetchPolicy) || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? (defaults && defaults.errorPolicy) || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
2253
- var normalized = Object.assign({}, options, {
2254
- query: query,
2255
- variables: variables,
2256
- fetchPolicy: fetchPolicy,
2257
- errorPolicy: errorPolicy,
2258
- returnPartialData: returnPartialData,
2259
- notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
2260
- context: context,
2261
- });
2262
- var fromVariables = function (variables) {
2263
- // Since normalized is always a fresh copy of options, it's safe to
2264
- // modify its properties here, rather than creating yet another new
2265
- // WatchQueryOptions object.
2266
- normalized.variables = variables;
2267
- var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
2268
- if (
2269
- // If we're in standby, postpone advancing options.fetchPolicy using
2270
- // applyNextFetchPolicy.
2271
- normalized.fetchPolicy !== "standby" &&
2272
- // The "standby" policy currently returns [] from fetchQueryByPolicy, so
2273
- // this is another way to detect when nothing was done/fetched.
2274
- sourcesWithInfo.sources.length > 0 &&
2275
- queryInfo.observableQuery) {
2276
- queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
2277
- }
2278
- return sourcesWithInfo;
2279
- };
2280
- // This cancel function needs to be set before the concast is created,
2281
- // in case concast creation synchronously cancels the request.
2282
- var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryInfo.queryId); };
2283
- this.fetchCancelFns.set(queryInfo.queryId, function (reason) {
2284
- cleanupCancelFn();
2285
- // This delay ensures the concast variable has been initialized.
2286
- setTimeout(function () { return concast.cancel(reason); });
2287
- });
2288
- var concast, containsDataFromLink;
2289
- // If the query has @export(as: ...) directives, then we need to
2290
- // process those directives asynchronously. When there are no
2291
- // @export directives (the common case), we deliberately avoid
2292
- // wrapping the result of this.fetchQueryByPolicy in a Promise,
2293
- // since the timing of result delivery is (unfortunately) important
2294
- // for backwards compatibility. TODO This code could be simpler if
2295
- // we deprecated and removed LocalState.
2296
- if (this.getDocumentInfo(normalized.query).hasClientExports) {
2297
- concast = new Concast(this.localState
2298
- .addExportedVariables(normalized.query, normalized.variables, normalized.context)
2299
- .then(fromVariables)
2300
- .then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));
2301
- // there is just no way we can synchronously get the *right* value here,
2302
- // so we will assume `true`, which is the behaviour before the bug fix in
2303
- // #10597. This means that bug is not fixed in that case, and is probably
2304
- // un-fixable with reasonable effort for the edge case of @export as
2305
- // directives.
2306
- containsDataFromLink = true;
2307
- }
2308
- else {
2309
- var sourcesWithInfo = fromVariables(normalized.variables);
2310
- containsDataFromLink = sourcesWithInfo.fromLink;
2311
- concast = new Concast(sourcesWithInfo.sources);
2312
- }
2313
- concast.promise.then(cleanupCancelFn, cleanupCancelFn);
2314
- return {
2315
- concast: concast,
2316
- fromLink: containsDataFromLink,
2317
- };
2318
- };
2319
- QueryManager.prototype.refetchQueries = function (_a) {
2320
- var _this = this;
2321
- var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
2322
- var includedQueriesById = new Map();
2323
- if (include) {
2324
- this.getObservableQueries(include).forEach(function (oq, queryId) {
2325
- includedQueriesById.set(queryId, {
2326
- oq: oq,
2327
- lastDiff: (_this.queries.get(queryId) || oq["queryInfo"]).getDiff(),
2328
- });
2329
- });
2330
- }
2331
- var results = new Map();
2332
- if (updateCache) {
2333
- this.cache.batch({
2334
- update: updateCache,
2335
- // Since you can perform any combination of cache reads and/or writes in
2336
- // the cache.batch update function, its optimistic option can be either
2337
- // a boolean or a string, representing three distinct modes of
2338
- // operation:
2339
- //
2340
- // * false: read/write only the root layer
2341
- // * true: read/write the topmost layer
2342
- // * string: read/write a fresh optimistic layer with that ID string
2343
- //
2344
- // When typeof optimistic === "string", a new optimistic layer will be
2345
- // temporarily created within cache.batch with that string as its ID. If
2346
- // we then pass that same string as the removeOptimistic option, we can
2347
- // make cache.batch immediately remove the optimistic layer after
2348
- // running the updateCache function, triggering only one broadcast.
2349
- //
2350
- // However, the refetchQueries method accepts only true or false for its
2351
- // optimistic option (not string). We interpret true to mean a temporary
2352
- // optimistic layer should be created, to allow efficiently rolling back
2353
- // the effect of the updateCache function, which involves passing a
2354
- // string instead of true as the optimistic option to cache.batch, when
2355
- // refetchQueries receives optimistic: true.
2356
- //
2357
- // In other words, we are deliberately not supporting the use case of
2358
- // writing to an *existing* optimistic layer (using the refetchQueries
2359
- // updateCache function), since that would potentially interfere with
2360
- // other optimistic updates in progress. Instead, you can read/write
2361
- // only the root layer by passing optimistic: false to refetchQueries,
2362
- // or you can read/write a brand new optimistic layer that will be
2363
- // automatically removed by passing optimistic: true.
2364
- optimistic: (optimistic && removeOptimistic) || false,
2365
- // The removeOptimistic option can also be provided by itself, even if
2366
- // optimistic === false, to remove some previously-added optimistic
2367
- // layer safely and efficiently, like we do in markMutationResult.
2368
- //
2369
- // If an explicit removeOptimistic string is provided with optimistic:
2370
- // true, the removeOptimistic string will determine the ID of the
2371
- // temporary optimistic layer, in case that ever matters.
2372
- removeOptimistic: removeOptimistic,
2373
- onWatchUpdated: function (watch, diff, lastDiff) {
2374
- var oq = watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;
2375
- if (oq) {
2376
- if (onQueryUpdated) {
2377
- // Since we're about to handle this query now, remove it from
2378
- // includedQueriesById, in case it was added earlier because of
2379
- // options.include.
2380
- includedQueriesById.delete(oq.queryId);
2381
- var result = onQueryUpdated(oq, diff, lastDiff);
2382
- if (result === true) {
2383
- // The onQueryUpdated function requested the default refetching
2384
- // behavior by returning true.
2385
- result = oq.refetch();
2386
- }
2387
- // Record the result in the results Map, as long as onQueryUpdated
2388
- // did not return false to skip/ignore this result.
2389
- if (result !== false) {
2390
- results.set(oq, result);
2391
- }
2392
- // Allow the default cache broadcast to happen, except when
2393
- // onQueryUpdated returns false.
2394
- return result;
2395
- }
2396
- if (onQueryUpdated !== null) {
2397
- // If we don't have an onQueryUpdated function, and onQueryUpdated
2398
- // was not disabled by passing null, make sure this query is
2399
- // "included" like any other options.include-specified query.
2400
- includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
2401
- }
2402
- }
2403
- },
2404
- });
2405
- }
2406
- if (includedQueriesById.size) {
2407
- includedQueriesById.forEach(function (_a, queryId) {
2408
- var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
2409
- var result;
2410
- // If onQueryUpdated is provided, we want to use it for all included
2411
- // queries, even the QueryOptions ones.
2412
- if (onQueryUpdated) {
2413
- if (!diff) {
2414
- diff = muteDeprecations("canonizeResults", function () {
2415
- return _this.cache.diff(oq["queryInfo"]["getDiffOptions"]());
2416
- });
2417
- }
2418
- result = onQueryUpdated(oq, diff, lastDiff);
2419
- }
2420
- // Otherwise, we fall back to refetching.
2421
- if (!onQueryUpdated || result === true) {
2422
- result = oq.refetch();
2423
- }
2424
- if (result !== false) {
2425
- results.set(oq, result);
2426
- }
2427
- if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
2428
- _this.stopQueryNoBroadcast(queryId);
2429
- }
2430
- });
2431
- }
2432
- if (removeOptimistic) {
2433
- // In case no updateCache callback was provided (so cache.batch was not
2434
- // called above, and thus did not already remove the optimistic layer),
2435
- // remove it here. Since this is a no-op when the layer has already been
2436
- // removed, we do it even if we called cache.batch above, since it's
2437
- // possible this.cache is an instance of some ApolloCache subclass other
2438
- // than InMemoryCache, and does not fully support the removeOptimistic
2439
- // option for cache.batch.
2440
- this.cache.removeOptimistic(removeOptimistic);
2441
- }
2442
- return results;
2443
- };
2444
- QueryManager.prototype.maskOperation = function (options) {
2445
- var _a, _b, _c;
2446
- var document = options.document, data = options.data;
2447
- if (globalThis.__DEV__ !== false) {
2448
- var fetchPolicy = options.fetchPolicy, id = options.id;
2449
- var operationType = (_a = getOperationDefinition(document)) === null || _a === void 0 ? void 0 : _a.operation;
2450
- var operationId = ((_b = operationType === null || operationType === void 0 ? void 0 : operationType[0]) !== null && _b !== void 0 ? _b : "o") + id;
2451
- if (this.dataMasking &&
2452
- fetchPolicy === "no-cache" &&
2453
- !isFullyUnmaskedOperation(document) &&
2454
- !this.noCacheWarningsByQueryId.has(operationId)) {
2455
- this.noCacheWarningsByQueryId.add(operationId);
2456
- globalThis.__DEV__ !== false && invariant.warn(
2457
- 45,
2458
- (_c = getOperationName(document)) !== null && _c !== void 0 ? _c : "Unnamed ".concat(operationType !== null && operationType !== void 0 ? operationType : "operation")
2459
- );
2460
- }
2461
- }
2462
- return (this.dataMasking ?
2463
- maskOperation(data, document, this.cache)
2464
- : data);
2465
- };
2466
- QueryManager.prototype.maskFragment = function (options) {
2467
- var data = options.data, fragment = options.fragment, fragmentName = options.fragmentName;
2468
- return this.dataMasking ?
2469
- maskFragment(data, fragment, this.cache, fragmentName)
2470
- : data;
2471
- };
2472
- QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a,
2473
- // The initial networkStatus for this fetch, most often
2474
- // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
2475
- // or setVariables.
2476
- networkStatus) {
2477
- var _this = this;
2478
- var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
2479
- var oldNetworkStatus = queryInfo.networkStatus;
2480
- queryInfo.init({
2481
- document: query,
2482
- variables: variables,
2483
- networkStatus: networkStatus,
2484
- });
2485
- var readCache = function () { return queryInfo.getDiff(); };
2486
- var resultsFromCache = function (diff, networkStatus) {
2487
- if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }
2488
- var data = diff.result;
2489
- if (globalThis.__DEV__ !== false && !returnPartialData && !equal(data, {})) {
2490
- logMissingFieldErrors(diff.missing);
2491
- }
2492
- var fromData = function (data) {
2493
- return Observable.of(__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true })));
2494
- };
2495
- if (data && _this.getDocumentInfo(query).hasForcedResolvers) {
2496
- return _this.localState
2497
- .runResolvers({
2498
- document: query,
2499
- remoteResult: { data: data },
2500
- context: context,
2501
- variables: variables,
2502
- onlyRunForcedResolvers: true,
2503
- })
2504
- .then(function (resolved) { return fromData(resolved.data || void 0); });
2505
- }
2506
- // Resolves https://github.com/apollographql/apollo-client/issues/10317.
2507
- // If errorPolicy is 'none' and notifyOnNetworkStatusChange is true,
2508
- // data was incorrectly returned from the cache on refetch:
2509
- // if diff.missing exists, we should not return cache data.
2510
- if (errorPolicy === "none" &&
2511
- networkStatus === NetworkStatus.refetch &&
2512
- Array.isArray(diff.missing)) {
2513
- return fromData(void 0);
2514
- }
2515
- return fromData(data);
2516
- };
2517
- var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0 /* CacheWriteBehavior.FORBID */
2518
- // Watched queries must opt into overwriting existing data on refetch,
2519
- // by passing refetchWritePolicy: "overwrite" in their WatchQueryOptions.
2520
- : (networkStatus === NetworkStatus.refetch &&
2521
- refetchWritePolicy !== "merge") ?
2522
- 1 /* CacheWriteBehavior.OVERWRITE */
2523
- : 2 /* CacheWriteBehavior.MERGE */;
2524
- var resultsFromLink = function () {
2525
- return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
2526
- query: query,
2527
- variables: variables,
2528
- context: context,
2529
- fetchPolicy: fetchPolicy,
2530
- errorPolicy: errorPolicy,
2531
- });
2532
- };
2533
- var shouldNotify = notifyOnNetworkStatusChange &&
2534
- typeof oldNetworkStatus === "number" &&
2535
- oldNetworkStatus !== networkStatus &&
2536
- isNetworkRequestInFlight(networkStatus);
2537
- switch (fetchPolicy) {
2538
- default:
2539
- case "cache-first": {
2540
- var diff = readCache();
2541
- if (diff.complete) {
2542
- return {
2543
- fromLink: false,
2544
- sources: [resultsFromCache(diff, queryInfo.markReady())],
2545
- };
2546
- }
2547
- if (returnPartialData || shouldNotify) {
2548
- return {
2549
- fromLink: true,
2550
- sources: [resultsFromCache(diff), resultsFromLink()],
2551
- };
2552
- }
2553
- return { fromLink: true, sources: [resultsFromLink()] };
2554
- }
2555
- case "cache-and-network": {
2556
- var diff = readCache();
2557
- if (diff.complete || returnPartialData || shouldNotify) {
2558
- return {
2559
- fromLink: true,
2560
- sources: [resultsFromCache(diff), resultsFromLink()],
2561
- };
2562
- }
2563
- return { fromLink: true, sources: [resultsFromLink()] };
2564
- }
2565
- case "cache-only":
2566
- return {
2567
- fromLink: false,
2568
- sources: [resultsFromCache(readCache(), queryInfo.markReady())],
2569
- };
2570
- case "network-only":
2571
- if (shouldNotify) {
2572
- return {
2573
- fromLink: true,
2574
- sources: [resultsFromCache(readCache()), resultsFromLink()],
2575
- };
2576
- }
2577
- return { fromLink: true, sources: [resultsFromLink()] };
2578
- case "no-cache":
2579
- if (shouldNotify) {
2580
- return {
2581
- fromLink: true,
2582
- // Note that queryInfo.getDiff() for no-cache queries does not call
2583
- // cache.diff, but instead returns a { complete: false } stub result
2584
- // when there is no queryInfo.diff already defined.
2585
- sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],
2586
- };
2587
- }
2588
- return { fromLink: true, sources: [resultsFromLink()] };
2589
- case "standby":
2590
- return { fromLink: false, sources: [] };
2591
- }
2592
- };
2593
- QueryManager.prototype.getOrCreateQuery = function (queryId) {
2594
- if (queryId && !this.queries.has(queryId)) {
2595
- this.queries.set(queryId, new QueryInfo(this, queryId));
2596
- }
2597
- return this.queries.get(queryId);
2598
- };
2599
- QueryManager.prototype.prepareContext = function (context) {
2600
- if (context === void 0) { context = {}; }
2601
- var newContext = this.localState.prepareContext(context);
2602
- return __assign(__assign(__assign({}, this.defaultContext), newContext), { clientAwareness: this.clientAwareness });
2603
- };
2604
- return QueryManager;
2605
- }());
2606
-
2607
- var LocalState = /** @class */ (function () {
2608
- function LocalState(_a) {
2609
- var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
2610
- this.selectionsToResolveCache = new WeakMap();
2611
- this.cache = cache;
2612
- if (client) {
2613
- this.client = client;
2614
- }
2615
- if (resolvers) {
2616
- this.addResolvers(resolvers);
2617
- }
2618
- if (fragmentMatcher) {
2619
- this.setFragmentMatcher(fragmentMatcher);
2620
- }
2621
- }
2622
- LocalState.prototype.addResolvers = function (resolvers) {
2623
- var _this = this;
2624
- this.resolvers = this.resolvers || {};
2625
- if (Array.isArray(resolvers)) {
2626
- resolvers.forEach(function (resolverGroup) {
2627
- _this.resolvers = mergeDeep(_this.resolvers, resolverGroup);
2628
- });
2629
- }
2630
- else {
2631
- this.resolvers = mergeDeep(this.resolvers, resolvers);
2632
- }
2633
- };
2634
- LocalState.prototype.setResolvers = function (resolvers) {
2635
- this.resolvers = {};
2636
- this.addResolvers(resolvers);
2637
- };
2638
- LocalState.prototype.getResolvers = function () {
2639
- return this.resolvers || {};
2640
- };
2641
- // Run local client resolvers against the incoming query and remote data.
2642
- // Locally resolved field values are merged with the incoming remote data,
2643
- // and returned. Note that locally resolved fields will overwrite
2644
- // remote data using the same field name.
2645
- LocalState.prototype.runResolvers = function (_a) {
2646
- return __awaiter(this, arguments, void 0, function (_b) {
2647
- var document = _b.document, remoteResult = _b.remoteResult, context = _b.context, variables = _b.variables, _c = _b.onlyRunForcedResolvers, onlyRunForcedResolvers = _c === void 0 ? false : _c;
2648
- return __generator(this, function (_d) {
2649
- if (document) {
2650
- return [2 /*return*/, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];
2651
- }
2652
- return [2 /*return*/, remoteResult];
2653
- });
2654
- });
2655
- };
2656
- LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
2657
- this.fragmentMatcher = fragmentMatcher;
2658
- };
2659
- LocalState.prototype.getFragmentMatcher = function () {
2660
- return this.fragmentMatcher;
2661
- };
2662
- // Client queries contain everything in the incoming document (if a @client
2663
- // directive is found).
2664
- LocalState.prototype.clientQuery = function (document) {
2665
- if (hasDirectives(["client"], document)) {
2666
- if (this.resolvers) {
2667
- return document;
2668
- }
2669
- }
2670
- return null;
2671
- };
2672
- // Server queries are stripped of all @client based selection sets.
2673
- LocalState.prototype.serverQuery = function (document) {
2674
- return removeClientSetsFromDocument(document);
2675
- };
2676
- LocalState.prototype.prepareContext = function (context) {
2677
- var cache = this.cache;
2678
- return __assign(__assign({}, context), { cache: cache,
2679
- // Getting an entry's cache key is useful for local state resolvers.
2680
- getCacheKey: function (obj) {
2681
- return cache.identify(obj);
2682
- } });
2683
- };
2684
- // To support `@client @export(as: "someVar")` syntax, we'll first resolve
2685
- // @client @export fields locally, then pass the resolved values back to be
2686
- // used alongside the original operation variables.
2687
- LocalState.prototype.addExportedVariables = function (document_1) {
2688
- return __awaiter(this, arguments, void 0, function (document, variables, context) {
2689
- if (variables === void 0) { variables = {}; }
2690
- if (context === void 0) { context = {}; }
2691
- return __generator(this, function (_a) {
2692
- if (document) {
2693
- return [2 /*return*/, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];
2694
- }
2695
- return [2 /*return*/, __assign({}, variables)];
2696
- });
2697
- });
2698
- };
2699
- LocalState.prototype.shouldForceResolvers = function (document) {
2700
- var forceResolvers = false;
2701
- visit(document, {
2702
- Directive: {
2703
- enter: function (node) {
2704
- if (node.name.value === "client" && node.arguments) {
2705
- forceResolvers = node.arguments.some(function (arg) {
2706
- return arg.name.value === "always" &&
2707
- arg.value.kind === "BooleanValue" &&
2708
- arg.value.value === true;
2709
- });
2710
- if (forceResolvers) {
2711
- return BREAK;
2712
- }
2713
- }
2714
- },
2715
- },
2716
- });
2717
- return forceResolvers;
2718
- };
2719
- // Query the cache and return matching data.
2720
- LocalState.prototype.buildRootValueFromCache = function (document, variables) {
2721
- return this.cache.diff({
2722
- query: buildQueryFromSelectionSet(document),
2723
- variables: variables,
2724
- returnPartialData: true,
2725
- optimistic: false,
2726
- }).result;
2727
- };
2728
- LocalState.prototype.resolveDocument = function (document_1, rootValue_1) {
2729
- return __awaiter(this, arguments, void 0, function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
2730
- var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;
2731
- if (context === void 0) { context = {}; }
2732
- if (variables === void 0) { variables = {}; }
2733
- if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
2734
- if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
2735
- return __generator(this, function (_b) {
2736
- mainDefinition = getMainDefinition(document);
2737
- fragments = getFragmentDefinitions(document);
2738
- fragmentMap = createFragmentMap(fragments);
2739
- selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);
2740
- definitionOperation = mainDefinition.operation;
2741
- defaultOperationType = definitionOperation ?
2742
- definitionOperation.charAt(0).toUpperCase() +
2743
- definitionOperation.slice(1)
2744
- : "Query";
2745
- _a = this, cache = _a.cache, client = _a.client;
2746
- execContext = {
2747
- fragmentMap: fragmentMap,
2748
- context: __assign(__assign({}, context), { cache: cache, client: client }),
2749
- variables: variables,
2750
- fragmentMatcher: fragmentMatcher,
2751
- defaultOperationType: defaultOperationType,
2752
- exportedVariables: {},
2753
- selectionsToResolve: selectionsToResolve,
2754
- onlyRunForcedResolvers: onlyRunForcedResolvers,
2755
- };
2756
- isClientFieldDescendant = false;
2757
- return [2 /*return*/, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({
2758
- result: result,
2759
- exportedVariables: execContext.exportedVariables,
2760
- }); })];
2761
- });
2762
- });
2763
- };
2764
- LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {
2765
- return __awaiter(this, void 0, void 0, function () {
2766
- var fragmentMap, context, variables, resultsToMerge, execute;
2767
- var _this = this;
2768
- return __generator(this, function (_a) {
2769
- fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
2770
- resultsToMerge = [rootValue];
2771
- execute = function (selection) { return __awaiter(_this, void 0, void 0, function () {
2772
- var fragment, typeCondition;
2773
- return __generator(this, function (_a) {
2774
- if (!isClientFieldDescendant &&
2775
- !execContext.selectionsToResolve.has(selection)) {
2776
- // Skip selections without @client directives
2777
- // (still processing if one of the ancestors or one of the child fields has @client directive)
2778
- return [2 /*return*/];
2779
- }
2780
- if (!shouldInclude(selection, variables)) {
2781
- // Skip this entirely.
2782
- return [2 /*return*/];
2783
- }
2784
- if (isField(selection)) {
2785
- return [2 /*return*/, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {
2786
- var _a;
2787
- if (typeof fieldResult !== "undefined") {
2788
- resultsToMerge.push((_a = {},
2789
- _a[resultKeyNameFromField(selection)] = fieldResult,
2790
- _a));
2791
- }
2792
- })];
2793
- }
2794
- if (isInlineFragment(selection)) {
2795
- fragment = selection;
2796
- }
2797
- else {
2798
- // This is a named fragment.
2799
- fragment = fragmentMap[selection.name.value];
2800
- invariant(fragment, 21, selection.name.value);
2801
- }
2802
- if (fragment && fragment.typeCondition) {
2803
- typeCondition = fragment.typeCondition.name.value;
2804
- if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
2805
- return [2 /*return*/, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {
2806
- resultsToMerge.push(fragmentResult);
2807
- })];
2808
- }
2809
- }
2810
- return [2 /*return*/];
2811
- });
2812
- }); };
2813
- return [2 /*return*/, Promise.all(selectionSet.selections.map(execute)).then(function () {
2814
- return mergeDeepArray(resultsToMerge);
2815
- })];
2816
- });
2817
- });
2818
- };
2819
- LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {
2820
- return __awaiter(this, void 0, void 0, function () {
2821
- var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
2822
- var _this = this;
2823
- return __generator(this, function (_a) {
2824
- if (!rootValue) {
2825
- return [2 /*return*/, null];
2826
- }
2827
- variables = execContext.variables;
2828
- fieldName = field.name.value;
2829
- aliasedFieldName = resultKeyNameFromField(field);
2830
- aliasUsed = fieldName !== aliasedFieldName;
2831
- defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
2832
- resultPromise = Promise.resolve(defaultResult);
2833
- // Usually all local resolvers are run when passing through here, but
2834
- // if we've specifically identified that we only want to run forced
2835
- // resolvers (that is, resolvers for fields marked with
2836
- // `@client(always: true)`), then we'll skip running non-forced resolvers.
2837
- if (!execContext.onlyRunForcedResolvers ||
2838
- this.shouldForceResolvers(field)) {
2839
- resolverType = rootValue.__typename || execContext.defaultOperationType;
2840
- resolverMap = this.resolvers && this.resolvers[resolverType];
2841
- if (resolverMap) {
2842
- resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
2843
- if (resolve) {
2844
- resultPromise = Promise.resolve(
2845
- // In case the resolve function accesses reactive variables,
2846
- // set cacheSlot to the current cache instance.
2847
- cacheSlot.withValue(this.cache, resolve, [
2848
- rootValue,
2849
- argumentsObjectFromField(field, variables),
2850
- execContext.context,
2851
- { field: field, fragmentMap: execContext.fragmentMap },
2852
- ]));
2853
- }
2854
- }
2855
- }
2856
- return [2 /*return*/, resultPromise.then(function (result) {
2857
- var _a, _b;
2858
- if (result === void 0) { result = defaultResult; }
2859
- // If an @export directive is associated with the current field, store
2860
- // the `as` export variable name and current result for later use.
2861
- if (field.directives) {
2862
- field.directives.forEach(function (directive) {
2863
- if (directive.name.value === "export" && directive.arguments) {
2864
- directive.arguments.forEach(function (arg) {
2865
- if (arg.name.value === "as" && arg.value.kind === "StringValue") {
2866
- execContext.exportedVariables[arg.value.value] = result;
2867
- }
2868
- });
2869
- }
2870
- });
2871
- }
2872
- // Handle all scalar types here.
2873
- if (!field.selectionSet) {
2874
- return result;
2875
- }
2876
- // From here down, the field has a selection set, which means it's trying
2877
- // to query a GraphQLObjectType.
2878
- if (result == null) {
2879
- // Basically any field in a GraphQL response can be null, or missing
2880
- return result;
2881
- }
2882
- var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === "client"; })) !== null && _b !== void 0 ? _b : false;
2883
- if (Array.isArray(result)) {
2884
- return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);
2885
- }
2886
- // Returned value is an object, and the query has a sub-selection. Recurse.
2887
- if (field.selectionSet) {
2888
- return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);
2889
- }
2890
- })];
2891
- });
2892
- });
2893
- };
2894
- LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {
2895
- var _this = this;
2896
- return Promise.all(result.map(function (item) {
2897
- if (item === null) {
2898
- return null;
2899
- }
2900
- // This is a nested array, recurse.
2901
- if (Array.isArray(item)) {
2902
- return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);
2903
- }
2904
- // This is an object, run the selection set on it.
2905
- if (field.selectionSet) {
2906
- return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);
2907
- }
2908
- }));
2909
- };
2910
- // Collect selection nodes on paths from document root down to all @client directives.
2911
- // This function takes into account transitive fragment spreads.
2912
- // Complexity equals to a single `visit` over the full document.
2913
- LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {
2914
- var isSingleASTNode = function (node) { return !Array.isArray(node); };
2915
- var selectionsToResolveCache = this.selectionsToResolveCache;
2916
- function collectByDefinition(definitionNode) {
2917
- if (!selectionsToResolveCache.has(definitionNode)) {
2918
- var matches_1 = new Set();
2919
- selectionsToResolveCache.set(definitionNode, matches_1);
2920
- visit(definitionNode, {
2921
- Directive: function (node, _, __, ___, ancestors) {
2922
- if (node.name.value === "client") {
2923
- ancestors.forEach(function (node) {
2924
- if (isSingleASTNode(node) && isSelectionNode(node)) {
2925
- matches_1.add(node);
2926
- }
2927
- });
2928
- }
2929
- },
2930
- FragmentSpread: function (spread, _, __, ___, ancestors) {
2931
- var fragment = fragmentMap[spread.name.value];
2932
- invariant(fragment, 22, spread.name.value);
2933
- var fragmentSelections = collectByDefinition(fragment);
2934
- if (fragmentSelections.size > 0) {
2935
- // Fragment for this spread contains @client directive (either directly or transitively)
2936
- // Collect selection nodes on paths from the root down to fields with the @client directive
2937
- ancestors.forEach(function (node) {
2938
- if (isSingleASTNode(node) && isSelectionNode(node)) {
2939
- matches_1.add(node);
2940
- }
2941
- });
2942
- matches_1.add(spread);
2943
- fragmentSelections.forEach(function (selection) {
2944
- matches_1.add(selection);
2945
- });
2946
- }
2947
- },
2948
- });
2949
- }
2950
- return selectionsToResolveCache.get(definitionNode);
2951
- }
2952
- return collectByDefinition(mainDefinition);
2953
- };
2954
- return LocalState;
2955
- }());
2956
-
2957
- var hasSuggestedDevtools = false;
2958
- /**
2959
- * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
2960
- * and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,
2961
- * receive results from the server and cache the results in a store. It also delivers updates
2962
- * to GraphQL queries through `Observable` instances.
2963
- */
2964
- var ApolloClient = /** @class */ (function () {
2965
- /**
2966
- * Constructs an instance of `ApolloClient`.
2967
- *
2968
- * @example
2969
- * ```js
2970
- * import { ApolloClient, InMemoryCache } from '@apollo/client';
2971
- *
2972
- * const cache = new InMemoryCache();
2973
- *
2974
- * const client = new ApolloClient({
2975
- * // Provide required constructor fields
2976
- * cache: cache,
2977
- * uri: 'http://localhost:4000/',
2978
- *
2979
- * // Provide some optional constructor fields
2980
- * name: 'react-web-client',
2981
- * version: '1.3',
2982
- * queryDeduplication: false,
2983
- * defaultOptions: {
2984
- * watchQuery: {
2985
- * fetchPolicy: 'cache-and-network',
2986
- * },
2987
- * },
2988
- * });
2989
- * ```
2990
- */
2991
- function ApolloClient(options) {
2992
- var _this = this;
2993
- var _a, _b, _c;
2994
- this.resetStoreCallbacks = [];
2995
- this.clearStoreCallbacks = [];
2996
- if (!options.cache) {
2997
- throw newInvariantError(16);
2998
- }
2999
- var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, documentTransform = options.documentTransform, _d = options.ssrMode, ssrMode = _d === void 0 ? false : _d, _e = options.ssrForceFetchDelay, ssrForceFetchDelay = _e === void 0 ? 0 : _e,
3000
- // Expose the client instance as window.__APOLLO_CLIENT__ and call
3001
- // onBroadcast in queryManager.broadcastQueries to enable browser
3002
- // devtools, but disable them by default in production.
3003
- connectToDevTools = options.connectToDevTools, _f = options.queryDeduplication, queryDeduplication = _f === void 0 ? true : _f, defaultOptions = options.defaultOptions, defaultContext = options.defaultContext, _g = options.assumeImmutableResults, assumeImmutableResults = _g === void 0 ? cache.assumeImmutableResults : _g, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwareness = options.clientAwareness, clientAwarenessName = options.name, clientAwarenessVersion = options.version, devtools = options.devtools, dataMasking = options.dataMasking;
3004
- if (globalThis.__DEV__ !== false) {
3005
- warnRemovedOption(options, "connectToDevTools", "ApolloClient", "Please use `devtools.enabled` instead.");
3006
- warnRemovedOption(options, "uri", "ApolloClient", "Please initialize an instance of `HttpLink` with `uri` instead.");
3007
- warnRemovedOption(options, "credentials", "ApolloClient", "Please initialize an instance of `HttpLink` with `credentials` instead.");
3008
- warnRemovedOption(options, "headers", "ApolloClient", "Please initialize an instance of `HttpLink` with `headers` instead.");
3009
- warnRemovedOption(options, "name", "ApolloClient", "Please use the `clientAwareness.name` option instead.");
3010
- warnRemovedOption(options, "version", "ApolloClient", "Please use the `clientAwareness.version` option instead.");
3011
- warnRemovedOption(options, "typeDefs", "ApolloClient");
3012
- if (!options.link) {
3013
- globalThis.__DEV__ !== false && invariant.warn(17);
3014
- }
3015
- }
3016
- var link = options.link;
3017
- if (!link) {
3018
- link =
3019
- uri ? new HttpLink({ uri: uri, credentials: credentials, headers: headers }) : ApolloLink.empty();
3020
- }
3021
- this.link = link;
3022
- this.cache = cache;
3023
- this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
3024
- this.queryDeduplication = queryDeduplication;
3025
- this.defaultOptions = defaultOptions || Object.create(null);
3026
- this.typeDefs = typeDefs;
3027
- this.devtoolsConfig = __assign(__assign({}, devtools), { enabled: (_a = devtools === null || devtools === void 0 ? void 0 : devtools.enabled) !== null && _a !== void 0 ? _a : connectToDevTools });
3028
- if (this.devtoolsConfig.enabled === undefined) {
3029
- this.devtoolsConfig.enabled = globalThis.__DEV__ !== false;
3030
- }
3031
- if (ssrForceFetchDelay) {
3032
- setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
3033
- }
3034
- this.watchQuery = this.watchQuery.bind(this);
3035
- this.query = this.query.bind(this);
3036
- this.mutate = this.mutate.bind(this);
3037
- this.watchFragment = this.watchFragment.bind(this);
3038
- this.resetStore = this.resetStore.bind(this);
3039
- this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
3040
- this.version = version;
3041
- this.localState = new LocalState({
3042
- cache: cache,
3043
- client: this,
3044
- resolvers: resolvers,
3045
- fragmentMatcher: fragmentMatcher,
3046
- });
3047
- this.queryManager = new QueryManager({
3048
- cache: this.cache,
3049
- link: this.link,
3050
- defaultOptions: this.defaultOptions,
3051
- defaultContext: defaultContext,
3052
- documentTransform: documentTransform,
3053
- queryDeduplication: queryDeduplication,
3054
- ssrMode: ssrMode,
3055
- dataMasking: !!dataMasking,
3056
- clientAwareness: {
3057
- name: (_b = clientAwareness === null || clientAwareness === void 0 ? void 0 : clientAwareness.name) !== null && _b !== void 0 ? _b : clientAwarenessName,
3058
- version: (_c = clientAwareness === null || clientAwareness === void 0 ? void 0 : clientAwareness.version) !== null && _c !== void 0 ? _c : clientAwarenessVersion,
3059
- },
3060
- localState: this.localState,
3061
- assumeImmutableResults: assumeImmutableResults,
3062
- onBroadcast: this.devtoolsConfig.enabled ?
3063
- function () {
3064
- if (_this.devToolsHookCb) {
3065
- _this.devToolsHookCb({
3066
- action: {},
3067
- state: {
3068
- queries: _this.queryManager.getQueryStore(),
3069
- mutations: _this.queryManager.mutationStore || {},
3070
- },
3071
- dataWithOptimisticResults: _this.cache.extract(true),
3072
- });
3073
- }
3074
- }
3075
- : void 0,
3076
- });
3077
- if (this.devtoolsConfig.enabled)
3078
- this.connectToDevTools();
3079
- }
3080
- Object.defineProperty(ApolloClient.prototype, "prioritizeCacheValues", {
3081
- /**
3082
- * Whether to prioritize cache values over network results when `query` or `watchQuery` is called.
3083
- * This will essentially turn a `"network-only"` or `"cache-and-network"` fetchPolicy into a `"cache-first"` fetchPolicy,
3084
- * but without influencing the `fetchPolicy` of the created `ObservableQuery` long-term.
3085
- *
3086
- * This can e.g. be used to prioritize the cache during the first render after SSR.
3087
- */
3088
- get: function () {
3089
- return this.disableNetworkFetches;
3090
- },
3091
- set: function (value) {
3092
- this.disableNetworkFetches = value;
3093
- },
3094
- enumerable: false,
3095
- configurable: true
3096
- });
3097
- ApolloClient.prototype.connectToDevTools = function () {
3098
- if (typeof window === "undefined") {
3099
- return;
3100
- }
3101
- var windowWithDevTools = window;
3102
- var devtoolsSymbol = Symbol.for("apollo.devtools");
3103
- (windowWithDevTools[devtoolsSymbol] =
3104
- windowWithDevTools[devtoolsSymbol] || []).push(this);
3105
- windowWithDevTools.__APOLLO_CLIENT__ = this;
3106
- /**
3107
- * Suggest installing the devtools for developers who don't have them
3108
- */
3109
- if (!hasSuggestedDevtools && globalThis.__DEV__ !== false) {
3110
- hasSuggestedDevtools = true;
3111
- if (window.document &&
3112
- window.top === window.self &&
3113
- /^(https?|file):$/.test(window.location.protocol)) {
3114
- setTimeout(function () {
3115
- if (!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
3116
- var nav = window.navigator;
3117
- var ua = nav && nav.userAgent;
3118
- var url = void 0;
3119
- if (typeof ua === "string") {
3120
- if (ua.indexOf("Chrome/") > -1) {
3121
- url =
3122
- "https://chrome.google.com/webstore/detail/" +
3123
- "apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
3124
- }
3125
- else if (ua.indexOf("Firefox/") > -1) {
3126
- url =
3127
- "https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
3128
- }
3129
- }
3130
- if (url) {
3131
- globalThis.__DEV__ !== false && invariant.log("Download the Apollo DevTools for a better development " +
3132
- "experience: %s", url);
3133
- }
3134
- }
3135
- }, 10000);
3136
- }
3137
- }
3138
- };
3139
- Object.defineProperty(ApolloClient.prototype, "documentTransform", {
3140
- /**
3141
- * The `DocumentTransform` used to modify GraphQL documents before a request
3142
- * is made. If a custom `DocumentTransform` is not provided, this will be the
3143
- * default document transform.
3144
- */
3145
- get: function () {
3146
- return this.queryManager.documentTransform;
3147
- },
3148
- enumerable: false,
3149
- configurable: true
3150
- });
3151
- /**
3152
- * Call this method to terminate any active client processes, making it safe
3153
- * to dispose of this `ApolloClient` instance.
3154
- */
3155
- ApolloClient.prototype.stop = function () {
3156
- this.queryManager.stop();
3157
- };
3158
- /**
3159
- * This watches the cache store of the query according to the options specified and
3160
- * returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and
3161
- * receive updated results through an observer when the cache store changes.
3162
- *
3163
- * Note that this method is not an implementation of GraphQL subscriptions. Rather,
3164
- * it uses Apollo's store in order to reactively deliver updates to your query results.
3165
- *
3166
- * For example, suppose you call watchQuery on a GraphQL query that fetches a person's
3167
- * first and last name and this person has a particular object identifier, provided by
3168
- * dataIdFromObject. Later, a different query fetches that same person's
3169
- * first and last name and the first name has now changed. Then, any observers associated
3170
- * with the results of the first query will be updated with a new result object.
3171
- *
3172
- * Note that if the cache does not change, the subscriber will *not* be notified.
3173
- *
3174
- * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for
3175
- * a description of store reactivity.
3176
- */
3177
- ApolloClient.prototype.watchQuery = function (options) {
3178
- if (this.defaultOptions.watchQuery) {
3179
- options = mergeOptions(this.defaultOptions.watchQuery, options);
3180
- }
3181
- // XXX Overwriting options is probably not the best way to do this long term...
3182
- if (this.disableNetworkFetches &&
3183
- (options.fetchPolicy === "network-only" ||
3184
- options.fetchPolicy === "cache-and-network")) {
3185
- options = __assign(__assign({}, options), { fetchPolicy: "cache-first" });
3186
- }
3187
- if (globalThis.__DEV__ !== false) {
3188
- warnRemovedOption(options, "canonizeResults", "client.watchQuery");
3189
- warnRemovedOption(options, "partialRefetch", "client.watchQuery");
3190
- }
3191
- return this.queryManager.watchQuery(options);
3192
- };
3193
- /**
3194
- * This resolves a single query according to the options specified and
3195
- * returns a `Promise` which is either resolved with the resulting data
3196
- * or rejected with an error.
3197
- *
3198
- * @param options - An object of type `QueryOptions` that allows us to
3199
- * describe how this query should be treated e.g. whether it should hit the
3200
- * server at all or just resolve from the cache, etc.
3201
- */
3202
- ApolloClient.prototype.query = function (options) {
3203
- if (this.defaultOptions.query) {
3204
- options = mergeOptions(this.defaultOptions.query, options);
3205
- }
3206
- invariant(options.fetchPolicy !== "cache-and-network", 18);
3207
- if (this.disableNetworkFetches && options.fetchPolicy === "network-only") {
3208
- options = __assign(__assign({}, options), { fetchPolicy: "cache-first" });
3209
- }
3210
- if (globalThis.__DEV__ !== false) {
3211
- warnRemovedOption(options, "canonizeResults", "client.query");
3212
- warnRemovedOption(options, "notifyOnNetworkStatusChange", "client.query", "This option does not affect `client.query` and can be safely removed.");
3213
- if (options.fetchPolicy === "standby") {
3214
- globalThis.__DEV__ !== false && invariant.warn(19);
3215
- }
3216
- }
3217
- return this.queryManager.query(options);
3218
- };
3219
- /**
3220
- * This resolves a single mutation according to the options specified and returns a
3221
- * Promise which is either resolved with the resulting data or rejected with an
3222
- * error. In some cases both `data` and `errors` might be undefined, for example
3223
- * when `errorPolicy` is set to `'ignore'`.
3224
- *
3225
- * It takes options as an object with the following keys and values:
3226
- */
3227
- ApolloClient.prototype.mutate = function (options) {
3228
- if (this.defaultOptions.mutate) {
3229
- options = mergeOptions(this.defaultOptions.mutate, options);
3230
- }
3231
- return this.queryManager.mutate(options);
3232
- };
3233
- /**
3234
- * This subscribes to a graphql subscription according to the options specified and returns an
3235
- * `Observable` which either emits received data or an error.
3236
- */
3237
- ApolloClient.prototype.subscribe = function (options) {
3238
- var _this = this;
3239
- var id = this.queryManager.generateQueryId();
3240
- return this.queryManager
3241
- .startGraphQLSubscription(options)
3242
- .map(function (result) { return (__assign(__assign({}, result), { data: _this.queryManager.maskOperation({
3243
- document: options.query,
3244
- data: result.data,
3245
- fetchPolicy: options.fetchPolicy,
3246
- id: id,
3247
- }) })); });
3248
- };
3249
- /**
3250
- * Tries to read some data from the store in the shape of the provided
3251
- * GraphQL query without making a network request. This method will start at
3252
- * the root query. To start at a specific id returned by `dataIdFromObject`
3253
- * use `readFragment`.
3254
- *
3255
- * @param optimistic - Set to `true` to allow `readQuery` to return
3256
- * optimistic results. Is `false` by default.
3257
- */
3258
- ApolloClient.prototype.readQuery = function (options, optimistic) {
3259
- if (optimistic === void 0) { optimistic = false; }
3260
- return this.cache.readQuery(options, optimistic);
3261
- };
3262
- /**
3263
- * Watches the cache store of the fragment according to the options specified
3264
- * and returns an `Observable`. We can subscribe to this
3265
- * `Observable` and receive updated results through an
3266
- * observer when the cache store changes.
3267
- *
3268
- * You must pass in a GraphQL document with a single fragment or a document
3269
- * with multiple fragments that represent what you are reading. If you pass
3270
- * in a document with multiple fragments then you must also specify a
3271
- * `fragmentName`.
3272
- *
3273
- * @since 3.10.0
3274
- * @param options - An object of type `WatchFragmentOptions` that allows
3275
- * the cache to identify the fragment and optionally specify whether to react
3276
- * to optimistic updates.
3277
- */
3278
- ApolloClient.prototype.watchFragment = function (options) {
3279
- var _a;
3280
- return this.cache.watchFragment(__assign(__assign({}, options), (_a = {}, _a[Symbol.for("apollo.dataMasking")] = this.queryManager.dataMasking, _a)));
3281
- };
3282
- /**
3283
- * Tries to read some data from the store in the shape of the provided
3284
- * GraphQL fragment without making a network request. This method will read a
3285
- * GraphQL fragment from any arbitrary id that is currently cached, unlike
3286
- * `readQuery` which will only read from the root query.
3287
- *
3288
- * You must pass in a GraphQL document with a single fragment or a document
3289
- * with multiple fragments that represent what you are reading. If you pass
3290
- * in a document with multiple fragments then you must also specify a
3291
- * `fragmentName`.
3292
- *
3293
- * @param optimistic - Set to `true` to allow `readFragment` to return
3294
- * optimistic results. Is `false` by default.
3295
- */
3296
- ApolloClient.prototype.readFragment = function (options, optimistic) {
3297
- if (optimistic === void 0) { optimistic = false; }
3298
- return this.cache.readFragment(options, optimistic);
3299
- };
3300
- /**
3301
- * Writes some data in the shape of the provided GraphQL query directly to
3302
- * the store. This method will start at the root query. To start at a
3303
- * specific id returned by `dataIdFromObject` then use `writeFragment`.
3304
- */
3305
- ApolloClient.prototype.writeQuery = function (options) {
3306
- var ref = this.cache.writeQuery(options);
3307
- if (options.broadcast !== false) {
3308
- this.queryManager.broadcastQueries();
3309
- }
3310
- return ref;
3311
- };
3312
- /**
3313
- * Writes some data in the shape of the provided GraphQL fragment directly to
3314
- * the store. This method will write to a GraphQL fragment from any arbitrary
3315
- * id that is currently cached, unlike `writeQuery` which will only write
3316
- * from the root query.
3317
- *
3318
- * You must pass in a GraphQL document with a single fragment or a document
3319
- * with multiple fragments that represent what you are writing. If you pass
3320
- * in a document with multiple fragments then you must also specify a
3321
- * `fragmentName`.
3322
- */
3323
- ApolloClient.prototype.writeFragment = function (options) {
3324
- var ref = this.cache.writeFragment(options);
3325
- if (options.broadcast !== false) {
3326
- this.queryManager.broadcastQueries();
3327
- }
3328
- return ref;
3329
- };
3330
- ApolloClient.prototype.__actionHookForDevTools = function (cb) {
3331
- this.devToolsHookCb = cb;
3332
- };
3333
- ApolloClient.prototype.__requestRaw = function (payload) {
3334
- return execute(this.link, payload);
3335
- };
3336
- /**
3337
- * Resets your entire store by clearing out your cache and then re-executing
3338
- * all of your active queries. This makes it so that you may guarantee that
3339
- * there is no data left in your store from a time before you called this
3340
- * method.
3341
- *
3342
- * `resetStore()` is useful when your user just logged out. You’ve removed the
3343
- * user session, and you now want to make sure that any references to data you
3344
- * might have fetched while the user session was active is gone.
3345
- *
3346
- * It is important to remember that `resetStore()` *will* refetch any active
3347
- * queries. This means that any components that might be mounted will execute
3348
- * their queries again using your network interface. If you do not want to
3349
- * re-execute any queries then you should make sure to stop watching any
3350
- * active queries.
3351
- */
3352
- ApolloClient.prototype.resetStore = function () {
3353
- var _this = this;
3354
- return Promise.resolve()
3355
- .then(function () {
3356
- return _this.queryManager.clearStore({
3357
- discardWatches: false,
3358
- });
3359
- })
3360
- .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
3361
- .then(function () { return _this.reFetchObservableQueries(); });
3362
- };
3363
- /**
3364
- * Remove all data from the store. Unlike `resetStore`, `clearStore` will
3365
- * not refetch any active queries.
3366
- */
3367
- ApolloClient.prototype.clearStore = function () {
3368
- var _this = this;
3369
- return Promise.resolve()
3370
- .then(function () {
3371
- return _this.queryManager.clearStore({
3372
- discardWatches: true,
3373
- });
3374
- })
3375
- .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
3376
- };
3377
- /**
3378
- * Allows callbacks to be registered that are executed when the store is
3379
- * reset. `onResetStore` returns an unsubscribe function that can be used
3380
- * to remove registered callbacks.
3381
- */
3382
- ApolloClient.prototype.onResetStore = function (cb) {
3383
- var _this = this;
3384
- this.resetStoreCallbacks.push(cb);
3385
- return function () {
3386
- _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
3387
- };
3388
- };
3389
- /**
3390
- * Allows callbacks to be registered that are executed when the store is
3391
- * cleared. `onClearStore` returns an unsubscribe function that can be used
3392
- * to remove registered callbacks.
3393
- */
3394
- ApolloClient.prototype.onClearStore = function (cb) {
3395
- var _this = this;
3396
- this.clearStoreCallbacks.push(cb);
3397
- return function () {
3398
- _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
3399
- };
3400
- };
3401
- /**
3402
- * Refetches all of your active queries.
3403
- *
3404
- * `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage
3405
- *
3406
- * It is important to remember that `reFetchObservableQueries()` *will* refetch any active
3407
- * queries. This means that any components that might be mounted will execute
3408
- * their queries again using your network interface. If you do not want to
3409
- * re-execute any queries then you should make sure to stop watching any
3410
- * active queries.
3411
- * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.
3412
- */
3413
- ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
3414
- return this.queryManager.reFetchObservableQueries(includeStandby);
3415
- };
3416
- /**
3417
- * Refetches specified active queries. Similar to "reFetchObservableQueries()" but with a specific list of queries.
3418
- *
3419
- * `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.
3420
- *
3421
- * It is important to remember that `refetchQueries()` *will* refetch specified active
3422
- * queries. This means that any components that might be mounted will execute
3423
- * their queries again using your network interface. If you do not want to
3424
- * re-execute any queries then you should make sure to stop watching any
3425
- * active queries.
3426
- */
3427
- ApolloClient.prototype.refetchQueries = function (options) {
3428
- var map = this.queryManager.refetchQueries(options);
3429
- var queries = [];
3430
- var results = [];
3431
- map.forEach(function (result, obsQuery) {
3432
- queries.push(obsQuery);
3433
- results.push(result);
3434
- });
3435
- var result = Promise.all(results);
3436
- // In case you need the raw results immediately, without awaiting
3437
- // Promise.all(results):
3438
- result.queries = queries;
3439
- result.results = results;
3440
- // If you decide to ignore the result Promise because you're using
3441
- // result.queries and result.results instead, you shouldn't have to worry
3442
- // about preventing uncaught rejections for the Promise.all result.
3443
- result.catch(function (error) {
3444
- globalThis.__DEV__ !== false && invariant.debug(20, error);
3445
- });
3446
- return result;
3447
- };
3448
- /**
3449
- * Get all currently active `ObservableQuery` objects, in a `Map` keyed by
3450
- * query ID strings.
3451
- *
3452
- * An "active" query is one that has observers and a `fetchPolicy` other than
3453
- * "standby" or "cache-only".
3454
- *
3455
- * You can include all `ObservableQuery` objects (including the inactive ones)
3456
- * by passing "all" instead of "active", or you can include just a subset of
3457
- * active queries by passing an array of query names or DocumentNode objects.
3458
- */
3459
- ApolloClient.prototype.getObservableQueries = function (include) {
3460
- if (include === void 0) { include = "active"; }
3461
- return this.queryManager.getObservableQueries(include);
3462
- };
3463
- /**
3464
- * Exposes the cache's complete state, in a serializable format for later restoration.
3465
- */
3466
- ApolloClient.prototype.extract = function (optimistic) {
3467
- return this.cache.extract(optimistic);
3468
- };
3469
- /**
3470
- * Replaces existing state in the cache (if any) with the values expressed by
3471
- * `serializedState`.
3472
- *
3473
- * Called when hydrating a cache (server side rendering, or offline storage),
3474
- * and also (potentially) during hot reloads.
3475
- */
3476
- ApolloClient.prototype.restore = function (serializedState) {
3477
- return this.cache.restore(serializedState);
3478
- };
3479
- /**
3480
- * Add additional local resolvers.
3481
- *
3482
- * @deprecated `addResolvers` will been removed in Apollo Client 4.0. It is
3483
- * safe to continue using this method in Apollo Client 3.x.
3484
- *
3485
- * **Recommended now**
3486
- *
3487
- * No action needed
3488
- *
3489
- * **When upgrading**
3490
- *
3491
- * Use `client.localState.addResolvers(resolvers)`. Alternatively, store
3492
- * the `LocalState` instance in a separate variable and call `addResolvers` on
3493
- * that.
3494
- */
3495
- ApolloClient.prototype.addResolvers = function (resolvers) {
3496
- this.localState.addResolvers(resolvers);
3497
- };
3498
- /**
3499
- * Set (override existing) local resolvers.
3500
- *
3501
- * @deprecated `setResolvers` will been removed in Apollo Client 4.0. It is
3502
- * safe to continue using this method in Apollo Client 3.x.
3503
- *
3504
- * **Recommended now**
3505
- *
3506
- * If possible, stop using the `setResolvers` method.
3507
- *
3508
- * **When upgrading**
3509
- *
3510
- * Remove the use of `setResolvers`.
3511
- */
3512
- ApolloClient.prototype.setResolvers = function (resolvers) {
3513
- this.localState.setResolvers(resolvers);
3514
- };
3515
- /**
3516
- * Get all registered local resolvers.
3517
- *
3518
- * @deprecated `getResolvers` will be removed in Apollo Client 4.0. It is
3519
- * safe to continue using this method in Apollo Client 3.x.
3520
- *
3521
- * **Recommended now**
3522
- *
3523
- * If possible, stop using the `getResolvers` method.
3524
- *
3525
- * **When upgrading**
3526
- *
3527
- * Remove the use of `getResolvers`.
3528
- */
3529
- ApolloClient.prototype.getResolvers = function () {
3530
- return this.localState.getResolvers();
3531
- };
3532
- /**
3533
- * Set a custom local state fragment matcher.
3534
- *
3535
- * @deprecated Custom fragment matchers will no longer be supported in Apollo
3536
- * Client 4.0 and has been replaced by `cache.fragmentMatches`. It is safe to
3537
- * continue using `setLocalStateFragmentMatcher` in Apollo Client 3.x.
3538
- *
3539
- * **Recommended now**
3540
- *
3541
- * No action needed
3542
- *
3543
- * **When upgrading**
3544
- *
3545
- * Leverage `possibleTypes` with `InMemoryCache` to ensure fragments match
3546
- * correctly. Ensure `possibleTypes` include local types if needed. If working
3547
- * with a 3rd party cache implementation, ensure the 3rd party cache implements
3548
- * the `cache.fragmentMatches` method. This function should no longer be used.
3549
- */
3550
- ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
3551
- this.localState.setFragmentMatcher(fragmentMatcher);
3552
- };
3553
- /**
3554
- * Define a new ApolloLink (or link chain) that Apollo Client will use.
3555
- */
3556
- ApolloClient.prototype.setLink = function (newLink) {
3557
- this.link = this.queryManager.link = newLink;
3558
- };
3559
- Object.defineProperty(ApolloClient.prototype, "defaultContext", {
3560
- get: function () {
3561
- return this.queryManager.defaultContext;
3562
- },
3563
- enumerable: false,
3564
- configurable: true
3565
- });
3566
- return ApolloClient;
3567
- }());
3568
- if (globalThis.__DEV__ !== false) {
3569
- ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;
3570
- }
3571
-
3572
- function setContext(setter) {
3573
- return new ApolloLink(function (operation, forward) {
3574
- var request = __rest(operation, []);
3575
- return new Observable(function (observer) {
3576
- var handle;
3577
- var closed = false;
3578
- Promise.resolve(request)
3579
- .then(function (req) { return setter(req, operation.getContext()); })
3580
- .then(operation.setContext)
3581
- .then(function () {
3582
- // if the observer is already closed, no need to subscribe.
3583
- if (closed)
3584
- return;
3585
- handle = forward(operation).subscribe({
3586
- next: observer.next.bind(observer),
3587
- error: observer.error.bind(observer),
3588
- complete: observer.complete.bind(observer),
3589
- });
3590
- })
3591
- .catch(observer.error.bind(observer));
3592
- return function () {
3593
- closed = true;
3594
- if (handle)
3595
- handle.unsubscribe();
3596
- };
3597
- });
3598
- });
3599
- }
3600
-
3601
- function onError(errorHandler) {
3602
- return new ApolloLink(function (operation, forward) {
3603
- return new Observable(function (observer) {
3604
- var sub;
3605
- var retriedSub;
3606
- var retriedResult;
3607
- try {
3608
- sub = forward(operation).subscribe({
3609
- next: function (result) {
3610
- if (result.errors) {
3611
- retriedResult = errorHandler({
3612
- graphQLErrors: result.errors,
3613
- response: result,
3614
- operation: operation,
3615
- forward: forward,
3616
- });
3617
- }
3618
- else if (graphQLResultHasProtocolErrors(result)) {
3619
- retriedResult = errorHandler({
3620
- protocolErrors: result.extensions[PROTOCOL_ERRORS_SYMBOL],
3621
- response: result,
3622
- operation: operation,
3623
- forward: forward,
3624
- });
3625
- }
3626
- if (retriedResult) {
3627
- retriedSub = retriedResult.subscribe({
3628
- next: observer.next.bind(observer),
3629
- error: observer.error.bind(observer),
3630
- complete: observer.complete.bind(observer),
3631
- });
3632
- return;
3633
- }
3634
- observer.next(result);
3635
- },
3636
- error: function (networkError) {
3637
- retriedResult = errorHandler({
3638
- operation: operation,
3639
- networkError: networkError,
3640
- //Network errors can return GraphQL errors on for example a 403
3641
- graphQLErrors: (networkError &&
3642
- networkError.result &&
3643
- networkError.result.errors) ||
3644
- void 0,
3645
- forward: forward,
3646
- });
3647
- if (retriedResult) {
3648
- retriedSub = retriedResult.subscribe({
3649
- next: observer.next.bind(observer),
3650
- error: observer.error.bind(observer),
3651
- complete: observer.complete.bind(observer),
3652
- });
3653
- return;
3654
- }
3655
- observer.error(networkError);
3656
- },
3657
- complete: function () {
3658
- // disable the previous sub from calling complete on observable
3659
- // if retry is in flight.
3660
- if (!retriedResult) {
3661
- observer.complete.bind(observer)();
3662
- }
3663
- },
3664
- });
3665
- }
3666
- catch (e) {
3667
- errorHandler({ networkError: e, operation: operation, forward: forward });
3668
- observer.error(e);
3669
- }
3670
- return function () {
3671
- if (sub)
3672
- sub.unsubscribe();
3673
- if (retriedSub)
3674
- sub.unsubscribe();
3675
- };
3676
- });
3677
- });
3678
- }
3679
- /** @class */ ((function (_super) {
3680
- __extends(ErrorLink, _super);
3681
- function ErrorLink(errorHandler) {
3682
- var _this = _super.call(this) || this;
3683
- _this.link = onError(errorHandler);
3684
- return _this;
3685
- }
3686
- ErrorLink.prototype.request = function (operation, forward) {
3687
- return this.link.request(operation, forward);
3688
- };
3689
- return ErrorLink;
3690
- })(ApolloLink));
3691
-
3692
- export { ApolloClient, ApolloError, HttpLink, onError, setContext };
3693
- //# sourceMappingURL=apollo-client.client-DE7JUXjy.js.map