@apollo/client 3.7.0 → 3.7.1

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.
@@ -15,7 +15,7 @@ var utils = require('../link/utils');
15
15
  var tsInvariant = require('ts-invariant');
16
16
  var graphqlTag = require('graphql-tag');
17
17
 
18
- var version = '3.7.0';
18
+ var version = '3.7.1';
19
19
 
20
20
  function isExecutionPatchIncrementalResult(value) {
21
21
  return !!value.incremental;
@@ -159,8 +159,10 @@ var ObservableQuery = (function (_super) {
159
159
  }
160
160
  return result;
161
161
  };
162
- ObservableQuery.prototype.isDifferentFromLastResult = function (newResult) {
163
- return !this.last || !equality.equal(this.last.result, newResult);
162
+ ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
163
+ return (!this.last ||
164
+ !equality.equal(this.last.result, newResult) ||
165
+ (variables && !equality.equal(this.last.variables, variables)));
164
166
  };
165
167
  ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
166
168
  var last = this.last;
@@ -468,7 +470,7 @@ var ObservableQuery = (function (_super) {
468
470
  };
469
471
  ObservableQuery.prototype.reportResult = function (result, variables) {
470
472
  var lastError = this.getLastError();
471
- if (lastError || this.isDifferentFromLastResult(result)) {
473
+ if (lastError || this.isDifferentFromLastResult(result, variables)) {
472
474
  if (lastError || !result.partial || this.options.returnPartialData) {
473
475
  this.updateLastResult(result, variables);
474
476
  }
@@ -5,7 +5,7 @@
5
5
  // consult the @apollo/client/invariantErrorCodes.js file specific to
6
6
  // your @apollo/client version. This file is not meant to be imported.
7
7
  {
8
- "@apollo/client version": "3.7.0",
8
+ "@apollo/client version": "3.7.1",
9
9
 
10
10
  1: {
11
11
  file: "@apollo/client/cache/inmemory/entityStore.js",
@@ -1 +1 @@
1
- {"version":3,"file":"batchHttpLink.js","sourceRoot":"","sources":["../../../src/link/batch-http/batchHttpLink.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAA0B,MAAM,SAAS,CAAC;A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CAAC;gBACrC,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,QAAQ;YACN,QAAQ;gBACR,CAAC,UAAC,SAAoB;oBACpB,IAAM,OAAO,GAAG,SAAS,CAAC,UAAU,EAAE,CAAC;oBAEvC,IAAM,aAAa,GAAG;wBACpB,IAAI,EAAE,OAAO,CAAC,IAAI;wBAClB,OAAO,EAAE,OAAO,CAAC,YAAY;wBAC7B,WAAW,EAAE,OAAO,CAAC,WAAW;wBAChC,OAAO,EAAE,OAAO,CAAC,OAAO;qBACzB,CAAC;oBAGF,OAAO,SAAS,CAAC,SAAS,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;gBACnE,CAAC,CAAC,CAAC;QAEL,KAAI,CAAC,OAAO,GAAG,IAAI,SAAS,CAAC;YAC3B,aAAa,EAAE,KAAI,CAAC,aAAa;YACjC,aAAa,EAAE,KAAI,CAAC,aAAa;YACjC,QAAQ,EAAE,KAAI,CAAC,QAAQ;YACvB,QAAQ,UAAA;YACR,YAAY,cAAA;SACb,CAAC,CAAC;;IACL,CAAC;IAEM,+BAAO,GAAd,UAAe,SAAoB;QACjC,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC;IACH,oBAAC;AAAD,CAAC,AApMD,CAAmC,UAAU,GAoM5C","sourcesContent":["import { ApolloLink, Operation, FetchResult } from '../core';\nimport { Observable } from '../../utilities';\nimport { fromError } from '../utils';\nimport {\n serializeFetchParameter,\n selectURI,\n parseAndCheckHttpResponse,\n checkFetcher,\n selectHttpOptionsAndBodyInternal,\n defaultPrinter,\n fallbackHttpConfig,\n HttpOptions,\n createSignalIfSupported,\n} from '../http';\nimport { BatchLink } from '../batch';\n\nexport namespace BatchHttpLink {\n export type Options = Pick<\n BatchLink.Options,\n 'batchMax' | 'batchDebounce' | 'batchInterval' | 'batchKey'\n > & HttpOptions;\n}\n\n/**\n * Transforms Operation for into HTTP results.\n * context can include the headers property, which will be passed to the fetch function\n */\nexport class BatchHttpLink extends ApolloLink {\n private batchDebounce?: boolean;\n private batchInterval: number;\n private batchMax: number;\n private batcher: ApolloLink;\n\n constructor(fetchParams?: BatchHttpLink.Options) {\n super();\n\n let {\n uri = '/graphql',\n // use default global fetch if nothing is passed in\n fetch: fetcher,\n print = defaultPrinter,\n includeExtensions,\n preserveHeaderCase,\n batchInterval,\n batchDebounce,\n batchMax,\n batchKey,\n ...requestOptions\n } = fetchParams || ({} as BatchHttpLink.Options);\n\n // dev warnings to ensure fetch is present\n checkFetcher(fetcher);\n\n //fetcher is set here rather than the destructuring to ensure fetch is\n //declared before referencing it. Reference in the destructuring would cause\n //a ReferenceError\n if (!fetcher) {\n fetcher = fetch;\n }\n\n const linkConfig = {\n http: { includeExtensions, preserveHeaderCase },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n\n this.batchDebounce = batchDebounce;\n this.batchInterval = batchInterval || 10;\n this.batchMax = batchMax || 10;\n\n const batchHandler = (operations: Operation[]) => {\n const chosenURI = selectURI(operations[0], uri);\n\n const context = operations[0].getContext();\n\n const clientAwarenessHeaders: {\n 'apollographql-client-name'?: string;\n 'apollographql-client-version'?: string;\n } = {};\n if (context.clientAwareness) {\n const { name, version } = context.clientAwareness;\n if (name) {\n clientAwarenessHeaders['apollographql-client-name'] = name;\n }\n if (version) {\n clientAwarenessHeaders['apollographql-client-version'] = version;\n }\n }\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: { ...clientAwarenessHeaders, ...context.headers },\n };\n\n //uses fallback, link, and then context to build options\n const optsAndBody = operations.map(operation =>\n selectHttpOptionsAndBodyInternal(\n operation,\n print,\n fallbackHttpConfig,\n linkConfig,\n contextConfig,\n ),\n );\n\n const loadedBody = optsAndBody.map(({ body }) => body);\n const options = optsAndBody[0].options;\n\n // There's no spec for using GET with batches.\n if (options.method === 'GET') {\n return fromError<FetchResult[]>(\n new Error('apollo-link-batch-http does not support GET requests'),\n );\n }\n\n try {\n (options as any).body = serializeFetchParameter(loadedBody, 'Payload');\n } catch (parseError) {\n return fromError<FetchResult[]>(parseError);\n }\n\n let controller: any;\n if (!(options as any).signal) {\n const { controller: _controller, signal } = createSignalIfSupported();\n controller = _controller;\n if (controller) (options as any).signal = signal;\n }\n\n return new Observable<FetchResult[]>(observer => {\n fetcher!(chosenURI, options)\n .then(response => {\n // Make the raw response available in the context.\n operations.forEach(operation => operation.setContext({ response }));\n return response;\n })\n .then(parseAndCheckHttpResponse(operations))\n .then(result => {\n // we have data and can send it to back up the link chain\n observer.next(result);\n observer.complete();\n return result;\n })\n .catch(err => {\n // fetch was cancelled so its already been cleaned up in the unsubscribe\n if (err.name === 'AbortError') return;\n // if it is a network error, BUT there is graphql result info\n // fire the next observer before calling error\n // this gives apollo-client (and react-apollo) the `graphqlErrors` and `networErrors`\n // to pass to UI\n // this should only happen if we *also* have data as part of the response key per\n // the spec\n if (err.result && err.result.errors && err.result.data) {\n // if we dont' call next, the UI can only show networkError because AC didn't\n // get andy graphqlErrors\n // this is graphql execution result info (i.e errors and possibly data)\n // this is because there is no formal spec how errors should translate to\n // http status codes. So an auth error (401) could have both data\n // from a public field, errors from a private field, and a status of 401\n // {\n // user { // this will have errors\n // firstName\n // }\n // products { // this is public so will have data\n // cost\n // }\n // }\n //\n // the result of above *could* look like this:\n // {\n // data: { products: [{ cost: \"$10\" }] },\n // errors: [{\n // message: 'your session has timed out',\n // path: []\n // }]\n // }\n // status code of above would be a 401\n // in the UI you want to show data where you can, errors as data where you can\n // and use correct http status codes\n observer.next(err.result);\n }\n\n observer.error(err);\n });\n\n return () => {\n // XXX support canceling this request\n // https://developers.google.com/web/updates/2017/09/abortable-fetch\n if (controller) controller.abort();\n };\n });\n };\n\n batchKey =\n batchKey ||\n ((operation: Operation) => {\n const context = operation.getContext();\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: context.headers,\n };\n\n //may throw error if config not serializable\n return selectURI(operation, uri) + JSON.stringify(contextConfig);\n });\n\n this.batcher = new BatchLink({\n batchDebounce: this.batchDebounce,\n batchInterval: this.batchInterval,\n batchMax: this.batchMax,\n batchKey,\n batchHandler,\n });\n }\n\n public request(operation: Operation): Observable<FetchResult> | null {\n return this.batcher.request(operation);\n }\n}\n"]}
1
+ {"version":3,"file":"batchHttpLink.js","sourceRoot":"","sources":["../../../src/link/batch-http/batchHttpLink.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAA0B,MAAM,SAAS,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,EACL,uBAAuB,EACvB,SAAS,EACT,yBAAyB,EACzB,YAAY,EACZ,gCAAgC,EAChC,cAAc,EACd,kBAAkB,EAElB,uBAAuB,GACxB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAarC;IAAmC,iCAAU;IAM3C,uBAAY,WAAmC;QAA/C,YACE,iBAAO,SAwLR;QAtLC,IAAI,KAYA,WAAW,IAAK,EAA4B,EAX9C,WAAgB,EAAhB,GAAG,mBAAG,UAAU,KAAA,EAET,OAAO,WAAA,EACd,aAAsB,EAAtB,KAAK,mBAAG,cAAc,KAAA,EACtB,iBAAiB,uBAAA,EACjB,kBAAkB,wBAAA,EAClB,aAAa,mBAAA,EACb,aAAa,mBAAA,EACb,QAAQ,cAAA,EACR,QAAQ,cAAA,EACL,cAAc,cAXf,8HAYH,CAA+C,CAAC;QAGjD,YAAY,CAAC,OAAO,CAAC,CAAC;QAKtB,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,KAAK,CAAC;SACjB;QAED,IAAM,UAAU,GAAG;YACjB,IAAI,EAAE,EAAE,iBAAiB,mBAAA,EAAE,kBAAkB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CAAC,AApMD,CAAmC,UAAU,GAoM5C","sourcesContent":["import { ApolloLink, Operation, FetchResult } from '../core';\nimport { Observable } from '../../utilities';\nimport { fromError } from '../utils';\nimport {\n serializeFetchParameter,\n selectURI,\n parseAndCheckHttpResponse,\n checkFetcher,\n selectHttpOptionsAndBodyInternal,\n defaultPrinter,\n fallbackHttpConfig,\n HttpOptions,\n createSignalIfSupported,\n} from '../http';\nimport { BatchLink } from '../batch';\n\nexport namespace BatchHttpLink {\n export type Options = Pick<\n BatchLink.Options,\n 'batchMax' | 'batchDebounce' | 'batchInterval' | 'batchKey'\n > & HttpOptions;\n}\n\n/**\n * Transforms Operation for into HTTP results.\n * context can include the headers property, which will be passed to the fetch function\n */\nexport class BatchHttpLink extends ApolloLink {\n private batchDebounce?: boolean;\n private batchInterval: number;\n private batchMax: number;\n private batcher: ApolloLink;\n\n constructor(fetchParams?: BatchHttpLink.Options) {\n super();\n\n let {\n uri = '/graphql',\n // use default global fetch if nothing is passed in\n fetch: fetcher,\n print = defaultPrinter,\n includeExtensions,\n preserveHeaderCase,\n batchInterval,\n batchDebounce,\n batchMax,\n batchKey,\n ...requestOptions\n } = fetchParams || ({} as BatchHttpLink.Options);\n\n // dev warnings to ensure fetch is present\n checkFetcher(fetcher);\n\n //fetcher is set here rather than the destructuring to ensure fetch is\n //declared before referencing it. Reference in the destructuring would cause\n //a ReferenceError\n if (!fetcher) {\n fetcher = fetch;\n }\n\n const linkConfig = {\n http: { includeExtensions, preserveHeaderCase },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n\n this.batchDebounce = batchDebounce;\n this.batchInterval = batchInterval || 10;\n this.batchMax = batchMax || 10;\n\n const batchHandler = (operations: Operation[]) => {\n const chosenURI = selectURI(operations[0], uri);\n\n const context = operations[0].getContext();\n\n const clientAwarenessHeaders: {\n 'apollographql-client-name'?: string;\n 'apollographql-client-version'?: string;\n } = {};\n if (context.clientAwareness) {\n const { name, version } = context.clientAwareness;\n if (name) {\n clientAwarenessHeaders['apollographql-client-name'] = name;\n }\n if (version) {\n clientAwarenessHeaders['apollographql-client-version'] = version;\n }\n }\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: { ...clientAwarenessHeaders, ...context.headers },\n };\n\n //uses fallback, link, and then context to build options\n const optsAndBody = operations.map(operation =>\n selectHttpOptionsAndBodyInternal(\n operation,\n print,\n fallbackHttpConfig,\n linkConfig,\n contextConfig,\n ),\n );\n\n const loadedBody = optsAndBody.map(({ body }) => body);\n const options = optsAndBody[0].options;\n\n // There's no spec for using GET with batches.\n if (options.method === 'GET') {\n return fromError<FetchResult[]>(\n new Error('apollo-link-batch-http does not support GET requests'),\n );\n }\n\n try {\n (options as any).body = serializeFetchParameter(loadedBody, 'Payload');\n } catch (parseError) {\n return fromError<FetchResult[]>(parseError);\n }\n\n let controller: any;\n if (!(options as any).signal) {\n const { controller: _controller, signal } = createSignalIfSupported();\n controller = _controller;\n if (controller) (options as any).signal = signal;\n }\n\n return new Observable<FetchResult[]>(observer => {\n fetcher!(chosenURI, options)\n .then(response => {\n // Make the raw response available in the context.\n operations.forEach(operation => operation.setContext({ response }));\n return response;\n })\n .then(parseAndCheckHttpResponse(operations))\n .then(result => {\n // we have data and can send it to back up the link chain\n observer.next(result);\n observer.complete();\n return result;\n })\n .catch(err => {\n // fetch was cancelled so its already been cleaned up in the unsubscribe\n if (err.name === 'AbortError') return;\n // if it is a network error, BUT there is graphql result info\n // fire the next observer before calling error\n // this gives apollo-client (and react-apollo) the `graphqlErrors` and `networkErrors`\n // to pass to UI\n // this should only happen if we *also* have data as part of the response key per\n // the spec\n if (err.result && err.result.errors && err.result.data) {\n // if we dont' call next, the UI can only show networkError because AC didn't\n // get andy graphqlErrors\n // this is graphql execution result info (i.e errors and possibly data)\n // this is because there is no formal spec how errors should translate to\n // http status codes. So an auth error (401) could have both data\n // from a public field, errors from a private field, and a status of 401\n // {\n // user { // this will have errors\n // firstName\n // }\n // products { // this is public so will have data\n // cost\n // }\n // }\n //\n // the result of above *could* look like this:\n // {\n // data: { products: [{ cost: \"$10\" }] },\n // errors: [{\n // message: 'your session has timed out',\n // path: []\n // }]\n // }\n // status code of above would be a 401\n // in the UI you want to show data where you can, errors as data where you can\n // and use correct http status codes\n observer.next(err.result);\n }\n\n observer.error(err);\n });\n\n return () => {\n // XXX support canceling this request\n // https://developers.google.com/web/updates/2017/09/abortable-fetch\n if (controller) controller.abort();\n };\n });\n };\n\n batchKey =\n batchKey ||\n ((operation: Operation) => {\n const context = operation.getContext();\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: context.headers,\n };\n\n //may throw error if config not serializable\n return selectURI(operation, uri) + JSON.stringify(contextConfig);\n });\n\n this.batcher = new BatchLink({\n batchDebounce: this.batchDebounce,\n batchInterval: this.batchInterval,\n batchMax: this.batchMax,\n batchKey,\n batchHandler,\n });\n }\n\n public request(operation: Operation): Observable<FetchResult> | null {\n return this.batcher.request(operation);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"parseAndCheckHttpResponse.js","sourceRoot":"","sources":["../../../src/link/http/parseAndCheckHttpResponse.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAGpC,IAAA,cAAc,GAAK,MAAM,CAAC,SAAS,eAArB,CAAsB;AAQ5C,MAAM,UAAgB,iBAAiB,CACrC,QAAkB,EAClB,QAAqB;;;;;;;;oBAErB,IAAI,WAAW,KAAK,SAAS,EAAE;wBAC7B,MAAM,IAAI,KAAK,CACb,2EAA2E,CAC5E,CAAC;qBACH;oBACK,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;oBACnC,WAAW,GAAG,MAAA,QAAQ,CAAC,OAAO,0CAAE,GAAG,CAAC,cAAc,CAAC,CAAC;oBACpD,SAAS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,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,UAAC,EAAE,IAAK,OAAA,EAAE,CAAC,aAAa,EAAhB,CAAgB,CAAC;oBAC1C,CAAC,CAAC,UAAU,CAAC,aAAa,OAC1B,CACL,CAAC;aACH;YACD,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC;IA7BJ,CA6BI,CAAC;AACT,CAAC","sourcesContent":["import { responseIterator } from \"./responseIterator\";\nimport { Operation } from \"../core\";\nimport { throwServerError } from \"../utils\";\nimport { Observer } from \"../../utilities\";\n\nconst { hasOwnProperty } = Object.prototype;\n\nexport type ServerParseError = Error & {\n response: Response;\n statusCode: number;\n bodyText: string;\n};\n\nexport async function readMultipartBody<T = Record<string, unknown>>(\n response: Response,\n observer: Observer<T>\n) {\n if (TextDecoder === undefined) {\n throw new Error(\n \"TextDecoder must be defined in the environment: please import a polyfill.\"\n );\n }\n const decoder = new TextDecoder(\"utf-8\");\n const contentType = response.headers?.get('content-type');\n const delimiter = \"boundary=\";\n\n // parse boundary value and ignore any subsequent name/value pairs after ;\n // https://www.rfc-editor.org/rfc/rfc9110.html#name-parameters\n // e.g. multipart/mixed;boundary=\"graphql\";deferSpec=20220824\n // if no boundary is specified, default to -\n const boundaryVal = contentType?.includes(delimiter)\n ? contentType\n ?.substring(contentType?.indexOf(delimiter) + delimiter.length)\n .replace(/['\"]/g, \"\")\n .replace(/\\;(.*)/gm, \"\")\n .trim()\n : \"-\";\n\n let boundary = `--${boundaryVal}`;\n let buffer = \"\";\n const iterator = responseIterator(response);\n let running = true;\n\n while (running) {\n const { value, done } = await iterator.next();\n const chunk = typeof value === \"string\" ? value : decoder.decode(value);\n running = !done;\n buffer += chunk;\n let bi = buffer.indexOf(boundary);\n\n while (bi > -1) {\n let message: string;\n [message, buffer] = [\n buffer.slice(0, bi),\n buffer.slice(bi + boundary.length),\n ];\n if (message.trim()) {\n const i = message.indexOf(\"\\r\\n\\r\\n\");\n const headers = parseHeaders(message.slice(0, i));\n const contentType = headers[\"content-type\"];\n if (\n contentType &&\n contentType.toLowerCase().indexOf(\"application/json\") === -1\n ) {\n throw new Error(\"Unsupported patch content type: application/json is required.\");\n }\n const body = message.slice(i);\n\n try {\n const result = parseJsonBody<T>(response, body.replace(\"\\r\\n\", \"\"));\n if (\n Object.keys(result).length > 1 ||\n \"data\" in result ||\n \"incremental\" in result ||\n \"errors\" in result\n ) {\n // for the last chunk with only `hasNext: false`,\n // we don't need to call observer.next as there is no data/errors\n observer.next?.(result);\n }\n } catch (err) {\n handleError(err, observer);\n }\n }\n bi = buffer.indexOf(boundary);\n }\n }\n observer.complete?.();\n}\n\nexport function parseHeaders(headerText: string): Record<string, string> {\n const headersInit: Record<string, string> = {};\n headerText.split(\"\\n\").forEach((line) => {\n const i = line.indexOf(\":\");\n if (i > -1) {\n // normalize headers to lowercase\n const name = line.slice(0, i).trim().toLowerCase();\n const value = line.slice(i + 1).trim();\n headersInit[name] = value;\n }\n });\n return headersInit;\n}\n\nexport function parseJsonBody<T>(response: Response, bodyText: string): T {\n if (response.status >= 300) {\n // Network error\n const getResult = () => {\n try {\n return JSON.parse(bodyText);\n } catch (err) {\n return bodyText\n }\n }\n throwServerError(\n response,\n getResult(),\n `Response not successful: Received status code ${response.status}`,\n );\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch (err) {\n const parseError = err as ServerParseError;\n parseError.name = \"ServerParseError\";\n parseError.response = response;\n parseError.statusCode = response.status;\n parseError.bodyText = bodyText;\n throw parseError;\n }\n}\n\nexport function handleError(err: any, observer: Observer<any>) {\n if (err.name === \"AbortError\") return;\n // if it is a network error, BUT there is graphql result info fire\n // the next observer before calling error this gives apollo-client\n // (and react-apollo) the `graphqlErrors` and `networErrors` to\n // pass to UI this should only happen if we *also* have data as\n // part of the response key per the spec\n if (err.result && err.result.errors && err.result.data) {\n // if we don't call next, the UI can only show networkError\n // because AC didn't get any graphqlErrors this is graphql\n // execution result info (i.e errors and possibly data) this is\n // because there is no formal spec how errors should translate to\n // http status codes. So an auth error (401) could have both data\n // from a public field, errors from a private field, and a status\n // of 401\n // {\n // user { // this will have errors\n // firstName\n // }\n // products { // this is public so will have data\n // cost\n // }\n // }\n //\n // the result of above *could* look like this:\n // {\n // data: { products: [{ cost: \"$10\" }] },\n // errors: [{\n // message: 'your session has timed out',\n // path: []\n // }]\n // }\n // status code of above would be a 401\n // in the UI you want to show data where you can, errors as data where you can\n // and use correct http status codes\n observer.next?.(err.result);\n }\n\n observer.error?.(err);\n}\n\nexport function readJsonBody<T = Record<string, unknown>>(\n response: Response,\n operation: Operation,\n observer: Observer<T>\n) {\n parseAndCheckHttpResponse(operation)(response)\n .then((result) => {\n observer.next?.(result);\n observer.complete?.();\n })\n .catch((err) => handleError(err, observer));\n}\n\nexport function parseAndCheckHttpResponse(operations: Operation | Operation[]) {\n return (response: Response) =>\n response\n .text()\n .then((bodyText) => parseJsonBody(response, bodyText))\n .then((result: any) => {\n if (response.status >= 300) {\n // Network error\n throwServerError(\n response,\n result,\n `Response not successful: Received status code ${response.status}`\n );\n }\n if (\n !Array.isArray(result) &&\n !hasOwnProperty.call(result, \"data\") &&\n !hasOwnProperty.call(result, \"errors\")\n ) {\n // Data error\n throwServerError(\n response,\n result,\n `Server response was missing for query '${\n Array.isArray(operations)\n ? operations.map((op) => op.operationName)\n : operations.operationName\n }'.`\n );\n }\n return result;\n });\n}\n"]}
1
+ {"version":3,"file":"parseAndCheckHttpResponse.js","sourceRoot":"","sources":["../../../src/link/http/parseAndCheckHttpResponse.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAGpC,IAAA,cAAc,GAAK,MAAM,CAAC,SAAS,eAArB,CAAsB;AAQ5C,MAAM,UAAgB,iBAAiB,CACrC,QAAkB,EAClB,QAAqB;;;;;;;;oBAErB,IAAI,WAAW,KAAK,SAAS,EAAE;wBAC7B,MAAM,IAAI,KAAK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AM,EAAE,MAAM,CAAC;gBACpC,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,EACtC;gBAEA,gBAAgB,CACd,QAAQ,EACR,MAAM,EACN,iDACE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC;oBACvB,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,UAAC,EAAE,IAAK,OAAA,EAAE,CAAC,aAAa,EAAhB,CAAgB,CAAC;oBAC1C,CAAC,CAAC,UAAU,CAAC,aAAa,OAC1B,CACL,CAAC;aACH;YACD,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC;IA7BJ,CA6BI,CAAC;AACT,CAAC","sourcesContent":["import { responseIterator } from \"./responseIterator\";\nimport { Operation } from \"../core\";\nimport { throwServerError } from \"../utils\";\nimport { Observer } from \"../../utilities\";\n\nconst { hasOwnProperty } = Object.prototype;\n\nexport type ServerParseError = Error & {\n response: Response;\n statusCode: number;\n bodyText: string;\n};\n\nexport async function readMultipartBody<T = Record<string, unknown>>(\n response: Response,\n observer: Observer<T>\n) {\n if (TextDecoder === undefined) {\n throw new Error(\n \"TextDecoder must be defined in the environment: please import a polyfill.\"\n );\n }\n const decoder = new TextDecoder(\"utf-8\");\n const contentType = response.headers?.get('content-type');\n const delimiter = \"boundary=\";\n\n // parse boundary value and ignore any subsequent name/value pairs after ;\n // https://www.rfc-editor.org/rfc/rfc9110.html#name-parameters\n // e.g. multipart/mixed;boundary=\"graphql\";deferSpec=20220824\n // if no boundary is specified, default to -\n const boundaryVal = contentType?.includes(delimiter)\n ? contentType\n ?.substring(contentType?.indexOf(delimiter) + delimiter.length)\n .replace(/['\"]/g, \"\")\n .replace(/\\;(.*)/gm, \"\")\n .trim()\n : \"-\";\n\n let boundary = `--${boundaryVal}`;\n let buffer = \"\";\n const iterator = responseIterator(response);\n let running = true;\n\n while (running) {\n const { value, done } = await iterator.next();\n const chunk = typeof value === \"string\" ? value : decoder.decode(value);\n running = !done;\n buffer += chunk;\n let bi = buffer.indexOf(boundary);\n\n while (bi > -1) {\n let message: string;\n [message, buffer] = [\n buffer.slice(0, bi),\n buffer.slice(bi + boundary.length),\n ];\n if (message.trim()) {\n const i = message.indexOf(\"\\r\\n\\r\\n\");\n const headers = parseHeaders(message.slice(0, i));\n const contentType = headers[\"content-type\"];\n if (\n contentType &&\n contentType.toLowerCase().indexOf(\"application/json\") === -1\n ) {\n throw new Error(\"Unsupported patch content type: application/json is required.\");\n }\n const body = message.slice(i);\n\n try {\n const result = parseJsonBody<T>(response, body.replace(\"\\r\\n\", \"\"));\n if (\n Object.keys(result).length > 1 ||\n \"data\" in result ||\n \"incremental\" in result ||\n \"errors\" in result\n ) {\n // for the last chunk with only `hasNext: false`,\n // we don't need to call observer.next as there is no data/errors\n observer.next?.(result);\n }\n } catch (err) {\n handleError(err, observer);\n }\n }\n bi = buffer.indexOf(boundary);\n }\n }\n observer.complete?.();\n}\n\nexport function parseHeaders(headerText: string): Record<string, string> {\n const headersInit: Record<string, string> = {};\n headerText.split(\"\\n\").forEach((line) => {\n const i = line.indexOf(\":\");\n if (i > -1) {\n // normalize headers to lowercase\n const name = line.slice(0, i).trim().toLowerCase();\n const value = line.slice(i + 1).trim();\n headersInit[name] = value;\n }\n });\n return headersInit;\n}\n\nexport function parseJsonBody<T>(response: Response, bodyText: string): T {\n if (response.status >= 300) {\n // Network error\n const getResult = () => {\n try {\n return JSON.parse(bodyText);\n } catch (err) {\n return bodyText\n }\n }\n throwServerError(\n response,\n getResult(),\n `Response not successful: Received status code ${response.status}`,\n );\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch (err) {\n const parseError = err as ServerParseError;\n parseError.name = \"ServerParseError\";\n parseError.response = response;\n parseError.statusCode = response.status;\n parseError.bodyText = bodyText;\n throw parseError;\n }\n}\n\nexport function handleError(err: any, observer: Observer<any>) {\n if (err.name === \"AbortError\") return;\n // if it is a network error, BUT there is graphql result info fire\n // the next observer before calling error this gives apollo-client\n // (and react-apollo) the `graphqlErrors` and `networkErrors` to\n // pass to UI this should only happen if we *also* have data as\n // part of the response key per the spec\n if (err.result && err.result.errors && err.result.data) {\n // if we don't call next, the UI can only show networkError\n // because AC didn't get any graphqlErrors this is graphql\n // execution result info (i.e errors and possibly data) this is\n // because there is no formal spec how errors should translate to\n // http status codes. So an auth error (401) could have both data\n // from a public field, errors from a private field, and a status\n // of 401\n // {\n // user { // this will have errors\n // firstName\n // }\n // products { // this is public so will have data\n // cost\n // }\n // }\n //\n // the result of above *could* look like this:\n // {\n // data: { products: [{ cost: \"$10\" }] },\n // errors: [{\n // message: 'your session has timed out',\n // path: []\n // }]\n // }\n // status code of above would be a 401\n // in the UI you want to show data where you can, errors as data where you can\n // and use correct http status codes\n observer.next?.(err.result);\n }\n\n observer.error?.(err);\n}\n\nexport function readJsonBody<T = Record<string, unknown>>(\n response: Response,\n operation: Operation,\n observer: Observer<T>\n) {\n parseAndCheckHttpResponse(operation)(response)\n .then((result) => {\n observer.next?.(result);\n observer.complete?.();\n })\n .catch((err) => handleError(err, observer));\n}\n\nexport function parseAndCheckHttpResponse(operations: Operation | Operation[]) {\n return (response: Response) =>\n response\n .text()\n .then((bodyText) => parseJsonBody(response, bodyText))\n .then((result: any) => {\n if (response.status >= 300) {\n // Network error\n throwServerError(\n response,\n result,\n `Response not successful: Received status code ${response.status}`\n );\n }\n if (\n !Array.isArray(result) &&\n !hasOwnProperty.call(result, \"data\") &&\n !hasOwnProperty.call(result, \"errors\")\n ) {\n // Data error\n throwServerError(\n response,\n result,\n `Server response was missing for query '${\n Array.isArray(operations)\n ? operations.map((op) => op.operationName)\n : operations.operationName\n }'.`\n );\n }\n return result;\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/link/persisted-queries/index.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEpD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAOhC,OAAO,EA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CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC","sourcesContent":["import { invariant } from '../../utilities/globals';\n\nimport { print } from 'graphql';\nimport {\n DocumentNode,\n ExecutionResult,\n GraphQLError,\n} from 'graphql';\n\nimport { ApolloLink, Operation } from '../core';\nimport {\n Observable,\n Observer,\n ObservableSubscription,\n compact,\n isNonEmptyArray,\n} from '../../utilities';\nimport { NetworkError } from '../../errors';\nimport { ServerError } from '../utils';\n\nexport const VERSION = 1;\n\nexport interface ErrorResponse {\n graphQLErrors?: readonly GraphQLError[];\n networkError?: NetworkError;\n response?: ExecutionResult;\n operation: Operation;\n}\n\ntype SHA256Function = (...args: any[]) => string | PromiseLike<string>;\ntype GenerateHashFunction = (document: DocumentNode) => string | PromiseLike<string>;\n\nexport namespace PersistedQueryLink {\n interface BaseOptions {\n disable?: (error: ErrorResponse) => boolean;\n useGETForHashedQueries?: boolean;\n };\n\n interface SHA256Options extends BaseOptions {\n sha256: SHA256Function;\n generateHash?: never;\n };\n\n interface GenerateHashOptions extends BaseOptions {\n sha256?: never;\n generateHash: GenerateHashFunction;\n };\n\n export type Options = SHA256Options | GenerateHashOptions;\n}\n\nfunction collectErrorsByMessage<TError extends Error>(\n graphQLErrors: TError[] | readonly TError[] | undefined,\n): Record<string, TError> {\n const collected: Record<string, TError> = Object.create(null);\n if (isNonEmptyArray(graphQLErrors)) {\n graphQLErrors.forEach(error => collected[error.message] = error);\n }\n return collected;\n}\n\nconst defaultOptions = {\n disable: ({ graphQLErrors, operation }: ErrorResponse) => {\n const errorMessages = collectErrorsByMessage(graphQLErrors);\n\n // if the server doesn't support persisted queries, don't try anymore\n if (errorMessages.PersistedQueryNotSupported) {\n return true;\n }\n\n if (errorMessages.PersistedQueryNotFound) {\n return false;\n }\n\n const { response } = operation.getContext();\n // if the server responds with bad request\n // apollo-server responds with 400 for GET and 500 for POST when no query is found\n if (\n response &&\n response.status &&\n (response.status === 400 || response.status === 500)\n ) {\n return true;\n }\n\n return false;\n },\n useGETForHashedQueries: false,\n};\n\nfunction operationDefinesMutation(operation: Operation) {\n return operation.query.definitions.some(\n d => d.kind === 'OperationDefinition' && d.operation === 'mutation');\n}\n\nconst { hasOwnProperty } = Object.prototype;\n\nconst hashesByQuery = new WeakMap<\n DocumentNode,\n Record<string, Promise<string>>\n>();\n\nlet nextHashesChildKey = 0;\n\nexport const createPersistedQueryLink = (\n options: PersistedQueryLink.Options,\n) => {\n // Ensure a SHA-256 hash function is provided, if a custom hash\n // generation function is not provided. We don't supply a SHA-256 hash\n // function by default, to avoid forcing one as a dependency. Developers\n // should pick the most appropriate SHA-256 function (sync or async) for\n // their needs/environment, or provide a fully custom hash generation\n // function (via the `generateHash` option) if they want to handle\n // hashing with something other than SHA-256.\n invariant(\n options && (\n typeof options.sha256 === 'function' ||\n typeof options.generateHash === 'function'\n ),\n 'Missing/invalid \"sha256\" or \"generateHash\" function. Please ' +\n 'configure one using the \"createPersistedQueryLink(options)\" options ' +\n 'parameter.'\n );\n\n const {\n sha256,\n // If both a `sha256` and `generateHash` option are provided, the\n // `sha256` option will be ignored. Developers can configure and\n // use any hashing approach they want in a custom `generateHash`\n // function; they aren't limited to SHA-256.\n generateHash = (query: DocumentNode) =>\n Promise.resolve<string>(sha256!(print(query))),\n disable,\n useGETForHashedQueries\n } = compact(defaultOptions, options);\n\n let supportsPersistedQueries = true;\n\n const hashesChildKey = 'forLink' + nextHashesChildKey++;\n\n const getHashPromise = (query: DocumentNode) =>\n new Promise<string>(resolve => resolve(generateHash(query)));\n\n function getQueryHash(query: DocumentNode): Promise<string> {\n if (!query || typeof query !== 'object') {\n // If the query is not an object, we won't be able to store its hash as\n // a property of query[hashesKey], so we let generateHash(query) decide\n // what to do with the bogus query.\n return getHashPromise(query);\n }\n let hashes = hashesByQuery.get(query)!;\n if (!hashes) hashesByQuery.set(query, hashes = Object.create(null));\n return hasOwnProperty.call(hashes, hashesChildKey)\n ? hashes[hashesChildKey]\n : hashes[hashesChildKey] = getHashPromise(query);\n }\n\n return new ApolloLink((operation, forward) => {\n invariant(\n forward,\n 'PersistedQueryLink cannot be the last link in the chain.'\n );\n\n const { query } = operation;\n\n return new Observable((observer: Observer<ExecutionResult>) => {\n let subscription: ObservableSubscription;\n let retried = false;\n let originalFetchOptions: any;\n let setFetchOptions = false;\n const retry = (\n {\n response,\n networkError,\n }: { response?: ExecutionResult; networkError?: ServerError },\n cb: () => void,\n ) => {\n if (!retried && ((response && response.errors) || networkError)) {\n retried = true;\n\n const graphQLErrors: GraphQLError[] = [];\n\n const responseErrors = response && response.errors;\n if (isNonEmptyArray(responseErrors)) {\n graphQLErrors.push(...responseErrors);\n }\n\n // Network errors can return GraphQL errors on for example a 403\n const networkErrors =\n networkError &&\n networkError.result &&\n networkError.result.errors as GraphQLError[];\n if (isNonEmptyArray(networkErrors)) {\n graphQLErrors.push(...networkErrors);\n }\n\n const disablePayload = {\n response,\n networkError,\n operation,\n graphQLErrors: isNonEmptyArray(graphQLErrors) ? graphQLErrors : void 0,\n };\n\n // if the server doesn't support persisted queries, don't try anymore\n supportsPersistedQueries = !disable(disablePayload);\n\n // if its not found, we can try it again, otherwise just report the error\n if (\n collectErrorsByMessage(graphQLErrors).PersistedQueryNotFound ||\n !supportsPersistedQueries\n ) {\n // need to recall the link chain\n if (subscription) subscription.unsubscribe();\n // actually send the query this time\n operation.setContext({\n http: {\n includeQuery: true,\n includeExtensions: supportsPersistedQueries,\n },\n fetchOptions: {\n // Since we're including the full query, which may be\n // large, we should send it in the body of a POST request.\n // See issue #7456.\n method: 'POST',\n },\n });\n if (setFetchOptions) {\n operation.setContext({ fetchOptions: originalFetchOptions });\n }\n subscription = forward(operation).subscribe(handler);\n\n return;\n }\n }\n cb();\n };\n const handler = {\n next: (response: ExecutionResult) => {\n retry({ response }, () => observer.next!(response));\n },\n error: (networkError: ServerError) => {\n retry({ networkError }, () => observer.error!(networkError));\n },\n complete: observer.complete!.bind(observer),\n };\n\n // don't send the query the first time\n operation.setContext({\n http: {\n includeQuery: !supportsPersistedQueries,\n includeExtensions: supportsPersistedQueries,\n },\n });\n\n // If requested, set method to GET if there are no mutations. Remember the\n // original fetchOptions so we can restore them if we fall back to a\n // non-hashed request.\n if (\n useGETForHashedQueries &&\n supportsPersistedQueries &&\n !operationDefinesMutation(operation)\n ) {\n operation.setContext(\n ({ fetchOptions = {} }: { fetchOptions: Record<string, any> }) => {\n originalFetchOptions = fetchOptions;\n return {\n fetchOptions: {\n ...fetchOptions,\n method: 'GET',\n },\n };\n },\n );\n setFetchOptions = true;\n }\n\n if (supportsPersistedQueries) {\n getQueryHash(query).then((sha256Hash) => {\n operation.extensions.persistedQuery = {\n version: VERSION,\n sha256Hash,\n };\n subscription = forward(operation).subscribe(handler);\n }).catch(observer.error!.bind(observer));;\n } else {\n subscription = forward(operation).subscribe(handler);\n }\n\n return () => {\n if (subscription) subscription.unsubscribe();\n };\n });\n });\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/link/persisted-queries/index.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEpD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAOhC,OAAO,EAAE,UAAU,EAAa,MAAM,SAAS,CAAC;AAChD,OAAO,EACL,UAAU,EAGV,OAAO,EACP,eAAe,GAChB,MAAM,iBAAiB,CAAC;AAIzB,MAAM,CAAC,IAAM,OAAO,GAAG,CAAC,CAAC;AAYzB,MAAM,KAAW,kBAAkB,CAiBlC;AAjBD,WAAiB,kBAAkB;IAIhC,CAAC;IAKD,CAAC;IAKD,CAAC;AAGJ,CAAC,EAjBgB,kBAAkB,KAAlB,kBAAkB,QAiBlC;AAED,SAAS,sBAAsB,CAC7B,aAAuD;IAEvD,IAAM,SAAS,GAA2B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9D,IAAI,eAAe,CAAC,aAAa,CAAC,EAAE;QAClC,aAAa,CAAC,OAAO,C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AE,KAAA;oBAClB,oBAAoB,GAAG,YAAY,CAAC;oBACpC,OAAO;wBACL,YAAY,wBACP,YAAY,KACf,MAAM,EAAE,KAAK,GACd;qBACF,CAAC;gBACJ,CAAC,CACF,CAAC;gBACF,eAAe,GAAG,IAAI,CAAC;aACxB;YAED,IAAI,wBAAwB,EAAE;gBAC5B,YAAY,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,UAAC,UAAU;oBAClC,SAAS,CAAC,UAAU,CAAC,cAAc,GAAG;wBACpC,OAAO,EAAE,OAAO;wBAChB,UAAU,YAAA;qBACX,CAAC;oBACF,YAAY,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;gBACvD,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAA,CAAC;aAC3C;iBAAM;gBACL,YAAY,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;aACtD;YAED,OAAO;gBACL,IAAI,YAAY;oBAAE,YAAY,CAAC,WAAW,EAAE,CAAC;YAC/C,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC","sourcesContent":["import { invariant } from '../../utilities/globals';\n\nimport { print } from 'graphql';\nimport {\n DocumentNode,\n ExecutionResult,\n GraphQLError,\n} from 'graphql';\n\nimport { ApolloLink, Operation } from '../core';\nimport {\n Observable,\n Observer,\n ObservableSubscription,\n compact,\n isNonEmptyArray,\n} from '../../utilities';\nimport { NetworkError } from '../../errors';\nimport { ServerError } from '../utils';\n\nexport const VERSION = 1;\n\nexport interface ErrorResponse {\n graphQLErrors?: readonly GraphQLError[];\n networkError?: NetworkError;\n response?: ExecutionResult;\n operation: Operation;\n}\n\ntype SHA256Function = (...args: any[]) => string | PromiseLike<string>;\ntype GenerateHashFunction = (document: DocumentNode) => string | PromiseLike<string>;\n\nexport namespace PersistedQueryLink {\n interface BaseOptions {\n disable?: (error: ErrorResponse) => boolean;\n useGETForHashedQueries?: boolean;\n };\n\n interface SHA256Options extends BaseOptions {\n sha256: SHA256Function;\n generateHash?: never;\n };\n\n interface GenerateHashOptions extends BaseOptions {\n sha256?: never;\n generateHash: GenerateHashFunction;\n };\n\n export type Options = SHA256Options | GenerateHashOptions;\n}\n\nfunction collectErrorsByMessage<TError extends Error>(\n graphQLErrors: TError[] | readonly TError[] | undefined,\n): Record<string, TError> {\n const collected: Record<string, TError> = Object.create(null);\n if (isNonEmptyArray(graphQLErrors)) {\n graphQLErrors.forEach(error => collected[error.message] = error);\n }\n return collected;\n}\n\nconst defaultOptions = {\n disable: ({ graphQLErrors, operation }: ErrorResponse) => {\n const errorMessages = collectErrorsByMessage(graphQLErrors);\n\n // if the server doesn't support persisted queries, don't try anymore\n if (errorMessages.PersistedQueryNotSupported) {\n return true;\n }\n\n if (errorMessages.PersistedQueryNotFound) {\n return false;\n }\n\n const { response } = operation.getContext();\n // if the server responds with bad request\n // Apollo Server responds with 400 for GET and 500 for POST when no query is found\n if (\n response &&\n response.status &&\n (response.status === 400 || response.status === 500)\n ) {\n return true;\n }\n\n return false;\n },\n useGETForHashedQueries: false,\n};\n\nfunction operationDefinesMutation(operation: Operation) {\n return operation.query.definitions.some(\n d => d.kind === 'OperationDefinition' && d.operation === 'mutation');\n}\n\nconst { hasOwnProperty } = Object.prototype;\n\nconst hashesByQuery = new WeakMap<\n DocumentNode,\n Record<string, Promise<string>>\n>();\n\nlet nextHashesChildKey = 0;\n\nexport const createPersistedQueryLink = (\n options: PersistedQueryLink.Options,\n) => {\n // Ensure a SHA-256 hash function is provided, if a custom hash\n // generation function is not provided. We don't supply a SHA-256 hash\n // function by default, to avoid forcing one as a dependency. Developers\n // should pick the most appropriate SHA-256 function (sync or async) for\n // their needs/environment, or provide a fully custom hash generation\n // function (via the `generateHash` option) if they want to handle\n // hashing with something other than SHA-256.\n invariant(\n options && (\n typeof options.sha256 === 'function' ||\n typeof options.generateHash === 'function'\n ),\n 'Missing/invalid \"sha256\" or \"generateHash\" function. Please ' +\n 'configure one using the \"createPersistedQueryLink(options)\" options ' +\n 'parameter.'\n );\n\n const {\n sha256,\n // If both a `sha256` and `generateHash` option are provided, the\n // `sha256` option will be ignored. Developers can configure and\n // use any hashing approach they want in a custom `generateHash`\n // function; they aren't limited to SHA-256.\n generateHash = (query: DocumentNode) =>\n Promise.resolve<string>(sha256!(print(query))),\n disable,\n useGETForHashedQueries\n } = compact(defaultOptions, options);\n\n let supportsPersistedQueries = true;\n\n const hashesChildKey = 'forLink' + nextHashesChildKey++;\n\n const getHashPromise = (query: DocumentNode) =>\n new Promise<string>(resolve => resolve(generateHash(query)));\n\n function getQueryHash(query: DocumentNode): Promise<string> {\n if (!query || typeof query !== 'object') {\n // If the query is not an object, we won't be able to store its hash as\n // a property of query[hashesKey], so we let generateHash(query) decide\n // what to do with the bogus query.\n return getHashPromise(query);\n }\n let hashes = hashesByQuery.get(query)!;\n if (!hashes) hashesByQuery.set(query, hashes = Object.create(null));\n return hasOwnProperty.call(hashes, hashesChildKey)\n ? hashes[hashesChildKey]\n : hashes[hashesChildKey] = getHashPromise(query);\n }\n\n return new ApolloLink((operation, forward) => {\n invariant(\n forward,\n 'PersistedQueryLink cannot be the last link in the chain.'\n );\n\n const { query } = operation;\n\n return new Observable((observer: Observer<ExecutionResult>) => {\n let subscription: ObservableSubscription;\n let retried = false;\n let originalFetchOptions: any;\n let setFetchOptions = false;\n const retry = (\n {\n response,\n networkError,\n }: { response?: ExecutionResult; networkError?: ServerError },\n cb: () => void,\n ) => {\n if (!retried && ((response && response.errors) || networkError)) {\n retried = true;\n\n const graphQLErrors: GraphQLError[] = [];\n\n const responseErrors = response && response.errors;\n if (isNonEmptyArray(responseErrors)) {\n graphQLErrors.push(...responseErrors);\n }\n\n // Network errors can return GraphQL errors on for example a 403\n const networkErrors =\n networkError &&\n networkError.result &&\n networkError.result.errors as GraphQLError[];\n if (isNonEmptyArray(networkErrors)) {\n graphQLErrors.push(...networkErrors);\n }\n\n const disablePayload = {\n response,\n networkError,\n operation,\n graphQLErrors: isNonEmptyArray(graphQLErrors) ? graphQLErrors : void 0,\n };\n\n // if the server doesn't support persisted queries, don't try anymore\n supportsPersistedQueries = !disable(disablePayload);\n\n // if its not found, we can try it again, otherwise just report the error\n if (\n collectErrorsByMessage(graphQLErrors).PersistedQueryNotFound ||\n !supportsPersistedQueries\n ) {\n // need to recall the link chain\n if (subscription) subscription.unsubscribe();\n // actually send the query this time\n operation.setContext({\n http: {\n includeQuery: true,\n includeExtensions: supportsPersistedQueries,\n },\n fetchOptions: {\n // Since we're including the full query, which may be\n // large, we should send it in the body of a POST request.\n // See issue #7456.\n method: 'POST',\n },\n });\n if (setFetchOptions) {\n operation.setContext({ fetchOptions: originalFetchOptions });\n }\n subscription = forward(operation).subscribe(handler);\n\n return;\n }\n }\n cb();\n };\n const handler = {\n next: (response: ExecutionResult) => {\n retry({ response }, () => observer.next!(response));\n },\n error: (networkError: ServerError) => {\n retry({ networkError }, () => observer.error!(networkError));\n },\n complete: observer.complete!.bind(observer),\n };\n\n // don't send the query the first time\n operation.setContext({\n http: {\n includeQuery: !supportsPersistedQueries,\n includeExtensions: supportsPersistedQueries,\n },\n });\n\n // If requested, set method to GET if there are no mutations. Remember the\n // original fetchOptions so we can restore them if we fall back to a\n // non-hashed request.\n if (\n useGETForHashedQueries &&\n supportsPersistedQueries &&\n !operationDefinesMutation(operation)\n ) {\n operation.setContext(\n ({ fetchOptions = {} }: { fetchOptions: Record<string, any> }) => {\n originalFetchOptions = fetchOptions;\n return {\n fetchOptions: {\n ...fetchOptions,\n method: 'GET',\n },\n };\n },\n );\n setFetchOptions = true;\n }\n\n if (supportsPersistedQueries) {\n getQueryHash(query).then((sha256Hash) => {\n operation.extensions.persistedQuery = {\n version: VERSION,\n sha256Hash,\n };\n subscription = forward(operation).subscribe(handler);\n }).catch(observer.error!.bind(observer));;\n } else {\n subscription = forward(operation).subscribe(handler);\n }\n\n return () => {\n if (subscription) subscription.unsubscribe();\n };\n });\n });\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apollo/client",
3
- "version": "3.7.0",
3
+ "version": "3.7.1",
4
4
  "description": "A fully-featured caching GraphQL client.",
5
5
  "private": false,
6
6
  "keywords": [
@@ -66,49 +66,50 @@
66
66
  "zen-observable-ts": "^1.2.5"
67
67
  },
68
68
  "devDependencies": {
69
- "@babel/parser": "7.19.1",
69
+ "@babel/parser": "7.19.4",
70
70
  "@graphql-tools/schema": "9.0.4",
71
71
  "@rollup/plugin-node-resolve": "11.2.1",
72
72
  "@testing-library/react": "13.4.0",
73
73
  "@testing-library/react-12": "npm:@testing-library/react@^12",
74
74
  "@testing-library/react-hooks": "8.0.1",
75
75
  "@testing-library/user-event": "14.4.3",
76
+ "@types/bytes": "3.1.1",
76
77
  "@types/fast-json-stable-stringify": "2.0.0",
77
78
  "@types/fetch-mock": "7.3.5",
78
79
  "@types/glob": "8.0.0",
79
80
  "@types/hoist-non-react-statics": "3.3.1",
80
- "@types/jest": "29.0.3",
81
- "@types/lodash": "4.14.185",
82
- "@types/node": "16.11.60",
81
+ "@types/jest": "29.1.2",
82
+ "@types/lodash": "4.14.186",
83
+ "@types/node": "16.11.66",
83
84
  "@types/node-fetch": "2.6.2",
84
85
  "@types/react": "18.0.21",
85
86
  "@types/react-dom": "18.0.6",
86
87
  "@types/use-sync-external-store": "0.0.3",
87
88
  "acorn": "8.8.0",
88
89
  "blob-polyfill": "7.0.20220408",
89
- "bundlesize": "0.18.1",
90
+ "bytes": "3.1.2",
90
91
  "cross-fetch": "3.1.5",
91
92
  "fetch-mock": "9.11.0",
92
93
  "glob": "8.0.3",
93
94
  "graphql": "16.6.0",
94
95
  "graphql-ws": "5.11.2",
95
- "jest": "29.0.3",
96
- "jest-environment-jsdom": "29.0.3",
96
+ "jest": "29.2.0",
97
+ "jest-environment-jsdom": "29.2.0",
97
98
  "jest-junit": "14.0.1",
98
99
  "lodash": "4.17.21",
99
100
  "react": "18.2.0",
100
101
  "react-17": "npm:react@^17",
101
102
  "react-dom": "18.2.0",
102
103
  "react-dom-17": "npm:react-dom@^17",
103
- "recast": "0.21.2",
104
+ "recast": "0.21.5",
104
105
  "resolve": "1.22.1",
105
106
  "rimraf": "3.0.2",
106
107
  "rollup": "2.79.1",
107
108
  "rollup-plugin-terser": "7.0.2",
108
- "rxjs": "7.5.6",
109
+ "rxjs": "7.5.7",
109
110
  "subscriptions-transport-ws": "0.11.0",
110
- "terser": "5.15.0",
111
- "ts-jest": "29.0.2",
111
+ "terser": "5.15.1",
112
+ "ts-jest": "29.0.3",
112
113
  "ts-node": "10.9.1",
113
114
  "typedoc": "0.22.18",
114
115
  "typescript": "4.7.4",
@@ -657,13 +657,11 @@ function useFragment_experimental(options) {
657
657
  var resultRef = React.useRef();
658
658
  var latestDiff = cache.diff(diffOptions);
659
659
  return useSyncExternalStore(function (forceUpdate) {
660
- var immediate = true;
661
- return cache.watch(tslib.__assign(tslib.__assign({}, diffOptions), { immediate: immediate, callback: function (diff) {
662
- if (!immediate && !equality.equal(diff, latestDiff)) {
660
+ return cache.watch(tslib.__assign(tslib.__assign({}, diffOptions), { immediate: true, callback: function (diff) {
661
+ if (!equality.equal(diff, latestDiff)) {
663
662
  resultRef.current = diffToResult(latestDiff = diff);
664
663
  forceUpdate();
665
664
  }
666
- immediate = false;
667
665
  } }));
668
666
  }, function () {
669
667
  var latestDiffToResult = diffToResult(latestDiff);