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C,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"]}
\No newline at end of file