@graphql-tools/url-loader 7.16.12 → 7.16.13-alpha-20221108142800-3beb5fe2

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 (33) hide show
  1. package/cjs/index.js +6 -360
  2. package/cjs/utils.js +1 -22
  3. package/esm/index.js +9 -363
  4. package/esm/utils.js +0 -19
  5. package/package.json +5 -8
  6. package/typings/defaultAsyncFetch.d.cts +1 -2
  7. package/typings/defaultAsyncFetch.d.ts +1 -2
  8. package/typings/defaultSyncFetch.d.cts +1 -6
  9. package/typings/defaultSyncFetch.d.ts +1 -6
  10. package/typings/index.d.cts +4 -54
  11. package/typings/index.d.ts +4 -54
  12. package/typings/utils.d.cts +0 -22
  13. package/typings/utils.d.ts +0 -22
  14. package/cjs/event-stream/addCancelToResponseStream.js +0 -26
  15. package/cjs/event-stream/handleAsyncIterable.js +0 -25
  16. package/cjs/event-stream/handleEventStreamResponse.js +0 -31
  17. package/cjs/event-stream/handleReadableStream.js +0 -64
  18. package/cjs/handleMultipartMixedResponse.js +0 -66
  19. package/esm/event-stream/addCancelToResponseStream.js +0 -21
  20. package/esm/event-stream/handleAsyncIterable.js +0 -21
  21. package/esm/event-stream/handleEventStreamResponse.js +0 -26
  22. package/esm/event-stream/handleReadableStream.js +0 -60
  23. package/esm/handleMultipartMixedResponse.js +0 -62
  24. package/typings/event-stream/addCancelToResponseStream.d.cts +0 -2
  25. package/typings/event-stream/addCancelToResponseStream.d.ts +0 -2
  26. package/typings/event-stream/handleAsyncIterable.d.cts +0 -1
  27. package/typings/event-stream/handleAsyncIterable.d.ts +0 -1
  28. package/typings/event-stream/handleEventStreamResponse.d.cts +0 -3
  29. package/typings/event-stream/handleEventStreamResponse.d.ts +0 -3
  30. package/typings/event-stream/handleReadableStream.d.cts +0 -2
  31. package/typings/event-stream/handleReadableStream.d.ts +0 -2
  32. package/typings/handleMultipartMixedResponse.d.cts +0 -2
  33. package/typings/handleMultipartMixedResponse.d.ts +0 -2
package/cjs/index.js CHANGED
@@ -2,22 +2,17 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UrlLoader = exports.SubscriptionProtocol = void 0;
4
4
  const tslib_1 = require("tslib");
5
- /* eslint-disable no-case-declarations */
6
- /// <reference lib="dom" />
7
5
  const graphql_1 = require("graphql");
8
6
  const utils_1 = require("@graphql-tools/utils");
9
7
  const wrap_1 = require("@graphql-tools/wrap");
10
- const graphql_ws_1 = require("graphql-ws");
11
8
  const isomorphic_ws_1 = tslib_1.__importDefault(require("isomorphic-ws"));
12
- const extract_files_1 = require("extract-files");
13
9
  const value_or_promise_1 = require("value-or-promise");
14
10
  const defaultAsyncFetch_js_1 = require("./defaultAsyncFetch.js");
15
11
  const defaultSyncFetch_js_1 = require("./defaultSyncFetch.js");
16
- const handleMultipartMixedResponse_js_1 = require("./handleMultipartMixedResponse.js");
17
- const handleEventStreamResponse_js_1 = require("./event-stream/handleEventStreamResponse.js");
18
- const addCancelToResponseStream_js_1 = require("./event-stream/addCancelToResponseStream.js");
19
- const fetch_1 = require("@whatwg-node/fetch");
20
12
  const utils_js_1 = require("./utils.js");
13
+ const executor_graphql_ws_1 = require("@graphql-tools/executor-graphql-ws");
14
+ const executor_http_1 = require("@graphql-tools/executor-http");
15
+ const executor_legacy_ws_1 = require("@graphql-tools/executor-legacy-ws");
21
16
  const asyncImport = (moduleName) => Promise.resolve().then(() => tslib_1.__importStar(require(moduleName)));
22
17
  const syncImport = (moduleName) => require(moduleName);
23
18
  var SubscriptionProtocol;
@@ -59,245 +54,12 @@ function isCompatibleUri(uri) {
59
54
  * ```
60
55
  */
61
56
  class UrlLoader {
62
- createFormDataFromVariables({ query, variables, operationName, extensions, }) {
63
- const vars = Object.assign({}, variables);
64
- const { clone, files } = (0, extract_files_1.extractFiles)(vars, 'variables', ((v) => (0, extract_files_1.isExtractableFile)(v) ||
65
- (v === null || v === void 0 ? void 0 : v.promise) ||
66
- (0, utils_1.isAsyncIterable)(v) ||
67
- (v === null || v === void 0 ? void 0 : v.then) ||
68
- typeof (v === null || v === void 0 ? void 0 : v.arrayBuffer) === 'function'));
69
- if (files.size === 0) {
70
- return JSON.stringify({
71
- query,
72
- variables,
73
- operationName,
74
- extensions,
75
- });
76
- }
77
- const map = {};
78
- const uploads = [];
79
- let currIndex = 0;
80
- for (const [file, curr] of files) {
81
- map[currIndex] = curr;
82
- uploads[currIndex] = file;
83
- currIndex++;
84
- }
85
- const form = new fetch_1.FormData();
86
- form.append('operations', JSON.stringify({
87
- query,
88
- variables: clone,
89
- operationName,
90
- extensions,
91
- }));
92
- form.append('map', JSON.stringify(map));
93
- function handleUpload(upload, i) {
94
- const indexStr = i.toString();
95
- if (upload != null) {
96
- const filename = upload.filename || upload.name || upload.path || `blob-${indexStr}`;
97
- if ((0, utils_js_1.isPromiseLike)(upload)) {
98
- return upload.then((resolvedUpload) => handleUpload(resolvedUpload, i));
99
- // If Blob
100
- }
101
- else if ((0, utils_js_1.isBlob)(upload)) {
102
- form.append(indexStr, upload, filename);
103
- }
104
- else if ((0, utils_js_1.isGraphQLUpload)(upload)) {
105
- const stream = upload.createReadStream();
106
- const chunks = [];
107
- return Promise.resolve().then(async () => {
108
- for await (const chunk of stream) {
109
- if (chunk) {
110
- chunks.push(...chunk);
111
- }
112
- }
113
- const blobPart = new Uint8Array(chunks);
114
- form.append(indexStr, new fetch_1.File([blobPart], filename, { type: upload.mimetype }), filename);
115
- });
116
- }
117
- else {
118
- form.append(indexStr, new fetch_1.File([upload], filename), filename);
119
- }
120
- }
121
- }
122
- return value_or_promise_1.ValueOrPromise.all(uploads.map((upload, i) => new value_or_promise_1.ValueOrPromise(() => handleUpload(upload, i))))
123
- .then(() => form)
124
- .resolve();
125
- }
126
- prepareGETUrl({ baseUrl, query, variables, operationName, extensions, }) {
127
- const HTTP_URL = switchProtocols(baseUrl, {
128
- wss: 'https',
129
- ws: 'http',
130
- });
131
- const dummyHostname = 'https://dummyhostname.com';
132
- const validUrl = HTTP_URL.startsWith('http')
133
- ? HTTP_URL
134
- : HTTP_URL.startsWith('/')
135
- ? `${dummyHostname}${HTTP_URL}`
136
- : `${dummyHostname}/${HTTP_URL}`;
137
- const urlObj = new URL(validUrl);
138
- urlObj.searchParams.set('query', (0, graphql_1.stripIgnoredCharacters)(query));
139
- if (variables && Object.keys(variables).length > 0) {
140
- urlObj.searchParams.set('variables', JSON.stringify(variables));
141
- }
142
- if (operationName) {
143
- urlObj.searchParams.set('operationName', operationName);
144
- }
145
- if (extensions) {
146
- urlObj.searchParams.set('extensions', JSON.stringify(extensions));
147
- }
148
- const finalUrl = urlObj.toString().replace(dummyHostname, '');
149
- return finalUrl;
150
- }
151
57
  buildHTTPExecutor(initialEndpoint, fetch, options) {
152
- const defaultMethod = this.getDefaultMethodFromOptions(options === null || options === void 0 ? void 0 : options.method, 'POST');
153
58
  const HTTP_URL = switchProtocols(initialEndpoint, {
154
59
  wss: 'https',
155
60
  ws: 'http',
156
61
  });
157
- const executor = (request) => {
158
- var _a, _b;
159
- const controller = (0, addCancelToResponseStream_js_1.cancelNeeded)() ? new fetch_1.AbortController() : undefined;
160
- let method = defaultMethod;
161
- const operationAst = (0, utils_1.getOperationASTFromRequest)(request);
162
- const operationType = operationAst.operation;
163
- if ((options === null || options === void 0 ? void 0 : options.useGETForQueries) && operationType === 'query') {
164
- method = 'GET';
165
- }
166
- let accept = 'application/graphql-response+json, application/json, multipart/mixed';
167
- if (operationType === 'subscription' || (0, utils_js_1.isLiveQueryOperationDefinitionNode)(operationAst)) {
168
- method = 'GET';
169
- accept = 'text/event-stream';
170
- }
171
- const endpoint = ((_a = request.extensions) === null || _a === void 0 ? void 0 : _a.endpoint) || HTTP_URL;
172
- const headers = Object.assign({
173
- accept,
174
- }, options === null || options === void 0 ? void 0 : options.headers, ((_b = request.extensions) === null || _b === void 0 ? void 0 : _b.headers) || {});
175
- const query = (0, graphql_1.print)(request.document);
176
- const requestBody = {
177
- query,
178
- variables: request.variables,
179
- operationName: request.operationName,
180
- extensions: request.extensions,
181
- };
182
- let timeoutId;
183
- if (options === null || options === void 0 ? void 0 : options.timeout) {
184
- timeoutId = setTimeout(() => {
185
- if (!(controller === null || controller === void 0 ? void 0 : controller.signal.aborted)) {
186
- controller === null || controller === void 0 ? void 0 : controller.abort();
187
- }
188
- }, options.timeout);
189
- }
190
- return new value_or_promise_1.ValueOrPromise(() => {
191
- switch (method) {
192
- case 'GET':
193
- const finalUrl = this.prepareGETUrl({
194
- baseUrl: endpoint,
195
- ...requestBody,
196
- });
197
- return fetch(finalUrl, {
198
- method: 'GET',
199
- ...((options === null || options === void 0 ? void 0 : options.credentials) != null ? { credentials: options.credentials } : {}),
200
- headers,
201
- signal: controller === null || controller === void 0 ? void 0 : controller.signal,
202
- }, request.context, request.info);
203
- case 'POST':
204
- return new value_or_promise_1.ValueOrPromise(() => this.createFormDataFromVariables(requestBody))
205
- .then(body => fetch(endpoint, {
206
- method: 'POST',
207
- ...((options === null || options === void 0 ? void 0 : options.credentials) != null ? { credentials: options.credentials } : {}),
208
- body,
209
- headers: {
210
- ...headers,
211
- ...(typeof body === 'string' ? { 'content-type': 'application/json' } : {}),
212
- },
213
- signal: controller === null || controller === void 0 ? void 0 : controller.signal,
214
- }, request.context, request.info))
215
- .resolve();
216
- }
217
- })
218
- .then((fetchResult) => {
219
- if (timeoutId != null) {
220
- clearTimeout(timeoutId);
221
- }
222
- // Retry should respect HTTP Errors
223
- if ((options === null || options === void 0 ? void 0 : options.retry) != null && !fetchResult.status.toString().startsWith('2')) {
224
- throw new Error(fetchResult.statusText || `HTTP Error: ${fetchResult.status}`);
225
- }
226
- const contentType = fetchResult.headers.get('content-type');
227
- if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) {
228
- return (0, handleEventStreamResponse_js_1.handleEventStreamResponse)(fetchResult, controller);
229
- }
230
- else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('multipart/mixed')) {
231
- return (0, handleMultipartMixedResponse_js_1.handleMultipartMixedResponse)(fetchResult, controller);
232
- }
233
- return fetchResult.text();
234
- })
235
- .then(result => {
236
- if (typeof result === 'string') {
237
- if (result) {
238
- return JSON.parse(result);
239
- }
240
- }
241
- else {
242
- return result;
243
- }
244
- })
245
- .catch((e) => {
246
- if (typeof e === 'string') {
247
- return {
248
- errors: [
249
- (0, utils_1.createGraphQLError)(e, {
250
- extensions: {
251
- requestBody,
252
- },
253
- }),
254
- ],
255
- };
256
- }
257
- else if (e.name === 'GraphQLError') {
258
- return {
259
- errors: [e],
260
- };
261
- }
262
- else if (e.name === 'TypeError' && e.message === 'fetch failed') {
263
- return {
264
- errors: [
265
- (0, utils_1.createGraphQLError)(`fetch failed to ${endpoint}`, {
266
- extensions: {
267
- requestBody,
268
- },
269
- originalError: e,
270
- }),
271
- ],
272
- };
273
- }
274
- else if (e.message) {
275
- return {
276
- errors: [
277
- (0, utils_1.createGraphQLError)(e.message, {
278
- extensions: {
279
- requestBody,
280
- },
281
- originalError: e,
282
- }),
283
- ],
284
- };
285
- }
286
- else {
287
- return {
288
- errors: [
289
- (0, utils_1.createGraphQLError)('Unknown error', {
290
- extensions: {
291
- requestBody,
292
- },
293
- originalError: e,
294
- }),
295
- ],
296
- };
297
- }
298
- })
299
- .resolve();
300
- };
62
+ const executor = (0, executor_http_1.buildHTTPExecutor)(HTTP_URL, fetch, options);
301
63
  if ((options === null || options === void 0 ? void 0 : options.retry) != null) {
302
64
  return function retryExecutor(request) {
303
65
  let result;
@@ -333,130 +95,14 @@ class UrlLoader {
333
95
  https: 'wss',
334
96
  http: 'ws',
335
97
  });
336
- const subscriptionClient = (0, graphql_ws_1.createClient)({
337
- url: WS_URL,
338
- webSocketImpl,
339
- connectionParams,
340
- lazy: true,
341
- });
342
- return ({ document, variables, operationName, extensions }) => {
343
- const query = (0, graphql_1.print)(document);
344
- return (0, utils_1.observableToAsyncIterable)({
345
- subscribe: observer => {
346
- const unsubscribe = subscriptionClient.subscribe({
347
- query,
348
- variables: variables,
349
- operationName,
350
- extensions,
351
- }, observer);
352
- return {
353
- unsubscribe,
354
- };
355
- },
356
- });
357
- };
98
+ return (0, executor_graphql_ws_1.buildGraphQLWSExecutor)(WS_URL, webSocketImpl, connectionParams);
358
99
  }
359
100
  buildWSLegacyExecutor(subscriptionsEndpoint, WebSocketImpl, options) {
360
101
  const WS_URL = switchProtocols(subscriptionsEndpoint, {
361
102
  https: 'wss',
362
103
  http: 'ws',
363
104
  });
364
- const observerById = new Map();
365
- let websocket = null;
366
- const ensureWebsocket = () => {
367
- websocket = new WebSocketImpl(WS_URL, 'graphql-ws', {
368
- followRedirects: true,
369
- headers: options === null || options === void 0 ? void 0 : options.headers,
370
- rejectUnauthorized: false,
371
- skipUTF8Validation: true,
372
- });
373
- websocket.onopen = () => {
374
- let payload = {};
375
- switch (typeof (options === null || options === void 0 ? void 0 : options.connectionParams)) {
376
- case 'function':
377
- payload = options === null || options === void 0 ? void 0 : options.connectionParams();
378
- break;
379
- case 'object':
380
- payload = options === null || options === void 0 ? void 0 : options.connectionParams;
381
- break;
382
- }
383
- websocket.send(JSON.stringify({
384
- type: utils_js_1.LEGACY_WS.CONNECTION_INIT,
385
- payload,
386
- }));
387
- };
388
- };
389
- const cleanupWebsocket = () => {
390
- if (websocket != null && observerById.size === 0) {
391
- websocket.send(JSON.stringify({
392
- type: utils_js_1.LEGACY_WS.CONNECTION_TERMINATE,
393
- }));
394
- websocket.terminate();
395
- websocket = null;
396
- }
397
- };
398
- return function legacyExecutor(request) {
399
- const id = Date.now().toString();
400
- return (0, utils_1.observableToAsyncIterable)({
401
- subscribe(observer) {
402
- ensureWebsocket();
403
- if (websocket == null) {
404
- throw new Error(`WebSocket connection is not found!`);
405
- }
406
- websocket.onmessage = event => {
407
- const data = JSON.parse(event.data.toString('utf-8'));
408
- switch (data.type) {
409
- case utils_js_1.LEGACY_WS.CONNECTION_ACK: {
410
- if (websocket == null) {
411
- throw new Error(`WebSocket connection is not found!`);
412
- }
413
- websocket.send(JSON.stringify({
414
- type: utils_js_1.LEGACY_WS.START,
415
- id,
416
- payload: {
417
- query: (0, graphql_1.print)(request.document),
418
- variables: request.variables,
419
- operationName: request.operationName,
420
- },
421
- }));
422
- break;
423
- }
424
- case utils_js_1.LEGACY_WS.CONNECTION_ERROR: {
425
- observer.error(data.payload);
426
- break;
427
- }
428
- case utils_js_1.LEGACY_WS.CONNECTION_KEEP_ALIVE: {
429
- break;
430
- }
431
- case utils_js_1.LEGACY_WS.DATA: {
432
- observer.next(data.payload);
433
- break;
434
- }
435
- case utils_js_1.LEGACY_WS.COMPLETE: {
436
- if (websocket == null) {
437
- throw new Error(`WebSocket connection is not found!`);
438
- }
439
- websocket.send(JSON.stringify({
440
- type: utils_js_1.LEGACY_WS.CONNECTION_TERMINATE,
441
- }));
442
- observer.complete();
443
- cleanupWebsocket();
444
- break;
445
- }
446
- }
447
- };
448
- return {
449
- unsubscribe: () => {
450
- websocket === null || websocket === void 0 ? void 0 : websocket.send(JSON.stringify({
451
- type: utils_js_1.LEGACY_WS.STOP,
452
- id,
453
- }));
454
- cleanupWebsocket();
455
- },
456
- };
457
- },
458
- });
459
- };
105
+ return (0, executor_legacy_ws_1.buildWSLegacyExecutor)(WS_URL, WebSocketImpl, options);
460
106
  }
461
107
  getFetch(customFetch, importFn) {
462
108
  if (customFetch) {
package/cjs/utils.js CHANGED
@@ -1,15 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LEGACY_WS = exports.isLiveQueryOperationDefinitionNode = exports.isPromiseLike = exports.isGraphQLUpload = exports.isBlob = void 0;
3
+ exports.isLiveQueryOperationDefinitionNode = exports.isPromiseLike = void 0;
4
4
  const utils_1 = require("@graphql-tools/utils");
5
- function isBlob(obj) {
6
- return typeof obj.arrayBuffer === 'function';
7
- }
8
- exports.isBlob = isBlob;
9
- function isGraphQLUpload(upload) {
10
- return typeof upload.createReadStream === 'function';
11
- }
12
- exports.isGraphQLUpload = isGraphQLUpload;
13
5
  function isPromiseLike(obj) {
14
6
  return typeof obj.then === 'function';
15
7
  }
@@ -18,16 +10,3 @@ exports.isLiveQueryOperationDefinitionNode = (0, utils_1.memoize1)(function isLi
18
10
  var _a;
19
11
  return (_a = node.directives) === null || _a === void 0 ? void 0 : _a.some(directive => directive.name.value === 'live');
20
12
  });
21
- var LEGACY_WS;
22
- (function (LEGACY_WS) {
23
- LEGACY_WS["CONNECTION_INIT"] = "connection_init";
24
- LEGACY_WS["CONNECTION_ACK"] = "connection_ack";
25
- LEGACY_WS["CONNECTION_ERROR"] = "connection_error";
26
- LEGACY_WS["CONNECTION_KEEP_ALIVE"] = "ka";
27
- LEGACY_WS["START"] = "start";
28
- LEGACY_WS["STOP"] = "stop";
29
- LEGACY_WS["CONNECTION_TERMINATE"] = "connection_terminate";
30
- LEGACY_WS["DATA"] = "data";
31
- LEGACY_WS["ERROR"] = "error";
32
- LEGACY_WS["COMPLETE"] = "complete";
33
- })(LEGACY_WS = exports.LEGACY_WS || (exports.LEGACY_WS = {}));