@graphql-tools/executor-http 1.1.9 → 1.1.10-alpha-f6e086f56c835f084b67e73148dbd7a9dcdd1ec9

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 (41) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/dist/index.cjs +542 -0
  3. package/{typings → dist}/index.d.cts +28 -25
  4. package/{typings → dist}/index.d.ts +28 -25
  5. package/dist/index.js +539 -0
  6. package/package.json +38 -46
  7. package/cjs/createFormDataFromVariables.js +0 -76
  8. package/cjs/createTimeoutSignal.js +0 -1
  9. package/cjs/defaultPrintFn.js +0 -14
  10. package/cjs/handleEventStreamResponse.js +0 -55
  11. package/cjs/handleMultipartMixedResponse.js +0 -48
  12. package/cjs/index.js +0 -314
  13. package/cjs/isGraphQLUpload.js +0 -7
  14. package/cjs/isLiveQueryOperationDefinitionNode.js +0 -8
  15. package/cjs/package.json +0 -1
  16. package/cjs/prepareGETUrl.js +0 -26
  17. package/esm/createFormDataFromVariables.js +0 -72
  18. package/esm/createTimeoutSignal.js +0 -1
  19. package/esm/defaultPrintFn.js +0 -10
  20. package/esm/handleEventStreamResponse.js +0 -50
  21. package/esm/handleMultipartMixedResponse.js +0 -44
  22. package/esm/index.js +0 -310
  23. package/esm/isGraphQLUpload.js +0 -3
  24. package/esm/isLiveQueryOperationDefinitionNode.js +0 -5
  25. package/esm/prepareGETUrl.js +0 -22
  26. package/typings/createFormDataFromVariables.d.cts +0 -10
  27. package/typings/createFormDataFromVariables.d.ts +0 -10
  28. package/typings/createTimeoutSignal.d.cts +0 -0
  29. package/typings/createTimeoutSignal.d.ts +0 -0
  30. package/typings/defaultPrintFn.d.cts +0 -2
  31. package/typings/defaultPrintFn.d.ts +0 -2
  32. package/typings/handleEventStreamResponse.d.cts +0 -4
  33. package/typings/handleEventStreamResponse.d.ts +0 -4
  34. package/typings/handleMultipartMixedResponse.d.cts +0 -2
  35. package/typings/handleMultipartMixedResponse.d.ts +0 -2
  36. package/typings/isGraphQLUpload.d.cts +0 -9
  37. package/typings/isGraphQLUpload.d.ts +0 -9
  38. package/typings/isLiveQueryOperationDefinitionNode.d.cts +0 -2
  39. package/typings/isLiveQueryOperationDefinitionNode.d.ts +0 -2
  40. package/typings/prepareGETUrl.d.cts +0 -7
  41. package/typings/prepareGETUrl.d.ts +0 -7
@@ -1,17 +1,19 @@
1
- import { DocumentNode, GraphQLResolveInfo } from 'graphql';
2
- import { AsyncExecutor, DisposableAsyncExecutor, DisposableSyncExecutor, ExecutionRequest, SyncExecutor } from '@graphql-tools/utils';
3
- import { isLiveQueryOperationDefinitionNode } from './isLiveQueryOperationDefinitionNode.js';
4
- export type SyncFetchFn = (url: string, init?: RequestInit, context?: any, info?: GraphQLResolveInfo) => SyncResponse;
5
- export type SyncResponse = Omit<Response, 'json' | 'text'> & {
1
+ import { ExecutionRequest, DisposableSyncExecutor, SyncExecutor, DisposableAsyncExecutor, AsyncExecutor } from '@graphql-tools/utils';
2
+ import { OperationDefinitionNode, GraphQLResolveInfo, DocumentNode } from 'graphql';
3
+
4
+ declare const isLiveQueryOperationDefinitionNode: (node: OperationDefinitionNode) => boolean | undefined;
5
+
6
+ type SyncFetchFn = (url: string, init?: RequestInit, context?: any, info?: GraphQLResolveInfo) => SyncResponse;
7
+ type SyncResponse = Omit<Response, 'json' | 'text'> & {
6
8
  json: () => any;
7
9
  text: () => string;
8
10
  };
9
- export type AsyncFetchFn = (url: string, options?: RequestInit, context?: any, info?: GraphQLResolveInfo) => Promise<Response> | Response;
10
- export type RegularFetchFn = (url: string) => Promise<Response> | Response;
11
- export type FetchFn = AsyncFetchFn | SyncFetchFn | RegularFetchFn;
12
- export type AsyncImportFn = (moduleName: string) => PromiseLike<any>;
13
- export type SyncImportFn = (moduleName: string) => any;
14
- export interface HTTPExecutorOptions {
11
+ type AsyncFetchFn = (url: string, options?: RequestInit, context?: any, info?: GraphQLResolveInfo) => Promise<Response> | Response;
12
+ type RegularFetchFn = (url: string) => Promise<Response> | Response;
13
+ type FetchFn = AsyncFetchFn | SyncFetchFn | RegularFetchFn;
14
+ type AsyncImportFn = (moduleName: string) => PromiseLike<any>;
15
+ type SyncImportFn = (moduleName: string) => any;
16
+ interface HTTPExecutorOptions {
15
17
  endpoint?: string;
16
18
  fetch?: FetchFn;
17
19
  /**
@@ -59,45 +61,46 @@ export interface HTTPExecutorOptions {
59
61
  */
60
62
  disposable?: boolean;
61
63
  }
62
- export type HeadersConfig = Record<string, string>;
63
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
64
+ type HeadersConfig = Record<string, string>;
65
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
64
66
  fetch: SyncFetchFn;
65
67
  disposable: true;
66
68
  }): DisposableSyncExecutor<any, HTTPExecutorOptions>;
67
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
69
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
68
70
  fetch: SyncFetchFn;
69
71
  disposable: false;
70
72
  }): SyncExecutor<any, HTTPExecutorOptions>;
71
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'> & {
73
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'> & {
72
74
  fetch: SyncFetchFn;
73
75
  }): SyncExecutor<any, HTTPExecutorOptions>;
74
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
76
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
75
77
  fetch: AsyncFetchFn;
76
78
  disposable: true;
77
79
  }): DisposableAsyncExecutor<any, HTTPExecutorOptions>;
78
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
80
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
79
81
  fetch: AsyncFetchFn;
80
82
  disposable: false;
81
83
  }): AsyncExecutor<any, HTTPExecutorOptions>;
82
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'> & {
84
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'> & {
83
85
  fetch: AsyncFetchFn;
84
86
  }): AsyncExecutor<any, HTTPExecutorOptions>;
85
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
87
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
86
88
  fetch: RegularFetchFn;
87
89
  disposable: true;
88
90
  }): DisposableAsyncExecutor<any, HTTPExecutorOptions>;
89
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
91
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
90
92
  fetch: RegularFetchFn;
91
93
  disposable: false;
92
94
  }): AsyncExecutor<any, HTTPExecutorOptions>;
93
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'> & {
95
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'> & {
94
96
  fetch: RegularFetchFn;
95
97
  }): AsyncExecutor<any, HTTPExecutorOptions>;
96
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
98
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
97
99
  disposable: true;
98
100
  }): DisposableAsyncExecutor<any, HTTPExecutorOptions>;
99
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
101
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch' | 'disposable'> & {
100
102
  disposable: false;
101
103
  }): AsyncExecutor<any, HTTPExecutorOptions>;
102
- export declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'>): AsyncExecutor<any, HTTPExecutorOptions>;
103
- export { isLiveQueryOperationDefinitionNode };
104
+ declare function buildHTTPExecutor(options?: Omit<HTTPExecutorOptions, 'fetch'>): AsyncExecutor<any, HTTPExecutorOptions>;
105
+
106
+ export { type AsyncFetchFn, type AsyncImportFn, type FetchFn, type HTTPExecutorOptions, type HeadersConfig, type RegularFetchFn, type SyncFetchFn, type SyncImportFn, type SyncResponse, buildHTTPExecutor, isLiveQueryOperationDefinitionNode };
package/dist/index.js ADDED
@@ -0,0 +1,539 @@
1
+ import { isAsyncIterable, isPromise, inspect, mapAsyncIterator, mergeIncrementalResult, memoize1, createGraphQLError, getOperationASTFromRequest } from '@graphql-tools/utils';
2
+ import { File, FormData, TextDecoder, fetch } from '@whatwg-node/fetch';
3
+ import { ValueOrPromise } from 'value-or-promise';
4
+ import { extractFiles, isExtractableFile } from 'extract-files';
5
+ import { stripIgnoredCharacters, print } from 'graphql';
6
+ import { Repeater } from '@repeaterjs/repeater';
7
+ import { meros as meros$1 } from 'meros/browser';
8
+ import { meros } from 'meros/node';
9
+
10
+ function isGraphQLUpload(upload) {
11
+ return typeof upload.createReadStream === "function";
12
+ }
13
+
14
+ function createFormDataFromVariables({
15
+ query,
16
+ variables,
17
+ operationName,
18
+ extensions
19
+ }, {
20
+ File: FileCtor = File,
21
+ FormData: FormDataCtor = FormData
22
+ }) {
23
+ const vars = Object.assign({}, variables);
24
+ const { clone, files } = extractFiles(
25
+ vars,
26
+ "variables",
27
+ (v) => isExtractableFile(v) || v?.promise || isAsyncIterable(v) || v?.then || typeof v?.arrayBuffer === "function"
28
+ );
29
+ if (files.size === 0) {
30
+ return JSON.stringify(
31
+ {
32
+ query,
33
+ variables,
34
+ operationName,
35
+ extensions
36
+ },
37
+ null,
38
+ 2
39
+ );
40
+ }
41
+ const map = {};
42
+ const uploads = [];
43
+ let currIndex = 0;
44
+ for (const [file, curr] of files) {
45
+ map[currIndex] = curr;
46
+ uploads[currIndex] = file;
47
+ currIndex++;
48
+ }
49
+ const form = new FormDataCtor();
50
+ form.append(
51
+ "operations",
52
+ JSON.stringify({
53
+ query,
54
+ variables: clone,
55
+ operationName,
56
+ extensions
57
+ })
58
+ );
59
+ form.append("map", JSON.stringify(map, null, 2));
60
+ function handleUpload(upload, i) {
61
+ const indexStr = i.toString();
62
+ if (upload != null) {
63
+ const filename = upload.filename || upload.name || upload.path || `blob-${indexStr}`;
64
+ if (isPromise(upload)) {
65
+ return upload.then(
66
+ (resolvedUpload) => handleUpload(resolvedUpload, i)
67
+ );
68
+ } else if (isBlob(upload)) {
69
+ form.append(indexStr, upload, filename);
70
+ } else if (isGraphQLUpload(upload)) {
71
+ const stream = upload.createReadStream();
72
+ const chunks = [];
73
+ return Promise.resolve().then(async () => {
74
+ for await (const chunk of stream) {
75
+ if (chunk) {
76
+ chunks.push(...chunk);
77
+ }
78
+ }
79
+ const blobPart = new Uint8Array(chunks);
80
+ form.append(
81
+ indexStr,
82
+ new FileCtor([blobPart], filename, { type: upload.mimetype }),
83
+ filename
84
+ );
85
+ });
86
+ } else {
87
+ form.append(indexStr, new FileCtor([upload], filename), filename);
88
+ }
89
+ }
90
+ }
91
+ return ValueOrPromise.all(
92
+ uploads.map(
93
+ (upload, i) => new ValueOrPromise(() => handleUpload(upload, i))
94
+ )
95
+ ).then(() => form).resolve();
96
+ }
97
+ function isBlob(obj) {
98
+ return typeof obj.arrayBuffer === "function";
99
+ }
100
+
101
+ const printCache = /* @__PURE__ */ new WeakMap();
102
+ function defaultPrintFn(document) {
103
+ let printed = printCache.get(document);
104
+ if (!printed) {
105
+ printed = stripIgnoredCharacters(print(document));
106
+ printCache.set(document, printed);
107
+ }
108
+ return printed;
109
+ }
110
+
111
+ const DELIM = "\n\n";
112
+ function isReadableStream(value) {
113
+ return value && typeof value.getReader === "function";
114
+ }
115
+ function handleEventStreamResponse(response) {
116
+ const body = response.body;
117
+ if (!isReadableStream(body)) {
118
+ throw new Error(
119
+ "Response body is expected to be a readable stream but got; " + inspect(body)
120
+ );
121
+ }
122
+ return new Repeater((push, stop) => {
123
+ const decoder = new TextDecoder();
124
+ const reader = body.getReader();
125
+ reader.closed.then(stop).catch(stop);
126
+ stop.finally(() => reader.cancel());
127
+ let currChunk = "";
128
+ async function pump() {
129
+ const { done, value: chunk } = await reader.read();
130
+ if (done) {
131
+ return stop();
132
+ }
133
+ currChunk += typeof chunk === "string" ? chunk : decoder.decode(chunk);
134
+ for (; ; ) {
135
+ const delimIndex = currChunk.indexOf(DELIM);
136
+ if (delimIndex === -1) {
137
+ break;
138
+ }
139
+ const msg = currChunk.slice(0, delimIndex);
140
+ currChunk = currChunk.slice(delimIndex + DELIM.length);
141
+ const dataStr = msg.split("data:")[1]?.trim();
142
+ if (dataStr) {
143
+ const data = JSON.parse(dataStr);
144
+ await push(data.payload || data);
145
+ }
146
+ const event = msg.split("event:")[1]?.trim();
147
+ if (event === "complete") {
148
+ return stop();
149
+ }
150
+ }
151
+ return pump();
152
+ }
153
+ return pump();
154
+ });
155
+ }
156
+
157
+ function isIncomingMessage(body) {
158
+ return body != null && typeof body === "object" && "pipe" in body;
159
+ }
160
+ async function handleMultipartMixedResponse(response) {
161
+ const body = response.body;
162
+ const contentType = response.headers.get("content-type") || "";
163
+ let asyncIterator;
164
+ if (isIncomingMessage(body)) {
165
+ body.headers = {
166
+ "content-type": contentType
167
+ };
168
+ const result = await meros(body);
169
+ if ("next" in result) {
170
+ asyncIterator = result;
171
+ }
172
+ } else {
173
+ const result = await meros$1(response);
174
+ if ("next" in result) {
175
+ asyncIterator = result;
176
+ }
177
+ }
178
+ const executionResult = {};
179
+ if (asyncIterator == null) {
180
+ return executionResult;
181
+ }
182
+ const resultStream = mapAsyncIterator(asyncIterator, (part) => {
183
+ if (part.json) {
184
+ const incrementalResult = part.body;
185
+ mergeIncrementalResult({
186
+ incrementalResult,
187
+ executionResult
188
+ });
189
+ }
190
+ return executionResult;
191
+ });
192
+ return resultStream;
193
+ }
194
+
195
+ const isLiveQueryOperationDefinitionNode = memoize1(
196
+ function isLiveQueryOperationDefinitionNode2(node) {
197
+ return node.operation === "query" && node.directives?.some((directive) => directive.name.value === "live");
198
+ }
199
+ );
200
+
201
+ function prepareGETUrl({
202
+ baseUrl = "",
203
+ query,
204
+ variables,
205
+ operationName,
206
+ extensions
207
+ }) {
208
+ const dummyHostname = "https://dummyhostname.com";
209
+ const validUrl = baseUrl.startsWith("http") ? baseUrl : baseUrl?.startsWith("/") ? `${dummyHostname}${baseUrl}` : `${dummyHostname}/${baseUrl}`;
210
+ const urlObj = new URL(validUrl);
211
+ urlObj.searchParams.set("query", stripIgnoredCharacters(query));
212
+ if (variables && Object.keys(variables).length > 0) {
213
+ urlObj.searchParams.set("variables", JSON.stringify(variables));
214
+ }
215
+ if (operationName) {
216
+ urlObj.searchParams.set("operationName", operationName);
217
+ }
218
+ if (extensions) {
219
+ urlObj.searchParams.set("extensions", JSON.stringify(extensions));
220
+ }
221
+ const finalUrl = urlObj.toString().replace(dummyHostname, "");
222
+ return finalUrl;
223
+ }
224
+
225
+ function buildHTTPExecutor(options) {
226
+ const printFn = options?.print ?? defaultPrintFn;
227
+ let disposeCtrl;
228
+ const baseExecutor = (request) => {
229
+ if (disposeCtrl?.signal.aborted) {
230
+ return createResultForAbort(disposeCtrl.signal);
231
+ }
232
+ const fetchFn = request.extensions?.fetch ?? options?.fetch ?? fetch;
233
+ let method = request.extensions?.method || options?.method;
234
+ const operationAst = getOperationASTFromRequest(request);
235
+ const operationType = operationAst.operation;
236
+ if ((options?.useGETForQueries || request.extensions?.useGETForQueries) && operationType === "query") {
237
+ method = "GET";
238
+ }
239
+ let accept = "application/graphql-response+json, application/json, multipart/mixed";
240
+ if (operationType === "subscription" || isLiveQueryOperationDefinitionNode(operationAst)) {
241
+ method ||= "GET";
242
+ accept = "text/event-stream";
243
+ } else {
244
+ method ||= "POST";
245
+ }
246
+ const endpoint = request.extensions?.endpoint || options?.endpoint || "/graphql";
247
+ const headers = { accept };
248
+ if (options?.headers) {
249
+ Object.assign(
250
+ headers,
251
+ typeof options?.headers === "function" ? options.headers(request) : options?.headers
252
+ );
253
+ }
254
+ if (request.extensions?.headers) {
255
+ const { headers: headersFromExtensions, ...restExtensions } = request.extensions;
256
+ Object.assign(headers, headersFromExtensions);
257
+ request.extensions = restExtensions;
258
+ }
259
+ const query = printFn(request.document);
260
+ let signal = disposeCtrl?.signal;
261
+ let clearTimeoutFn = () => {
262
+ };
263
+ if (options?.timeout) {
264
+ const timeoutCtrl = new AbortController();
265
+ signal = timeoutCtrl.signal;
266
+ disposeCtrl?.signal.addEventListener("abort", clearTimeoutFn);
267
+ const timeoutId = setTimeout(() => {
268
+ if (!timeoutCtrl.signal.aborted) {
269
+ timeoutCtrl.abort("timeout");
270
+ }
271
+ disposeCtrl?.signal.removeEventListener("abort", clearTimeoutFn);
272
+ }, options.timeout);
273
+ clearTimeoutFn = () => {
274
+ clearTimeout(timeoutId);
275
+ };
276
+ }
277
+ const upstreamErrorExtensions = {
278
+ request: {
279
+ method
280
+ },
281
+ response: {}
282
+ };
283
+ return new ValueOrPromise(() => {
284
+ switch (method) {
285
+ case "GET": {
286
+ const finalUrl = prepareGETUrl({
287
+ baseUrl: endpoint,
288
+ query,
289
+ variables: request.variables,
290
+ operationName: request.operationName,
291
+ extensions: request.extensions
292
+ });
293
+ const fetchOptions = {
294
+ method: "GET",
295
+ headers,
296
+ signal
297
+ };
298
+ if (options?.credentials != null) {
299
+ fetchOptions.credentials = options.credentials;
300
+ }
301
+ upstreamErrorExtensions.request.url = finalUrl;
302
+ return fetchFn(finalUrl, fetchOptions, request.context, request.info);
303
+ }
304
+ case "POST": {
305
+ const body = {
306
+ query,
307
+ variables: request.variables,
308
+ operationName: request.operationName,
309
+ extensions: request.extensions
310
+ };
311
+ upstreamErrorExtensions.request.body = body;
312
+ return new ValueOrPromise(
313
+ () => createFormDataFromVariables(body, {
314
+ File: options?.File,
315
+ FormData: options?.FormData
316
+ })
317
+ ).then((body2) => {
318
+ if (typeof body2 === "string" && !headers["content-type"]) {
319
+ upstreamErrorExtensions.request.body = body2;
320
+ headers["content-type"] = "application/json";
321
+ }
322
+ const fetchOptions = {
323
+ method: "POST",
324
+ body: body2,
325
+ headers,
326
+ signal
327
+ };
328
+ if (options?.credentials != null) {
329
+ fetchOptions.credentials = options.credentials;
330
+ }
331
+ return fetchFn(
332
+ endpoint,
333
+ fetchOptions,
334
+ request.context,
335
+ request.info
336
+ );
337
+ }).resolve();
338
+ }
339
+ }
340
+ }).then((fetchResult) => {
341
+ upstreamErrorExtensions.response.status = fetchResult.status;
342
+ upstreamErrorExtensions.response.statusText = fetchResult.statusText;
343
+ Object.defineProperty(upstreamErrorExtensions.response, "headers", {
344
+ get() {
345
+ return Object.fromEntries(fetchResult.headers.entries());
346
+ }
347
+ });
348
+ clearTimeoutFn();
349
+ if (options?.retry != null && !fetchResult.status.toString().startsWith("2")) {
350
+ throw new Error(
351
+ fetchResult.statusText || `Upstream HTTP Error: ${fetchResult.status}`
352
+ );
353
+ }
354
+ const contentType = fetchResult.headers.get("content-type");
355
+ if (contentType?.includes("text/event-stream")) {
356
+ return handleEventStreamResponse(fetchResult);
357
+ } else if (contentType?.includes("multipart/mixed")) {
358
+ return handleMultipartMixedResponse(fetchResult);
359
+ }
360
+ return fetchResult.text();
361
+ }).then((result) => {
362
+ if (typeof result === "string") {
363
+ upstreamErrorExtensions.response.body = result;
364
+ if (result) {
365
+ try {
366
+ const parsedResult = JSON.parse(result);
367
+ upstreamErrorExtensions.response.body = parsedResult;
368
+ if (parsedResult.data == null && (parsedResult.errors == null || parsedResult.errors.length === 0)) {
369
+ return {
370
+ errors: [
371
+ createGraphQLError(
372
+ 'Unexpected empty "data" and "errors" fields in result: ' + result,
373
+ {
374
+ extensions: upstreamErrorExtensions
375
+ }
376
+ )
377
+ ]
378
+ };
379
+ }
380
+ if (Array.isArray(parsedResult.errors)) {
381
+ return {
382
+ ...parsedResult,
383
+ errors: parsedResult.errors.map(
384
+ ({
385
+ message,
386
+ ...options2
387
+ }) => createGraphQLError(message, {
388
+ ...options2,
389
+ extensions: {
390
+ code: "DOWNSTREAM_SERVICE_ERROR",
391
+ ...options2.extensions || {}
392
+ }
393
+ })
394
+ )
395
+ };
396
+ }
397
+ return parsedResult;
398
+ } catch (e) {
399
+ return {
400
+ errors: [
401
+ createGraphQLError(
402
+ `Unexpected response: ${JSON.stringify(result)}`,
403
+ {
404
+ extensions: upstreamErrorExtensions,
405
+ originalError: e
406
+ }
407
+ )
408
+ ]
409
+ };
410
+ }
411
+ }
412
+ } else {
413
+ return result;
414
+ }
415
+ }).catch((e) => {
416
+ if (e.name === "AggregateError") {
417
+ return {
418
+ errors: e.errors.map(
419
+ (e2) => coerceFetchError(e2, {
420
+ signal,
421
+ endpoint,
422
+ upstreamErrorExtensions
423
+ })
424
+ )
425
+ };
426
+ }
427
+ return {
428
+ errors: [
429
+ coerceFetchError(e, {
430
+ signal,
431
+ endpoint,
432
+ upstreamErrorExtensions
433
+ })
434
+ ]
435
+ };
436
+ }).resolve();
437
+ };
438
+ let executor = baseExecutor;
439
+ if (options?.retry != null) {
440
+ executor = function retryExecutor(request) {
441
+ let result;
442
+ let attempt = 0;
443
+ function retryAttempt() {
444
+ if (disposeCtrl?.signal.aborted) {
445
+ return createResultForAbort(disposeCtrl.signal);
446
+ }
447
+ attempt++;
448
+ if (attempt > options.retry) {
449
+ if (result != null) {
450
+ return result;
451
+ }
452
+ return {
453
+ errors: [createGraphQLError("No response returned from fetch")]
454
+ };
455
+ }
456
+ return new ValueOrPromise(() => baseExecutor(request)).then((res) => {
457
+ result = res;
458
+ if (result?.errors?.length) {
459
+ return retryAttempt();
460
+ }
461
+ return result;
462
+ }).resolve();
463
+ }
464
+ return retryAttempt();
465
+ };
466
+ }
467
+ if (!options?.disposable) {
468
+ disposeCtrl = void 0;
469
+ return executor;
470
+ }
471
+ disposeCtrl = new AbortController();
472
+ Object.defineProperties(executor, {
473
+ [Symbol.dispose]: {
474
+ get() {
475
+ return function dispose() {
476
+ return disposeCtrl.abort(createAbortErrorReason());
477
+ };
478
+ }
479
+ },
480
+ [Symbol.asyncDispose]: {
481
+ get() {
482
+ return function asyncDispose() {
483
+ return disposeCtrl.abort(createAbortErrorReason());
484
+ };
485
+ }
486
+ }
487
+ });
488
+ return executor;
489
+ }
490
+ function coerceFetchError(e, {
491
+ signal,
492
+ endpoint,
493
+ upstreamErrorExtensions
494
+ }) {
495
+ if (typeof e === "string") {
496
+ return createGraphQLError(e, {
497
+ extensions: upstreamErrorExtensions
498
+ });
499
+ } else if (e.name === "GraphQLError") {
500
+ return e;
501
+ } else if (e.name === "TypeError" && e.message === "fetch failed") {
502
+ return createGraphQLError(`fetch failed to ${endpoint}`, {
503
+ extensions: upstreamErrorExtensions,
504
+ originalError: e
505
+ });
506
+ } else if (e.name === "AbortError" && signal?.reason) {
507
+ return createGraphQLErrorForAbort(signal, {
508
+ extensions: upstreamErrorExtensions
509
+ });
510
+ } else if (e.message) {
511
+ return createGraphQLError(e.message, {
512
+ extensions: upstreamErrorExtensions,
513
+ originalError: e
514
+ });
515
+ } else {
516
+ return createGraphQLError("Unknown error", {
517
+ extensions: upstreamErrorExtensions,
518
+ originalError: e
519
+ });
520
+ }
521
+ }
522
+ function createAbortErrorReason() {
523
+ return new Error("Executor was disposed.");
524
+ }
525
+ function createGraphQLErrorForAbort(signal, extensions) {
526
+ return createGraphQLError(
527
+ "The operation was aborted. reason: " + signal.reason,
528
+ {
529
+ extensions
530
+ }
531
+ );
532
+ }
533
+ function createResultForAbort(signal, extensions) {
534
+ return {
535
+ errors: [createGraphQLErrorForAbort(signal, extensions)]
536
+ };
537
+ }
538
+
539
+ export { buildHTTPExecutor, isLiveQueryOperationDefinitionNode };