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nD,EAAU+C,EAAiBpmC,UAGnD,cAAgB,WAAM,OAAAomC,EAAiBrJ,QAAjB,GAA2B,CAACqJ,IAElD,IAAMpmC,GAAU,EAAA0kC,GAAA,GACd,gBACE,SAACa,GACC,OAAOa,EAAiB2B,QAAO,SAAC/nC,GAC9BwmC,GAAsBnD,EAAUrjC,GAChCulC,GACF,GACF,GACA,CAACa,IAEH4E,EACAA,GAGI7oC,EAAS4jC,GAAM/lC,GAErB,OAAO,YAAc,WACnB,MAAO,CACLc,KAAMqB,EAAOrB,KACbif,cAAe5d,EAAO4d,cACtBlf,MAAO0oC,GAAcpnC,GAEzB,GAAG,CAACA,GACN,CCiEO,SAAS8oC,GACdjoB,GAEA,OAAO,SAILjc,EACAnB,G,QAcA,YAdA,IAAAA,IAAAA,EACgCxC,OAAOmD,OAAO,OAavC4/B,GAXU,IAAIqC,GACnBxlB,EAAOwL,YAAW,oBACb5oB,GAAO,CACVmB,MAAK,KAEP,CACEkgC,qBACuC,QAArC,EAA2B,QAA3B,EAAAjkB,EAAOhE,eAAe6pB,aAAK,eAAEC,gBAAQ,eAAE7B,uBAK/C,CACF,C","sources":["webpack://customer-portal/./node_modules/@apollo/src/link/core/execute.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/serializeFetchParameter.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/selectURI.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/iterators/reader.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/responseIterator.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/iterators/async.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/iterators/promise.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/iterators/nodeStream.ts","webpack://customer-portal/./node_modules/@apollo/src/link/utils/throwServerError.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/common/incrementalResult.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/parseAndCheckHttpResponse.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/checkFetcher.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/graphql/print.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/selectHttpOptionsAndBody.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/rewriteURIForGET.ts","webpack://customer-portal/./node_modules/@apollo/src/link/utils/fromError.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/graphql/transform.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/createHttpLink.ts","webpack://customer-portal/./node_modules/@apollo/src/link/utils/filterOperationVariables.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/HttpLink.ts","webpack://customer-portal/./node_modules/@wry/trie/src/index.ts","webpack://customer-portal/./node_modules/optimism/node_modules/@wry/trie/src/index.ts","webpack://customer-portal/./node_modules/@wry/context/src/slot.ts","webpack://customer-portal/./node_modules/@wry/context/src/index.ts","webpack://customer-portal/./node_modules/optimism/src/context.ts","webpack://customer-portal/./node_modules/optimism/src/helpers.ts","webpack://customer-portal/./node_modules/optimism/src/entry.ts","webpack://customer-portal/./node_modules/optimism/src/dep.ts","webpack://customer-portal/./node_modules/optimism/src/index.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/graphql/DocumentTransform.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/observables/asyncMap.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/common/errorHandling.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/observables/iteration.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/observables/subclassing.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/observables/Concast.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/common/cloneDeep.ts","webpack://customer-portal/./node_modules/@apollo/src/core/equalByQuery.ts","webpack://customer-portal/./node_modules/@apollo/src/core/ObservableQuery.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/reactiveVars.ts","webpack://customer-portal/./node_modules/@apollo/src/core/LocalState.ts","webpack://customer-portal/./node_modules/@apollo/src/core/QueryInfo.ts","webpack://customer-portal/./node_modules/@apollo/src/core/QueryManager.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/core/types/Cache.ts","webpack://customer-portal/./node_modules/@apollo/src/core/ApolloClient.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/core/cache.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/core/types/common.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/entityStore.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/object-canon.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/readFromStore.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/key-extractor.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/policies.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/writeToStore.ts","webpack://customer-portal/./node_modules/@apollo/src/cache/inmemory/inMemoryCache.ts","webpack://customer-portal/./node_modules/@apollo/src/link/core/empty.ts","webpack://customer-portal/./node_modules/@apollo/src/link/core/from.ts","webpack://customer-portal/./node_modules/@apollo/src/link/core/split.ts","webpack://customer-portal/./node_modules/@apollo/src/link/core/concat.ts","webpack://customer-portal/./node_modules/@apollo/src/link/http/createSignalIfSupported.ts","webpack://customer-portal/./node_modules/@apollo/src/link/utils/toPromise.ts","webpack://customer-portal/./node_modules/@apollo/src/link/utils/fromPromise.ts","webpack://customer-portal/./node_modules/graphql-tag/src/index.ts","webpack://customer-portal/./node_modules/@apollo/src/core/index.ts","webpack://customer-portal/./node_modules/@apollo/src/react/context/ApolloProvider.tsx","webpack://customer-portal/./node_modules/@apollo/src/react/context/ApolloConsumer.tsx","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useLazyQuery.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useSubscription.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useReactiveVar.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/internal/useDeepMemo.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/internal/useLazyRef.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useFragment.ts","webpack://customer-portal/./node_modules/@apollo/src/utilities/promises/decoration.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/internal/__use.ts","webpack://customer-portal/./node_modules/@apollo/src/react/internal/cache/QueryReference.ts","webpack://customer-portal/./node_modules/@apollo/src/react/internal/cache/SuspenseCache.ts","webpack://customer-portal/./node_modules/@apollo/src/react/internal/cache/getSuspenseCache.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/constants.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useSuspenseQuery.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useBackgroundQuery.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/internal/useRenderGuard.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useLoadableQuery.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useQueryRefHandlers.ts","webpack://customer-portal/./node_modules/@apollo/src/react/hooks/useReadQuery.ts","webpack://customer-portal/./node_modules/@apollo/src/react/query-preloader/createQueryPreloader.ts"],"sourcesContent":["import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const execute = ApolloLink.execute;\n","import { newInvariantError } from \"../../utilities/globals/index.js\";\nimport type { InvariantError } from \"../../utilities/globals/index.js\";\n\nexport type ClientParseError = InvariantError & {\n parseError: Error;\n};\n\nexport const serializeFetchParameter = (p: any, label: string) => {\n let serialized;\n try {\n serialized = JSON.stringify(p);\n } catch (e: any) {\n const parseError = newInvariantError(\n `Network request failed. %s is not serializable: %s`,\n label,\n e.message\n ) as ClientParseError;\n parseError.parseError = e;\n throw parseError;\n }\n return serialized;\n};\n","import type { Operation } from \"../core/index.js\";\n\nexport const selectURI = (\n operation: Operation,\n fallbackURI?: string | ((operation: Operation) => string)\n) => {\n const context = operation.getContext();\n const contextURI = context.uri;\n\n if (contextURI) {\n return contextURI;\n } else if (typeof fallbackURI === \"function\") {\n return fallbackURI(operation);\n } else {\n return (fallbackURI as string) || \"/graphql\";\n }\n};\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts\n */\n\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface ReaderIterator {\n next(): Promise>;\n [Symbol.asyncIterator]?(): AsyncIterator;\n}\n\nexport default function readerIterator(\n reader: ReadableStreamDefaultReader\n): AsyncIterableIterator {\n const iterator: ReaderIterator = {\n next() {\n return reader.read() as Promise<\n | ReadableStreamReadValueResult\n // DoneResult has `value` optional, which doesn't comply with an\n // `IteratorResult`, so we assert it to `T | undefined` instead\n | Required>\n >;\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator<\n T,\n T | undefined\n > {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator;\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/index.ts\n */\n\nimport type { Response as NodeResponse } from \"node-fetch\";\nimport type { Readable as NodeReadableStream } from \"stream\";\nimport { canUseAsyncIteratorSymbol } from \"../../utilities/index.js\";\n\nimport asyncIterator from \"./iterators/async.js\";\nimport nodeStreamIterator from \"./iterators/nodeStream.js\";\nimport promiseIterator from \"./iterators/promise.js\";\nimport readerIterator from \"./iterators/reader.js\";\n\nfunction isNodeResponse(value: any): value is NodeResponse {\n return !!(value as NodeResponse).body;\n}\n\nfunction isReadableStream(value: any): value is ReadableStream {\n return !!(value as ReadableStream).getReader;\n}\n\nfunction isAsyncIterableIterator(\n value: any\n): value is AsyncIterableIterator {\n return !!(\n canUseAsyncIteratorSymbol &&\n (value as AsyncIterableIterator)[Symbol.asyncIterator]\n );\n}\n\nfunction isStreamableBlob(value: any): value is Blob {\n return !!(value as Blob).stream;\n}\n\nfunction isBlob(value: any): value is Blob {\n return !!(value as Blob).arrayBuffer;\n}\n\nfunction isNodeReadableStream(value: any): value is NodeReadableStream {\n return !!(value as NodeReadableStream).pipe;\n}\n\nexport function responseIterator(\n response: Response | NodeResponse\n): AsyncIterableIterator {\n let body: unknown = response;\n\n if (isNodeResponse(response)) body = response.body;\n\n if (isAsyncIterableIterator(body)) return asyncIterator(body);\n\n if (isReadableStream(body)) return readerIterator(body.getReader());\n\n // this errors without casting to ReadableStream\n // because Blob.stream() returns a NodeJS ReadableStream\n if (isStreamableBlob(body)) {\n return readerIterator(\n (body.stream() as unknown as ReadableStream).getReader()\n );\n }\n\n if (isBlob(body)) return promiseIterator(body.arrayBuffer());\n\n if (isNodeReadableStream(body)) return nodeStreamIterator(body);\n\n throw new Error(\n \"Unknown body type for responseIterator. Please pass a streamable response.\"\n );\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts\n */\n\nexport default function asyncIterator(\n source: AsyncIterableIterator\n): AsyncIterableIterator {\n const iterator = source[Symbol.asyncIterator]();\n return {\n next(): Promise> {\n return iterator.next();\n },\n [Symbol.asyncIterator](): AsyncIterableIterator {\n return this;\n },\n };\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts\n */\n\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface PromiseIterator {\n next(): Promise>;\n [Symbol.asyncIterator]?(): AsyncIterator;\n}\n\nexport default function promiseIterator(\n promise: Promise\n): AsyncIterableIterator {\n let resolved = false;\n\n const iterator: PromiseIterator = {\n next(): Promise> {\n if (resolved)\n return Promise.resolve({\n value: undefined,\n done: true,\n });\n resolved = true;\n return new Promise(function (resolve, reject) {\n promise\n .then(function (value) {\n resolve({ value: value as unknown as T, done: false });\n })\n .catch(reject);\n });\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator;\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/nodeStream.ts\n */\n\nimport type { Readable as NodeReadableStream } from \"stream\";\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface NodeStreamIterator {\n next(): Promise>;\n [Symbol.asyncIterator]?(): AsyncIterator;\n}\n\nexport default function nodeStreamIterator(\n stream: NodeReadableStream\n): AsyncIterableIterator {\n let cleanup: (() => void) | null = null;\n let error: Error | null = null;\n let done = false;\n const data: unknown[] = [];\n\n const waiting: [\n (\n value:\n | IteratorResult\n | PromiseLike>\n ) => void,\n (reason?: any) => void,\n ][] = [];\n\n function onData(chunk: any) {\n if (error) return;\n if (waiting.length) {\n const shiftedArr = waiting.shift();\n if (Array.isArray(shiftedArr) && shiftedArr[0]) {\n return shiftedArr[0]({ value: chunk, done: false });\n }\n }\n data.push(chunk);\n }\n function onError(err: Error) {\n error = err;\n const all = waiting.slice();\n all.forEach(function (pair) {\n pair[1](err);\n });\n !cleanup || cleanup();\n }\n function onEnd() {\n done = true;\n const all = waiting.slice();\n all.forEach(function (pair) {\n pair[0]({ value: undefined, done: true });\n });\n !cleanup || cleanup();\n }\n\n cleanup = function () {\n cleanup = null;\n stream.removeListener(\"data\", onData);\n stream.removeListener(\"error\", onError);\n stream.removeListener(\"end\", onEnd);\n stream.removeListener(\"finish\", onEnd);\n stream.removeListener(\"close\", onEnd);\n };\n stream.on(\"data\", onData);\n stream.on(\"error\", onError);\n stream.on(\"end\", onEnd);\n stream.on(\"finish\", onEnd);\n stream.on(\"close\", onEnd);\n\n function getNext(): Promise> {\n return new Promise(function (resolve, reject) {\n if (error) return reject(error);\n if (data.length)\n return resolve({ value: data.shift() as T, done: false });\n if (done) return resolve({ value: undefined, done: true });\n waiting.push([resolve, reject]);\n });\n }\n\n const iterator: NodeStreamIterator = {\n next(): Promise> {\n return getNext();\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator;\n}\n","export type ServerError = Error & {\n response: Response;\n result: Record | string;\n statusCode: number;\n};\n\nexport const throwServerError = (\n response: Response,\n result: any,\n message: string\n) => {\n const error = new Error(message) as ServerError;\n error.name = \"ServerError\";\n error.response = response;\n error.statusCode = response.status;\n error.result = result;\n throw error;\n};\n","import type {\n ExecutionPatchIncrementalResult,\n ExecutionPatchInitialResult,\n ExecutionPatchResult,\n ApolloPayloadResult,\n FetchResult,\n} from \"../../link/core/index.js\";\nimport { isNonNullObject } from \"./objects.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { DeepMerger } from \"./mergeDeep.js\";\n\nexport function isExecutionPatchIncrementalResult(\n value: FetchResult\n): value is ExecutionPatchIncrementalResult {\n return \"incremental\" in value;\n}\n\nexport function isExecutionPatchInitialResult(\n value: FetchResult\n): value is ExecutionPatchInitialResult {\n return \"hasNext\" in value && \"data\" in value;\n}\n\nexport function isExecutionPatchResult(\n value: FetchResult\n): value is ExecutionPatchResult {\n return (\n isExecutionPatchIncrementalResult(value) ||\n isExecutionPatchInitialResult(value)\n );\n}\n\n// This function detects an Apollo payload result before it is transformed\n// into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult\n// once it leaves the link chain.\nexport function isApolloPayloadResult(\n value: unknown\n): value is ApolloPayloadResult {\n return isNonNullObject(value) && \"payload\" in value;\n}\n\nexport function mergeIncrementalData(\n prevResult: TData,\n result: ExecutionPatchResult\n) {\n let mergedData = prevResult;\n const merger = new DeepMerger();\n if (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n result.incremental.forEach(({ data, path }) => {\n for (let i = path.length - 1; i >= 0; --i) {\n const key = path[i];\n const isNumericKey = !isNaN(+key);\n const parent: Record = isNumericKey ? [] : {};\n parent[key] = data;\n data = parent as typeof data;\n }\n mergedData = merger.merge(mergedData, data);\n });\n }\n return mergedData as TData;\n}\n","import { responseIterator } from \"./responseIterator.js\";\nimport type { Operation } from \"../core/index.js\";\nimport { throwServerError } from \"../utils/index.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../../errors/index.js\";\nimport { isApolloPayloadResult } from \"../../utilities/common/incrementalResult.js\";\nimport type { SubscriptionObserver } from \"zen-observable-ts\";\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<\n T extends object = Record,\n>(response: Response, nextValue: (value: T) => void) {\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 =\n contentType?.includes(delimiter) ?\n contentType\n ?.substring(contentType?.indexOf(delimiter) + delimiter.length)\n .replace(/['\"]/g, \"\")\n .replace(/\\;(.*)/gm, \"\")\n .trim()\n : \"-\";\n\n const boundary = `\\r\\n--${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 const searchFrom = buffer.length - boundary.length + 1;\n running = !done;\n buffer += chunk;\n let bi = buffer.indexOf(boundary, searchFrom);\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 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(\n \"Unsupported patch content type: application/json is required.\"\n );\n }\n // nb: Technically you'd want to slice off the beginning \"\\r\\n\" but since\n // this is going to be `JSON.parse`d there is no need.\n const body = message.slice(i);\n\n if (body) {\n const result = parseJsonBody(response, body);\n if (\n Object.keys(result).length > 1 ||\n \"data\" in result ||\n \"incremental\" in result ||\n \"errors\" in result ||\n \"payload\" in result\n ) {\n if (isApolloPayloadResult(result)) {\n let next = {};\n if (\"payload\" in result) {\n if (Object.keys(result).length === 1 && result.payload === null) {\n return;\n }\n next = { ...result.payload };\n }\n if (\"errors\" in result) {\n next = {\n ...next,\n extensions: {\n ...(\"extensions\" in next ? next.extensions : (null as any)),\n [PROTOCOL_ERRORS_SYMBOL]: result.errors,\n },\n };\n }\n nextValue(next as T);\n } else {\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 nextValue(result);\n }\n } else if (\n // If the chunk contains only a \"hasNext: false\", we can call\n // observer.complete() immediately.\n Object.keys(result).length === 1 &&\n \"hasNext\" in result &&\n !result.hasNext\n ) {\n return;\n }\n }\n bi = buffer.indexOf(boundary);\n }\n }\n}\n\nexport function parseHeaders(headerText: string): Record {\n const headersInit: Record = {};\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(response: Response, bodyText: string): T {\n if (response.status >= 300) {\n // Network error\n const getResult = (): Record | string => {\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: SubscriptionObserver) {\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 parseAndCheckHttpResponse(operations: Operation | Operation[]) {\n return (response: Response) =>\n response\n .text()\n .then((bodyText) => parseJsonBody(response, bodyText))\n .then((result: any) => {\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","import { newInvariantError } from \"../../utilities/globals/index.js\";\n\nexport const checkFetcher = (fetcher: typeof fetch | undefined) => {\n if (!fetcher && typeof fetch === \"undefined\") {\n throw newInvariantError(`\n\"fetch\" has not been found globally and no fetcher has been \\\nconfigured. To fix this, install a fetch package (like \\\nhttps://www.npmjs.com/package/cross-fetch), instantiate the \\\nfetcher, and pass it into your HttpLink constructor. For example:\n\nimport fetch from 'cross-fetch';\nimport { ApolloClient, HttpLink } from '@apollo/client';\nconst client = new ApolloClient({\n link: new HttpLink({ uri: '/graphql', fetch })\n});\n `);\n }\n};\n","import type { ASTNode } from \"graphql\";\nimport { print as origPrint } from \"graphql\";\nimport {\n AutoCleanedWeakCache,\n cacheSizes,\n defaultCacheSizes,\n} from \"../caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\n\nlet printCache!: AutoCleanedWeakCache;\nexport const print = Object.assign(\n (ast: ASTNode) => {\n let result = printCache.get(ast);\n\n if (!result) {\n result = origPrint(ast);\n printCache.set(ast, result);\n }\n return result;\n },\n {\n reset() {\n printCache = new AutoCleanedWeakCache(\n cacheSizes.print || defaultCacheSizes.print\n );\n },\n }\n);\nprint.reset();\n\nif (__DEV__) {\n registerGlobalCache(\"print\", () => (printCache ? printCache.size : 0));\n}\n","import type { ASTNode } from \"graphql\";\nimport { print } from \"../../utilities/index.js\";\n\nimport type { Operation } from \"../core/index.js\";\n\nexport interface Printer {\n (node: ASTNode, originalPrint: typeof print): string;\n}\n\nexport interface UriFunction {\n (operation: Operation): string;\n}\n\nexport interface Body {\n query?: string;\n operationName?: string;\n variables?: Record;\n extensions?: Record;\n}\n\nexport interface HttpOptions {\n /**\n * The URI to use when fetching operations.\n *\n * Defaults to '/graphql'.\n */\n uri?: string | UriFunction;\n\n /**\n * Passes the extensions field to your graphql server.\n *\n * Defaults to false.\n */\n includeExtensions?: boolean;\n\n /**\n * A `fetch`-compatible API to use when making requests.\n */\n fetch?: typeof fetch;\n\n /**\n * An object representing values to be sent as headers on the request.\n */\n headers?: Record;\n\n /**\n * If set to true, header names won't be automatically normalized to\n * lowercase. This allows for non-http-spec-compliant servers that might\n * expect capitalized header names.\n */\n preserveHeaderCase?: boolean;\n\n /**\n * The credentials policy you want to use for the fetch call.\n */\n credentials?: string;\n\n /**\n * Any overrides of the fetch options argument to pass to the fetch call.\n */\n fetchOptions?: any;\n\n /**\n * If set to true, use the HTTP GET method for query operations. Mutations\n * will still use the method specified in fetchOptions.method (which defaults\n * to POST).\n */\n useGETForQueries?: boolean;\n\n /**\n * If set to true, the default behavior of stripping unused variables\n * from the request will be disabled.\n *\n * Unused variables are likely to trigger server-side validation errors,\n * per https://spec.graphql.org/draft/#sec-All-Variables-Used, but this\n * includeUnusedVariables option can be useful if your server deviates\n * from the GraphQL specification by not strictly enforcing that rule.\n */\n includeUnusedVariables?: boolean;\n /**\n * A function to substitute for the default query print function. Can be\n * used to apply changes to the results of the print function.\n */\n print?: Printer;\n}\n\nexport interface HttpQueryOptions {\n includeQuery?: boolean;\n includeExtensions?: boolean;\n preserveHeaderCase?: boolean;\n}\n\nexport interface HttpConfig {\n http?: HttpQueryOptions;\n options?: any;\n headers?: Record;\n credentials?: any;\n}\n\nconst defaultHttpOptions: HttpQueryOptions = {\n includeQuery: true,\n includeExtensions: false,\n preserveHeaderCase: false,\n};\n\nconst defaultHeaders = {\n // headers are case insensitive (https://stackoverflow.com/a/5259004)\n accept: \"*/*\",\n // The content-type header describes the type of the body of the request, and\n // so it typically only is sent with requests that actually have bodies. One\n // could imagine that Apollo Client would remove this header when constructing\n // a GET request (which has no body), but we historically have not done that.\n // This means that browsers will preflight all Apollo Client requests (even\n // GET requests). Apollo Server's CSRF prevention feature (introduced in\n // AS3.7) takes advantage of this fact and does not block requests with this\n // header. If you want to drop this header from GET requests, then you should\n // probably replace it with a `apollo-require-preflight` header, or servers\n // with CSRF prevention enabled might block your GET request. See\n // https://www.apollographql.com/docs/apollo-server/security/cors/#preventing-cross-site-request-forgery-csrf\n // for more details.\n \"content-type\": \"application/json\",\n};\n\nconst defaultOptions = {\n method: \"POST\",\n};\n\nexport const fallbackHttpConfig = {\n http: defaultHttpOptions,\n headers: defaultHeaders,\n options: defaultOptions,\n};\n\nexport const defaultPrinter: Printer = (ast, printer) => printer(ast);\n\nexport function selectHttpOptionsAndBody(\n operation: Operation,\n fallbackConfig: HttpConfig,\n ...configs: Array\n) {\n configs.unshift(fallbackConfig);\n return selectHttpOptionsAndBodyInternal(\n operation,\n defaultPrinter,\n ...configs\n );\n}\n\nexport function selectHttpOptionsAndBodyInternal(\n operation: Operation,\n printer: Printer,\n ...configs: HttpConfig[]\n) {\n let options = {} as HttpConfig & Record;\n let http = {} as HttpQueryOptions;\n\n configs.forEach((config) => {\n options = {\n ...options,\n ...config.options,\n headers: {\n ...options.headers,\n ...config.headers,\n },\n };\n\n if (config.credentials) {\n options.credentials = config.credentials;\n }\n\n http = {\n ...http,\n ...config.http,\n };\n });\n\n if (options.headers) {\n options.headers = removeDuplicateHeaders(\n options.headers,\n http.preserveHeaderCase\n );\n }\n\n //The body depends on the http options\n const { operationName, extensions, variables, query } = operation;\n const body: Body = { operationName, variables };\n\n if (http.includeExtensions) (body as any).extensions = extensions;\n\n // not sending the query (i.e persisted queries)\n if (http.includeQuery) (body as any).query = printer(query, print);\n\n return {\n options,\n body,\n };\n}\n\n// Remove potential duplicate header names, preserving last (by insertion order).\n// This is done to prevent unintentionally duplicating a header instead of\n// overwriting it (See #8447 and #8449).\nfunction removeDuplicateHeaders(\n headers: Record,\n preserveHeaderCase: boolean | undefined\n): typeof headers {\n // If we're not preserving the case, just remove duplicates w/ normalization.\n if (!preserveHeaderCase) {\n const normalizedHeaders = Object.create(null);\n Object.keys(Object(headers)).forEach((name) => {\n normalizedHeaders[name.toLowerCase()] = headers[name];\n });\n return normalizedHeaders;\n }\n\n // If we are preserving the case, remove duplicates w/ normalization,\n // preserving the original name.\n // This allows for non-http-spec-compliant servers that expect intentionally\n // capitalized header names (See #6741).\n const headerData = Object.create(null);\n Object.keys(Object(headers)).forEach((name) => {\n headerData[name.toLowerCase()] = {\n originalName: name,\n value: headers[name],\n };\n });\n\n const normalizedHeaders = Object.create(null);\n Object.keys(headerData).forEach((name) => {\n normalizedHeaders[headerData[name].originalName] = headerData[name].value;\n });\n return normalizedHeaders;\n}\n","import { serializeFetchParameter } from \"./serializeFetchParameter.js\";\nimport type { Body } from \"./selectHttpOptionsAndBody.js\";\n\n// For GET operations, returns the given URI rewritten with parameters, or a\n// parse error.\nexport function rewriteURIForGET(chosenURI: string, body: Body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n const queryParams: string[] = [];\n const addQueryParam = (key: string, value: string) => {\n queryParams.push(`${key}=${encodeURIComponent(value)}`);\n };\n\n if (\"query\" in body) {\n addQueryParam(\"query\", body.query!);\n }\n if (body.operationName) {\n addQueryParam(\"operationName\", body.operationName);\n }\n if (body.variables) {\n let serializedVariables;\n try {\n serializedVariables = serializeFetchParameter(\n body.variables,\n \"Variables map\"\n );\n } catch (parseError) {\n return { parseError };\n }\n addQueryParam(\"variables\", serializedVariables);\n }\n if (body.extensions) {\n let serializedExtensions;\n try {\n serializedExtensions = serializeFetchParameter(\n body.extensions,\n \"Extensions map\"\n );\n } catch (parseError) {\n return { parseError };\n }\n addQueryParam(\"extensions\", serializedExtensions);\n }\n\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n let fragment = \"\",\n preFragment = chosenURI;\n const fragmentStart = chosenURI.indexOf(\"#\");\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n const queryParamsPrefix = preFragment.indexOf(\"?\") === -1 ? \"?\" : \"&\";\n const newURI =\n preFragment + queryParamsPrefix + queryParams.join(\"&\") + fragment;\n return { newURI };\n}\n","import { Observable } from \"../../utilities/index.js\";\n\nexport function fromError(errorValue: any): Observable {\n return new Observable((observer) => {\n observer.error(errorValue);\n });\n}\n","import { invariant } from \"../globals/index.js\";\n\nimport type {\n DocumentNode,\n SelectionNode,\n SelectionSetNode,\n OperationDefinitionNode,\n FieldNode,\n DirectiveNode,\n FragmentDefinitionNode,\n ArgumentNode,\n FragmentSpreadNode,\n VariableDefinitionNode,\n ASTNode,\n ASTVisitFn,\n InlineFragmentNode,\n} from \"graphql\";\nimport { visit, Kind } from \"graphql\";\n\nimport {\n checkDocument,\n getOperationDefinition,\n getFragmentDefinition,\n getFragmentDefinitions,\n getMainDefinition,\n} from \"./getFromAST.js\";\nimport { isField } from \"./storeUtils.js\";\nimport type { FragmentMap } from \"./fragments.js\";\nimport { createFragmentMap } from \"./fragments.js\";\nimport { isArray, isNonEmptyArray } from \"../common/arrays.js\";\n\n// https://github.com/graphql/graphql-js/blob/8d7c8fccf5a9846a50785de04abda58a7eb13fc0/src/language/visitor.ts#L20-L23\ninterface EnterLeaveVisitor {\n readonly enter?: ASTVisitFn;\n readonly leave?: ASTVisitFn;\n}\n\nexport type RemoveNodeConfig = {\n name?: string;\n test?: (node: N) => boolean;\n remove?: boolean;\n};\n\nexport type GetNodeConfig = {\n name?: string;\n test?: (node: N) => boolean;\n};\n\nexport type RemoveDirectiveConfig = RemoveNodeConfig;\nexport type GetDirectiveConfig = GetNodeConfig;\nexport type RemoveArgumentsConfig = RemoveNodeConfig;\nexport type GetFragmentSpreadConfig = GetNodeConfig;\nexport type RemoveFragmentSpreadConfig = RemoveNodeConfig;\nexport type RemoveFragmentDefinitionConfig =\n RemoveNodeConfig;\nexport type RemoveVariableDefinitionConfig =\n RemoveNodeConfig;\n\nconst TYPENAME_FIELD: FieldNode = {\n kind: Kind.FIELD,\n name: {\n kind: Kind.NAME,\n value: \"__typename\",\n },\n};\n\nfunction isEmpty(\n op: OperationDefinitionNode | FragmentDefinitionNode,\n fragmentMap: FragmentMap\n): boolean {\n return (\n !op ||\n op.selectionSet.selections.every(\n (selection) =>\n selection.kind === Kind.FRAGMENT_SPREAD &&\n isEmpty(fragmentMap[selection.name.value], fragmentMap)\n )\n );\n}\n\nfunction nullIfDocIsEmpty(doc: DocumentNode) {\n return (\n isEmpty(\n getOperationDefinition(doc) || getFragmentDefinition(doc),\n createFragmentMap(getFragmentDefinitions(doc))\n )\n ) ?\n null\n : doc;\n}\n\nfunction getDirectiveMatcher(\n configs: (RemoveDirectiveConfig | GetDirectiveConfig)[]\n) {\n const names = new Map();\n\n const tests = new Map<\n (directive: DirectiveNode) => boolean,\n RemoveDirectiveConfig | GetDirectiveConfig\n >();\n\n configs.forEach((directive) => {\n if (directive) {\n if (directive.name) {\n names.set(directive.name, directive);\n } else if (directive.test) {\n tests.set(directive.test, directive);\n }\n }\n });\n\n return (directive: DirectiveNode) => {\n let config = names.get(directive.name.value);\n if (!config && tests.size) {\n tests.forEach((testConfig, test) => {\n if (test(directive)) {\n config = testConfig;\n }\n });\n }\n return config;\n };\n}\n\n// Helper interface and function used by removeDirectivesFromDocument to keep\n// track of variable references and fragments spreads found within a given\n// operation or fragment definition.\ninterface InternalInUseInfo {\n variables: Set;\n fragmentSpreads: Set;\n // Set to true when we deliberately remove a fragment definition, so we can\n // make sure also to remove dangling ...spreads that refer to it.\n removed?: boolean;\n // Populated by the populateTransitiveVars helper function below.\n transitiveVars?: Set;\n}\nfunction makeInUseGetterFunction(defaultKey: TKey) {\n const map = new Map();\n\n return function inUseGetterFunction(\n key: TKey = defaultKey\n ): InternalInUseInfo {\n let inUse = map.get(key);\n if (!inUse) {\n map.set(\n key,\n (inUse = {\n // Variable and fragment spread names used directly within this\n // operation or fragment definition, as identified by key. These sets\n // will be populated during the first traversal of the document in\n // removeDirectivesFromDocument below.\n variables: new Set(),\n fragmentSpreads: new Set(),\n })\n );\n }\n return inUse;\n };\n}\n\nexport function removeDirectivesFromDocument(\n directives: RemoveDirectiveConfig[],\n doc: DocumentNode\n): DocumentNode | null {\n checkDocument(doc);\n\n // Passing empty strings to makeInUseGetterFunction means we handle anonymous\n // operations as if their names were \"\". Anonymous fragment definitions are\n // not supposed to be possible, but the same default naming strategy seems\n // appropriate for that case as well.\n const getInUseByOperationName = makeInUseGetterFunction(\"\");\n const getInUseByFragmentName = makeInUseGetterFunction(\"\");\n const getInUse = (\n ancestors: readonly (ASTNode | readonly ASTNode[])[]\n ): InternalInUseInfo | null => {\n for (\n let p = 0, ancestor: ASTNode | readonly ASTNode[];\n p < ancestors.length && (ancestor = ancestors[p]);\n ++p\n ) {\n if (isArray(ancestor)) continue;\n if (ancestor.kind === Kind.OPERATION_DEFINITION) {\n // If an operation is anonymous, we use the empty string as its key.\n return getInUseByOperationName(ancestor.name && ancestor.name.value);\n }\n if (ancestor.kind === Kind.FRAGMENT_DEFINITION) {\n return getInUseByFragmentName(ancestor.name.value);\n }\n }\n invariant.error(`Could not find operation or fragment`);\n return null;\n };\n\n let operationCount = 0;\n for (let i = doc.definitions.length - 1; i >= 0; --i) {\n if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {\n ++operationCount;\n }\n }\n\n const directiveMatcher = getDirectiveMatcher(directives);\n const shouldRemoveField = (nodeDirectives: FieldNode[\"directives\"]) =>\n isNonEmptyArray(nodeDirectives) &&\n nodeDirectives\n .map(directiveMatcher)\n .some(\n (config: RemoveDirectiveConfig | undefined) => config && config.remove\n );\n\n const originalFragmentDefsByPath = new Map();\n\n // Any time the first traversal of the document below makes a change like\n // removing a fragment (by returning null), this variable should be set to\n // true. Once it becomes true, it should never be set to false again. If this\n // variable remains false throughout the traversal, then we can return the\n // original doc immediately without any modifications.\n let firstVisitMadeChanges = false;\n\n const fieldOrInlineFragmentVisitor: EnterLeaveVisitor<\n FieldNode | InlineFragmentNode\n > = {\n enter(node) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n },\n };\n\n const docWithoutDirectiveSubtrees = visit(doc, {\n // These two AST node types share the same implementation, defined above.\n Field: fieldOrInlineFragmentVisitor,\n InlineFragment: fieldOrInlineFragmentVisitor,\n\n VariableDefinition: {\n enter() {\n // VariableDefinition nodes do not count as variables in use, though\n // they do contain Variable nodes that might be visited below. To avoid\n // counting variable declarations as usages, we skip visiting the\n // contents of this VariableDefinition node by returning false.\n return false;\n },\n },\n\n Variable: {\n enter(node, _key, _parent, _path, ancestors) {\n const inUse = getInUse(ancestors);\n if (inUse) {\n inUse.variables.add(node.name.value);\n }\n },\n },\n\n FragmentSpread: {\n enter(node, _key, _parent, _path, ancestors) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n const inUse = getInUse(ancestors);\n if (inUse) {\n inUse.fragmentSpreads.add(node.name.value);\n }\n // We might like to remove this FragmentSpread by returning null here if\n // the corresponding FragmentDefinition node is also going to be removed\n // by the logic below, but we can't control the relative order of those\n // events, so we have to postpone the removal of dangling FragmentSpread\n // nodes until after the current visit of the document has finished.\n },\n },\n\n FragmentDefinition: {\n enter(node, _key, _parent, path) {\n originalFragmentDefsByPath.set(JSON.stringify(path), node);\n },\n leave(node, _key, _parent, path) {\n const originalNode = originalFragmentDefsByPath.get(\n JSON.stringify(path)\n );\n if (node === originalNode) {\n // If the FragmentNode received by this leave function is identical to\n // the one received by the corresponding enter function (above), then\n // the visitor must not have made any changes within this\n // FragmentDefinition node. This fragment definition may still be\n // removed if there are no ...spread references to it, but it won't be\n // removed just because it has only a __typename field.\n return node;\n }\n\n if (\n // This logic applies only if the document contains one or more\n // operations, since removing all fragments from a document containing\n // only fragments makes the document useless.\n operationCount > 0 &&\n node.selectionSet.selections.every(\n (selection) =>\n selection.kind === Kind.FIELD &&\n selection.name.value === \"__typename\"\n )\n ) {\n // This is a somewhat opinionated choice: if a FragmentDefinition ends\n // up having no fields other than __typename, we remove the whole\n // fragment definition, and later prune ...spread references to it.\n getInUseByFragmentName(node.name.value).removed = true;\n firstVisitMadeChanges = true;\n return null;\n }\n },\n },\n\n Directive: {\n leave(node) {\n // If a matching directive is found, remove the directive itself. Note\n // that this does not remove the target (field, argument, etc) of the\n // directive, but only the directive itself.\n if (directiveMatcher(node)) {\n firstVisitMadeChanges = true;\n return null;\n }\n },\n },\n });\n\n if (!firstVisitMadeChanges) {\n // If our first pass did not change anything about the document, then there\n // is no cleanup we need to do, and we can return the original doc.\n return doc;\n }\n\n // Utility for making sure inUse.transitiveVars is recursively populated.\n // Because this logic assumes inUse.fragmentSpreads has been completely\n // populated and inUse.removed has been set if appropriate,\n // populateTransitiveVars must be called after that information has been\n // collected by the first traversal of the document.\n const populateTransitiveVars = (inUse: InternalInUseInfo) => {\n if (!inUse.transitiveVars) {\n inUse.transitiveVars = new Set(inUse.variables);\n if (!inUse.removed) {\n inUse.fragmentSpreads.forEach((childFragmentName) => {\n populateTransitiveVars(\n getInUseByFragmentName(childFragmentName)\n ).transitiveVars!.forEach((varName) => {\n inUse.transitiveVars!.add(varName);\n });\n });\n }\n }\n return inUse;\n };\n\n // Since we've been keeping track of fragment spreads used by particular\n // operations and fragment definitions, we now need to compute the set of all\n // spreads used (transitively) by any operations in the document.\n const allFragmentNamesUsed = new Set();\n docWithoutDirectiveSubtrees.definitions.forEach((def) => {\n if (def.kind === Kind.OPERATION_DEFINITION) {\n populateTransitiveVars(\n getInUseByOperationName(def.name && def.name.value)\n ).fragmentSpreads.forEach((childFragmentName) => {\n allFragmentNamesUsed.add(childFragmentName);\n });\n } else if (\n def.kind === Kind.FRAGMENT_DEFINITION &&\n // If there are no operations in the document, then all fragment\n // definitions count as usages of their own fragment names. This heuristic\n // prevents accidentally removing all fragment definitions from the\n // document just because it contains no operations that use the fragments.\n operationCount === 0 &&\n !getInUseByFragmentName(def.name.value).removed\n ) {\n allFragmentNamesUsed.add(def.name.value);\n }\n });\n // Now that we have added all fragment spreads used by operations to the\n // allFragmentNamesUsed set, we can complete the set by transitively adding\n // all fragment spreads used by those fragments, and so on.\n allFragmentNamesUsed.forEach((fragmentName) => {\n // Once all the childFragmentName strings added here have been seen already,\n // the top-level allFragmentNamesUsed.forEach loop will terminate.\n populateTransitiveVars(\n getInUseByFragmentName(fragmentName)\n ).fragmentSpreads.forEach((childFragmentName) => {\n allFragmentNamesUsed.add(childFragmentName);\n });\n });\n\n const fragmentWillBeRemoved = (fragmentName: string) =>\n !!(\n // A fragment definition will be removed if there are no spreads that refer\n // to it, or the fragment was explicitly removed because it had no fields\n // other than __typename.\n (\n !allFragmentNamesUsed.has(fragmentName) ||\n getInUseByFragmentName(fragmentName).removed\n )\n );\n\n const enterVisitor: EnterLeaveVisitor<\n FragmentSpreadNode | FragmentDefinitionNode\n > = {\n enter(node) {\n if (fragmentWillBeRemoved(node.name.value)) {\n return null;\n }\n },\n };\n\n return nullIfDocIsEmpty(\n visit(docWithoutDirectiveSubtrees, {\n // If the fragment is going to be removed, then leaving any dangling\n // FragmentSpread nodes with the same name would be a mistake.\n FragmentSpread: enterVisitor,\n\n // This is where the fragment definition is actually removed.\n FragmentDefinition: enterVisitor,\n\n OperationDefinition: {\n leave(node) {\n // Upon leaving each operation in the depth-first AST traversal, prune\n // any variables that are declared by the operation but unused within.\n if (node.variableDefinitions) {\n const usedVariableNames = populateTransitiveVars(\n // If an operation is anonymous, we use the empty string as its key.\n getInUseByOperationName(node.name && node.name.value)\n ).transitiveVars!;\n\n // According to the GraphQL spec, all variables declared by an\n // operation must either be used by that operation or used by some\n // fragment included transitively into that operation:\n // https://spec.graphql.org/draft/#sec-All-Variables-Used\n //\n // To stay on the right side of this validation rule, if/when we\n // remove the last $var references from an operation or its fragments,\n // we must also remove the corresponding $var declaration from the\n // enclosing operation. This pruning applies only to operations and\n // not fragment definitions, at the moment. Fragments may be able to\n // declare variables eventually, but today they can only consume them.\n if (usedVariableNames.size < node.variableDefinitions.length) {\n return {\n ...node,\n variableDefinitions: node.variableDefinitions.filter((varDef) =>\n usedVariableNames.has(varDef.variable.name.value)\n ),\n };\n }\n }\n },\n },\n })\n );\n}\n\nexport const addTypenameToDocument = Object.assign(\n function (doc: TNode): TNode {\n return visit(doc, {\n SelectionSet: {\n enter(node, _key, parent) {\n // Don't add __typename to OperationDefinitions.\n if (\n parent &&\n (parent as OperationDefinitionNode).kind ===\n Kind.OPERATION_DEFINITION\n ) {\n return;\n }\n\n // No changes if no selections.\n const { selections } = node;\n if (!selections) {\n return;\n }\n\n // If selections already have a __typename, or are part of an\n // introspection query, do nothing.\n const skip = selections.some((selection) => {\n return (\n isField(selection) &&\n (selection.name.value === \"__typename\" ||\n selection.name.value.lastIndexOf(\"__\", 0) === 0)\n );\n });\n if (skip) {\n return;\n }\n\n // If this SelectionSet is @export-ed as an input variable, it should\n // not have a __typename field (see issue #4691).\n const field = parent as FieldNode;\n if (\n isField(field) &&\n field.directives &&\n field.directives.some((d) => d.name.value === \"export\")\n ) {\n return;\n }\n\n // Create and return a new SelectionSet with a __typename Field.\n return {\n ...node,\n selections: [...selections, TYPENAME_FIELD],\n };\n },\n },\n });\n },\n {\n added(field: FieldNode): boolean {\n return field === TYPENAME_FIELD;\n },\n }\n);\n\nconst connectionRemoveConfig = {\n test: (directive: DirectiveNode) => {\n const willRemove = directive.name.value === \"connection\";\n if (willRemove) {\n if (\n !directive.arguments ||\n !directive.arguments.some((arg) => arg.name.value === \"key\")\n ) {\n invariant.warn(\n \"Removing an @connection directive even though it does not have a key. \" +\n \"You may want to use the key parameter to specify a store key.\"\n );\n }\n }\n\n return willRemove;\n },\n};\n\nexport function removeConnectionDirectiveFromDocument(doc: DocumentNode) {\n return removeDirectivesFromDocument(\n [connectionRemoveConfig],\n checkDocument(doc)\n );\n}\n\nfunction hasDirectivesInSelectionSet(\n directives: GetDirectiveConfig[],\n selectionSet: SelectionSetNode | undefined,\n nestedCheck = true\n): boolean {\n return (\n !!selectionSet &&\n selectionSet.selections &&\n selectionSet.selections.some((selection) =>\n hasDirectivesInSelection(directives, selection, nestedCheck)\n )\n );\n}\n\nfunction hasDirectivesInSelection(\n directives: GetDirectiveConfig[],\n selection: SelectionNode,\n nestedCheck = true\n): boolean {\n if (!isField(selection)) {\n return true;\n }\n\n if (!selection.directives) {\n return false;\n }\n\n return (\n selection.directives.some(getDirectiveMatcher(directives)) ||\n (nestedCheck &&\n hasDirectivesInSelectionSet(\n directives,\n selection.selectionSet,\n nestedCheck\n ))\n );\n}\n\nfunction getArgumentMatcher(config: RemoveArgumentsConfig[]) {\n return function argumentMatcher(argument: ArgumentNode) {\n return config.some(\n (aConfig: RemoveArgumentsConfig) =>\n argument.value &&\n argument.value.kind === Kind.VARIABLE &&\n argument.value.name &&\n (aConfig.name === argument.value.name.value ||\n (aConfig.test && aConfig.test(argument)))\n );\n };\n}\n\nexport function removeArgumentsFromDocument(\n config: RemoveArgumentsConfig[],\n doc: DocumentNode\n): DocumentNode | null {\n const argMatcher = getArgumentMatcher(config);\n\n return nullIfDocIsEmpty(\n visit(doc, {\n OperationDefinition: {\n enter(node) {\n return {\n ...node,\n // Remove matching top level variables definitions.\n variableDefinitions:\n node.variableDefinitions ?\n node.variableDefinitions.filter(\n (varDef) =>\n !config.some(\n (arg) => arg.name === varDef.variable.name.value\n )\n )\n : [],\n };\n },\n },\n\n Field: {\n enter(node) {\n // If `remove` is set to true for an argument, and an argument match\n // is found for a field, remove the field as well.\n const shouldRemoveField = config.some(\n (argConfig) => argConfig.remove\n );\n\n if (shouldRemoveField) {\n let argMatchCount = 0;\n if (node.arguments) {\n node.arguments.forEach((arg) => {\n if (argMatcher(arg)) {\n argMatchCount += 1;\n }\n });\n }\n\n if (argMatchCount === 1) {\n return null;\n }\n }\n },\n },\n\n Argument: {\n enter(node) {\n // Remove all matching arguments.\n if (argMatcher(node)) {\n return null;\n }\n },\n },\n })\n );\n}\n\nexport function removeFragmentSpreadFromDocument(\n config: RemoveFragmentSpreadConfig[],\n doc: DocumentNode\n): DocumentNode | null {\n function enter(\n node: FragmentSpreadNode | FragmentDefinitionNode\n ): null | void {\n if (config.some((def) => def.name === node.name.value)) {\n return null;\n }\n }\n\n return nullIfDocIsEmpty(\n visit(doc, {\n FragmentSpread: { enter },\n FragmentDefinition: { enter },\n })\n );\n}\n\n// If the incoming document is a query, return it as is. Otherwise, build a\n// new document containing a query operation based on the selection set\n// of the previous main operation.\nexport function buildQueryFromSelectionSet(\n document: DocumentNode\n): DocumentNode {\n const definition = getMainDefinition(document);\n const definitionOperation = (definition).operation;\n\n if (definitionOperation === \"query\") {\n // Already a query, so return the existing document.\n return document;\n }\n\n // Build a new query using the selection set of the main operation.\n const modifiedDoc = visit(document, {\n OperationDefinition: {\n enter(node) {\n return {\n ...node,\n operation: \"query\",\n };\n },\n },\n });\n return modifiedDoc;\n}\n\n// Remove fields / selection sets that include an @client directive.\nexport function removeClientSetsFromDocument(\n document: DocumentNode\n): DocumentNode | null {\n checkDocument(document);\n\n let modifiedDoc = removeDirectivesFromDocument(\n [\n {\n test: (directive: DirectiveNode) => directive.name.value === \"client\",\n remove: true,\n },\n ],\n document\n );\n\n return modifiedDoc;\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport type { DefinitionNode } from \"graphql\";\n\nimport { ApolloLink } from \"../core/index.js\";\nimport { Observable, hasDirectives } from \"../../utilities/index.js\";\nimport { serializeFetchParameter } from \"./serializeFetchParameter.js\";\nimport { selectURI } from \"./selectURI.js\";\nimport {\n handleError,\n readMultipartBody,\n parseAndCheckHttpResponse,\n} from \"./parseAndCheckHttpResponse.js\";\nimport { checkFetcher } from \"./checkFetcher.js\";\nimport type { HttpOptions } from \"./selectHttpOptionsAndBody.js\";\nimport {\n selectHttpOptionsAndBodyInternal,\n defaultPrinter,\n fallbackHttpConfig,\n} from \"./selectHttpOptionsAndBody.js\";\nimport { rewriteURIForGET } from \"./rewriteURIForGET.js\";\nimport { fromError, filterOperationVariables } from \"../utils/index.js\";\nimport {\n maybe,\n getMainDefinition,\n removeClientSetsFromDocument,\n} from \"../../utilities/index.js\";\n\nconst backupFetch = maybe(() => fetch);\n\nexport const createHttpLink = (linkOptions: HttpOptions = {}) => {\n let {\n uri = \"/graphql\",\n // use default global fetch if nothing passed in\n fetch: preferredFetch,\n print = defaultPrinter,\n includeExtensions,\n preserveHeaderCase,\n useGETForQueries,\n includeUnusedVariables = false,\n ...requestOptions\n } = linkOptions;\n\n if (__DEV__) {\n // Make sure at least one of preferredFetch, window.fetch, or backupFetch is\n // defined, so requests won't fail at runtime.\n checkFetcher(preferredFetch || backupFetch);\n }\n\n const linkConfig = {\n http: { includeExtensions, preserveHeaderCase },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n\n return new ApolloLink((operation) => {\n let chosenURI = selectURI(operation, uri);\n\n const context = operation.getContext();\n\n // `apollographql-client-*` headers are automatically set if a\n // `clientAwareness` object is found in the context. These headers are\n // set first, followed by the rest of the headers pulled from\n // `context.headers`. If desired, `apollographql-client-*` headers set by\n // the `clientAwareness` object can be overridden by\n // `apollographql-client-*` headers set in `context.headers`.\n const clientAwarenessHeaders: {\n \"apollographql-client-name\"?: string;\n \"apollographql-client-version\"?: string;\n } = {};\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 contextHeaders = { ...clientAwarenessHeaders, ...context.headers };\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: contextHeaders,\n };\n\n if (hasDirectives([\"client\"], operation.query)) {\n const transformedQuery = removeClientSetsFromDocument(operation.query);\n\n if (!transformedQuery) {\n return fromError(\n new Error(\n \"HttpLink: Trying to send a client-only query to the server. To send to the server, ensure a non-client field is added to the query or set the `transformOptions.removeClientFields` option to `true`.\"\n )\n );\n }\n\n operation.query = transformedQuery;\n }\n\n //uses fallback, link, and then context to build options\n const { options, body } = selectHttpOptionsAndBodyInternal(\n operation,\n print,\n fallbackHttpConfig,\n linkConfig,\n contextConfig\n );\n\n if (body.variables && !includeUnusedVariables) {\n body.variables = filterOperationVariables(\n body.variables,\n operation.query\n );\n }\n\n let controller: AbortController | undefined;\n if (!options.signal && typeof AbortController !== \"undefined\") {\n controller = new AbortController();\n options.signal = controller.signal;\n }\n\n // If requested, set method to GET if there are no mutations.\n const definitionIsMutation = (d: DefinitionNode) => {\n return d.kind === \"OperationDefinition\" && d.operation === \"mutation\";\n };\n const definitionIsSubscription = (d: DefinitionNode) => {\n return d.kind === \"OperationDefinition\" && d.operation === \"subscription\";\n };\n const isSubscription = definitionIsSubscription(\n getMainDefinition(operation.query)\n );\n // does not match custom directives beginning with @defer\n const hasDefer = hasDirectives([\"defer\"], operation.query);\n if (\n useGETForQueries &&\n !operation.query.definitions.some(definitionIsMutation)\n ) {\n options.method = \"GET\";\n }\n\n if (hasDefer || isSubscription) {\n options.headers = options.headers || {};\n let acceptHeader = \"multipart/mixed;\";\n // Omit defer-specific headers if the user attempts to defer a selection\n // set on a subscription and log a warning.\n if (isSubscription && hasDefer) {\n invariant.warn(\"Multipart-subscriptions do not support @defer\");\n }\n\n if (isSubscription) {\n acceptHeader +=\n \"boundary=graphql;subscriptionSpec=1.0,application/json\";\n } else if (hasDefer) {\n acceptHeader += \"deferSpec=20220824,application/json\";\n }\n options.headers.accept = acceptHeader;\n }\n\n if (options.method === \"GET\") {\n const { newURI, parseError } = rewriteURIForGET(chosenURI, body);\n if (parseError) {\n return fromError(parseError);\n }\n chosenURI = newURI;\n } else {\n try {\n (options as any).body = serializeFetchParameter(body, \"Payload\");\n } catch (parseError) {\n return fromError(parseError);\n }\n }\n\n return new Observable((observer) => {\n // Prefer linkOptions.fetch (preferredFetch) if provided, and otherwise\n // fall back to the *current* global window.fetch function (see issue\n // #7832), or (if all else fails) the backupFetch function we saved when\n // this module was first evaluated. This last option protects against the\n // removal of window.fetch, which is unlikely but not impossible.\n const currentFetch = preferredFetch || maybe(() => fetch) || backupFetch;\n\n const observerNext = observer.next.bind(observer);\n currentFetch!(chosenURI, options)\n .then((response) => {\n operation.setContext({ response });\n const ctype = response.headers?.get(\"content-type\");\n\n if (ctype !== null && /^multipart\\/mixed/i.test(ctype)) {\n return readMultipartBody(response, observerNext);\n } else {\n return parseAndCheckHttpResponse(operation)(response).then(\n observerNext\n );\n }\n })\n .then(() => {\n controller = undefined;\n observer.complete();\n })\n .catch((err) => {\n controller = undefined;\n handleError(err, observer);\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","import type { VariableDefinitionNode, DocumentNode } from \"graphql\";\nimport { visit } from \"graphql\";\n\nexport function filterOperationVariables(\n variables: Record,\n query: DocumentNode\n) {\n const result = { ...variables };\n const unusedNames = new Set(Object.keys(variables));\n visit(query, {\n Variable(node, _key, parent) {\n // A variable type definition at the top level of a query is not\n // enough to silence server-side errors about the variable being\n // unused, so variable definitions do not count as usage.\n // https://spec.graphql.org/draft/#sec-All-Variables-Used\n if (\n parent &&\n (parent as VariableDefinitionNode).kind !== \"VariableDefinition\"\n ) {\n unusedNames.delete(node.name.value);\n }\n },\n });\n unusedNames.forEach((name) => {\n delete result![name];\n });\n return result;\n}\n","import { ApolloLink } from \"../core/index.js\";\nimport type { HttpOptions } from \"./selectHttpOptionsAndBody.js\";\nimport { createHttpLink } from \"./createHttpLink.js\";\n\nexport class HttpLink extends ApolloLink {\n constructor(public options: HttpOptions = {}) {\n super(createHttpLink(options).request);\n }\n}\n","// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds\n// object keys weakly, yet can also hold non-object keys, unlike the\n// native `WeakMap`.\n\n// If no makeData function is supplied, the looked-up data will be an empty,\n// null-prototype Object.\nconst defaultMakeData = () => Object.create(null);\n\n// Useful for processing arguments objects as well as arrays.\nconst { forEach, slice } = Array.prototype;\nconst { hasOwnProperty } = Object.prototype;\n\nexport class Trie {\n // Since a `WeakMap` cannot hold primitive values as keys, we need a\n // backup `Map` instance to hold primitive keys. Both `this._weakMap`\n // and `this._strongMap` are lazily initialized.\n private weak?: WeakMap>;\n private strong?: Map>;\n private data?: Data;\n\n constructor(\n private weakness = true,\n private makeData: (array: any[]) => Data = defaultMakeData,\n ) {}\n\n public lookup(...array: T): Data;\n public lookup(): Data {\n return this.lookupArray(arguments);\n }\n\n public lookupArray(array: T): Data {\n let node: Trie = this;\n forEach.call(array, key => node = node.getChildTrie(key));\n return hasOwnProperty.call(node, \"data\")\n ? node.data as Data\n : node.data = this.makeData(slice.call(array));\n }\n\n public peek(...array: T): Data | undefined;\n public peek(): Data | undefined {\n return this.peekArray(arguments);\n }\n\n public peekArray(array: T): Data | undefined {\n let node: Trie | undefined = this;\n\n for (let i = 0, len = array.length; node && i < len; ++i) {\n const map = node.mapFor(array[i], false);\n node = map && map.get(array[i]);\n }\n\n return node && node.data;\n }\n\n public remove(...array: any[]): Data | undefined;\n public remove(): Data | undefined {\n return this.removeArray(arguments);\n }\n\n public removeArray(array: T): Data | undefined {\n let data: Data | undefined;\n\n if (array.length) {\n const head = array[0];\n const map = this.mapFor(head, false);\n const child = map && map.get(head);\n if (child) {\n data = child.removeArray(slice.call(array, 1));\n if (!child.data && !child.weak && !(child.strong && child.strong.size)) {\n map.delete(head);\n }\n }\n } else {\n data = this.data;\n delete this.data;\n }\n\n return data;\n }\n\n private getChildTrie(key: any) {\n const map = this.mapFor(key, true)!;\n let child = map.get(key);\n if (!child) map.set(key, child = new Trie(this.weakness, this.makeData));\n return child;\n }\n\n private mapFor(key: any, create: boolean): Trie[\"weak\" | \"strong\"] | undefined {\n return this.weakness && isObjRef(key)\n ? this.weak || (create ? this.weak = new WeakMap : void 0)\n : this.strong || (create ? this.strong = new Map : void 0);\n }\n}\n\nfunction isObjRef(value: any) {\n switch (typeof value) {\n case \"object\":\n if (value === null) break;\n // Fall through to return true...\n case \"function\":\n return true;\n }\n return false;\n}\n","// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds\n// object keys weakly, yet can also hold non-object keys, unlike the\n// native `WeakMap`.\n\n// If no makeData function is supplied, the looked-up data will be an empty,\n// null-prototype Object.\nconst defaultMakeData = () => Object.create(null);\n\n// Useful for processing arguments objects as well as arrays.\nconst { forEach, slice } = Array.prototype;\nconst { hasOwnProperty } = Object.prototype;\n\nexport class Trie {\n // Since a `WeakMap` cannot hold primitive values as keys, we need a\n // backup `Map` instance to hold primitive keys. Both `this._weakMap`\n // and `this._strongMap` are lazily initialized.\n private weak?: WeakMap>;\n private strong?: Map>;\n private data?: Data;\n\n constructor(\n private weakness = true,\n private makeData: (array: any[]) => Data = defaultMakeData,\n ) {}\n\n public lookup(...array: T): Data {\n return this.lookupArray(array);\n }\n\n public lookupArray(array: T): Data {\n let node: Trie = this;\n forEach.call(array, key => node = node.getChildTrie(key));\n return hasOwnProperty.call(node, \"data\")\n ? node.data as Data\n : node.data = this.makeData(slice.call(array));\n }\n\n public peek(...array: T): Data | undefined {\n return this.peekArray(array);\n }\n\n public peekArray(array: T): Data | undefined {\n let node: Trie | undefined = this;\n\n for (let i = 0, len = array.length; node && i < len; ++i) {\n const map: Trie[\"weak\" | \"strong\"] =\n this.weakness && isObjRef(array[i]) ? node.weak : node.strong;\n\n node = map && map.get(array[i]);\n }\n\n return node && node.data;\n }\n\n private getChildTrie(key: any) {\n const map = this.weakness && isObjRef(key)\n ? this.weak || (this.weak = new WeakMap>())\n : this.strong || (this.strong = new Map>());\n let child = map.get(key);\n if (!child) map.set(key, child = new Trie(this.weakness, this.makeData));\n return child;\n }\n}\n\nfunction isObjRef(value: any) {\n switch (typeof value) {\n case \"object\":\n if (value === null) break;\n // Fall through to return true...\n case \"function\":\n return true;\n }\n return false;\n}\n","type Context = {\n parent: Context | null;\n slots: { [slotId: string]: any };\n}\n\n// This currentContext variable will only be used if the makeSlotClass\n// function is called, which happens only if this is the first copy of the\n// @wry/context package to be imported.\nlet currentContext: Context | null = null;\n\n// This unique internal object is used to denote the absence of a value\n// for a given Slot, and is never exposed to outside code.\nconst MISSING_VALUE: any = {};\n\nlet idCounter = 1;\n\n// Although we can't do anything about the cost of duplicated code from\n// accidentally bundling multiple copies of the @wry/context package, we can\n// avoid creating the Slot class more than once using makeSlotClass.\nconst makeSlotClass = () => class Slot {\n // If you have a Slot object, you can find out its slot.id, but you cannot\n // guess the slot.id of a Slot you don't have access to, thanks to the\n // randomized suffix.\n public readonly id = [\n \"slot\",\n idCounter++,\n Date.now(),\n Math.random().toString(36).slice(2),\n ].join(\":\");\n\n public hasValue() {\n for (let context = currentContext; context; context = context.parent) {\n // We use the Slot object iself as a key to its value, which means the\n // value cannot be obtained without a reference to the Slot object.\n if (this.id in context.slots) {\n const value = context.slots[this.id];\n if (value === MISSING_VALUE) break;\n if (context !== currentContext) {\n // Cache the value in currentContext.slots so the next lookup will\n // be faster. This caching is safe because the tree of contexts and\n // the values of the slots are logically immutable.\n currentContext!.slots[this.id] = value;\n }\n return true;\n }\n }\n if (currentContext) {\n // If a value was not found for this Slot, it's never going to be found\n // no matter how many times we look it up, so we might as well cache\n // the absence of the value, too.\n currentContext.slots[this.id] = MISSING_VALUE;\n }\n return false;\n }\n\n public getValue(): TValue | undefined {\n if (this.hasValue()) {\n return currentContext!.slots[this.id] as TValue;\n }\n }\n\n public withValue(\n value: TValue,\n callback: (this: TThis, ...args: TArgs) => TResult,\n // Given the prevalence of arrow functions, specifying arguments is likely\n // to be much more common than specifying `this`, hence this ordering:\n args?: TArgs,\n thisArg?: TThis,\n ): TResult {\n const slots = {\n __proto__: null,\n [this.id]: value,\n };\n const parent = currentContext;\n currentContext = { parent, slots };\n try {\n // Function.prototype.apply allows the arguments array argument to be\n // omitted or undefined, so args! is fine here.\n return callback.apply(thisArg!, args!);\n } finally {\n currentContext = parent;\n }\n }\n\n // Capture the current context and wrap a callback function so that it\n // reestablishes the captured context when called.\n static bind(\n callback: (this: TThis, ...args: TArgs) => TResult,\n ) {\n const context = currentContext;\n return function (this: TThis) {\n const saved = currentContext;\n try {\n currentContext = context;\n return callback.apply(this, arguments as any);\n } finally {\n currentContext = saved;\n }\n } as typeof callback;\n }\n\n // Immediately run a callback function without any captured context.\n static noContext(\n callback: (this: TThis, ...args: TArgs) => TResult,\n // Given the prevalence of arrow functions, specifying arguments is likely\n // to be much more common than specifying `this`, hence this ordering:\n args?: TArgs,\n thisArg?: TThis,\n ) {\n if (currentContext) {\n const saved = currentContext;\n try {\n currentContext = null;\n // Function.prototype.apply allows the arguments array argument to be\n // omitted or undefined, so args! is fine here.\n return callback.apply(thisArg!, args!);\n } finally {\n currentContext = saved;\n }\n } else {\n return callback.apply(thisArg!, args!);\n }\n }\n};\n\nfunction maybe(fn: () => T): T | undefined {\n try {\n return fn();\n } catch (ignored) {}\n}\n\n// We store a single global implementation of the Slot class as a permanent\n// non-enumerable property of the globalThis object. This obfuscation does\n// nothing to prevent access to the Slot class, but at least it ensures the\n// implementation (i.e. currentContext) cannot be tampered with, and all copies\n// of the @wry/context package (hopefully just one) will share the same Slot\n// implementation. Since the first copy of the @wry/context package to be\n// imported wins, this technique imposes a steep cost for any future breaking\n// changes to the Slot class.\nconst globalKey = \"@wry/context:Slot\";\n\nconst host =\n // Prefer globalThis when available.\n // https://github.com/benjamn/wryware/issues/347\n maybe(() => globalThis) ||\n // Fall back to global, which works in Node.js and may be converted by some\n // bundlers to the appropriate identifier (window, self, ...) depending on the\n // bundling target. https://github.com/endojs/endo/issues/576#issuecomment-1178515224\n maybe(() => global) ||\n // Otherwise, use a dummy host that's local to this module. We used to fall\n // back to using the Array constructor as a namespace, but that was flagged in\n // https://github.com/benjamn/wryware/issues/347, and can be avoided.\n Object.create(null) as typeof Array;\n\n// Whichever globalHost we're using, make TypeScript happy about the additional\n// globalKey property.\nconst globalHost: typeof host & {\n [globalKey]?: typeof Slot;\n} = host;\n\nexport const Slot: ReturnType =\n globalHost[globalKey] ||\n // Earlier versions of this package stored the globalKey property on the Array\n // constructor, so we check there as well, to prevent Slot class duplication.\n (Array as typeof globalHost)[globalKey] ||\n (function (Slot) {\n try {\n Object.defineProperty(globalHost, globalKey, {\n value: Slot,\n enumerable: false,\n writable: false,\n // When it was possible for globalHost to be the Array constructor (a\n // legacy Slot dedup strategy), it was important for the property to be\n // configurable:true so it could be deleted. That does not seem to be as\n // important when globalHost is the global object, but I don't want to\n // cause similar problems again, and configurable:true seems safest.\n // https://github.com/endojs/endo/issues/576#issuecomment-1178274008\n configurable: true\n });\n } finally {\n return Slot;\n }\n })(makeSlotClass());\n","import { Slot } from \"./slot.js\";\nexport { Slot }\nexport const { bind, noContext } = Slot;\n\n// Relying on the @types/node declaration of global.setTimeout can make\n// things tricky for dowstream projects (see PR #7).\ndeclare function setTimeout(\n callback: (...args: any[]) => any,\n ms?: number,\n ...args: any[]\n): any;\n\n// Like global.setTimeout, except the callback runs with captured context.\nexport { setTimeoutWithContext as setTimeout };\nfunction setTimeoutWithContext(callback: () => any, delay: number) {\n return setTimeout(bind(callback), delay);\n}\n\n// Turn any generator function into an async function (using yield instead\n// of await), with context automatically preserved across yields.\nexport function asyncFromGen<\n TArgs extends any[],\n TYield = any,\n TReturn = any,\n TNext = any,\n>(\n genFn: (...args: TArgs) => Generator\n) {\n return function (this: any) {\n const gen = genFn.apply(this, arguments as any);\n\n type Method = (\n this: Generator,\n arg: any,\n ) => IteratorResult;\n\n const boundNext: Method = bind(gen.next);\n const boundThrow: Method = bind(gen.throw!);\n\n return new Promise((resolve, reject) => {\n function invoke(method: Method, argument: any) {\n try {\n var result: any = method.call(gen, argument);\n } catch (error) {\n return reject(error);\n }\n const next = result.done ? resolve : invokeNext;\n if (isPromiseLike(result.value)) {\n result.value.then(next, result.done ? reject : invokeThrow);\n } else {\n next(result.value);\n }\n }\n const invokeNext = (value?: any) => invoke(boundNext, value);\n const invokeThrow = (error: any) => invoke(boundThrow, error);\n invokeNext();\n });\n } as (...args: TArgs) => Promise;\n}\n\nfunction isPromiseLike(value: any): value is PromiseLike {\n return value && typeof value.then === \"function\";\n}\n\n// If you use the fibers npm package to implement coroutines in Node.js,\n// you should call this function at least once to ensure context management\n// remains coherent across any yields.\nconst wrappedFibers: Function[] = [];\nexport function wrapYieldingFiberMethods(Fiber: F): F {\n // There can be only one implementation of Fiber per process, so this array\n // should never grow longer than one element.\n if (wrappedFibers.indexOf(Fiber) < 0) {\n const wrap = (obj: any, method: string) => {\n const fn = obj[method];\n obj[method] = function () {\n return noContext(fn, arguments as any, this);\n };\n }\n // These methods can yield, according to\n // https://github.com/laverdet/node-fibers/blob/ddebed9b8ae3883e57f822e2108e6943e5c8d2a8/fibers.js#L97-L100\n wrap(Fiber, \"yield\");\n wrap(Fiber.prototype, \"run\");\n wrap(Fiber.prototype, \"throwInto\");\n wrappedFibers.push(Fiber);\n }\n return Fiber;\n}\n","import { Slot } from \"@wry/context\";\nimport { AnyEntry } from \"./entry.js\";\n\nexport const parentEntrySlot = new Slot();\n\nexport function nonReactive(fn: () => R): R {\n return parentEntrySlot.withValue(void 0, fn);\n}\n\nexport { Slot }\nexport {\n bind as bindContext,\n noContext,\n setTimeout,\n asyncFromGen,\n} from \"@wry/context\";\n","export type NoInfer = [T][T extends any ? 0 : never];\n\nexport const {\n hasOwnProperty,\n} = Object.prototype;\n\nexport const arrayFromSet: (set: Set) => T[] =\n Array.from ||\n function (set) {\n const array: any[] = [];\n set.forEach(item => array.push(item));\n return array;\n };\n\nexport type Unsubscribable = {\n unsubscribe?: void | (() => any);\n}\n\nexport function maybeUnsubscribe(entryOrDep: Unsubscribable) {\n const { unsubscribe } = entryOrDep;\n if (typeof unsubscribe === \"function\") {\n entryOrDep.unsubscribe = void 0;\n unsubscribe();\n }\n}\n","import { parentEntrySlot } from \"./context.js\";\nimport { OptimisticWrapOptions } from \"./index.js\";\nimport { Dep } from \"./dep.js\";\nimport { maybeUnsubscribe, arrayFromSet, Unsubscribable } from \"./helpers.js\";\n\nconst emptySetPool: Set[] = [];\nconst POOL_TARGET_SIZE = 100;\n\n// Since this package might be used browsers, we should avoid using the\n// Node built-in assert module.\nfunction assert(condition: any, optionalMessage?: string) {\n if (! condition) {\n throw new Error(optionalMessage || \"assertion failure\");\n }\n}\n\n// Since exceptions are cached just like normal values, we need an efficient\n// way of representing unknown, ordinary, and exceptional values.\ntype Value =\n | [] // unknown\n | [T] // known value\n | [void, any]; // known exception\n\nfunction valueIs(a: Value, b: Value) {\n const len = a.length;\n return (\n // Unknown values are not equal to each other.\n len > 0 &&\n // Both values must be ordinary (or both exceptional) to be equal.\n len === b.length &&\n // The underlying value or exception must be the same.\n a[len - 1] === b[len - 1]\n );\n}\n\nfunction valueGet(value: Value): T {\n switch (value.length) {\n case 0: throw new Error(\"unknown value\");\n case 1: return value[0];\n case 2: throw value[1];\n }\n}\n\nfunction valueCopy(value: Value): Value {\n return value.slice(0) as Value;\n}\n\nexport type AnyEntry = Entry;\n\nexport class Entry {\n public static count = 0;\n\n public normalizeResult: OptimisticWrapOptions[\"normalizeResult\"];\n public subscribe: OptimisticWrapOptions[\"subscribe\"];\n public unsubscribe: Unsubscribable[\"unsubscribe\"];\n\n public readonly parents = new Set();\n public readonly childValues = new Map>();\n\n // When this Entry has children that are dirty, this property becomes\n // a Set containing other Entry objects, borrowed from emptySetPool.\n // When the set becomes empty, it gets recycled back to emptySetPool.\n public dirtyChildren: Set | null = null;\n\n public dirty = true;\n public recomputing = false;\n public readonly value: Value = [];\n\n constructor(\n public readonly fn: (...args: TArgs) => TValue,\n ) {\n ++Entry.count;\n }\n\n public peek(): TValue | undefined {\n if (this.value.length === 1 && !mightBeDirty(this)) {\n rememberParent(this);\n return this.value[0];\n }\n }\n\n // This is the most important method of the Entry API, because it\n // determines whether the cached this.value can be returned immediately,\n // or must be recomputed. The overall performance of the caching system\n // depends on the truth of the following observations: (1) this.dirty is\n // usually false, (2) this.dirtyChildren is usually null/empty, and thus\n // (3) valueGet(this.value) is usually returned without recomputation.\n public recompute(args: TArgs): TValue {\n assert(! this.recomputing, \"already recomputing\");\n rememberParent(this);\n return mightBeDirty(this)\n ? reallyRecompute(this, args)\n : valueGet(this.value);\n }\n\n public setDirty() {\n if (this.dirty) return;\n this.dirty = true;\n reportDirty(this);\n // We can go ahead and unsubscribe here, since any further dirty\n // notifications we receive will be redundant, and unsubscribing may\n // free up some resources, e.g. file watchers.\n maybeUnsubscribe(this);\n }\n\n public dispose() {\n this.setDirty();\n\n // Sever any dependency relationships with our own children, so those\n // children don't retain this parent Entry in their child.parents sets,\n // thereby preventing it from being fully garbage collected.\n forgetChildren(this);\n\n // Because this entry has been kicked out of the cache (in index.js),\n // we've lost the ability to find out if/when this entry becomes dirty,\n // whether that happens through a subscription, because of a direct call\n // to entry.setDirty(), or because one of its children becomes dirty.\n // Because of this loss of future information, we have to assume the\n // worst (that this entry might have become dirty very soon), so we must\n // immediately mark this entry's parents as dirty. Normally we could\n // just call entry.setDirty() rather than calling parent.setDirty() for\n // each parent, but that would leave this entry in parent.childValues\n // and parent.dirtyChildren, which would prevent the child from being\n // truly forgotten.\n eachParent(this, (parent, child) => {\n parent.setDirty();\n forgetChild(parent, this);\n });\n }\n\n public forget() {\n // The code that creates Entry objects in index.ts will replace this method\n // with one that actually removes the Entry from the cache, which will also\n // trigger the entry.dispose method.\n this.dispose();\n }\n\n private deps: Set> | null = null;\n\n public dependOn(dep: Dep) {\n dep.add(this);\n if (! this.deps) {\n this.deps = emptySetPool.pop() || new Set>();\n }\n this.deps.add(dep);\n }\n\n public forgetDeps() {\n if (this.deps) {\n arrayFromSet(this.deps).forEach(dep => dep.delete(this));\n this.deps.clear();\n emptySetPool.push(this.deps);\n this.deps = null;\n }\n }\n}\n\nfunction rememberParent(child: AnyEntry) {\n const parent = parentEntrySlot.getValue();\n if (parent) {\n child.parents.add(parent);\n\n if (! parent.childValues.has(child)) {\n parent.childValues.set(child, []);\n }\n\n if (mightBeDirty(child)) {\n reportDirtyChild(parent, child);\n } else {\n reportCleanChild(parent, child);\n }\n\n return parent;\n }\n}\n\nfunction reallyRecompute(entry: AnyEntry, args: any[]) {\n forgetChildren(entry);\n\n // Set entry as the parent entry while calling recomputeNewValue(entry).\n parentEntrySlot.withValue(entry, recomputeNewValue, [entry, args]);\n\n if (maybeSubscribe(entry, args)) {\n // If we successfully recomputed entry.value and did not fail to\n // (re)subscribe, then this Entry is no longer explicitly dirty.\n setClean(entry);\n }\n\n return valueGet(entry.value);\n}\n\nfunction recomputeNewValue(entry: AnyEntry, args: any[]) {\n entry.recomputing = true;\n\n const { normalizeResult } = entry;\n let oldValueCopy: Value | undefined;\n if (normalizeResult && entry.value.length === 1) {\n oldValueCopy = valueCopy(entry.value);\n }\n\n // Make entry.value an empty array, representing an unknown value.\n entry.value.length = 0;\n\n try {\n // If entry.fn succeeds, entry.value will become a normal Value.\n entry.value[0] = entry.fn.apply(null, args);\n\n // If we have a viable oldValueCopy to compare with the (successfully\n // recomputed) new entry.value, and they are not already === identical, give\n // normalizeResult a chance to pick/choose/reuse parts of oldValueCopy[0]\n // and/or entry.value[0] to determine the final cached entry.value.\n if (normalizeResult && oldValueCopy && !valueIs(oldValueCopy, entry.value)) {\n try {\n entry.value[0] = normalizeResult(entry.value[0], oldValueCopy[0]);\n } catch {\n // If normalizeResult throws, just use the newer value, rather than\n // saving the exception as entry.value[1].\n }\n }\n\n } catch (e) {\n // If entry.fn throws, entry.value will hold that exception.\n entry.value[1] = e;\n }\n\n // Either way, this line is always reached.\n entry.recomputing = false;\n}\n\nfunction mightBeDirty(entry: AnyEntry) {\n return entry.dirty || !!(entry.dirtyChildren && entry.dirtyChildren.size);\n}\n\nfunction setClean(entry: AnyEntry) {\n entry.dirty = false;\n\n if (mightBeDirty(entry)) {\n // This Entry may still have dirty children, in which case we can't\n // let our parents know we're clean just yet.\n return;\n }\n\n reportClean(entry);\n}\n\nfunction reportDirty(child: AnyEntry) {\n eachParent(child, reportDirtyChild);\n}\n\nfunction reportClean(child: AnyEntry) {\n eachParent(child, reportCleanChild);\n}\n\nfunction eachParent(\n child: AnyEntry,\n callback: (parent: AnyEntry, child: AnyEntry) => any,\n) {\n const parentCount = child.parents.size;\n if (parentCount) {\n const parents = arrayFromSet(child.parents);\n for (let i = 0; i < parentCount; ++i) {\n callback(parents[i], child);\n }\n }\n}\n\n// Let a parent Entry know that one of its children may be dirty.\nfunction reportDirtyChild(parent: AnyEntry, child: AnyEntry) {\n // Must have called rememberParent(child) before calling\n // reportDirtyChild(parent, child).\n assert(parent.childValues.has(child));\n assert(mightBeDirty(child));\n const parentWasClean = !mightBeDirty(parent);\n\n if (! parent.dirtyChildren) {\n parent.dirtyChildren = emptySetPool.pop() || new Set;\n\n } else if (parent.dirtyChildren.has(child)) {\n // If we already know this child is dirty, then we must have already\n // informed our own parents that we are dirty, so we can terminate\n // the recursion early.\n return;\n }\n\n parent.dirtyChildren.add(child);\n\n // If parent was clean before, it just became (possibly) dirty (according to\n // mightBeDirty), since we just added child to parent.dirtyChildren.\n if (parentWasClean) {\n reportDirty(parent);\n }\n}\n\n// Let a parent Entry know that one of its children is no longer dirty.\nfunction reportCleanChild(parent: AnyEntry, child: AnyEntry) {\n // Must have called rememberChild(child) before calling\n // reportCleanChild(parent, child).\n assert(parent.childValues.has(child));\n assert(! mightBeDirty(child));\n\n const childValue = parent.childValues.get(child)!;\n if (childValue.length === 0) {\n parent.childValues.set(child, valueCopy(child.value));\n } else if (! valueIs(childValue, child.value)) {\n parent.setDirty();\n }\n\n removeDirtyChild(parent, child);\n\n if (mightBeDirty(parent)) {\n return;\n }\n\n reportClean(parent);\n}\n\nfunction removeDirtyChild(parent: AnyEntry, child: AnyEntry) {\n const dc = parent.dirtyChildren;\n if (dc) {\n dc.delete(child);\n if (dc.size === 0) {\n if (emptySetPool.length < POOL_TARGET_SIZE) {\n emptySetPool.push(dc);\n }\n parent.dirtyChildren = null;\n }\n }\n}\n\n// Removes all children from this entry and returns an array of the\n// removed children.\nfunction forgetChildren(parent: AnyEntry) {\n if (parent.childValues.size > 0) {\n parent.childValues.forEach((_value, child) => {\n forgetChild(parent, child);\n });\n }\n\n // Remove this parent Entry from any sets to which it was added by the\n // addToSet method.\n parent.forgetDeps();\n\n // After we forget all our children, this.dirtyChildren must be empty\n // and therefore must have been reset to null.\n assert(parent.dirtyChildren === null);\n}\n\nfunction forgetChild(parent: AnyEntry, child: AnyEntry) {\n child.parents.delete(parent);\n parent.childValues.delete(child);\n removeDirtyChild(parent, child);\n}\n\nfunction maybeSubscribe(entry: AnyEntry, args: any[]) {\n if (typeof entry.subscribe === \"function\") {\n try {\n maybeUnsubscribe(entry); // Prevent double subscriptions.\n entry.unsubscribe = entry.subscribe.apply(null, args);\n } catch (e) {\n // If this Entry has a subscribe function and it threw an exception\n // (or an unsubscribe function it previously returned now throws),\n // return false to indicate that we were not able to subscribe (or\n // unsubscribe), and this Entry should remain dirty.\n entry.setDirty();\n return false;\n }\n }\n\n // Returning true indicates either that there was no entry.subscribe\n // function or that it succeeded.\n return true;\n}\n","import { AnyEntry } from \"./entry.js\";\nimport { OptimisticWrapOptions } from \"./index.js\";\nimport { parentEntrySlot } from \"./context.js\";\nimport {\n hasOwnProperty,\n Unsubscribable,\n maybeUnsubscribe,\n arrayFromSet,\n } from \"./helpers.js\";\n\ntype EntryMethodName = keyof typeof EntryMethods;\nconst EntryMethods = {\n setDirty: true, // Mark parent Entry as needing to be recomputed (default)\n dispose: true, // Detach parent Entry from parents and children, but leave in LRU cache\n forget: true, // Fully remove parent Entry from LRU cache and computation graph\n};\n\nexport type OptimisticDependencyFunction =\n ((key: TKey) => void) & {\n dirty: (key: TKey, entryMethodName?: EntryMethodName) => void;\n };\n\nexport type Dep = Set & {\n subscribe: OptimisticWrapOptions<[TKey]>[\"subscribe\"];\n} & Unsubscribable;\n\nexport function dep(options?: {\n subscribe: Dep[\"subscribe\"];\n}) {\n const depsByKey = new Map>();\n const subscribe = options && options.subscribe;\n\n function depend(key: TKey) {\n const parent = parentEntrySlot.getValue();\n if (parent) {\n let dep = depsByKey.get(key);\n if (!dep) {\n depsByKey.set(key, dep = new Set as Dep);\n }\n parent.dependOn(dep);\n if (typeof subscribe === \"function\") {\n maybeUnsubscribe(dep);\n dep.unsubscribe = subscribe(key);\n }\n }\n }\n\n depend.dirty = function dirty(\n key: TKey,\n entryMethodName?: EntryMethodName,\n ) {\n const dep = depsByKey.get(key);\n if (dep) {\n const m: EntryMethodName = (\n entryMethodName &&\n hasOwnProperty.call(EntryMethods, entryMethodName)\n ) ? entryMethodName : \"setDirty\";\n // We have to use arrayFromSet(dep).forEach instead of dep.forEach,\n // because modifying a Set while iterating over it can cause elements in\n // the Set to be removed from the Set before they've been iterated over.\n arrayFromSet(dep).forEach(entry => entry[m]());\n depsByKey.delete(key);\n maybeUnsubscribe(dep);\n }\n };\n\n return depend as OptimisticDependencyFunction;\n}\n","import { Trie } from \"@wry/trie\";\n\nimport { StrongCache, CommonCache } from \"@wry/caches\";\nimport { Entry, AnyEntry } from \"./entry.js\";\nimport { parentEntrySlot } from \"./context.js\";\nimport type { NoInfer } from \"./helpers.js\";\n\n// These helper functions are important for making optimism work with\n// asynchronous code. In order to register parent-child dependencies,\n// optimism needs to know about any currently active parent computations.\n// In ordinary synchronous code, the parent context is implicit in the\n// execution stack, but asynchronous code requires some extra guidance in\n// order to propagate context from one async task segment to the next.\nexport {\n bindContext,\n noContext,\n nonReactive,\n setTimeout,\n asyncFromGen,\n Slot,\n} from \"./context.js\";\n\n// A lighter-weight dependency, similar to OptimisticWrapperFunction, except\n// with only one argument, no makeCacheKey, no wrapped function to recompute,\n// and no result value. Useful for representing dependency leaves in the graph\n// of computation. Subscriptions are supported.\nexport { dep, OptimisticDependencyFunction } from \"./dep.js\";\n\n// The defaultMakeCacheKey function is remarkably powerful, because it gives\n// a unique object for any shallow-identical list of arguments. If you need\n// to implement a custom makeCacheKey function, you may find it helpful to\n// delegate the final work to defaultMakeCacheKey, which is why we export it\n// here. However, you may want to avoid defaultMakeCacheKey if your runtime\n// does not support WeakMap, or you have the ability to return a string key.\n// In those cases, just write your own custom makeCacheKey functions.\nlet defaultKeyTrie: Trie | undefined;\nexport function defaultMakeCacheKey(...args: any[]): object {\n const trie = defaultKeyTrie || (\n defaultKeyTrie = new Trie(typeof WeakMap === \"function\")\n );\n return trie.lookupArray(args);\n}\n\n// If you're paranoid about memory leaks, or you want to avoid using WeakMap\n// under the hood, but you still need the behavior of defaultMakeCacheKey,\n// import this constructor to create your own tries.\nexport { Trie as KeyTrie }\n\nexport type OptimisticWrapperFunction<\n TArgs extends any[],\n TResult,\n TKeyArgs extends any[] = TArgs,\n TCacheKey = any,\n> = ((...args: TArgs) => TResult) & {\n // Get the current number of Entry objects in the LRU cache.\n readonly size: number;\n\n // Snapshot of wrap options used to create this wrapper function.\n options: OptionsWithCacheInstance;\n\n // \"Dirty\" any cached Entry stored for the given arguments, marking that Entry\n // and its ancestors as potentially needing to be recomputed. The .dirty(...)\n // method of an optimistic function takes the same parameter types as the\n // original function by default, unless a keyArgs function is configured, and\n // then it matters that .dirty takes TKeyArgs instead of TArgs.\n dirty: (...args: TKeyArgs) => void;\n // A version of .dirty that accepts a key returned by .getKey.\n dirtyKey: (key: TCacheKey | undefined) => void;\n\n // Examine the current value without recomputing it.\n peek: (...args: TKeyArgs) => TResult | undefined;\n // A version of .peek that accepts a key returned by .getKey.\n peekKey: (key: TCacheKey | undefined) => TResult | undefined;\n\n // Completely remove the entry from the cache, dirtying any parent entries.\n forget: (...args: TKeyArgs) => boolean;\n // A version of .forget that accepts a key returned by .getKey.\n forgetKey: (key: TCacheKey | undefined) => boolean;\n\n // In order to use the -Key version of the above functions, you need a key\n // rather than the arguments used to compute the key. These two functions take\n // TArgs or TKeyArgs and return the corresponding TCacheKey. If no keyArgs\n // function has been configured, TArgs will be the same as TKeyArgs, and thus\n // getKey and makeCacheKey will be synonymous.\n getKey: (...args: TArgs) => TCacheKey | undefined;\n\n // This property is equivalent to the makeCacheKey function provided in the\n // OptimisticWrapOptions, or (if no options.makeCacheKey function is provided)\n // a default implementation of makeCacheKey. This function is also exposed as\n // optimistic.options.makeCacheKey, somewhat redundantly.\n makeCacheKey: (...args: TKeyArgs) => TCacheKey | undefined;\n};\n\nexport { CommonCache }\nexport interface CommonCacheConstructor extends Function {\n new >(max?: number, dispose?: (value: V, key?: K) => void): CommonCache;\n}\n\nexport type OptimisticWrapOptions<\n TArgs extends any[],\n TKeyArgs extends any[] = TArgs,\n TCacheKey = any,\n TResult = any,\n> = {\n // The maximum number of cache entries that should be retained before the\n // cache begins evicting the oldest ones.\n max?: number;\n // Transform the raw arguments to some other type of array, which will then\n // be passed to makeCacheKey.\n keyArgs?: (...args: TArgs) => TKeyArgs;\n // The makeCacheKey function takes the same arguments that were passed to\n // the wrapper function and returns a single value that can be used as a key\n // in a Map to identify the cached result.\n makeCacheKey?: (...args: NoInfer) => TCacheKey | undefined;\n // Called when a new value is computed to allow efficient normalization of\n // results over time, for example by returning older if equal(newer, older).\n normalizeResult?: (newer: TResult, older: TResult) => TResult;\n // If provided, the subscribe function should either return an unsubscribe\n // function or return nothing.\n subscribe?: (...args: TArgs) => void | (() => any);\n cache?: CommonCache, Entry, NoInfer>>\n | CommonCacheConstructor, NoInfer, NoInfer>;\n};\n\nexport interface OptionsWithCacheInstance<\n TArgs extends any[],\n TKeyArgs extends any[] = TArgs,\n TCacheKey = any,\n TResult = any,\n> extends OptimisticWrapOptions {\n cache: CommonCache, Entry, NoInfer>>;\n};\n\nconst caches = new Set>();\n\nexport function wrap<\n TArgs extends any[],\n TResult,\n TKeyArgs extends any[] = TArgs,\n TCacheKey = any,\n>(originalFunction: (...args: TArgs) => TResult, {\n max = Math.pow(2, 16),\n keyArgs,\n makeCacheKey = (defaultMakeCacheKey as () => TCacheKey),\n normalizeResult,\n subscribe,\n cache: cacheOption = StrongCache,\n}: OptimisticWrapOptions = Object.create(null)) {\n const cache: CommonCache> =\n typeof cacheOption === \"function\"\n ? new cacheOption(max, entry => entry.dispose())\n : cacheOption;\n\n const optimistic = function (): TResult {\n const key = makeCacheKey.apply(\n null,\n keyArgs ? keyArgs.apply(null, arguments as any) : arguments as any\n );\n\n if (key === void 0) {\n return originalFunction.apply(null, arguments as any);\n }\n\n let entry = cache.get(key)!;\n if (!entry) {\n cache.set(key, entry = new Entry(originalFunction));\n entry.normalizeResult = normalizeResult;\n entry.subscribe = subscribe;\n // Give the Entry the ability to trigger cache.delete(key), even though\n // the Entry itself does not know about key or cache.\n entry.forget = () => cache.delete(key);\n }\n\n const value = entry.recompute(\n Array.prototype.slice.call(arguments) as TArgs,\n );\n\n // Move this entry to the front of the least-recently used queue,\n // since we just finished computing its value.\n cache.set(key, entry);\n\n caches.add(cache);\n\n // Clean up any excess entries in the cache, but only if there is no\n // active parent entry, meaning we're not in the middle of a larger\n // computation that might be flummoxed by the cleaning.\n if (! parentEntrySlot.hasValue()) {\n caches.forEach(cache => cache.clean());\n caches.clear();\n }\n\n return value;\n } as OptimisticWrapperFunction;\n\n Object.defineProperty(optimistic, \"size\", {\n get: () => cache.size,\n configurable: false,\n enumerable: false,\n });\n\n Object.freeze(optimistic.options = {\n max,\n keyArgs,\n makeCacheKey,\n normalizeResult,\n subscribe,\n cache,\n });\n\n function dirtyKey(key: TCacheKey | undefined) {\n const entry = key && cache.get(key);\n if (entry) {\n entry.setDirty();\n }\n }\n optimistic.dirtyKey = dirtyKey;\n optimistic.dirty = function dirty() {\n dirtyKey(makeCacheKey.apply(null, arguments as any));\n };\n\n function peekKey(key: TCacheKey | undefined) {\n const entry = key && cache.get(key);\n if (entry) {\n return entry.peek();\n }\n }\n optimistic.peekKey = peekKey;\n optimistic.peek = function peek() {\n return peekKey(makeCacheKey.apply(null, arguments as any));\n };\n\n function forgetKey(key: TCacheKey | undefined) {\n return key ? cache.delete(key) : false;\n }\n optimistic.forgetKey = forgetKey;\n optimistic.forget = function forget() {\n return forgetKey(makeCacheKey.apply(null, arguments as any));\n };\n\n optimistic.makeCacheKey = makeCacheKey;\n optimistic.getKey = keyArgs ? function getKey() {\n return makeCacheKey.apply(null, keyArgs.apply(null, arguments as any));\n } : makeCacheKey as (...args: any[]) => TCacheKey | undefined;\n\n return Object.freeze(optimistic);\n}\n","import { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet } from \"../common/canUse.js\";\nimport { checkDocument } from \"./getFromAST.js\";\nimport { invariant } from \"../globals/index.js\";\nimport type { DocumentNode } from \"graphql\";\nimport { WeakCache } from \"@wry/caches\";\nimport { wrap } from \"optimism\";\nimport { cacheSizes } from \"../caching/index.js\";\n\nexport type DocumentTransformCacheKey = ReadonlyArray;\n\ntype TransformFn = (document: DocumentNode) => DocumentNode;\n\ninterface DocumentTransformOptions {\n /**\n * Determines whether to cache the transformed GraphQL document. Caching can speed up repeated calls to the document transform for the same input document. Set to `false` to completely disable caching for the document transform. When disabled, this option takes precedence over the [`getCacheKey`](#getcachekey) option.\n *\n * The default value is `true`.\n */\n cache?: boolean;\n /**\n * Defines a custom cache key for a GraphQL document that will determine whether to re-run the document transform when given the same input GraphQL document. Returns an array that defines the cache key. Return `undefined` to disable caching for that GraphQL document.\n *\n * > **Note:** The items in the array may be any type, but also need to be referentially stable to guarantee a stable cache key.\n *\n * The default implementation of this function returns the `document` as the cache key.\n */\n getCacheKey?: (\n document: DocumentNode\n ) => DocumentTransformCacheKey | undefined;\n}\n\nfunction identity(document: DocumentNode) {\n return document;\n}\n\nexport class DocumentTransform {\n private readonly transform: TransformFn;\n private cached: boolean;\n\n private readonly resultCache =\n canUseWeakSet ? new WeakSet() : new Set();\n\n // This default implementation of getCacheKey can be overridden by providing\n // options.getCacheKey to the DocumentTransform constructor. In general, a\n // getCacheKey function may either return an array of keys (often including\n // the document) to be used as a cache key, or undefined to indicate the\n // transform for this document should not be cached.\n private getCacheKey(\n document: DocumentNode\n ): DocumentTransformCacheKey | undefined {\n return [document];\n }\n\n static identity() {\n // No need to cache this transform since it just returns the document\n // unchanged. This should save a bit of memory that would otherwise be\n // needed to populate the `documentCache` of this transform.\n return new DocumentTransform(identity, { cache: false });\n }\n\n static split(\n predicate: (document: DocumentNode) => boolean,\n left: DocumentTransform,\n right: DocumentTransform = DocumentTransform.identity()\n ) {\n return Object.assign(\n new DocumentTransform(\n (document) => {\n const documentTransform = predicate(document) ? left : right;\n\n return documentTransform.transformDocument(document);\n },\n // Reasonably assume both `left` and `right` transforms handle their own caching\n { cache: false }\n ),\n { left, right }\n );\n }\n\n constructor(\n transform: TransformFn,\n options: DocumentTransformOptions = Object.create(null)\n ) {\n this.transform = transform;\n\n if (options.getCacheKey) {\n // Override default `getCacheKey` function, which returns [document].\n this.getCacheKey = options.getCacheKey;\n }\n this.cached = options.cache !== false;\n\n this.resetCache();\n }\n\n /**\n * Resets the internal cache of this transform, if it has one.\n */\n resetCache() {\n if (this.cached) {\n const stableCacheKeys = new Trie(canUseWeakMap);\n this.performWork = wrap(\n DocumentTransform.prototype.performWork.bind(this),\n {\n makeCacheKey: (document) => {\n const cacheKeys = this.getCacheKey(document);\n if (cacheKeys) {\n invariant(\n Array.isArray(cacheKeys),\n \"`getCacheKey` must return an array or undefined\"\n );\n return stableCacheKeys.lookupArray(cacheKeys);\n }\n },\n max: cacheSizes[\"documentTransform.cache\"],\n cache: WeakCache,\n }\n );\n }\n }\n\n private performWork(document: DocumentNode) {\n checkDocument(document);\n return this.transform(document);\n }\n\n transformDocument(document: DocumentNode) {\n // If a user passes an already transformed result back to this function,\n // immediately return it.\n if (this.resultCache.has(document)) {\n return document;\n }\n\n const transformedDocument = this.performWork(document);\n\n this.resultCache.add(transformedDocument);\n\n return transformedDocument;\n }\n\n concat(otherTransform: DocumentTransform): DocumentTransform {\n return Object.assign(\n new DocumentTransform(\n (document) => {\n return otherTransform.transformDocument(\n this.transformDocument(document)\n );\n },\n // Reasonably assume both transforms handle their own caching\n { cache: false }\n ),\n {\n left: this,\n right: otherTransform,\n }\n );\n }\n\n /**\n * @internal\n * Used to iterate through all transforms that are concatenations or `split` links.\n */\n readonly left?: DocumentTransform;\n /**\n * @internal\n * Used to iterate through all transforms that are concatenations or `split` links.\n */\n readonly right?: DocumentTransform;\n}\n","import type { Observer } from \"./Observable.js\";\nimport { Observable } from \"./Observable.js\";\n\n// Like Observable.prototype.map, except that the mapping function can\n// optionally return a Promise (or be async).\nexport function asyncMap(\n observable: Observable,\n mapFn: (value: V) => R | PromiseLike,\n catchFn?: (error: any) => R | PromiseLike\n): Observable {\n return new Observable((observer) => {\n let promiseQueue = {\n // Normally we would initialize promiseQueue to Promise.resolve(), but\n // in this case, for backwards compatibility, we need to be careful to\n // invoke the first callback synchronously.\n then(callback: () => any) {\n return new Promise((resolve) => resolve(callback()));\n },\n } as Promise;\n\n function makeCallback(\n examiner: typeof mapFn | typeof catchFn,\n key: \"next\" | \"error\"\n ): (arg: any) => void {\n return (arg) => {\n if (examiner) {\n const both = () =>\n // If the observer is closed, we don't want to continue calling the\n // mapping function - it's result will be swallowed anyways.\n observer.closed ?\n /* will be swallowed */ (0 as any)\n : examiner(arg);\n\n promiseQueue = promiseQueue.then(both, both).then(\n (result) => observer.next(result),\n (error) => observer.error(error)\n );\n } else {\n observer[key](arg);\n }\n };\n }\n\n const handler: Observer = {\n next: makeCallback(mapFn, \"next\"),\n error: makeCallback(catchFn, \"error\"),\n complete() {\n // no need to reassign `promiseQueue`, after `observer.complete`,\n // the observer will be closed and short-circuit everything anyways\n /*promiseQueue = */ promiseQueue.then(() => observer.complete());\n },\n };\n\n const sub = observable.subscribe(handler);\n return () => sub.unsubscribe();\n });\n}\n","import type { FetchResult } from \"../../link/core/index.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { isExecutionPatchIncrementalResult } from \"./incrementalResult.js\";\n\nexport function graphQLResultHasError(result: FetchResult): boolean {\n const errors = getGraphQLErrorsFromResult(result);\n return isNonEmptyArray(errors);\n}\n\nexport function getGraphQLErrorsFromResult(result: FetchResult) {\n const graphQLErrors =\n isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n\n if (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n result.incremental.forEach((incrementalResult) => {\n if (incrementalResult.errors) {\n graphQLErrors.push(...incrementalResult.errors);\n }\n });\n }\n return graphQLErrors;\n}\n","import type { Observer } from \"./Observable.js\";\n\nexport function iterateObserversSafely(\n observers: Set>,\n method: keyof Observer,\n argument?: A\n) {\n // In case observers is modified during iteration, we need to commit to the\n // original elements, which also provides an opportunity to filter them down\n // to just the observers with the given method.\n const observersWithMethod: Observer[] = [];\n observers.forEach((obs) => obs[method] && observersWithMethod.push(obs));\n observersWithMethod.forEach((obs) => (obs as any)[method](argument));\n}\n","import { Observable } from \"./Observable.js\";\nimport { canUseSymbol } from \"../common/canUse.js\";\n\n// Generic implementations of Observable.prototype methods like map and\n// filter need to know how to create a new Observable from an Observable\n// subclass (like Concast or ObservableQuery). Those methods assume\n// (perhaps unwisely?) that they can call the subtype's constructor with a\n// Subscriber function, even though the subclass constructor might expect\n// different parameters. Defining this static Symbol.species property on\n// the subclass is a hint to generic Observable code to use the default\n// constructor instead of trying to do `new Subclass(observer => ...)`.\nexport function fixObservableSubclass<\n S extends new (...args: any[]) => Observable,\n>(subclass: S): S {\n function set(key: symbol | string) {\n // Object.defineProperty is necessary because the Symbol.species\n // property is a getter by default in modern JS environments, so we\n // can't assign to it with a normal assignment expression.\n Object.defineProperty(subclass, key, { value: Observable });\n }\n if (canUseSymbol && Symbol.species) {\n set(Symbol.species);\n }\n // The \"@@species\" string is used as a fake Symbol.species value in some\n // polyfill systems (including the SymbolSpecies variable used by\n // zen-observable), so we should set it as well, to be safe.\n set(\"@@species\");\n return subclass;\n}\n","import type {\n Observer,\n ObservableSubscription,\n Subscriber,\n} from \"./Observable.js\";\nimport { Observable } from \"./Observable.js\";\nimport { iterateObserversSafely } from \"./iteration.js\";\nimport { fixObservableSubclass } from \"./subclassing.js\";\n\ntype MaybeAsync = T | PromiseLike;\n\nfunction isPromiseLike(value: MaybeAsync): value is PromiseLike {\n return value && typeof (value as any).then === \"function\";\n}\n\n// Any individual Source can be an Observable or a promise for one.\ntype Source = MaybeAsync>;\n\nexport type ConcastSourcesIterable = Iterable>;\nexport type ConcastSourcesArray = Array>;\n\n// A Concast observable concatenates the given sources into a single\n// non-overlapping sequence of Ts, automatically unwrapping any promises,\n// and broadcasts the T elements of that sequence to any number of\n// subscribers, all without creating a bunch of intermediary Observable\n// wrapper objects.\n//\n// Even though any number of observers can subscribe to the Concast, each\n// source observable is guaranteed to receive at most one subscribe call,\n// and the results are multicast to all observers.\n//\n// In addition to broadcasting every next/error message to this.observers,\n// the Concast stores the most recent message using this.latest, so any\n// new observers can immediately receive the latest message, even if it\n// was originally delivered in the past. This behavior means we can assume\n// every active observer in this.observers has received the same most\n// recent message.\n//\n// With the exception of this.latest replay, a Concast is a \"hot\"\n// observable in the sense that it does not replay past results from the\n// beginning of time for each new observer.\n//\n// Could we have used some existing RxJS class instead? Concast is\n// similar to a BehaviorSubject, because it is multicast and redelivers\n// the latest next/error message to new subscribers. Unlike Subject,\n// Concast does not expose an Observer interface (this.handlers is\n// intentionally private), since Concast gets its inputs from the\n// concatenated sources. If we ever switch to RxJS, there may be some\n// value in reusing their code, but for now we use zen-observable, which\n// does not contain any Subject implementations.\nexport class Concast extends Observable {\n // Active observers receiving broadcast messages. Thanks to this.latest,\n // we can assume all observers in this Set have received the same most\n // recent message, though possibly at different times in the past.\n private observers = new Set>();\n\n // This property starts off undefined to indicate the initial\n // subscription has not yet begun, then points to each source\n // subscription in turn, and finally becomes null after the sources have\n // been exhausted. After that, it stays null.\n private sub?: ObservableSubscription | null;\n\n // Not only can the individual elements of the iterable be promises, but\n // also the iterable itself can be wrapped in a promise.\n constructor(sources: MaybeAsync> | Subscriber) {\n super((observer) => {\n this.addObserver(observer);\n return () => this.removeObserver(observer);\n });\n\n // Suppress rejection warnings for this.promise, since it's perfectly\n // acceptable to pay no attention to this.promise if you're consuming\n // the results through the normal observable API.\n this.promise.catch((_) => {});\n\n // If someone accidentally tries to create a Concast using a subscriber\n // function, recover by creating an Observable from that subscriber and\n // using it as the source.\n if (typeof sources === \"function\") {\n sources = [new Observable(sources)];\n }\n\n if (isPromiseLike(sources)) {\n sources.then((iterable) => this.start(iterable), this.handlers.error);\n } else {\n this.start(sources);\n }\n }\n\n // A consumable array of source observables, incrementally consumed each time\n // this.handlers.complete is called. This private field is not initialized\n // until the concast.start method is called, which can happen asynchronously\n // if a Promise is passed to the Concast constructor, so undefined is a\n // possible value for this.sources before concast.start is called.\n private sources: Source[] | undefined;\n\n private start(sources: ConcastSourcesIterable) {\n if (this.sub !== void 0) return;\n\n // In practice, sources is most often simply an Array of observables.\n // TODO Consider using sources[Symbol.iterator]() to take advantage\n // of the laziness of non-Array iterables.\n this.sources = Array.from(sources);\n\n // Calling this.handlers.complete() kicks off consumption of the first\n // source observable. It's tempting to do this step lazily in\n // addObserver, but this.promise can be accessed without calling\n // addObserver, so consumption needs to begin eagerly.\n this.handlers.complete();\n }\n\n private deliverLastMessage(observer: Observer) {\n if (this.latest) {\n const nextOrError = this.latest[0];\n const method = observer[nextOrError];\n if (method) {\n method.call(observer, this.latest[1]);\n }\n // If the subscription is already closed, and the last message was\n // a 'next' message, simulate delivery of the final 'complete'\n // message again.\n if (this.sub === null && nextOrError === \"next\" && observer.complete) {\n observer.complete();\n }\n }\n }\n\n public addObserver(observer: Observer) {\n if (!this.observers.has(observer)) {\n // Immediately deliver the most recent message, so we can always\n // be sure all observers have the latest information.\n this.deliverLastMessage(observer);\n this.observers.add(observer);\n }\n }\n\n public removeObserver(observer: Observer) {\n if (this.observers.delete(observer) && this.observers.size < 1) {\n // In case there are still any listeners in this.nextResultListeners, and\n // no error or completion has been broadcast yet, make sure those\n // observers have a chance to run and then remove themselves from\n // this.observers.\n this.handlers.complete();\n }\n }\n\n // Any Concast object can be trivially converted to a Promise, without\n // having to create a new wrapper Observable. This promise provides an\n // easy way to observe the final state of the Concast.\n private resolve!: (result?: T | PromiseLike) => void;\n private reject!: (reason: any) => void;\n public readonly promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n\n // Name and argument of the most recently invoked observer method, used\n // to deliver latest results immediately to new observers.\n private latest?: [\"next\", T] | [\"error\", any];\n\n // Bound handler functions that can be reused for every internal\n // subscription.\n private handlers = {\n next: (result: T) => {\n if (this.sub !== null) {\n this.latest = [\"next\", result];\n this.notify(\"next\", result);\n iterateObserversSafely(this.observers, \"next\", result);\n }\n },\n\n error: (error: any) => {\n const { sub } = this;\n if (sub !== null) {\n // Delay unsubscribing from the underlying subscription slightly,\n // so that immediately subscribing another observer can keep the\n // subscription active.\n if (sub) setTimeout(() => sub.unsubscribe());\n this.sub = null;\n this.latest = [\"error\", error];\n this.reject(error);\n this.notify(\"error\", error);\n iterateObserversSafely(this.observers, \"error\", error);\n }\n },\n\n complete: () => {\n const { sub, sources = [] } = this;\n if (sub !== null) {\n // If complete is called before concast.start, this.sources may be\n // undefined, so we use a default value of [] for sources. That works\n // here because it falls into the if (!value) {...} block, which\n // appropriately terminates the Concast, even if this.sources might\n // eventually have been initialized to a non-empty array.\n const value = sources.shift();\n if (!value) {\n if (sub) setTimeout(() => sub.unsubscribe());\n this.sub = null;\n if (this.latest && this.latest[0] === \"next\") {\n this.resolve(this.latest[1]);\n } else {\n this.resolve();\n }\n this.notify(\"complete\");\n // We do not store this.latest = [\"complete\"], because doing so\n // discards useful information about the previous next (or\n // error) message. Instead, if new observers subscribe after\n // this Concast has completed, they will receive the final\n // 'next' message (unless there was an error) immediately\n // followed by a 'complete' message (see addObserver).\n iterateObserversSafely(this.observers, \"complete\");\n } else if (isPromiseLike(value)) {\n value.then(\n (obs) => (this.sub = obs.subscribe(this.handlers)),\n this.handlers.error\n );\n } else {\n this.sub = value.subscribe(this.handlers);\n }\n }\n },\n };\n\n private nextResultListeners = new Set();\n\n private notify(\n method: Parameters[0],\n arg?: Parameters[1]\n ) {\n const { nextResultListeners } = this;\n if (nextResultListeners.size) {\n // Replacing this.nextResultListeners first ensures it does not grow while\n // we are iterating over it, potentially leading to infinite loops.\n this.nextResultListeners = new Set();\n nextResultListeners.forEach((listener) => listener(method, arg));\n }\n }\n\n // We need a way to run callbacks just *before* the next result (or error or\n // completion) is delivered by this Concast, so we can be sure any code that\n // runs as a result of delivering that result/error observes the effects of\n // running the callback(s). It was tempting to reuse the Observer type instead\n // of introducing NextResultListener, but that messes with the sizing and\n // maintenance of this.observers, and ends up being more code overall.\n beforeNext(callback: NextResultListener) {\n let called = false;\n this.nextResultListeners.add((method, arg) => {\n if (!called) {\n called = true;\n callback(method, arg);\n }\n });\n }\n\n // A public way to abort observation and broadcast.\n public cancel = (reason: any) => {\n this.reject(reason);\n this.sources = [];\n this.handlers.complete();\n };\n}\n\ntype NextResultListener = (\n method: \"next\" | \"error\" | \"complete\",\n arg?: any\n) => any;\n\n// Necessary because the Concast constructor has a different signature\n// than the Observable constructor.\nfixObservableSubclass(Concast);\n","const { toString } = Object.prototype;\n\n/**\n * Deeply clones a value to create a new instance.\n */\nexport function cloneDeep(value: T): T {\n return cloneDeepHelper(value);\n}\n\nfunction cloneDeepHelper(val: T, seen?: Map): T {\n switch (toString.call(val)) {\n case \"[object Array]\": {\n seen = seen || new Map();\n if (seen.has(val)) return seen.get(val);\n const copy: T & any[] = (val as any).slice(0);\n seen.set(val, copy);\n copy.forEach(function (child, i) {\n copy[i] = cloneDeepHelper(child, seen);\n });\n return copy;\n }\n\n case \"[object Object]\": {\n seen = seen || new Map();\n if (seen.has(val)) return seen.get(val);\n // High fidelity polyfills of Object.create and Object.getPrototypeOf are\n // possible in all JS environments, so we will assume they exist/work.\n const copy = Object.create(Object.getPrototypeOf(val));\n seen.set(val, copy);\n Object.keys(val as T & Record).forEach((key) => {\n copy[key] = cloneDeepHelper((val as any)[key], seen);\n });\n return copy;\n }\n\n default:\n return val;\n }\n}\n","import equal from \"@wry/equality\";\n\nimport type {\n DirectiveNode,\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n FragmentSpreadNode,\n InlineFragmentNode,\n SelectionNode,\n SelectionSetNode,\n} from \"graphql\";\n\nimport type { ApolloQueryResult, OperationVariables } from \"./types.js\";\n\nimport type { FragmentMap } from \"../utilities/index.js\";\nimport {\n createFragmentMap,\n getFragmentDefinitions,\n getFragmentFromSelection,\n getMainDefinition,\n isField,\n resultKeyNameFromField,\n shouldInclude,\n} from \"../utilities/index.js\";\n\n// Returns true if aResult and bResult are deeply equal according to the fields\n// selected by the given query, ignoring any fields marked as @nonreactive.\nexport function equalByQuery(\n query: DocumentNode,\n { data: aData, ...aRest }: Partial>,\n { data: bData, ...bRest }: Partial>,\n variables?: OperationVariables\n): boolean {\n return (\n equal(aRest, bRest) &&\n equalBySelectionSet(getMainDefinition(query).selectionSet, aData, bData, {\n fragmentMap: createFragmentMap(getFragmentDefinitions(query)),\n variables,\n })\n );\n}\n\n// Encapsulates the information used by equalBySelectionSet that does not change\n// during the recursion.\ninterface CompareContext {\n fragmentMap: FragmentMap;\n variables: TVariables | undefined;\n}\n\nfunction equalBySelectionSet(\n selectionSet: SelectionSetNode,\n aResult: any,\n bResult: any,\n context: CompareContext\n): boolean {\n if (aResult === bResult) {\n return true;\n }\n\n const seenSelections = new Set();\n\n // Returning true from this Array.prototype.every callback function skips the\n // current field/subtree. Returning false aborts the entire traversal\n // immediately, causing equalBySelectionSet to return false.\n return selectionSet.selections.every((selection) => {\n // Avoid re-processing the same selection at the same level of recursion, in\n // case the same field gets included via multiple indirect fragment spreads.\n if (seenSelections.has(selection)) return true;\n seenSelections.add(selection);\n\n // Ignore @skip(if: true) and @include(if: false) fields.\n if (!shouldInclude(selection, context.variables)) return true;\n\n // If the field or (named) fragment spread has a @nonreactive directive on\n // it, we don't care if it's different, so we pretend it's the same.\n if (selectionHasNonreactiveDirective(selection)) return true;\n\n if (isField(selection)) {\n const resultKey = resultKeyNameFromField(selection);\n const aResultChild = aResult && aResult[resultKey];\n const bResultChild = bResult && bResult[resultKey];\n const childSelectionSet = selection.selectionSet;\n\n if (!childSelectionSet) {\n // These are scalar values, so we can compare them with deep equal\n // without redoing the main recursive work.\n return equal(aResultChild, bResultChild);\n }\n\n const aChildIsArray = Array.isArray(aResultChild);\n const bChildIsArray = Array.isArray(bResultChild);\n if (aChildIsArray !== bChildIsArray) return false;\n if (aChildIsArray && bChildIsArray) {\n const length = aResultChild.length;\n if (bResultChild.length !== length) {\n return false;\n }\n for (let i = 0; i < length; ++i) {\n if (\n !equalBySelectionSet(\n childSelectionSet,\n aResultChild[i],\n bResultChild[i],\n context\n )\n ) {\n return false;\n }\n }\n return true;\n }\n\n return equalBySelectionSet(\n childSelectionSet,\n aResultChild,\n bResultChild,\n context\n );\n } else {\n const fragment = getFragmentFromSelection(selection, context.fragmentMap);\n if (fragment) {\n // The fragment might === selection if it's an inline fragment, but\n // could be !== if it's a named fragment ...spread.\n if (selectionHasNonreactiveDirective(fragment)) return true;\n\n return equalBySelectionSet(\n fragment.selectionSet,\n // Notice that we reuse the same aResult and bResult values here,\n // since the fragment ...spread does not specify a field name, but\n // consists of multiple fields (within the fragment's selection set)\n // that should be applied to the current result value(s).\n aResult,\n bResult,\n context\n );\n }\n }\n });\n}\n\nfunction selectionHasNonreactiveDirective(\n selection:\n | FieldNode\n | InlineFragmentNode\n | FragmentSpreadNode\n | FragmentDefinitionNode\n): boolean {\n return (\n !!selection.directives && selection.directives.some(directiveIsNonreactive)\n );\n}\n\nfunction directiveIsNonreactive(dir: DirectiveNode): boolean {\n return dir.name.value === \"nonreactive\";\n}\n","import { invariant } from \"../utilities/globals/index.js\";\nimport type { DocumentNode } from \"graphql\";\nimport { equal } from \"@wry/equality\";\n\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport type {\n Concast,\n Observer,\n ObservableSubscription,\n} from \"../utilities/index.js\";\nimport {\n cloneDeep,\n compact,\n getOperationDefinition,\n Observable,\n iterateObserversSafely,\n fixObservableSubclass,\n getQueryDefinition,\n} from \"../utilities/index.js\";\nimport type { ApolloError } from \"../errors/index.js\";\nimport type { QueryManager } from \"./QueryManager.js\";\nimport type {\n ApolloQueryResult,\n OperationVariables,\n TypedDocumentNode,\n} from \"./types.js\";\nimport type {\n WatchQueryOptions,\n FetchMoreQueryOptions,\n SubscribeToMoreOptions,\n NextFetchPolicyContext,\n WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\nimport type { QueryInfo } from \"./QueryInfo.js\";\nimport type { MissingFieldError } from \"../cache/index.js\";\nimport type { MissingTree } from \"../cache/core/types/common.js\";\nimport { equalByQuery } from \"./equalByQuery.js\";\nimport type { TODO } from \"../utilities/types/TODO.js\";\n\nconst { assign, hasOwnProperty } = Object;\n\nexport interface FetchMoreOptions<\n TData = any,\n TVariables = OperationVariables,\n> {\n updateQuery?: (\n previousQueryResult: TData,\n options: {\n fetchMoreResult?: TData;\n variables?: TVariables;\n }\n ) => TData;\n}\n\nexport interface UpdateQueryOptions {\n variables?: TVariables;\n}\n\ninterface Last {\n result: ApolloQueryResult;\n variables?: TVariables;\n error?: ApolloError;\n}\n\nexport class ObservableQuery<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n> extends Observable> {\n public readonly options: WatchQueryOptions;\n public readonly queryId: string;\n public readonly queryName?: string;\n\n // The `query` computed property will always reflect the document transformed\n // by the last run query. `this.options.query` will always reflect the raw\n // untransformed query to ensure document transforms with runtime conditionals\n // are run on the original document.\n public get query(): TypedDocumentNode {\n return this.lastQuery || this.options.query;\n }\n\n // Computed shorthand for this.options.variables, preserved for\n // backwards compatibility.\n /**\n * An object containing the variables that were provided for the query.\n */\n public get variables(): TVariables | undefined {\n return this.options.variables;\n }\n\n private isTornDown: boolean;\n private queryManager: QueryManager;\n private observers = new Set>>();\n private subscriptions = new Set();\n\n private waitForOwnResult: boolean;\n private last?: Last;\n private lastQuery?: DocumentNode;\n\n private queryInfo: QueryInfo;\n\n // When this.concast is defined, this.observer is the Observer currently\n // subscribed to that Concast.\n private concast?: Concast>;\n private observer?: Observer>;\n\n private pollingInfo?: {\n interval: number;\n timeout: ReturnType;\n };\n\n constructor({\n queryManager,\n queryInfo,\n options,\n }: {\n queryManager: QueryManager;\n queryInfo: QueryInfo;\n options: WatchQueryOptions;\n }) {\n super((observer: Observer>) => {\n // Zen Observable has its own error function, so in order to log correctly\n // we need to provide a custom error callback.\n try {\n var subObserver = (observer as any)._subscription._observer;\n if (subObserver && !subObserver.error) {\n subObserver.error = defaultSubscriptionObserverErrorCallback;\n }\n } catch {}\n\n const first = !this.observers.size;\n this.observers.add(observer);\n\n // Deliver most recent error or result.\n const last = this.last;\n if (last && last.error) {\n observer.error && observer.error(last.error);\n } else if (last && last.result) {\n observer.next && observer.next(last.result);\n }\n\n // Initiate observation of this query if it hasn't been reported to\n // the QueryManager yet.\n if (first) {\n // Blindly catching here prevents unhandled promise rejections,\n // and is safe because the ObservableQuery handles this error with\n // this.observer.error, so we're not just swallowing the error by\n // ignoring it here.\n this.reobserve().catch(() => {});\n }\n\n return () => {\n if (this.observers.delete(observer) && !this.observers.size) {\n this.tearDownQuery();\n }\n };\n });\n\n // related classes\n this.queryInfo = queryInfo;\n this.queryManager = queryManager;\n\n // active state\n this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);\n this.isTornDown = false;\n\n const {\n watchQuery: { fetchPolicy: defaultFetchPolicy = \"cache-first\" } = {},\n } = queryManager.defaultOptions;\n\n const {\n fetchPolicy = defaultFetchPolicy,\n // Make sure we don't store \"standby\" as the initialFetchPolicy.\n initialFetchPolicy = fetchPolicy === \"standby\" ? defaultFetchPolicy : (\n fetchPolicy\n ),\n } = options;\n\n this.options = {\n ...options,\n\n // Remember the initial options.fetchPolicy so we can revert back to this\n // policy when variables change. This information can also be specified\n // (or overridden) by providing options.initialFetchPolicy explicitly.\n initialFetchPolicy,\n\n // This ensures this.options.fetchPolicy always has a string value, in\n // case options.fetchPolicy was not provided.\n fetchPolicy,\n };\n\n this.queryId = queryInfo.queryId || queryManager.generateQueryId();\n\n const opDef = getOperationDefinition(this.query);\n this.queryName = opDef && opDef.name && opDef.name.value;\n }\n\n public result(): Promise> {\n return new Promise((resolve, reject) => {\n // TODO: this code doesn’t actually make sense insofar as the observer\n // will never exist in this.observers due how zen-observable wraps observables.\n // https://github.com/zenparsing/zen-observable/blob/master/src/Observable.js#L169\n const observer: Observer> = {\n next: (result: ApolloQueryResult) => {\n resolve(result);\n\n // Stop the query within the QueryManager if we can before\n // this function returns.\n //\n // We do this in order to prevent observers piling up within\n // the QueryManager. Notice that we only fully unsubscribe\n // from the subscription in a setTimeout(..., 0) call. This call can\n // actually be handled by the browser at a much later time. If queries\n // are fired in the meantime, observers that should have been removed\n // from the QueryManager will continue to fire, causing an unnecessary\n // performance hit.\n this.observers.delete(observer);\n if (!this.observers.size) {\n this.queryManager.removeQuery(this.queryId);\n }\n\n setTimeout(() => {\n subscription.unsubscribe();\n }, 0);\n },\n error: reject,\n };\n const subscription = this.subscribe(observer);\n });\n }\n\n /** @internal */\n public resetDiff() {\n this.queryInfo.resetDiff();\n }\n\n public getCurrentResult(saveAsLastResult = true): ApolloQueryResult {\n // Use the last result as long as the variables match this.variables.\n const lastResult = this.getLastResult(true);\n\n const networkStatus =\n this.queryInfo.networkStatus ||\n (lastResult && lastResult.networkStatus) ||\n NetworkStatus.ready;\n\n const result = {\n ...lastResult,\n loading: isNetworkRequestInFlight(networkStatus),\n networkStatus,\n } as ApolloQueryResult;\n\n const { fetchPolicy = \"cache-first\" } = this.options;\n if (\n // These fetch policies should never deliver data from the cache, unless\n // redelivering a previously delivered result.\n skipCacheDataFor(fetchPolicy) ||\n // If this.options.query has @client(always: true) fields, we cannot\n // trust diff.result, since it was read from the cache without running\n // local resolvers (and it's too late to run resolvers now, since we must\n // return a result synchronously).\n this.queryManager.getDocumentInfo(this.query).hasForcedResolvers\n ) {\n // Fall through.\n } else if (this.waitForOwnResult) {\n // This would usually be a part of `QueryInfo.getDiff()`.\n // which we skip in the waitForOwnResult case since we are not\n // interested in the diff.\n this.queryInfo[\"updateWatch\"]();\n } else {\n const diff = this.queryInfo.getDiff();\n\n if (diff.complete || this.options.returnPartialData) {\n result.data = diff.result;\n }\n\n if (equal(result.data, {})) {\n result.data = void 0 as any;\n }\n\n if (diff.complete) {\n // Similar to setting result.partial to false, but taking advantage of the\n // falsiness of missing fields.\n delete result.partial;\n\n // If the diff is complete, and we're using a FetchPolicy that\n // terminates after a complete cache read, we can assume the next result\n // we receive will have NetworkStatus.ready and !loading.\n if (\n diff.complete &&\n result.networkStatus === NetworkStatus.loading &&\n (fetchPolicy === \"cache-first\" || fetchPolicy === \"cache-only\")\n ) {\n result.networkStatus = NetworkStatus.ready;\n result.loading = false;\n }\n } else {\n result.partial = true;\n }\n\n if (\n __DEV__ &&\n !diff.complete &&\n !this.options.partialRefetch &&\n !result.loading &&\n !result.data &&\n !result.error\n ) {\n logMissingFieldErrors(diff.missing);\n }\n }\n\n if (saveAsLastResult) {\n this.updateLastResult(result);\n }\n\n return result;\n }\n\n // Compares newResult to the snapshot we took of this.lastResult when it was\n // first received.\n public isDifferentFromLastResult(\n newResult: ApolloQueryResult,\n variables?: TVariables\n ) {\n if (!this.last) {\n return true;\n }\n\n const resultIsDifferent =\n this.queryManager.getDocumentInfo(this.query).hasNonreactiveDirective ?\n !equalByQuery(this.query, this.last.result, newResult, this.variables)\n : !equal(this.last.result, newResult);\n\n return (\n resultIsDifferent || (variables && !equal(this.last.variables, variables))\n );\n }\n\n private getLast>(\n key: K,\n variablesMustMatch?: boolean\n ) {\n const last = this.last;\n if (\n last &&\n last[key] &&\n (!variablesMustMatch || equal(last.variables, this.variables))\n ) {\n return last[key];\n }\n }\n\n public getLastResult(\n variablesMustMatch?: boolean\n ): ApolloQueryResult | undefined {\n return this.getLast(\"result\", variablesMustMatch);\n }\n\n public getLastError(variablesMustMatch?: boolean): ApolloError | undefined {\n return this.getLast(\"error\", variablesMustMatch);\n }\n\n public resetLastResults(): void {\n delete this.last;\n this.isTornDown = false;\n }\n\n public resetQueryStoreErrors() {\n this.queryManager.resetErrors(this.queryId);\n }\n\n /**\n * Update the variables of this observable query, and fetch the new results.\n * This method should be preferred over `setVariables` in most use cases.\n *\n * @param variables - The new set of variables. If there are missing variables,\n * the previous values of those variables will be used.\n */\n public refetch(\n variables?: Partial\n ): Promise> {\n const reobserveOptions: Partial> = {\n // Always disable polling for refetches.\n pollInterval: 0,\n };\n\n // Unless the provided fetchPolicy always consults the network\n // (no-cache, network-only, or cache-and-network), override it with\n // network-only to force the refetch for this fetchQuery call.\n const { fetchPolicy } = this.options;\n if (fetchPolicy === \"cache-and-network\") {\n reobserveOptions.fetchPolicy = fetchPolicy;\n } else if (fetchPolicy === \"no-cache\") {\n reobserveOptions.fetchPolicy = \"no-cache\";\n } else {\n reobserveOptions.fetchPolicy = \"network-only\";\n }\n\n if (__DEV__ && variables && hasOwnProperty.call(variables, \"variables\")) {\n const queryDef = getQueryDefinition(this.query);\n const vars = queryDef.variableDefinitions;\n if (!vars || !vars.some((v) => v.variable.name.value === \"variables\")) {\n invariant.warn(\n `Called refetch(%o) for query %o, which does not declare a $variables variable.\nDid you mean to call refetch(variables) instead of refetch({ variables })?`,\n variables,\n queryDef.name?.value || queryDef\n );\n }\n }\n\n if (variables && !equal(this.options.variables, variables)) {\n // Update the existing options with new variables\n reobserveOptions.variables = this.options.variables = {\n ...this.options.variables,\n ...variables,\n } as TVariables;\n }\n\n this.queryInfo.resetLastWrite();\n return this.reobserve(reobserveOptions, NetworkStatus.refetch);\n }\n\n /**\n * A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).\n */\n public fetchMore<\n TFetchData = TData,\n TFetchVars extends OperationVariables = TVariables,\n >(\n fetchMoreOptions: FetchMoreQueryOptions & {\n updateQuery?: (\n previousQueryResult: TData,\n options: {\n fetchMoreResult: TFetchData;\n variables: TFetchVars;\n }\n ) => TData;\n }\n ): Promise> {\n const combinedOptions = {\n ...(fetchMoreOptions.query ? fetchMoreOptions : (\n {\n ...this.options,\n query: this.options.query,\n ...fetchMoreOptions,\n variables: {\n ...this.options.variables,\n ...fetchMoreOptions.variables,\n },\n }\n )),\n // The fetchMore request goes immediately to the network and does\n // not automatically write its result to the cache (hence no-cache\n // instead of network-only), because we allow the caller of\n // fetchMore to provide an updateQuery callback that determines how\n // the data gets written to the cache.\n fetchPolicy: \"no-cache\",\n } as WatchQueryOptions;\n\n combinedOptions.query = this.transformDocument(combinedOptions.query);\n\n const qid = this.queryManager.generateQueryId();\n\n // If a temporary query is passed to `fetchMore`, we don't want to store\n // it as the last query result since it may be an optimized query for\n // pagination. We will however run the transforms on the original document\n // as well as the document passed in `fetchMoreOptions` to ensure the cache\n // uses the most up-to-date document which may rely on runtime conditionals.\n this.lastQuery =\n fetchMoreOptions.query ?\n this.transformDocument(this.options.query)\n : combinedOptions.query;\n\n // Simulate a loading result for the original query with\n // result.networkStatus === NetworkStatus.fetchMore.\n const { queryInfo } = this;\n const originalNetworkStatus = queryInfo.networkStatus;\n queryInfo.networkStatus = NetworkStatus.fetchMore;\n if (combinedOptions.notifyOnNetworkStatusChange) {\n this.observe();\n }\n\n const updatedQuerySet = new Set();\n\n return this.queryManager\n .fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore)\n .then((fetchMoreResult) => {\n this.queryManager.removeQuery(qid);\n\n if (queryInfo.networkStatus === NetworkStatus.fetchMore) {\n queryInfo.networkStatus = originalNetworkStatus;\n }\n\n // Performing this cache update inside a cache.batch transaction ensures\n // any affected cache.watch watchers are notified at most once about any\n // updates. Most watchers will be using the QueryInfo class, which\n // responds to notifications by calling reobserveCacheFirst to deliver\n // fetchMore cache results back to this ObservableQuery.\n this.queryManager.cache.batch({\n update: (cache) => {\n const { updateQuery } = fetchMoreOptions;\n if (updateQuery) {\n cache.updateQuery(\n {\n query: this.query,\n variables: this.variables,\n returnPartialData: true,\n optimistic: false,\n },\n (previous) =>\n updateQuery(previous!, {\n fetchMoreResult: fetchMoreResult.data,\n variables: combinedOptions.variables as TFetchVars,\n })\n );\n } else {\n // If we're using a field policy instead of updateQuery, the only\n // thing we need to do is write the new data to the cache using\n // combinedOptions.variables (instead of this.variables, which is\n // what this.updateQuery uses, because it works by abusing the\n // original field value, keyed by the original variables).\n cache.writeQuery({\n query: combinedOptions.query,\n variables: combinedOptions.variables,\n data: fetchMoreResult.data,\n });\n }\n },\n\n onWatchUpdated: (watch) => {\n // Record the DocumentNode associated with any watched query whose\n // data were updated by the cache writes above.\n updatedQuerySet.add(watch.query);\n },\n });\n\n return fetchMoreResult;\n })\n .finally(() => {\n // In case the cache writes above did not generate a broadcast\n // notification (which would have been intercepted by onWatchUpdated),\n // likely because the written data were the same as what was already in\n // the cache, we still want fetchMore to deliver its final loading:false\n // result with the unchanged data.\n if (!updatedQuerySet.has(this.query)) {\n reobserveCacheFirst(this);\n }\n });\n }\n\n // XXX the subscription variables are separate from the query variables.\n // if you want to update subscription variables, right now you have to do that separately,\n // and you can only do it by stopping the subscription and then subscribing again with new variables.\n /**\n * A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), usually to subscribe to specific fields that were included in the query.\n *\n * This function returns _another_ function that you can call to terminate the subscription.\n */\n public subscribeToMore<\n TSubscriptionData = TData,\n TSubscriptionVariables extends OperationVariables = TVariables,\n >(\n options: SubscribeToMoreOptions<\n TData,\n TSubscriptionVariables,\n TSubscriptionData\n >\n ) {\n const subscription = this.queryManager\n .startGraphQLSubscription({\n query: options.document,\n variables: options.variables,\n context: options.context,\n })\n .subscribe({\n next: (subscriptionData: { data: TSubscriptionData }) => {\n const { updateQuery } = options;\n if (updateQuery) {\n this.updateQuery(\n (previous, { variables }) =>\n updateQuery(previous, {\n subscriptionData,\n variables,\n })\n );\n }\n },\n error: (err: any) => {\n if (options.onError) {\n options.onError(err);\n return;\n }\n invariant.error(\"Unhandled GraphQL subscription error\", err);\n },\n });\n\n this.subscriptions.add(subscription);\n\n return () => {\n if (this.subscriptions.delete(subscription)) {\n subscription.unsubscribe();\n }\n };\n }\n\n public setOptions(\n newOptions: Partial>\n ): Promise> {\n return this.reobserve(newOptions);\n }\n\n public silentSetOptions(\n newOptions: Partial>\n ) {\n const mergedOptions = compact(this.options, newOptions || {});\n assign(this.options, mergedOptions);\n }\n\n /**\n * Update the variables of this observable query, and fetch the new results\n * if they've changed. Most users should prefer `refetch` instead of\n * `setVariables` in order to to be properly notified of results even when\n * they come from the cache.\n *\n * Note: the `next` callback will *not* fire if the variables have not changed\n * or if the result is coming from cache.\n *\n * Note: the promise will return the old results immediately if the variables\n * have not changed.\n *\n * Note: the promise will return null immediately if the query is not active\n * (there are no subscribers).\n *\n * @param variables - The new set of variables. If there are missing variables,\n * the previous values of those variables will be used.\n */\n public setVariables(\n variables: TVariables\n ): Promise | void> {\n if (equal(this.variables, variables)) {\n // If we have no observers, then we don't actually want to make a network\n // request. As soon as someone observes the query, the request will kick\n // off. For now, we just store any changes. (See #1077)\n return this.observers.size ? this.result() : Promise.resolve();\n }\n\n this.options.variables = variables;\n\n // See comment above\n if (!this.observers.size) {\n return Promise.resolve();\n }\n\n return this.reobserve(\n {\n // Reset options.fetchPolicy to its original value.\n fetchPolicy: this.options.initialFetchPolicy,\n variables,\n },\n NetworkStatus.setVariables\n );\n }\n\n /**\n * A function that enables you to update the query's cached result without executing a followup GraphQL operation.\n *\n * See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.\n */\n public updateQuery(\n mapFn: (\n previousQueryResult: TData,\n options: Pick, \"variables\">\n ) => TData\n ): void {\n const { queryManager } = this;\n const { result } = queryManager.cache.diff({\n query: this.options.query,\n variables: this.variables,\n returnPartialData: true,\n optimistic: false,\n });\n\n const newResult = mapFn(result!, {\n variables: (this as any).variables,\n });\n\n if (newResult) {\n queryManager.cache.writeQuery({\n query: this.options.query,\n data: newResult,\n variables: this.variables,\n });\n\n queryManager.broadcastQueries();\n }\n }\n\n /**\n * A function that instructs the query to begin re-executing at a specified interval (in milliseconds).\n */\n public startPolling(pollInterval: number) {\n this.options.pollInterval = pollInterval;\n this.updatePolling();\n }\n\n /**\n * A function that instructs the query to stop polling after a previous call to `startPolling`.\n */\n public stopPolling() {\n this.options.pollInterval = 0;\n this.updatePolling();\n }\n\n // Update options.fetchPolicy according to options.nextFetchPolicy.\n private applyNextFetchPolicy(\n reason: NextFetchPolicyContext[\"reason\"],\n // It's possible to use this method to apply options.nextFetchPolicy to\n // options.fetchPolicy even if options !== this.options, though that happens\n // most often when the options are temporary, used for only one request and\n // then thrown away, so nextFetchPolicy may not end up mattering.\n options: WatchQueryOptions\n ) {\n if (options.nextFetchPolicy) {\n const { fetchPolicy = \"cache-first\", initialFetchPolicy = fetchPolicy } =\n options;\n\n if (fetchPolicy === \"standby\") {\n // Do nothing, leaving options.fetchPolicy unchanged.\n } else if (typeof options.nextFetchPolicy === \"function\") {\n // When someone chooses \"cache-and-network\" or \"network-only\" as their\n // initial FetchPolicy, they often do not want future cache updates to\n // trigger unconditional network requests, which is what repeatedly\n // applying the \"cache-and-network\" or \"network-only\" policies would\n // seem to imply. Instead, when the cache reports an update after the\n // initial network request, it may be desirable for subsequent network\n // requests to be triggered only if the cache result is incomplete. To\n // that end, the options.nextFetchPolicy option provides an easy way to\n // update options.fetchPolicy after the initial network request, without\n // having to call observableQuery.setOptions.\n options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {\n reason,\n options,\n observable: this,\n initialFetchPolicy,\n });\n } else if (reason === \"variables-changed\") {\n options.fetchPolicy = initialFetchPolicy;\n } else {\n options.fetchPolicy = options.nextFetchPolicy;\n }\n }\n\n return options.fetchPolicy;\n }\n\n private fetch(\n options: WatchQueryOptions,\n newNetworkStatus?: NetworkStatus,\n query?: DocumentNode\n ) {\n // TODO Make sure we update the networkStatus (and infer fetchVariables)\n // before actually committing to the fetch.\n this.queryManager.setObservableQuery(this);\n return this.queryManager[\"fetchConcastWithInfo\"](\n this.queryId,\n options,\n newNetworkStatus,\n query\n );\n }\n\n // Turns polling on or off based on this.options.pollInterval.\n private updatePolling() {\n // Avoid polling in SSR mode\n if (this.queryManager.ssrMode) {\n return;\n }\n\n const {\n pollingInfo,\n options: { pollInterval },\n } = this;\n\n if (!pollInterval || !this.hasObservers()) {\n if (pollingInfo) {\n clearTimeout(pollingInfo.timeout);\n delete this.pollingInfo;\n }\n return;\n }\n\n if (pollingInfo && pollingInfo.interval === pollInterval) {\n return;\n }\n\n invariant(\n pollInterval,\n \"Attempted to start a polling query without a polling interval.\"\n );\n\n const info = pollingInfo || (this.pollingInfo = {} as any);\n info.interval = pollInterval;\n\n const maybeFetch = () => {\n if (this.pollingInfo) {\n if (\n !isNetworkRequestInFlight(this.queryInfo.networkStatus) &&\n !this.options.skipPollAttempt?.()\n ) {\n this.reobserve(\n {\n // Most fetchPolicy options don't make sense to use in a polling context, as\n // users wouldn't want to be polling the cache directly. However, network-only and\n // no-cache are both useful for when the user wants to control whether or not the\n // polled results are written to the cache.\n fetchPolicy:\n this.options.initialFetchPolicy === \"no-cache\" ?\n \"no-cache\"\n : \"network-only\",\n },\n NetworkStatus.poll\n ).then(poll, poll);\n } else {\n poll();\n }\n }\n };\n\n const poll = () => {\n const info = this.pollingInfo;\n if (info) {\n clearTimeout(info.timeout);\n info.timeout = setTimeout(maybeFetch, info.interval);\n }\n };\n\n poll();\n }\n\n private updateLastResult(\n newResult: ApolloQueryResult,\n variables = this.variables\n ) {\n let error: ApolloError | undefined = this.getLastError();\n // Preserve this.last.error unless the variables have changed.\n if (error && this.last && !equal(variables, this.last.variables)) {\n error = void 0;\n }\n return (this.last = {\n result:\n this.queryManager.assumeImmutableResults ?\n newResult\n : cloneDeep(newResult),\n variables,\n ...(error ? { error } : null),\n });\n }\n\n public reobserveAsConcast(\n newOptions?: Partial>,\n newNetworkStatus?: NetworkStatus\n ): Concast> {\n this.isTornDown = false;\n\n const useDisposableConcast =\n // Refetching uses a disposable Concast to allow refetches using different\n // options/variables, without permanently altering the options of the\n // original ObservableQuery.\n newNetworkStatus === NetworkStatus.refetch ||\n // The fetchMore method does not actually call the reobserve method, but,\n // if it did, it would definitely use a disposable Concast.\n newNetworkStatus === NetworkStatus.fetchMore ||\n // Polling uses a disposable Concast so the polling options (which force\n // fetchPolicy to be \"network-only\" or \"no-cache\") won't override the original options.\n newNetworkStatus === NetworkStatus.poll;\n\n // Save the old variables, since Object.assign may modify them below.\n const oldVariables = this.options.variables;\n const oldFetchPolicy = this.options.fetchPolicy;\n\n const mergedOptions = compact(this.options, newOptions || {});\n const options =\n useDisposableConcast ?\n // Disposable Concast fetches receive a shallow copy of this.options\n // (merged with newOptions), leaving this.options unmodified.\n mergedOptions\n : assign(this.options, mergedOptions);\n\n // Don't update options.query with the transformed query to avoid\n // overwriting this.options.query when we aren't using a disposable concast.\n // We want to ensure we can re-run the custom document transforms the next\n // time a request is made against the original query.\n const query = this.transformDocument(options.query);\n\n this.lastQuery = query;\n\n if (!useDisposableConcast) {\n // We can skip calling updatePolling if we're not changing this.options.\n this.updatePolling();\n\n // Reset options.fetchPolicy to its original value when variables change,\n // unless a new fetchPolicy was provided by newOptions.\n if (\n newOptions &&\n newOptions.variables &&\n !equal(newOptions.variables, oldVariables) &&\n // Don't mess with the fetchPolicy if it's currently \"standby\".\n options.fetchPolicy !== \"standby\" &&\n // If we're changing the fetchPolicy anyway, don't try to change it here\n // using applyNextFetchPolicy. The explicit options.fetchPolicy wins.\n options.fetchPolicy === oldFetchPolicy\n ) {\n this.applyNextFetchPolicy(\"variables-changed\", options);\n if (newNetworkStatus === void 0) {\n newNetworkStatus = NetworkStatus.setVariables;\n }\n }\n }\n\n this.waitForOwnResult &&= skipCacheDataFor(options.fetchPolicy);\n const finishWaitingForOwnResult = () => {\n if (this.concast === concast) {\n this.waitForOwnResult = false;\n }\n };\n\n const variables = options.variables && { ...options.variables };\n const { concast, fromLink } = this.fetch(options, newNetworkStatus, query);\n const observer: Observer> = {\n next: (result) => {\n if (equal(this.variables, variables)) {\n finishWaitingForOwnResult();\n this.reportResult(result, variables);\n }\n },\n error: (error) => {\n if (equal(this.variables, variables)) {\n finishWaitingForOwnResult();\n this.reportError(error, variables);\n }\n },\n };\n\n if (!useDisposableConcast && (fromLink || !this.concast)) {\n // We use the {add,remove}Observer methods directly to avoid wrapping\n // observer with an unnecessary SubscriptionObserver object.\n if (this.concast && this.observer) {\n this.concast.removeObserver(this.observer);\n }\n\n this.concast = concast;\n this.observer = observer;\n }\n\n concast.addObserver(observer);\n\n return concast;\n }\n\n public reobserve(\n newOptions?: Partial>,\n newNetworkStatus?: NetworkStatus\n ): Promise> {\n return this.reobserveAsConcast(newOptions, newNetworkStatus)\n .promise as TODO;\n }\n\n public resubscribeAfterError(\n onNext: (value: ApolloQueryResult) => void,\n onError?: (error: any) => void,\n onComplete?: () => void\n ): ObservableSubscription;\n\n public resubscribeAfterError(\n observer: Observer>\n ): ObservableSubscription;\n\n public resubscribeAfterError(...args: [any, any?, any?]) {\n // If `lastError` is set in the current when the subscription is re-created,\n // the subscription will immediately receive the error, which will\n // cause it to terminate again. To avoid this, we first clear\n // the last error/result from the `observableQuery` before re-starting\n // the subscription, and restore the last value afterwards so that the\n // subscription has a chance to stay open.\n const last = this.last;\n this.resetLastResults();\n\n const subscription = this.subscribe(...args);\n this.last = last;\n\n return subscription;\n }\n\n // (Re)deliver the current result to this.observers without applying fetch\n // policies or making network requests.\n private observe() {\n this.reportResult(\n // Passing false is important so that this.getCurrentResult doesn't\n // save the fetchMore result as this.lastResult, causing it to be\n // ignored due to the this.isDifferentFromLastResult check in\n // this.reportResult.\n this.getCurrentResult(false),\n this.variables\n );\n }\n\n private reportResult(\n result: ApolloQueryResult,\n variables: TVariables | undefined\n ) {\n const lastError = this.getLastError();\n const isDifferent = this.isDifferentFromLastResult(result, variables);\n // Update the last result even when isDifferentFromLastResult returns false,\n // because the query may be using the @nonreactive directive, and we want to\n // save the the latest version of any nonreactive subtrees (in case\n // getCurrentResult is called), even though we skip broadcasting changes.\n if (lastError || !result.partial || this.options.returnPartialData) {\n this.updateLastResult(result, variables);\n }\n if (lastError || isDifferent) {\n iterateObserversSafely(this.observers, \"next\", result);\n }\n }\n\n private reportError(error: ApolloError, variables: TVariables | undefined) {\n // Since we don't get the current result on errors, only the error, we\n // must mirror the updates that occur in QueryStore.markQueryError here\n const errorResult = {\n ...this.getLastResult(),\n error,\n errors: error.graphQLErrors,\n networkStatus: NetworkStatus.error,\n loading: false,\n } as ApolloQueryResult;\n\n this.updateLastResult(errorResult, variables);\n\n iterateObserversSafely(this.observers, \"error\", (this.last!.error = error));\n }\n\n public hasObservers() {\n return this.observers.size > 0;\n }\n\n private tearDownQuery() {\n if (this.isTornDown) return;\n if (this.concast && this.observer) {\n this.concast.removeObserver(this.observer);\n delete this.concast;\n delete this.observer;\n }\n\n this.stopPolling();\n // stop all active GraphQL subscriptions\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n this.subscriptions.clear();\n this.queryManager.stopQuery(this.queryId);\n this.observers.clear();\n this.isTornDown = true;\n }\n\n private transformDocument(document: DocumentNode) {\n return this.queryManager.transform(document);\n }\n}\n\n// Necessary because the ObservableQuery constructor has a different\n// signature than the Observable constructor.\nfixObservableSubclass(ObservableQuery);\n\n// Reobserve with fetchPolicy effectively set to \"cache-first\", triggering\n// delivery of any new data from the cache, possibly falling back to the network\n// if any cache data are missing. This allows _complete_ cache results to be\n// delivered without also kicking off unnecessary network requests when\n// this.options.fetchPolicy is \"cache-and-network\" or \"network-only\". When\n// this.options.fetchPolicy is any other policy (\"cache-first\", \"cache-only\",\n// \"standby\", or \"no-cache\"), we call this.reobserve() as usual.\nexport function reobserveCacheFirst(\n obsQuery: ObservableQuery\n) {\n const { fetchPolicy, nextFetchPolicy } = obsQuery.options;\n\n if (fetchPolicy === \"cache-and-network\" || fetchPolicy === \"network-only\") {\n return obsQuery.reobserve({\n fetchPolicy: \"cache-first\",\n // Use a temporary nextFetchPolicy function that replaces itself with the\n // previous nextFetchPolicy value and returns the original fetchPolicy.\n nextFetchPolicy(\n this: WatchQueryOptions,\n currentFetchPolicy: WatchQueryFetchPolicy,\n context: NextFetchPolicyContext\n ) {\n // Replace this nextFetchPolicy function in the options object with the\n // original this.options.nextFetchPolicy value.\n this.nextFetchPolicy = nextFetchPolicy;\n // If the original nextFetchPolicy value was a function, give it a\n // chance to decide what happens here.\n if (typeof this.nextFetchPolicy === \"function\") {\n return this.nextFetchPolicy(currentFetchPolicy, context);\n }\n // Otherwise go back to the original this.options.fetchPolicy.\n return fetchPolicy!;\n },\n });\n }\n\n return obsQuery.reobserve();\n}\n\nfunction defaultSubscriptionObserverErrorCallback(error: ApolloError) {\n invariant.error(\"Unhandled error\", error.message, error.stack);\n}\n\nexport function logMissingFieldErrors(\n missing: MissingFieldError[] | MissingTree | undefined\n) {\n if (__DEV__ && missing) {\n invariant.debug(`Missing cache result fields: %o`, missing);\n }\n}\n\nfunction skipCacheDataFor(\n fetchPolicy?: WatchQueryFetchPolicy /* `undefined` would mean `\"cache-first\"` */\n) {\n return (\n fetchPolicy === \"network-only\" ||\n fetchPolicy === \"no-cache\" ||\n fetchPolicy === \"standby\"\n );\n}\n","import type { OptimisticDependencyFunction } from \"optimism\";\nimport { dep, Slot } from \"optimism\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type { ApolloCache } from \"../../core/index.js\";\n\nexport interface ReactiveVar {\n (newValue?: T): T;\n onNextChange(listener: ReactiveListener): () => void;\n attachCache(cache: ApolloCache): this;\n forgetCache(cache: ApolloCache): boolean;\n}\n\nexport type ReactiveListener = (value: T) => any;\n\n// Contextual Slot that acquires its value when custom read functions are\n// called in Policies#readField.\nexport const cacheSlot = new Slot>();\n\nconst cacheInfoMap = new WeakMap<\n ApolloCache,\n {\n vars: Set>;\n dep: OptimisticDependencyFunction>;\n }\n>();\n\nfunction getCacheInfo(cache: ApolloCache) {\n let info = cacheInfoMap.get(cache)!;\n if (!info) {\n cacheInfoMap.set(\n cache,\n (info = {\n vars: new Set(),\n dep: dep(),\n })\n );\n }\n return info;\n}\n\nexport function forgetCache(cache: ApolloCache) {\n getCacheInfo(cache).vars.forEach((rv) => rv.forgetCache(cache));\n}\n\n// Calling forgetCache(cache) serves to silence broadcasts and allows the\n// cache to be garbage collected. However, the varsByCache WeakMap\n// preserves the set of reactive variables that were previously associated\n// with this cache, which makes it possible to \"recall\" the cache at a\n// later time, by reattaching it to those variables. If the cache has been\n// garbage collected in the meantime, because it is no longer reachable,\n// you won't be able to call recallCache(cache), and the cache will\n// automatically disappear from the varsByCache WeakMap.\nexport function recallCache(cache: ApolloCache) {\n getCacheInfo(cache).vars.forEach((rv) => rv.attachCache(cache));\n}\n\nexport function makeVar(value: T): ReactiveVar {\n const caches = new Set>();\n const listeners = new Set>();\n\n const rv: ReactiveVar = function (newValue) {\n if (arguments.length > 0) {\n if (value !== newValue) {\n value = newValue!;\n caches.forEach((cache) => {\n // Invalidate any fields with custom read functions that\n // consumed this variable, so query results involving those\n // fields will be recomputed the next time we read them.\n getCacheInfo(cache).dep.dirty(rv);\n // Broadcast changes to any caches that have previously read\n // from this variable.\n broadcast(cache);\n });\n // Finally, notify any listeners added via rv.onNextChange.\n const oldListeners = Array.from(listeners);\n listeners.clear();\n oldListeners.forEach((listener) => listener(value));\n }\n } else {\n // When reading from the variable, obtain the current cache from\n // context via cacheSlot. This isn't entirely foolproof, but it's\n // the same system that powers varDep.\n const cache = cacheSlot.getValue();\n if (cache) {\n attach(cache);\n getCacheInfo(cache).dep(rv);\n }\n }\n\n return value;\n };\n\n rv.onNextChange = (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n };\n\n const attach = (rv.attachCache = (cache) => {\n caches.add(cache);\n getCacheInfo(cache).vars.add(rv);\n return rv;\n });\n\n rv.forgetCache = (cache) => caches.delete(cache);\n\n return rv;\n}\n\ntype Broadcastable = ApolloCache & {\n // This method is protected in InMemoryCache, which we are ignoring, but\n // we still want some semblance of type safety when we call it.\n broadcastWatches?: InMemoryCache[\"broadcastWatches\"];\n};\n\nfunction broadcast(cache: Broadcastable) {\n if (cache.broadcastWatches) {\n cache.broadcastWatches();\n }\n}\n","import { invariant } from \"../utilities/globals/index.js\";\n\nimport type {\n DocumentNode,\n OperationDefinitionNode,\n SelectionSetNode,\n SelectionNode,\n InlineFragmentNode,\n FragmentDefinitionNode,\n FieldNode,\n ASTNode,\n DirectiveNode,\n FragmentSpreadNode,\n ExecutableDefinitionNode,\n} from \"graphql\";\nimport { visit, BREAK, isSelectionNode } from \"graphql\";\n\nimport type { ApolloCache } from \"../cache/index.js\";\nimport type { FragmentMap, StoreObject } from \"../utilities/index.js\";\nimport {\n argumentsObjectFromField,\n buildQueryFromSelectionSet,\n createFragmentMap,\n getFragmentDefinitions,\n getMainDefinition,\n hasDirectives,\n isField,\n isInlineFragment,\n mergeDeep,\n mergeDeepArray,\n removeClientSetsFromDocument,\n resultKeyNameFromField,\n shouldInclude,\n} from \"../utilities/index.js\";\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport type { Resolvers, OperationVariables } from \"./types.js\";\nimport type { FetchResult } from \"../link/core/index.js\";\nimport { cacheSlot } from \"../cache/index.js\";\n\nexport type Resolver = (\n rootValue?: any,\n args?: any,\n context?: any,\n info?: {\n field: FieldNode;\n fragmentMap: FragmentMap;\n }\n) => any;\n\nexport type VariableMap = { [name: string]: any };\n\nexport type FragmentMatcher = (\n rootValue: any,\n typeCondition: string,\n context: any\n) => boolean;\n\nexport type ExecContext = {\n fragmentMap: FragmentMap;\n context: any;\n variables: VariableMap;\n fragmentMatcher: FragmentMatcher;\n defaultOperationType: string;\n exportedVariables: Record;\n onlyRunForcedResolvers: boolean;\n selectionsToResolve: Set;\n};\n\nexport type LocalStateOptions = {\n cache: ApolloCache;\n client?: ApolloClient;\n resolvers?: Resolvers | Resolvers[];\n fragmentMatcher?: FragmentMatcher;\n};\n\nexport class LocalState {\n private cache: ApolloCache;\n private client?: ApolloClient;\n private resolvers?: Resolvers;\n private fragmentMatcher?: FragmentMatcher;\n private selectionsToResolveCache = new WeakMap<\n ExecutableDefinitionNode,\n Set\n >();\n\n constructor({\n cache,\n client,\n resolvers,\n fragmentMatcher,\n }: LocalStateOptions) {\n this.cache = cache;\n\n if (client) {\n this.client = client;\n }\n\n if (resolvers) {\n this.addResolvers(resolvers);\n }\n\n if (fragmentMatcher) {\n this.setFragmentMatcher(fragmentMatcher);\n }\n }\n\n public addResolvers(resolvers: Resolvers | Resolvers[]) {\n this.resolvers = this.resolvers || {};\n if (Array.isArray(resolvers)) {\n resolvers.forEach((resolverGroup) => {\n this.resolvers = mergeDeep(this.resolvers, resolverGroup);\n });\n } else {\n this.resolvers = mergeDeep(this.resolvers, resolvers);\n }\n }\n\n public setResolvers(resolvers: Resolvers | Resolvers[]) {\n this.resolvers = {};\n this.addResolvers(resolvers);\n }\n\n public getResolvers() {\n return this.resolvers || {};\n }\n\n // Run local client resolvers against the incoming query and remote data.\n // Locally resolved field values are merged with the incoming remote data,\n // and returned. Note that locally resolved fields will overwrite\n // remote data using the same field name.\n public async runResolvers({\n document,\n remoteResult,\n context,\n variables,\n onlyRunForcedResolvers = false,\n }: {\n document: DocumentNode | null;\n remoteResult: FetchResult;\n context?: Record;\n variables?: Record;\n onlyRunForcedResolvers?: boolean;\n }): Promise> {\n if (document) {\n return this.resolveDocument(\n document,\n remoteResult.data,\n context,\n variables,\n this.fragmentMatcher,\n onlyRunForcedResolvers\n ).then((localResult) => ({\n ...remoteResult,\n data: localResult.result,\n }));\n }\n\n return remoteResult;\n }\n\n public setFragmentMatcher(fragmentMatcher: FragmentMatcher) {\n this.fragmentMatcher = fragmentMatcher;\n }\n\n public getFragmentMatcher(): FragmentMatcher | undefined {\n return this.fragmentMatcher;\n }\n\n // Client queries contain everything in the incoming document (if a @client\n // directive is found).\n public clientQuery(document: DocumentNode) {\n if (hasDirectives([\"client\"], document)) {\n if (this.resolvers) {\n return document;\n }\n }\n return null;\n }\n\n // Server queries are stripped of all @client based selection sets.\n public serverQuery(document: DocumentNode) {\n return removeClientSetsFromDocument(document);\n }\n\n public prepareContext(context?: Record) {\n const { cache } = this;\n return {\n ...context,\n cache,\n // Getting an entry's cache key is useful for local state resolvers.\n getCacheKey(obj: StoreObject) {\n return cache.identify(obj);\n },\n };\n }\n\n // To support `@client @export(as: \"someVar\")` syntax, we'll first resolve\n // @client @export fields locally, then pass the resolved values back to be\n // used alongside the original operation variables.\n public async addExportedVariables(\n document: DocumentNode,\n variables: TVars = {} as TVars,\n context = {}\n ): /* returns at least the variables that were passed in */ Promise {\n if (document) {\n return this.resolveDocument(\n document,\n this.buildRootValueFromCache(document, variables) || {},\n this.prepareContext(context),\n variables\n ).then((data) => ({\n ...variables,\n ...data.exportedVariables,\n }));\n }\n\n return {\n ...variables,\n };\n }\n\n public shouldForceResolvers(document: ASTNode) {\n let forceResolvers = false;\n visit(document, {\n Directive: {\n enter(node) {\n if (node.name.value === \"client\" && node.arguments) {\n forceResolvers = node.arguments.some(\n (arg) =>\n arg.name.value === \"always\" &&\n arg.value.kind === \"BooleanValue\" &&\n arg.value.value === true\n );\n if (forceResolvers) {\n return BREAK;\n }\n }\n },\n },\n });\n return forceResolvers;\n }\n\n // Query the cache and return matching data.\n private buildRootValueFromCache(\n document: DocumentNode,\n variables?: Record\n ) {\n return this.cache.diff({\n query: buildQueryFromSelectionSet(document),\n variables,\n returnPartialData: true,\n optimistic: false,\n }).result;\n }\n\n private async resolveDocument(\n document: DocumentNode,\n rootValue: TData,\n context: any = {},\n variables: VariableMap = {},\n fragmentMatcher: FragmentMatcher = () => true,\n onlyRunForcedResolvers: boolean = false\n ) {\n const mainDefinition = getMainDefinition(\n document\n ) as OperationDefinitionNode;\n const fragments = getFragmentDefinitions(document);\n const fragmentMap = createFragmentMap(fragments);\n const selectionsToResolve = this.collectSelectionsToResolve(\n mainDefinition,\n fragmentMap\n );\n\n const definitionOperation = mainDefinition.operation;\n\n const defaultOperationType =\n definitionOperation ?\n definitionOperation.charAt(0).toUpperCase() +\n definitionOperation.slice(1)\n : \"Query\";\n\n const { cache, client } = this;\n const execContext: ExecContext = {\n fragmentMap,\n context: {\n ...context,\n cache,\n client,\n },\n variables,\n fragmentMatcher,\n defaultOperationType,\n exportedVariables: {},\n selectionsToResolve,\n onlyRunForcedResolvers,\n };\n const isClientFieldDescendant = false;\n\n return this.resolveSelectionSet(\n mainDefinition.selectionSet,\n isClientFieldDescendant,\n rootValue,\n execContext\n ).then((result) => ({\n result,\n exportedVariables: execContext.exportedVariables,\n }));\n }\n\n private async resolveSelectionSet(\n selectionSet: SelectionSetNode,\n isClientFieldDescendant: boolean,\n rootValue: TData,\n execContext: ExecContext\n ) {\n const { fragmentMap, context, variables } = execContext;\n const resultsToMerge: TData[] = [rootValue];\n\n const execute = async (selection: SelectionNode): Promise => {\n if (\n !isClientFieldDescendant &&\n !execContext.selectionsToResolve.has(selection)\n ) {\n // Skip selections without @client directives\n // (still processing if one of the ancestors or one of the child fields has @client directive)\n return;\n }\n if (!shouldInclude(selection, variables)) {\n // Skip this entirely.\n return;\n }\n\n if (isField(selection)) {\n return this.resolveField(\n selection,\n isClientFieldDescendant,\n rootValue,\n execContext\n ).then((fieldResult) => {\n if (typeof fieldResult !== \"undefined\") {\n resultsToMerge.push({\n [resultKeyNameFromField(selection)]: fieldResult,\n } as TData);\n }\n });\n }\n\n let fragment: InlineFragmentNode | FragmentDefinitionNode;\n\n if (isInlineFragment(selection)) {\n fragment = selection;\n } else {\n // This is a named fragment.\n fragment = fragmentMap[selection.name.value];\n invariant(fragment, `No fragment named %s`, selection.name.value);\n }\n\n if (fragment && fragment.typeCondition) {\n const typeCondition = fragment.typeCondition.name.value;\n if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {\n return this.resolveSelectionSet(\n fragment.selectionSet,\n isClientFieldDescendant,\n rootValue,\n execContext\n ).then((fragmentResult) => {\n resultsToMerge.push(fragmentResult);\n });\n }\n }\n };\n\n return Promise.all(selectionSet.selections.map(execute)).then(function () {\n return mergeDeepArray(resultsToMerge);\n });\n }\n\n private async resolveField(\n field: FieldNode,\n isClientFieldDescendant: boolean,\n rootValue: any,\n execContext: ExecContext\n ): Promise {\n if (!rootValue) {\n return null;\n }\n\n const { variables } = execContext;\n const fieldName = field.name.value;\n const aliasedFieldName = resultKeyNameFromField(field);\n const aliasUsed = fieldName !== aliasedFieldName;\n const defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];\n let resultPromise = Promise.resolve(defaultResult);\n\n // Usually all local resolvers are run when passing through here, but\n // if we've specifically identified that we only want to run forced\n // resolvers (that is, resolvers for fields marked with\n // `@client(always: true)`), then we'll skip running non-forced resolvers.\n if (\n !execContext.onlyRunForcedResolvers ||\n this.shouldForceResolvers(field)\n ) {\n const resolverType =\n rootValue.__typename || execContext.defaultOperationType;\n const resolverMap = this.resolvers && this.resolvers[resolverType];\n if (resolverMap) {\n const resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];\n if (resolve) {\n resultPromise = Promise.resolve(\n // In case the resolve function accesses reactive variables,\n // set cacheSlot to the current cache instance.\n cacheSlot.withValue(this.cache, resolve, [\n rootValue,\n argumentsObjectFromField(field, variables),\n execContext.context,\n { field, fragmentMap: execContext.fragmentMap },\n ])\n );\n }\n }\n }\n\n return resultPromise.then((result = defaultResult) => {\n // If an @export directive is associated with the current field, store\n // the `as` export variable name and current result for later use.\n if (field.directives) {\n field.directives.forEach((directive) => {\n if (directive.name.value === \"export\" && directive.arguments) {\n directive.arguments.forEach((arg) => {\n if (arg.name.value === \"as\" && arg.value.kind === \"StringValue\") {\n execContext.exportedVariables[arg.value.value] = result;\n }\n });\n }\n });\n }\n\n // Handle all scalar types here.\n if (!field.selectionSet) {\n return result;\n }\n\n // From here down, the field has a selection set, which means it's trying\n // to query a GraphQLObjectType.\n if (result == null) {\n // Basically any field in a GraphQL response can be null, or missing\n return result;\n }\n\n const isClientField =\n field.directives?.some((d) => d.name.value === \"client\") ?? false;\n\n if (Array.isArray(result)) {\n return this.resolveSubSelectedArray(\n field,\n isClientFieldDescendant || isClientField,\n result,\n execContext\n );\n }\n\n // Returned value is an object, and the query has a sub-selection. Recurse.\n if (field.selectionSet) {\n return this.resolveSelectionSet(\n field.selectionSet,\n isClientFieldDescendant || isClientField,\n result,\n execContext\n );\n }\n });\n }\n\n private resolveSubSelectedArray(\n field: FieldNode,\n isClientFieldDescendant: boolean,\n result: any[],\n execContext: ExecContext\n ): any {\n return Promise.all(\n result.map((item) => {\n if (item === null) {\n return null;\n }\n\n // This is a nested array, recurse.\n if (Array.isArray(item)) {\n return this.resolveSubSelectedArray(\n field,\n isClientFieldDescendant,\n item,\n execContext\n );\n }\n\n // This is an object, run the selection set on it.\n if (field.selectionSet) {\n return this.resolveSelectionSet(\n field.selectionSet,\n isClientFieldDescendant,\n item,\n execContext\n );\n }\n })\n );\n }\n\n // Collect selection nodes on paths from document root down to all @client directives.\n // This function takes into account transitive fragment spreads.\n // Complexity equals to a single `visit` over the full document.\n private collectSelectionsToResolve(\n mainDefinition: OperationDefinitionNode,\n fragmentMap: FragmentMap\n ): Set {\n const isSingleASTNode = (\n node: ASTNode | readonly ASTNode[]\n ): node is ASTNode => !Array.isArray(node);\n const selectionsToResolveCache = this.selectionsToResolveCache;\n\n function collectByDefinition(\n definitionNode: ExecutableDefinitionNode\n ): Set {\n if (!selectionsToResolveCache.has(definitionNode)) {\n const matches = new Set();\n selectionsToResolveCache.set(definitionNode, matches);\n\n visit(definitionNode, {\n Directive(node: DirectiveNode, _, __, ___, ancestors) {\n if (node.name.value === \"client\") {\n ancestors.forEach((node) => {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches.add(node);\n }\n });\n }\n },\n FragmentSpread(spread: FragmentSpreadNode, _, __, ___, ancestors) {\n const fragment = fragmentMap[spread.name.value];\n invariant(fragment, `No fragment named %s`, spread.name.value);\n\n const fragmentSelections = collectByDefinition(fragment);\n if (fragmentSelections.size > 0) {\n // Fragment for this spread contains @client directive (either directly or transitively)\n // Collect selection nodes on paths from the root down to fields with the @client directive\n ancestors.forEach((node) => {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches.add(node);\n }\n });\n matches.add(spread);\n fragmentSelections.forEach((selection) => {\n matches.add(selection);\n });\n }\n },\n });\n }\n return selectionsToResolveCache.get(definitionNode)!;\n }\n return collectByDefinition(mainDefinition);\n }\n}\n","import type { DocumentNode, GraphQLError } from \"graphql\";\nimport { equal } from \"@wry/equality\";\n\nimport type { Cache, ApolloCache } from \"../cache/index.js\";\nimport { DeepMerger } from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/index.js\";\nimport type { WatchQueryOptions, ErrorPolicy } from \"./watchQueryOptions.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\nimport { reobserveCacheFirst } from \"./ObservableQuery.js\";\nimport type { QueryListener } from \"./types.js\";\nimport type { FetchResult } from \"../link/core/index.js\";\nimport {\n isNonEmptyArray,\n graphQLResultHasError,\n canUseWeakMap,\n} from \"../utilities/index.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport type { ApolloError } from \"../errors/index.js\";\nimport type { QueryManager } from \"./QueryManager.js\";\n\nexport type QueryStoreValue = Pick<\n QueryInfo,\n \"variables\" | \"networkStatus\" | \"networkError\" | \"graphQLErrors\"\n>;\n\nexport const enum CacheWriteBehavior {\n FORBID,\n OVERWRITE,\n MERGE,\n}\n\nconst destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)<\n ApolloCache,\n number\n>();\n\nfunction wrapDestructiveCacheMethod(\n cache: ApolloCache,\n methodName: \"evict\" | \"modify\" | \"reset\"\n) {\n const original = cache[methodName];\n if (typeof original === \"function\") {\n // @ts-expect-error this is just too generic to be typed correctly\n cache[methodName] = function () {\n destructiveMethodCounts.set(\n cache,\n // The %1e15 allows the count to wrap around to 0 safely every\n // quadrillion evictions, so there's no risk of overflow. To be\n // clear, this is more of a pedantic principle than something\n // that matters in any conceivable practical scenario.\n (destructiveMethodCounts.get(cache)! + 1) % 1e15\n );\n // @ts-expect-error this is just too generic to be typed correctly\n return original.apply(this, arguments);\n };\n }\n}\n\nfunction cancelNotifyTimeout(info: QueryInfo) {\n if (info[\"notifyTimeout\"]) {\n clearTimeout(info[\"notifyTimeout\"]);\n info[\"notifyTimeout\"] = void 0;\n }\n}\n\n// A QueryInfo object represents a single query managed by the\n// QueryManager, which tracks all QueryInfo objects by queryId in its\n// this.queries Map. QueryInfo objects store the latest results and errors\n// for the given query, and are responsible for reporting those results to\n// the corresponding ObservableQuery, via the QueryInfo.notify method.\n// Results are reported asynchronously whenever setDiff marks the\n// QueryInfo object as dirty, though a call to the QueryManager's\n// broadcastQueries method may trigger the notification before it happens\n// automatically. This class used to be a simple interface type without\n// any field privacy or meaningful methods, which is why it still has so\n// many public fields. The effort to lock down and simplify the QueryInfo\n// interface is ongoing, and further improvements are welcome.\nexport class QueryInfo {\n listeners = new Set();\n document: DocumentNode | null = null;\n lastRequestId = 1;\n variables?: Record;\n networkStatus?: NetworkStatus;\n networkError?: Error | null;\n graphQLErrors?: ReadonlyArray;\n stopped = false;\n\n private cache: ApolloCache;\n\n constructor(\n queryManager: QueryManager,\n public readonly queryId = queryManager.generateQueryId()\n ) {\n const cache = (this.cache = queryManager.cache);\n\n // Track how often cache.evict is called, since we want eviction to\n // override the feud-stopping logic in the markResult method, by\n // causing shouldWrite to return true. Wrapping the cache.evict method\n // is a bit of a hack, but it saves us from having to make eviction\n // counting an official part of the ApolloCache API.\n if (!destructiveMethodCounts.has(cache)) {\n destructiveMethodCounts.set(cache, 0);\n wrapDestructiveCacheMethod(cache, \"evict\");\n wrapDestructiveCacheMethod(cache, \"modify\");\n wrapDestructiveCacheMethod(cache, \"reset\");\n }\n }\n\n public init(query: {\n document: DocumentNode;\n variables: Record | undefined;\n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus?: NetworkStatus;\n observableQuery?: ObservableQuery;\n lastRequestId?: number;\n }): this {\n let networkStatus = query.networkStatus || NetworkStatus.loading;\n if (\n this.variables &&\n this.networkStatus !== NetworkStatus.loading &&\n !equal(this.variables, query.variables)\n ) {\n networkStatus = NetworkStatus.setVariables;\n }\n\n if (!equal(query.variables, this.variables)) {\n this.lastDiff = void 0;\n }\n\n Object.assign(this, {\n document: query.document,\n variables: query.variables,\n networkError: null,\n graphQLErrors: this.graphQLErrors || [],\n networkStatus,\n });\n\n if (query.observableQuery) {\n this.setObservableQuery(query.observableQuery);\n }\n\n if (query.lastRequestId) {\n this.lastRequestId = query.lastRequestId;\n }\n\n return this;\n }\n\n private dirty: boolean = false;\n\n private notifyTimeout?: ReturnType;\n\n reset() {\n cancelNotifyTimeout(this);\n this.dirty = false;\n }\n\n resetDiff() {\n this.lastDiff = void 0;\n }\n\n getDiff(): Cache.DiffResult {\n const options = this.getDiffOptions();\n\n if (this.lastDiff && equal(options, this.lastDiff.options)) {\n return this.lastDiff.diff;\n }\n\n this.updateWatch(this.variables);\n\n const oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return { complete: false };\n }\n\n const diff = this.cache.diff(options);\n this.updateLastDiff(diff, options);\n return diff;\n }\n\n private lastDiff?: {\n diff: Cache.DiffResult;\n options: Cache.DiffOptions;\n };\n\n private updateLastDiff(\n diff: Cache.DiffResult | null,\n options?: Cache.DiffOptions\n ) {\n this.lastDiff =\n diff ?\n {\n diff,\n options: options || this.getDiffOptions(),\n }\n : void 0;\n }\n\n private getDiffOptions(variables = this.variables): Cache.DiffOptions {\n return {\n query: this.document!,\n variables,\n returnPartialData: true,\n optimistic: true,\n canonizeResults: this.observableQuery?.options.canonizeResults,\n };\n }\n\n setDiff(diff: Cache.DiffResult | null) {\n const oldDiff = this.lastDiff && this.lastDiff.diff;\n\n // If we are trying to deliver an incomplete cache result, we avoid\n // reporting it if the query has errored, otherwise we let the broadcast try\n // and repair the partial result by refetching the query. This check avoids\n // a situation where a query that errors and another succeeds with\n // overlapping data does not report the partial data result to the errored\n // query.\n //\n // See https://github.com/apollographql/apollo-client/issues/11400 for more\n // information on this issue.\n if (diff && !diff.complete && this.observableQuery?.getLastError()) {\n return;\n }\n\n this.updateLastDiff(diff);\n\n if (!this.dirty && !equal(oldDiff && oldDiff.result, diff && diff.result)) {\n this.dirty = true;\n if (!this.notifyTimeout) {\n this.notifyTimeout = setTimeout(() => this.notify(), 0);\n }\n }\n }\n\n public readonly observableQuery: ObservableQuery | null = null;\n private oqListener?: QueryListener;\n\n setObservableQuery(oq: ObservableQuery | null) {\n if (oq === this.observableQuery) return;\n\n if (this.oqListener) {\n this.listeners.delete(this.oqListener);\n }\n\n (this as any).observableQuery = oq;\n\n if (oq) {\n oq[\"queryInfo\"] = this;\n this.listeners.add(\n (this.oqListener = () => {\n const diff = this.getDiff();\n if (diff.fromOptimisticTransaction) {\n // If this diff came from an optimistic transaction, deliver the\n // current cache data to the ObservableQuery, but don't perform a\n // reobservation, since oq.reobserveCacheFirst might make a network\n // request, and we never want to trigger network requests in the\n // middle of optimistic updates.\n oq[\"observe\"]();\n } else {\n // Otherwise, make the ObservableQuery \"reobserve\" the latest data\n // using a temporary fetch policy of \"cache-first\", so complete cache\n // results have a chance to be delivered without triggering additional\n // network requests, even when options.fetchPolicy is \"network-only\"\n // or \"cache-and-network\". All other fetch policies are preserved by\n // this method, and are handled by calling oq.reobserve(). If this\n // reobservation is spurious, isDifferentFromLastResult still has a\n // chance to catch it before delivery to ObservableQuery subscribers.\n reobserveCacheFirst(oq);\n }\n })\n );\n } else {\n delete this.oqListener;\n }\n }\n\n notify() {\n cancelNotifyTimeout(this);\n\n if (this.shouldNotify()) {\n this.listeners.forEach((listener) => listener(this));\n }\n\n this.dirty = false;\n }\n\n private shouldNotify() {\n if (!this.dirty || !this.listeners.size) {\n return false;\n }\n\n if (isNetworkRequestInFlight(this.networkStatus) && this.observableQuery) {\n const { fetchPolicy } = this.observableQuery.options;\n if (fetchPolicy !== \"cache-only\" && fetchPolicy !== \"cache-and-network\") {\n return false;\n }\n }\n\n return true;\n }\n\n public stop() {\n if (!this.stopped) {\n this.stopped = true;\n\n // Cancel the pending notify timeout\n this.reset();\n\n this.cancel();\n // Revert back to the no-op version of cancel inherited from\n // QueryInfo.prototype.\n this.cancel = QueryInfo.prototype.cancel;\n\n const oq = this.observableQuery;\n if (oq) oq.stopPolling();\n }\n }\n\n // This method is a no-op by default, until/unless overridden by the\n // updateWatch method.\n private cancel() {}\n\n private lastWatch?: Cache.WatchOptions;\n\n private updateWatch(variables = this.variables) {\n const oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return;\n }\n\n const watchOptions: Cache.WatchOptions = {\n // Although this.getDiffOptions returns Cache.DiffOptions instead of\n // Cache.WatchOptions, all the overlapping options should be the same, so\n // we can reuse getDiffOptions here, for consistency.\n ...this.getDiffOptions(variables),\n watcher: this,\n callback: (diff) => this.setDiff(diff),\n };\n\n if (!this.lastWatch || !equal(watchOptions, this.lastWatch)) {\n this.cancel();\n this.cancel = this.cache.watch((this.lastWatch = watchOptions));\n }\n }\n\n private lastWrite?: {\n result: FetchResult;\n variables: WatchQueryOptions[\"variables\"];\n dmCount: number | undefined;\n };\n\n public resetLastWrite() {\n this.lastWrite = void 0;\n }\n\n private shouldWrite(\n result: FetchResult,\n variables: WatchQueryOptions[\"variables\"]\n ) {\n const { lastWrite } = this;\n return !(\n lastWrite &&\n // If cache.evict has been called since the last time we wrote this\n // data into the cache, there's a chance writing this result into\n // the cache will repair what was evicted.\n lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&\n equal(variables, lastWrite.variables) &&\n equal(result.data, lastWrite.result.data)\n );\n }\n\n public markResult(\n result: FetchResult,\n document: DocumentNode,\n options: Pick<\n WatchQueryOptions,\n \"variables\" | \"fetchPolicy\" | \"errorPolicy\"\n >,\n cacheWriteBehavior: CacheWriteBehavior\n ) {\n const merger = new DeepMerger();\n const graphQLErrors =\n isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n\n // Cancel the pending notify timeout (if it exists) to prevent extraneous network\n // requests. To allow future notify timeouts, diff and dirty are reset as well.\n this.reset();\n\n if (\"incremental\" in result && isNonEmptyArray(result.incremental)) {\n const mergedData = mergeIncrementalData(this.getDiff().result, result);\n result.data = mergedData;\n\n // Detect the first chunk of a deferred query and merge it with existing\n // cache data. This ensures a `cache-first` fetch policy that returns\n // partial cache data or a `cache-and-network` fetch policy that already\n // has full data in the cache does not complain when trying to merge the\n // initial deferred server data with existing cache data.\n } else if (\"hasNext\" in result && result.hasNext) {\n const diff = this.getDiff();\n result.data = merger.merge(diff.result, result.data);\n }\n\n this.graphQLErrors = graphQLErrors;\n\n if (options.fetchPolicy === \"no-cache\") {\n this.updateLastDiff(\n { result: result.data, complete: true },\n this.getDiffOptions(options.variables)\n );\n } else if (cacheWriteBehavior !== CacheWriteBehavior.FORBID) {\n if (shouldWriteResult(result, options.errorPolicy)) {\n // Using a transaction here so we have a chance to read the result\n // back from the cache before the watch callback fires as a result\n // of writeQuery, so we can store the new diff quietly and ignore\n // it when we receive it redundantly from the watch callback.\n this.cache.performTransaction((cache) => {\n if (this.shouldWrite(result, options.variables)) {\n cache.writeQuery({\n query: document,\n data: result.data as T,\n variables: options.variables,\n overwrite: cacheWriteBehavior === CacheWriteBehavior.OVERWRITE,\n });\n\n this.lastWrite = {\n result,\n variables: options.variables,\n dmCount: destructiveMethodCounts.get(this.cache),\n };\n } else {\n // If result is the same as the last result we received from\n // the network (and the variables match too), avoid writing\n // result into the cache again. The wisdom of skipping this\n // cache write is far from obvious, since any cache write\n // could be the one that puts the cache back into a desired\n // state, fixing corruption or missing data. However, if we\n // always write every network result into the cache, we enable\n // feuds between queries competing to update the same data in\n // incompatible ways, which can lead to an endless cycle of\n // cache broadcasts and useless network requests. As with any\n // feud, eventually one side must step back from the brink,\n // letting the other side(s) have the last word(s). There may\n // be other points where we could break this cycle, such as\n // silencing the broadcast for cache.writeQuery (not a good\n // idea, since it just delays the feud a bit) or somehow\n // avoiding the network request that just happened (also bad,\n // because the server could return useful new data). All\n // options considered, skipping this cache write seems to be\n // the least damaging place to break the cycle, because it\n // reflects the intuition that we recently wrote this exact\n // result into the cache, so the cache *should* already/still\n // contain this data. If some other query has clobbered that\n // data in the meantime, that's too bad, but there will be no\n // winners if every query blindly reverts to its own version\n // of the data. This approach also gives the network a chance\n // to return new data, which will be written into the cache as\n // usual, notifying only those queries that are directly\n // affected by the cache updates, as usual. In the future, an\n // even more sophisticated cache could perhaps prevent or\n // mitigate the clobbering somehow, but that would make this\n // particular cache write even less important, and thus\n // skipping it would be even safer than it is today.\n if (this.lastDiff && this.lastDiff.diff.complete) {\n // Reuse data from the last good (complete) diff that we\n // received, when possible.\n result.data = this.lastDiff.diff.result;\n return;\n }\n // If the previous this.diff was incomplete, fall through to\n // re-reading the latest data with cache.diff, below.\n }\n\n const diffOptions = this.getDiffOptions(options.variables);\n const diff = cache.diff(diffOptions);\n\n // In case the QueryManager stops this QueryInfo before its\n // results are delivered, it's important to avoid restarting the\n // cache watch when markResult is called. We also avoid updating\n // the watch if we are writing a result that doesn't match the current\n // variables to avoid race conditions from broadcasting the wrong\n // result.\n if (!this.stopped && equal(this.variables, options.variables)) {\n // Any time we're about to update this.diff, we need to make\n // sure we've started watching the cache.\n this.updateWatch(options.variables);\n }\n\n // If we're allowed to write to the cache, and we can read a\n // complete result from the cache, update result.data to be the\n // result from the cache, rather than the raw network result.\n // Set without setDiff to avoid triggering a notify call, since\n // we have other ways of notifying for this result.\n this.updateLastDiff(diff, diffOptions);\n if (diff.complete) {\n result.data = diff.result;\n }\n });\n } else {\n this.lastWrite = void 0;\n }\n }\n }\n\n public markReady() {\n this.networkError = null;\n return (this.networkStatus = NetworkStatus.ready);\n }\n\n public markError(error: ApolloError) {\n this.networkStatus = NetworkStatus.error;\n this.lastWrite = void 0;\n\n this.reset();\n\n if (error.graphQLErrors) {\n this.graphQLErrors = error.graphQLErrors;\n }\n\n if (error.networkError) {\n this.networkError = error.networkError;\n }\n\n return error;\n }\n}\n\nexport function shouldWriteResult(\n result: FetchResult,\n errorPolicy: ErrorPolicy = \"none\"\n) {\n const ignoreErrors = errorPolicy === \"ignore\" || errorPolicy === \"all\";\n let writeWithErrors = !graphQLResultHasError(result);\n if (!writeWithErrors && ignoreErrors && result.data) {\n writeWithErrors = true;\n }\n return writeWithErrors;\n}\n","import { invariant, newInvariantError } from \"../utilities/globals/index.js\";\n\nimport type { DocumentNode } from \"graphql\";\n// TODO(brian): A hack until this issue is resolved (https://github.com/graphql/graphql-js/issues/3356)\ntype OperationTypeNode = any;\nimport { equal } from \"@wry/equality\";\n\nimport type { ApolloLink, FetchResult } from \"../link/core/index.js\";\nimport { execute } from \"../link/core/index.js\";\nimport {\n defaultCacheSizes,\n hasDirectives,\n isExecutionPatchIncrementalResult,\n isExecutionPatchResult,\n removeDirectivesFromDocument,\n} from \"../utilities/index.js\";\nimport type { Cache, ApolloCache } from \"../cache/index.js\";\nimport { canonicalStringify } from \"../cache/index.js\";\n\nimport type {\n ObservableSubscription,\n ConcastSourcesArray,\n} from \"../utilities/index.js\";\nimport {\n getDefaultValues,\n getOperationDefinition,\n getOperationName,\n hasClientExports,\n graphQLResultHasError,\n getGraphQLErrorsFromResult,\n Observable,\n asyncMap,\n isNonEmptyArray,\n Concast,\n makeUniqueId,\n isDocumentNode,\n isNonNullObject,\n DocumentTransform,\n} from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/common/incrementalResult.js\";\nimport {\n ApolloError,\n isApolloError,\n graphQLResultHasProtocolErrors,\n} from \"../errors/index.js\";\nimport type {\n QueryOptions,\n WatchQueryOptions,\n SubscriptionOptions,\n MutationOptions,\n ErrorPolicy,\n MutationFetchPolicy,\n} from \"./watchQueryOptions.js\";\nimport { ObservableQuery, logMissingFieldErrors } from \"./ObservableQuery.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport type {\n ApolloQueryResult,\n OperationVariables,\n MutationUpdaterFunction,\n OnQueryUpdated,\n InternalRefetchQueriesInclude,\n InternalRefetchQueriesOptions,\n InternalRefetchQueriesResult,\n InternalRefetchQueriesMap,\n DefaultContext,\n} from \"./types.js\";\nimport { LocalState } from \"./LocalState.js\";\n\nimport type { QueryStoreValue } from \"./QueryInfo.js\";\nimport {\n QueryInfo,\n shouldWriteResult,\n CacheWriteBehavior,\n} from \"./QueryInfo.js\";\nimport type { ApolloErrorOptions } from \"../errors/index.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../errors/index.js\";\nimport { print } from \"../utilities/index.js\";\nimport type { IgnoreModifier } from \"../cache/core/types/common.js\";\nimport type { TODO } from \"../utilities/types/TODO.js\";\n\nconst { hasOwnProperty } = Object.prototype;\n\nconst IGNORE: IgnoreModifier = Object.create(null);\n\ninterface MutationStoreValue {\n mutation: DocumentNode;\n variables: Record;\n loading: boolean;\n error: Error | null;\n}\n\ntype UpdateQueries = MutationOptions[\"updateQueries\"];\n\ninterface TransformCacheEntry {\n hasClientExports: boolean;\n hasForcedResolvers: boolean;\n hasNonreactiveDirective: boolean;\n clientQuery: DocumentNode | null;\n serverQuery: DocumentNode | null;\n defaultVars: OperationVariables;\n asQuery: DocumentNode;\n}\n\nimport type { DefaultOptions } from \"./ApolloClient.js\";\nimport { Trie } from \"@wry/trie\";\nimport { AutoCleanedWeakCache, cacheSizes } from \"../utilities/index.js\";\n\nexport class QueryManager {\n public cache: ApolloCache;\n public link: ApolloLink;\n public defaultOptions: DefaultOptions;\n\n public readonly assumeImmutableResults: boolean;\n public readonly documentTransform: DocumentTransform;\n public readonly ssrMode: boolean;\n public readonly defaultContext: Partial;\n\n private queryDeduplication: boolean;\n private clientAwareness: Record = {};\n private localState: LocalState;\n\n private onBroadcast?: () => void;\n public mutationStore?: {\n [mutationId: string]: MutationStoreValue;\n };\n\n // All the queries that the QueryManager is currently managing (not\n // including mutations and subscriptions).\n private queries = new Map();\n\n // Maps from queryId strings to Promise rejection functions for\n // currently active queries and fetches.\n // Use protected instead of private field so\n // @apollo/experimental-nextjs-app-support can access type info.\n protected fetchCancelFns = new Map any>();\n\n constructor({\n cache,\n link,\n defaultOptions,\n documentTransform,\n queryDeduplication = false,\n onBroadcast,\n ssrMode = false,\n clientAwareness = {},\n localState,\n assumeImmutableResults = !!cache.assumeImmutableResults,\n defaultContext,\n }: {\n cache: ApolloCache;\n link: ApolloLink;\n defaultOptions?: DefaultOptions;\n documentTransform?: DocumentTransform;\n queryDeduplication?: boolean;\n onBroadcast?: () => void;\n ssrMode?: boolean;\n clientAwareness?: Record;\n localState?: LocalState;\n assumeImmutableResults?: boolean;\n defaultContext?: Partial;\n }) {\n const defaultDocumentTransform = new DocumentTransform(\n (document) => this.cache.transformDocument(document),\n // Allow the apollo cache to manage its own transform caches\n { cache: false }\n );\n\n this.cache = cache;\n this.link = link;\n this.defaultOptions = defaultOptions || Object.create(null);\n this.queryDeduplication = queryDeduplication;\n this.clientAwareness = clientAwareness;\n this.localState = localState || new LocalState({ cache });\n this.ssrMode = ssrMode;\n this.assumeImmutableResults = assumeImmutableResults;\n this.documentTransform =\n documentTransform ?\n defaultDocumentTransform\n .concat(documentTransform)\n // The custom document transform may add new fragment spreads or new\n // field selections, so we want to give the cache a chance to run\n // again. For example, the InMemoryCache adds __typename to field\n // selections and fragments from the fragment registry.\n .concat(defaultDocumentTransform)\n : defaultDocumentTransform;\n this.defaultContext = defaultContext || Object.create(null);\n\n if ((this.onBroadcast = onBroadcast)) {\n this.mutationStore = Object.create(null);\n }\n }\n\n /**\n * Call this method to terminate any active query processes, making it safe\n * to dispose of this QueryManager instance.\n */\n public stop() {\n this.queries.forEach((_info, queryId) => {\n this.stopQueryNoBroadcast(queryId);\n });\n\n this.cancelPendingFetches(\n newInvariantError(\"QueryManager stopped while query was in flight\")\n );\n }\n\n private cancelPendingFetches(error: Error) {\n this.fetchCancelFns.forEach((cancel) => cancel(error));\n this.fetchCancelFns.clear();\n }\n\n public async mutate<\n TData,\n TVariables extends OperationVariables,\n TContext extends Record,\n TCache extends ApolloCache,\n >({\n mutation,\n variables,\n optimisticResponse,\n updateQueries,\n refetchQueries = [],\n awaitRefetchQueries = false,\n update: updateWithProxyFn,\n onQueryUpdated,\n fetchPolicy = this.defaultOptions.mutate?.fetchPolicy || \"network-only\",\n errorPolicy = this.defaultOptions.mutate?.errorPolicy || \"none\",\n keepRootFields,\n context,\n }: MutationOptions): Promise<\n FetchResult\n > {\n invariant(\n mutation,\n \"mutation option is required. You must specify your GraphQL document in the mutation option.\"\n );\n\n invariant(\n fetchPolicy === \"network-only\" || fetchPolicy === \"no-cache\",\n \"Mutations support only 'network-only' or 'no-cache' fetchPolicy strings. The default `network-only` behavior automatically writes mutation results to the cache. Passing `no-cache` skips the cache write.\"\n );\n\n const mutationId = this.generateMutationId();\n\n mutation = this.cache.transformForLink(this.transform(mutation));\n const { hasClientExports } = this.getDocumentInfo(mutation);\n\n variables = this.getVariables(mutation, variables) as TVariables;\n if (hasClientExports) {\n variables = (await this.localState.addExportedVariables(\n mutation,\n variables,\n context\n )) as TVariables;\n }\n\n const mutationStoreValue =\n this.mutationStore &&\n (this.mutationStore[mutationId] = {\n mutation,\n variables,\n loading: true,\n error: null,\n } as MutationStoreValue);\n\n const isOptimistic =\n optimisticResponse &&\n this.markMutationOptimistic(\n optimisticResponse,\n {\n mutationId,\n document: mutation,\n variables,\n fetchPolicy,\n errorPolicy,\n context,\n updateQueries,\n update: updateWithProxyFn,\n keepRootFields,\n }\n );\n\n this.broadcastQueries();\n\n const self = this;\n\n return new Promise((resolve, reject) => {\n return asyncMap(\n self.getObservableFromLink(\n mutation,\n {\n ...context,\n optimisticResponse: isOptimistic ? optimisticResponse : void 0,\n },\n variables,\n false\n ),\n\n (result: FetchResult) => {\n if (graphQLResultHasError(result) && errorPolicy === \"none\") {\n throw new ApolloError({\n graphQLErrors: getGraphQLErrorsFromResult(result),\n });\n }\n\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = null;\n }\n\n const storeResult: typeof result = { ...result };\n\n if (typeof refetchQueries === \"function\") {\n refetchQueries = refetchQueries(storeResult);\n }\n\n if (errorPolicy === \"ignore\" && graphQLResultHasError(storeResult)) {\n delete storeResult.errors;\n }\n\n return self.markMutationResult({\n mutationId,\n result: storeResult,\n document: mutation,\n variables,\n fetchPolicy,\n errorPolicy,\n context,\n update: updateWithProxyFn,\n updateQueries,\n awaitRefetchQueries,\n refetchQueries,\n removeOptimistic: isOptimistic ? mutationId : void 0,\n onQueryUpdated,\n keepRootFields,\n });\n }\n ).subscribe({\n next(storeResult) {\n self.broadcastQueries();\n\n // Since mutations might receive multiple payloads from the\n // ApolloLink chain (e.g. when used with @defer),\n // we resolve with a SingleExecutionResult or after the final\n // ExecutionPatchResult has arrived and we have assembled the\n // multipart response into a single result.\n if (!(\"hasNext\" in storeResult) || storeResult.hasNext === false) {\n resolve(storeResult);\n }\n },\n\n error(err: Error) {\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = err;\n }\n\n if (isOptimistic) {\n self.cache.removeOptimistic(mutationId);\n }\n\n self.broadcastQueries();\n\n reject(\n err instanceof ApolloError ? err : (\n new ApolloError({\n networkError: err,\n })\n )\n );\n },\n });\n });\n }\n\n public markMutationResult<\n TData,\n TVariables,\n TContext,\n TCache extends ApolloCache,\n >(\n mutation: {\n mutationId: string;\n result: FetchResult;\n document: DocumentNode;\n variables?: TVariables;\n fetchPolicy?: MutationFetchPolicy;\n errorPolicy: ErrorPolicy;\n context?: TContext;\n updateQueries: UpdateQueries;\n update?: MutationUpdaterFunction;\n awaitRefetchQueries?: boolean;\n refetchQueries?: InternalRefetchQueriesInclude;\n removeOptimistic?: string;\n onQueryUpdated?: OnQueryUpdated;\n keepRootFields?: boolean;\n },\n cache = this.cache\n ): Promise> {\n let { result } = mutation;\n const cacheWrites: Cache.WriteOptions[] = [];\n const skipCache = mutation.fetchPolicy === \"no-cache\";\n\n if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {\n if (!isExecutionPatchIncrementalResult(result)) {\n cacheWrites.push({\n result: result.data,\n dataId: \"ROOT_MUTATION\",\n query: mutation.document,\n variables: mutation.variables,\n });\n }\n if (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n const diff = cache.diff({\n id: \"ROOT_MUTATION\",\n // The cache complains if passed a mutation where it expects a\n // query, so we transform mutations and subscriptions to queries\n // (only once, thanks to this.transformCache).\n query: this.getDocumentInfo(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n let mergedData;\n if (diff.result) {\n mergedData = mergeIncrementalData(diff.result, result);\n }\n if (typeof mergedData !== \"undefined\") {\n // cast the ExecutionPatchResult to FetchResult here since\n // ExecutionPatchResult never has `data` when returned from the server\n (result as FetchResult).data = mergedData;\n cacheWrites.push({\n result: mergedData,\n dataId: \"ROOT_MUTATION\",\n query: mutation.document,\n variables: mutation.variables,\n });\n }\n }\n\n const { updateQueries } = mutation;\n if (updateQueries) {\n this.queries.forEach(({ observableQuery }, queryId) => {\n const queryName = observableQuery && observableQuery.queryName;\n if (!queryName || !hasOwnProperty.call(updateQueries, queryName)) {\n return;\n }\n const updater = updateQueries[queryName];\n const { document, variables } = this.queries.get(queryId)!;\n\n // Read the current query result from the store.\n const { result: currentQueryResult, complete } = cache.diff({\n query: document!,\n variables,\n returnPartialData: true,\n optimistic: false,\n });\n\n if (complete && currentQueryResult) {\n // Run our reducer using the current query result and the mutation result.\n const nextQueryResult = updater(currentQueryResult, {\n mutationResult: result,\n queryName: (document && getOperationName(document)) || void 0,\n queryVariables: variables!,\n });\n\n // Write the modified result back into the store if we got a new result.\n if (nextQueryResult) {\n cacheWrites.push({\n result: nextQueryResult,\n dataId: \"ROOT_QUERY\",\n query: document!,\n variables,\n });\n }\n }\n });\n }\n }\n\n if (\n cacheWrites.length > 0 ||\n (mutation.refetchQueries || \"\").length > 0 ||\n mutation.update ||\n mutation.onQueryUpdated ||\n mutation.removeOptimistic\n ) {\n const results: any[] = [];\n\n this.refetchQueries({\n updateCache: (cache) => {\n if (!skipCache) {\n cacheWrites.forEach((write) => cache.write(write));\n }\n\n // If the mutation has some writes associated with it then we need to\n // apply those writes to the store by running this reducer again with\n // a write action.\n const { update } = mutation;\n // Determine whether result is a SingleExecutionResult,\n // or the final ExecutionPatchResult.\n const isFinalResult =\n !isExecutionPatchResult(result) ||\n (isExecutionPatchIncrementalResult(result) && !result.hasNext);\n\n if (update) {\n if (!skipCache) {\n // Re-read the ROOT_MUTATION data we just wrote into the cache\n // (the first cache.write call in the cacheWrites.forEach loop\n // above), so field read functions have a chance to run for\n // fields within mutation result objects.\n const diff = cache.diff({\n id: \"ROOT_MUTATION\",\n // The cache complains if passed a mutation where it expects a\n // query, so we transform mutations and subscriptions to queries\n // (only once, thanks to this.transformCache).\n query: this.getDocumentInfo(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n\n if (diff.complete) {\n result = { ...(result as FetchResult), data: diff.result };\n if (\"incremental\" in result) {\n delete result.incremental;\n }\n if (\"hasNext\" in result) {\n delete result.hasNext;\n }\n }\n }\n\n // If we've received the whole response,\n // either a SingleExecutionResult or the final ExecutionPatchResult,\n // call the update function.\n if (isFinalResult) {\n update(cache as TCache, result, {\n context: mutation.context,\n variables: mutation.variables,\n });\n }\n }\n\n // TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it\n // shallow to allow rolling back optimistic evictions.\n if (!skipCache && !mutation.keepRootFields && isFinalResult) {\n cache.modify({\n id: \"ROOT_MUTATION\",\n fields(value, { fieldName, DELETE }) {\n return fieldName === \"__typename\" ? value : DELETE;\n },\n });\n }\n },\n\n include: mutation.refetchQueries,\n\n // Write the final mutation.result to the root layer of the cache.\n optimistic: false,\n\n // Remove the corresponding optimistic layer at the same time as we\n // write the final non-optimistic result.\n removeOptimistic: mutation.removeOptimistic,\n\n // Let the caller of client.mutate optionally determine the refetching\n // behavior for watched queries after the mutation.update function runs.\n // If no onQueryUpdated function was provided for this mutation, pass\n // null instead of undefined to disable the default refetching behavior.\n onQueryUpdated: mutation.onQueryUpdated || null,\n }).forEach((result) => results.push(result));\n\n if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {\n // Returning a promise here makes the mutation await that promise, so we\n // include results in that promise's work if awaitRefetchQueries or an\n // onQueryUpdated function was specified.\n return Promise.all(results).then(() => result);\n }\n }\n\n return Promise.resolve(result);\n }\n\n public markMutationOptimistic<\n TData,\n TVariables,\n TContext,\n TCache extends ApolloCache,\n >(\n optimisticResponse: any,\n mutation: {\n mutationId: string;\n document: DocumentNode;\n variables?: TVariables;\n fetchPolicy?: MutationFetchPolicy;\n errorPolicy: ErrorPolicy;\n context?: TContext;\n updateQueries: UpdateQueries;\n update?: MutationUpdaterFunction;\n keepRootFields?: boolean;\n }\n ) {\n const data =\n typeof optimisticResponse === \"function\" ?\n optimisticResponse(mutation.variables, { IGNORE })\n : optimisticResponse;\n\n if (data === IGNORE) {\n return false;\n }\n\n this.cache.recordOptimisticTransaction((cache) => {\n try {\n this.markMutationResult(\n {\n ...mutation,\n result: { data },\n },\n cache\n );\n } catch (error) {\n invariant.error(error);\n }\n }, mutation.mutationId);\n\n return true;\n }\n\n public fetchQuery(\n queryId: string,\n options: WatchQueryOptions,\n networkStatus?: NetworkStatus\n ): Promise> {\n return this.fetchConcastWithInfo(queryId, options, networkStatus).concast\n .promise as TODO;\n }\n\n public getQueryStore() {\n const store: Record = Object.create(null);\n this.queries.forEach((info, queryId) => {\n store[queryId] = {\n variables: info.variables,\n networkStatus: info.networkStatus,\n networkError: info.networkError,\n graphQLErrors: info.graphQLErrors,\n };\n });\n return store;\n }\n\n public resetErrors(queryId: string) {\n const queryInfo = this.queries.get(queryId);\n if (queryInfo) {\n queryInfo.networkError = undefined;\n queryInfo.graphQLErrors = [];\n }\n }\n\n public transform(document: DocumentNode) {\n return this.documentTransform.transformDocument(document);\n }\n\n private transformCache = new AutoCleanedWeakCache<\n DocumentNode,\n TransformCacheEntry\n >(\n cacheSizes[\"queryManager.getDocumentInfo\"] ||\n defaultCacheSizes[\"queryManager.getDocumentInfo\"]\n );\n\n public getDocumentInfo(document: DocumentNode) {\n const { transformCache } = this;\n\n if (!transformCache.has(document)) {\n const cacheEntry: TransformCacheEntry = {\n // TODO These three calls (hasClientExports, shouldForceResolvers, and\n // usesNonreactiveDirective) are performing independent full traversals\n // of the transformed document. We should consider merging these\n // traversals into a single pass in the future, though the work is\n // cached after the first time.\n hasClientExports: hasClientExports(document),\n hasForcedResolvers: this.localState.shouldForceResolvers(document),\n hasNonreactiveDirective: hasDirectives([\"nonreactive\"], document),\n clientQuery: this.localState.clientQuery(document),\n serverQuery: removeDirectivesFromDocument(\n [\n { name: \"client\", remove: true },\n { name: \"connection\" },\n { name: \"nonreactive\" },\n ],\n document\n ),\n defaultVars: getDefaultValues(\n getOperationDefinition(document)\n ) as OperationVariables,\n // Transform any mutation or subscription operations to query operations\n // so we can read/write them from/to the cache.\n asQuery: {\n ...document,\n definitions: document.definitions.map((def) => {\n if (\n def.kind === \"OperationDefinition\" &&\n def.operation !== \"query\"\n ) {\n return { ...def, operation: \"query\" as OperationTypeNode };\n }\n return def;\n }),\n },\n };\n\n transformCache.set(document, cacheEntry);\n }\n\n return transformCache.get(document)!;\n }\n\n private getVariables(\n document: DocumentNode,\n variables?: TVariables\n ): OperationVariables {\n return {\n ...this.getDocumentInfo(document).defaultVars,\n ...variables,\n };\n }\n\n public watchQuery<\n T,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions): ObservableQuery {\n const query = this.transform(options.query);\n\n // assign variable default values if supplied\n // NOTE: We don't modify options.query here with the transformed query to\n // ensure observable.options.query is set to the raw untransformed query.\n options = {\n ...options,\n variables: this.getVariables(query, options.variables) as TVariables,\n };\n\n if (typeof options.notifyOnNetworkStatusChange === \"undefined\") {\n options.notifyOnNetworkStatusChange = false;\n }\n\n const queryInfo = new QueryInfo(this);\n const observable = new ObservableQuery({\n queryManager: this,\n queryInfo,\n options,\n });\n observable[\"lastQuery\"] = query;\n\n this.queries.set(observable.queryId, queryInfo);\n\n // We give queryInfo the transformed query to ensure the first cache diff\n // uses the transformed query instead of the raw query\n queryInfo.init({\n document: query,\n observableQuery: observable,\n variables: observable.variables,\n });\n\n return observable;\n }\n\n public query(\n options: QueryOptions,\n queryId = this.generateQueryId()\n ): Promise> {\n invariant(\n options.query,\n \"query option is required. You must specify your GraphQL document \" +\n \"in the query option.\"\n );\n\n invariant(\n options.query.kind === \"Document\",\n 'You must wrap the query string in a \"gql\" tag.'\n );\n\n invariant(\n !(options as any).returnPartialData,\n \"returnPartialData option only supported on watchQuery.\"\n );\n\n invariant(\n !(options as any).pollInterval,\n \"pollInterval option only supported on watchQuery.\"\n );\n\n return this.fetchQuery(queryId, {\n ...options,\n query: this.transform(options.query),\n }).finally(() => this.stopQuery(queryId));\n }\n\n private queryIdCounter = 1;\n public generateQueryId() {\n return String(this.queryIdCounter++);\n }\n\n private requestIdCounter = 1;\n public generateRequestId() {\n return this.requestIdCounter++;\n }\n\n private mutationIdCounter = 1;\n public generateMutationId() {\n return String(this.mutationIdCounter++);\n }\n\n public stopQueryInStore(queryId: string) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.broadcastQueries();\n }\n\n private stopQueryInStoreNoBroadcast(queryId: string) {\n const queryInfo = this.queries.get(queryId);\n if (queryInfo) queryInfo.stop();\n }\n\n public clearStore(\n options: Cache.ResetOptions = {\n discardWatches: true,\n }\n ): Promise {\n // Before we have sent the reset action to the store, we can no longer\n // rely on the results returned by in-flight requests since these may\n // depend on values that previously existed in the data portion of the\n // store. So, we cancel the promises and observers that we have issued\n // so far and not yet resolved (in the case of queries).\n this.cancelPendingFetches(\n newInvariantError(\n \"Store reset while query was in flight (not completed in link chain)\"\n )\n );\n\n this.queries.forEach((queryInfo) => {\n if (queryInfo.observableQuery) {\n // Set loading to true so listeners don't trigger unless they want\n // results with partial data.\n queryInfo.networkStatus = NetworkStatus.loading;\n } else {\n queryInfo.stop();\n }\n });\n\n if (this.mutationStore) {\n this.mutationStore = Object.create(null);\n }\n\n // begin removing data from the store\n return this.cache.reset(options);\n }\n\n public getObservableQueries(\n include: InternalRefetchQueriesInclude = \"active\"\n ) {\n const queries = new Map>();\n const queryNamesAndDocs = new Map();\n const legacyQueryOptions = new Set();\n\n if (Array.isArray(include)) {\n include.forEach((desc) => {\n if (typeof desc === \"string\") {\n queryNamesAndDocs.set(desc, false);\n } else if (isDocumentNode(desc)) {\n queryNamesAndDocs.set(this.transform(desc), false);\n } else if (isNonNullObject(desc) && desc.query) {\n legacyQueryOptions.add(desc);\n }\n });\n }\n\n this.queries.forEach(({ observableQuery: oq, document }, queryId) => {\n if (oq) {\n if (include === \"all\") {\n queries.set(queryId, oq);\n return;\n }\n\n const {\n queryName,\n options: { fetchPolicy },\n } = oq;\n\n if (\n fetchPolicy === \"standby\" ||\n (include === \"active\" && !oq.hasObservers())\n ) {\n return;\n }\n\n if (\n include === \"active\" ||\n (queryName && queryNamesAndDocs.has(queryName)) ||\n (document && queryNamesAndDocs.has(document))\n ) {\n queries.set(queryId, oq);\n if (queryName) queryNamesAndDocs.set(queryName, true);\n if (document) queryNamesAndDocs.set(document, true);\n }\n }\n });\n\n if (legacyQueryOptions.size) {\n legacyQueryOptions.forEach((options: QueryOptions) => {\n // We will be issuing a fresh network request for this query, so we\n // pre-allocate a new query ID here, using a special prefix to enable\n // cleaning up these temporary queries later, after fetching.\n const queryId = makeUniqueId(\"legacyOneTimeQuery\");\n const queryInfo = this.getQuery(queryId).init({\n document: options.query,\n variables: options.variables,\n });\n const oq = new ObservableQuery({\n queryManager: this,\n queryInfo,\n options: {\n ...options,\n fetchPolicy: \"network-only\",\n },\n });\n invariant(oq.queryId === queryId);\n queryInfo.setObservableQuery(oq);\n queries.set(queryId, oq);\n });\n }\n\n if (__DEV__ && queryNamesAndDocs.size) {\n queryNamesAndDocs.forEach((included, nameOrDoc) => {\n if (!included) {\n invariant.warn(\n typeof nameOrDoc === \"string\" ?\n `Unknown query named \"%s\" requested in refetchQueries options.include array`\n : `Unknown query %o requested in refetchQueries options.include array`,\n nameOrDoc\n );\n }\n });\n }\n\n return queries;\n }\n\n public reFetchObservableQueries(\n includeStandby: boolean = false\n ): Promise[]> {\n const observableQueryPromises: Promise>[] = [];\n\n this.getObservableQueries(includeStandby ? \"all\" : \"active\").forEach(\n (observableQuery, queryId) => {\n const { fetchPolicy } = observableQuery.options;\n observableQuery.resetLastResults();\n if (\n includeStandby ||\n (fetchPolicy !== \"standby\" && fetchPolicy !== \"cache-only\")\n ) {\n observableQueryPromises.push(observableQuery.refetch());\n }\n this.getQuery(queryId).setDiff(null);\n }\n );\n\n this.broadcastQueries();\n\n return Promise.all(observableQueryPromises);\n }\n\n public setObservableQuery(observableQuery: ObservableQuery) {\n this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);\n }\n\n public startGraphQLSubscription({\n query,\n fetchPolicy,\n errorPolicy = \"none\",\n variables,\n context = {},\n }: SubscriptionOptions): Observable> {\n query = this.transform(query);\n variables = this.getVariables(query, variables);\n\n const makeObservable = (variables: OperationVariables) =>\n this.getObservableFromLink(query, context, variables).map((result) => {\n if (fetchPolicy !== \"no-cache\") {\n // the subscription interface should handle not sending us results we no longer subscribe to.\n // XXX I don't think we ever send in an object with errors, but we might in the future...\n if (shouldWriteResult(result, errorPolicy)) {\n this.cache.write({\n query,\n result: result.data,\n dataId: \"ROOT_SUBSCRIPTION\",\n variables: variables,\n });\n }\n\n this.broadcastQueries();\n }\n\n const hasErrors = graphQLResultHasError(result);\n const hasProtocolErrors = graphQLResultHasProtocolErrors(result);\n if (hasErrors || hasProtocolErrors) {\n const errors: ApolloErrorOptions = {};\n if (hasErrors) {\n errors.graphQLErrors = result.errors;\n }\n if (hasProtocolErrors) {\n errors.protocolErrors = result.extensions[PROTOCOL_ERRORS_SYMBOL];\n }\n\n // `errorPolicy` is a mechanism for handling GraphQL errors, according\n // to our documentation, so we throw protocol errors regardless of the\n // set error policy.\n if (errorPolicy === \"none\" || hasProtocolErrors) {\n throw new ApolloError(errors);\n }\n }\n\n if (errorPolicy === \"ignore\") {\n delete result.errors;\n }\n\n return result;\n });\n\n if (this.getDocumentInfo(query).hasClientExports) {\n const observablePromise = this.localState\n .addExportedVariables(query, variables, context)\n .then(makeObservable);\n\n return new Observable>((observer) => {\n let sub: ObservableSubscription | null = null;\n observablePromise.then(\n (observable) => (sub = observable.subscribe(observer)),\n observer.error\n );\n return () => sub && sub.unsubscribe();\n });\n }\n\n return makeObservable(variables);\n }\n\n public stopQuery(queryId: string) {\n this.stopQueryNoBroadcast(queryId);\n this.broadcastQueries();\n }\n\n private stopQueryNoBroadcast(queryId: string) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.removeQuery(queryId);\n }\n\n public removeQuery(queryId: string) {\n // teardown all links\n // Both `QueryManager.fetchRequest` and `QueryManager.query` create separate promises\n // that each add their reject functions to fetchCancelFns.\n // A query created with `QueryManager.query()` could trigger a `QueryManager.fetchRequest`.\n // The same queryId could have two rejection fns for two promises\n this.fetchCancelFns.delete(queryId);\n if (this.queries.has(queryId)) {\n this.getQuery(queryId).stop();\n this.queries.delete(queryId);\n }\n }\n\n public broadcastQueries() {\n if (this.onBroadcast) this.onBroadcast();\n this.queries.forEach((info) => info.notify());\n }\n\n public getLocalState(): LocalState {\n return this.localState;\n }\n\n // Use protected instead of private field so\n // @apollo/experimental-nextjs-app-support can access type info.\n protected inFlightLinkObservables = new Trie<{\n observable?: Observable>;\n }>(false);\n\n private getObservableFromLink(\n query: DocumentNode,\n context: any,\n variables?: OperationVariables,\n // Prefer context.queryDeduplication if specified.\n deduplication: boolean = context?.queryDeduplication ??\n this.queryDeduplication\n ): Observable> {\n let observable: Observable> | undefined;\n\n const { serverQuery, clientQuery } = this.getDocumentInfo(query);\n if (serverQuery) {\n const { inFlightLinkObservables, link } = this;\n\n const operation = {\n query: serverQuery,\n variables,\n operationName: getOperationName(serverQuery) || void 0,\n context: this.prepareContext({\n ...context,\n forceFetch: !deduplication,\n }),\n };\n\n context = operation.context;\n\n if (deduplication) {\n const printedServerQuery = print(serverQuery);\n const varJson = canonicalStringify(variables);\n\n const entry = inFlightLinkObservables.lookup(\n printedServerQuery,\n varJson\n );\n\n observable = entry.observable;\n if (!observable) {\n const concast = new Concast([\n execute(link, operation) as Observable>,\n ]);\n observable = entry.observable = concast;\n\n concast.beforeNext(() => {\n inFlightLinkObservables.remove(printedServerQuery, varJson);\n });\n }\n } else {\n observable = new Concast([\n execute(link, operation) as Observable>,\n ]);\n }\n } else {\n observable = new Concast([Observable.of({ data: {} } as FetchResult)]);\n context = this.prepareContext(context);\n }\n\n if (clientQuery) {\n observable = asyncMap(observable, (result) => {\n return this.localState.runResolvers({\n document: clientQuery,\n remoteResult: result,\n context,\n variables,\n });\n });\n }\n\n return observable;\n }\n\n private getResultsFromLink(\n queryInfo: QueryInfo,\n cacheWriteBehavior: CacheWriteBehavior,\n options: Pick<\n WatchQueryOptions,\n \"query\" | \"variables\" | \"context\" | \"fetchPolicy\" | \"errorPolicy\"\n >\n ): Observable> {\n const requestId = (queryInfo.lastRequestId = this.generateRequestId());\n\n // Performing transformForLink here gives this.cache a chance to fill in\n // missing fragment definitions (for example) before sending this document\n // through the link chain.\n const linkDocument = this.cache.transformForLink(options.query);\n\n return asyncMap(\n this.getObservableFromLink(\n linkDocument,\n options.context,\n options.variables\n ),\n\n (result) => {\n const graphQLErrors = getGraphQLErrorsFromResult(result);\n const hasErrors = graphQLErrors.length > 0;\n\n // If we interrupted this request by calling getResultsFromLink again\n // with the same QueryInfo object, we ignore the old results.\n if (requestId >= queryInfo.lastRequestId) {\n if (hasErrors && options.errorPolicy === \"none\") {\n // Throwing here effectively calls observer.error.\n throw queryInfo.markError(\n new ApolloError({\n graphQLErrors,\n })\n );\n }\n // Use linkDocument rather than queryInfo.document so the\n // operation/fragments used to write the result are the same as the\n // ones used to obtain it from the link.\n queryInfo.markResult(\n result,\n linkDocument,\n options,\n cacheWriteBehavior\n );\n queryInfo.markReady();\n }\n\n const aqr: ApolloQueryResult = {\n data: result.data,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n\n if (hasErrors && options.errorPolicy !== \"ignore\") {\n aqr.errors = graphQLErrors;\n aqr.networkStatus = NetworkStatus.error;\n }\n\n return aqr;\n },\n\n (networkError) => {\n const error =\n isApolloError(networkError) ? networkError : (\n new ApolloError({ networkError })\n );\n\n // Avoid storing errors from older interrupted queries.\n if (requestId >= queryInfo.lastRequestId) {\n queryInfo.markError(error);\n }\n\n throw error;\n }\n );\n }\n\n private fetchConcastWithInfo(\n queryId: string,\n options: WatchQueryOptions,\n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus = NetworkStatus.loading,\n query = options.query\n ): ConcastAndInfo {\n const variables = this.getVariables(query, options.variables) as TVars;\n const queryInfo = this.getQuery(queryId);\n\n const defaults = this.defaultOptions.watchQuery;\n let {\n fetchPolicy = (defaults && defaults.fetchPolicy) || \"cache-first\",\n errorPolicy = (defaults && defaults.errorPolicy) || \"none\",\n returnPartialData = false,\n notifyOnNetworkStatusChange = false,\n context = {},\n } = options;\n\n const normalized = Object.assign({}, options, {\n query,\n variables,\n fetchPolicy,\n errorPolicy,\n returnPartialData,\n notifyOnNetworkStatusChange,\n context,\n });\n\n const fromVariables = (variables: TVars) => {\n // Since normalized is always a fresh copy of options, it's safe to\n // modify its properties here, rather than creating yet another new\n // WatchQueryOptions object.\n normalized.variables = variables;\n\n const sourcesWithInfo = this.fetchQueryByPolicy(\n queryInfo,\n normalized,\n networkStatus\n );\n\n if (\n // If we're in standby, postpone advancing options.fetchPolicy using\n // applyNextFetchPolicy.\n normalized.fetchPolicy !== \"standby\" &&\n // The \"standby\" policy currently returns [] from fetchQueryByPolicy, so\n // this is another way to detect when nothing was done/fetched.\n sourcesWithInfo.sources.length > 0 &&\n queryInfo.observableQuery\n ) {\n queryInfo.observableQuery[\"applyNextFetchPolicy\"](\n \"after-fetch\",\n options\n );\n }\n\n return sourcesWithInfo;\n };\n\n // This cancel function needs to be set before the concast is created,\n // in case concast creation synchronously cancels the request.\n const cleanupCancelFn = () => this.fetchCancelFns.delete(queryId);\n this.fetchCancelFns.set(queryId, (reason) => {\n cleanupCancelFn();\n // This delay ensures the concast variable has been initialized.\n setTimeout(() => concast.cancel(reason));\n });\n\n let concast: Concast>,\n containsDataFromLink: boolean;\n // If the query has @export(as: ...) directives, then we need to\n // process those directives asynchronously. When there are no\n // @export directives (the common case), we deliberately avoid\n // wrapping the result of this.fetchQueryByPolicy in a Promise,\n // since the timing of result delivery is (unfortunately) important\n // for backwards compatibility. TODO This code could be simpler if\n // we deprecated and removed LocalState.\n if (this.getDocumentInfo(normalized.query).hasClientExports) {\n concast = new Concast(\n this.localState\n .addExportedVariables(\n normalized.query,\n normalized.variables,\n normalized.context\n )\n .then(fromVariables)\n .then((sourcesWithInfo) => sourcesWithInfo.sources)\n );\n // there is just no way we can synchronously get the *right* value here,\n // so we will assume `true`, which is the behaviour before the bug fix in\n // #10597. This means that bug is not fixed in that case, and is probably\n // un-fixable with reasonable effort for the edge case of @export as\n // directives.\n containsDataFromLink = true;\n } else {\n const sourcesWithInfo = fromVariables(normalized.variables);\n containsDataFromLink = sourcesWithInfo.fromLink;\n concast = new Concast(sourcesWithInfo.sources);\n }\n\n concast.promise.then(cleanupCancelFn, cleanupCancelFn);\n\n return {\n concast,\n fromLink: containsDataFromLink,\n };\n }\n\n public refetchQueries({\n updateCache,\n include,\n optimistic = false,\n removeOptimistic = optimistic ? makeUniqueId(\"refetchQueries\") : void 0,\n onQueryUpdated,\n }: InternalRefetchQueriesOptions<\n ApolloCache,\n TResult\n >): InternalRefetchQueriesMap {\n const includedQueriesById = new Map<\n string,\n {\n oq: ObservableQuery;\n lastDiff?: Cache.DiffResult;\n diff?: Cache.DiffResult;\n }\n >();\n\n if (include) {\n this.getObservableQueries(include).forEach((oq, queryId) => {\n includedQueriesById.set(queryId, {\n oq,\n lastDiff: this.getQuery(queryId).getDiff(),\n });\n });\n }\n\n const results: InternalRefetchQueriesMap = new Map();\n\n if (updateCache) {\n this.cache.batch({\n update: updateCache,\n\n // Since you can perform any combination of cache reads and/or writes in\n // the cache.batch update function, its optimistic option can be either\n // a boolean or a string, representing three distinct modes of\n // operation:\n //\n // * false: read/write only the root layer\n // * true: read/write the topmost layer\n // * string: read/write a fresh optimistic layer with that ID string\n //\n // When typeof optimistic === \"string\", a new optimistic layer will be\n // temporarily created within cache.batch with that string as its ID. If\n // we then pass that same string as the removeOptimistic option, we can\n // make cache.batch immediately remove the optimistic layer after\n // running the updateCache function, triggering only one broadcast.\n //\n // However, the refetchQueries method accepts only true or false for its\n // optimistic option (not string). We interpret true to mean a temporary\n // optimistic layer should be created, to allow efficiently rolling back\n // the effect of the updateCache function, which involves passing a\n // string instead of true as the optimistic option to cache.batch, when\n // refetchQueries receives optimistic: true.\n //\n // In other words, we are deliberately not supporting the use case of\n // writing to an *existing* optimistic layer (using the refetchQueries\n // updateCache function), since that would potentially interfere with\n // other optimistic updates in progress. Instead, you can read/write\n // only the root layer by passing optimistic: false to refetchQueries,\n // or you can read/write a brand new optimistic layer that will be\n // automatically removed by passing optimistic: true.\n optimistic: (optimistic && removeOptimistic) || false,\n\n // The removeOptimistic option can also be provided by itself, even if\n // optimistic === false, to remove some previously-added optimistic\n // layer safely and efficiently, like we do in markMutationResult.\n //\n // If an explicit removeOptimistic string is provided with optimistic:\n // true, the removeOptimistic string will determine the ID of the\n // temporary optimistic layer, in case that ever matters.\n removeOptimistic,\n\n onWatchUpdated(watch, diff, lastDiff) {\n const oq =\n watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;\n\n if (oq) {\n if (onQueryUpdated) {\n // Since we're about to handle this query now, remove it from\n // includedQueriesById, in case it was added earlier because of\n // options.include.\n includedQueriesById.delete(oq.queryId);\n\n let result: TResult | boolean | Promise> =\n onQueryUpdated(oq, diff, lastDiff);\n\n if (result === true) {\n // The onQueryUpdated function requested the default refetching\n // behavior by returning true.\n result = oq.refetch();\n }\n\n // Record the result in the results Map, as long as onQueryUpdated\n // did not return false to skip/ignore this result.\n if (result !== false) {\n results.set(\n oq,\n result as InternalRefetchQueriesResult\n );\n }\n\n // Allow the default cache broadcast to happen, except when\n // onQueryUpdated returns false.\n return result;\n }\n\n if (onQueryUpdated !== null) {\n // If we don't have an onQueryUpdated function, and onQueryUpdated\n // was not disabled by passing null, make sure this query is\n // \"included\" like any other options.include-specified query.\n includedQueriesById.set(oq.queryId, { oq, lastDiff, diff });\n }\n }\n },\n });\n }\n\n if (includedQueriesById.size) {\n includedQueriesById.forEach(({ oq, lastDiff, diff }, queryId) => {\n let result:\n | TResult\n | boolean\n | Promise>\n | undefined;\n\n // If onQueryUpdated is provided, we want to use it for all included\n // queries, even the QueryOptions ones.\n if (onQueryUpdated) {\n if (!diff) {\n const info = oq[\"queryInfo\"];\n info.reset(); // Force info.getDiff() to read from cache.\n diff = info.getDiff();\n }\n result = onQueryUpdated(oq, diff, lastDiff);\n }\n\n // Otherwise, we fall back to refetching.\n if (!onQueryUpdated || result === true) {\n result = oq.refetch();\n }\n\n if (result !== false) {\n results.set(oq, result as InternalRefetchQueriesResult);\n }\n\n if (queryId.indexOf(\"legacyOneTimeQuery\") >= 0) {\n this.stopQueryNoBroadcast(queryId);\n }\n });\n }\n\n if (removeOptimistic) {\n // In case no updateCache callback was provided (so cache.batch was not\n // called above, and thus did not already remove the optimistic layer),\n // remove it here. Since this is a no-op when the layer has already been\n // removed, we do it even if we called cache.batch above, since it's\n // possible this.cache is an instance of some ApolloCache subclass other\n // than InMemoryCache, and does not fully support the removeOptimistic\n // option for cache.batch.\n this.cache.removeOptimistic(removeOptimistic);\n }\n\n return results;\n }\n\n private fetchQueryByPolicy(\n queryInfo: QueryInfo,\n {\n query,\n variables,\n fetchPolicy,\n refetchWritePolicy,\n errorPolicy,\n returnPartialData,\n context,\n notifyOnNetworkStatusChange,\n }: WatchQueryOptions,\n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus: NetworkStatus\n ): SourcesAndInfo {\n const oldNetworkStatus = queryInfo.networkStatus;\n\n queryInfo.init({\n document: query,\n variables,\n networkStatus,\n });\n\n const readCache = () => queryInfo.getDiff();\n\n const resultsFromCache = (\n diff: Cache.DiffResult,\n networkStatus = queryInfo.networkStatus || NetworkStatus.loading\n ) => {\n const data = diff.result;\n\n if (__DEV__ && !returnPartialData && !equal(data, {})) {\n logMissingFieldErrors(diff.missing);\n }\n\n const fromData = (data: TData | undefined) =>\n Observable.of({\n data,\n loading: isNetworkRequestInFlight(networkStatus),\n networkStatus,\n ...(diff.complete ? null : { partial: true }),\n } as ApolloQueryResult);\n\n if (data && this.getDocumentInfo(query).hasForcedResolvers) {\n return this.localState\n .runResolvers({\n document: query,\n remoteResult: { data },\n context,\n variables,\n onlyRunForcedResolvers: true,\n })\n .then((resolved) => fromData(resolved.data || void 0));\n }\n\n // Resolves https://github.com/apollographql/apollo-client/issues/10317.\n // If errorPolicy is 'none' and notifyOnNetworkStatusChange is true,\n // data was incorrectly returned from the cache on refetch:\n // if diff.missing exists, we should not return cache data.\n if (\n errorPolicy === \"none\" &&\n networkStatus === NetworkStatus.refetch &&\n Array.isArray(diff.missing)\n ) {\n return fromData(void 0);\n }\n\n return fromData(data);\n };\n\n const cacheWriteBehavior =\n fetchPolicy === \"no-cache\" ? CacheWriteBehavior.FORBID\n // Watched queries must opt into overwriting existing data on refetch,\n // by passing refetchWritePolicy: \"overwrite\" in their WatchQueryOptions.\n : (\n networkStatus === NetworkStatus.refetch &&\n refetchWritePolicy !== \"merge\"\n ) ?\n CacheWriteBehavior.OVERWRITE\n : CacheWriteBehavior.MERGE;\n\n const resultsFromLink = () =>\n this.getResultsFromLink(queryInfo, cacheWriteBehavior, {\n query,\n variables,\n context,\n fetchPolicy,\n errorPolicy,\n });\n\n const shouldNotify =\n notifyOnNetworkStatusChange &&\n typeof oldNetworkStatus === \"number\" &&\n oldNetworkStatus !== networkStatus &&\n isNetworkRequestInFlight(networkStatus);\n\n switch (fetchPolicy) {\n default:\n case \"cache-first\": {\n const diff = readCache();\n\n if (diff.complete) {\n return {\n fromLink: false,\n sources: [resultsFromCache(diff, queryInfo.markReady())],\n };\n }\n\n if (returnPartialData || shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(diff), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n }\n\n case \"cache-and-network\": {\n const diff = readCache();\n\n if (diff.complete || returnPartialData || shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(diff), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n }\n\n case \"cache-only\":\n return {\n fromLink: false,\n sources: [resultsFromCache(readCache(), queryInfo.markReady())],\n };\n\n case \"network-only\":\n if (shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(readCache()), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n\n case \"no-cache\":\n if (shouldNotify) {\n return {\n fromLink: true,\n // Note that queryInfo.getDiff() for no-cache queries does not call\n // cache.diff, but instead returns a { complete: false } stub result\n // when there is no queryInfo.diff already defined.\n sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n\n case \"standby\":\n return { fromLink: false, sources: [] };\n }\n }\n\n private getQuery(queryId: string): QueryInfo {\n if (queryId && !this.queries.has(queryId)) {\n this.queries.set(queryId, new QueryInfo(this, queryId));\n }\n return this.queries.get(queryId)!;\n }\n\n private prepareContext(context = {}) {\n const newContext = this.localState.prepareContext(context);\n return {\n ...this.defaultContext,\n ...newContext,\n clientAwareness: this.clientAwareness,\n };\n }\n}\n\n// Return types used by fetchQueryByPolicy and other private methods above.\ninterface FetchConcastInfo {\n // Metadata properties that can be returned in addition to the Concast.\n fromLink: boolean;\n}\ninterface SourcesAndInfo extends FetchConcastInfo {\n sources: ConcastSourcesArray>;\n}\ninterface ConcastAndInfo extends FetchConcastInfo {\n concast: Concast>;\n}\n","import { DataProxy } from \"./DataProxy.js\";\nimport type { AllFieldsModifier, Modifiers } from \"./common.js\";\nimport type { ApolloCache } from \"../cache.js\";\n\nexport namespace Cache {\n export type WatchCallback = (\n diff: Cache.DiffResult,\n lastDiff?: Cache.DiffResult\n ) => void;\n\n export interface ReadOptions\n extends DataProxy.Query {\n rootId?: string;\n previousResult?: any;\n optimistic: boolean;\n returnPartialData?: boolean;\n /**\n * @deprecated\n * Using `canonizeResults` can result in memory leaks so we generally do not\n * recommend using this option anymore.\n * A future version of Apollo Client will contain a similar feature without\n * the risk of memory leaks.\n */\n canonizeResults?: boolean;\n }\n\n export interface WriteOptions\n extends Omit, \"id\">,\n Omit, \"data\"> {\n dataId?: string;\n result: TResult;\n }\n\n export interface DiffOptions\n extends Omit, \"rootId\"> {\n // The DiffOptions interface is currently just an alias for\n // ReadOptions, though DiffOptions used to be responsible for\n // declaring the returnPartialData option.\n }\n\n export interface WatchOptions\n extends DiffOptions {\n watcher?: object;\n immediate?: boolean;\n callback: WatchCallback;\n lastDiff?: DiffResult;\n }\n\n export interface EvictOptions {\n id?: string;\n fieldName?: string;\n args?: Record;\n broadcast?: boolean;\n }\n\n // Although you can call cache.reset() without options, its behavior can be\n // configured by passing a Cache.ResetOptions object.\n export interface ResetOptions {\n discardWatches?: boolean;\n }\n\n export interface ModifyOptions<\n Entity extends Record = Record,\n > {\n id?: string;\n fields: Modifiers | AllFieldsModifier;\n optimistic?: boolean;\n broadcast?: boolean;\n }\n\n export interface BatchOptions<\n TCache extends ApolloCache,\n TUpdateResult = void,\n > {\n // Same as the first parameter of performTransaction, except the cache\n // argument will have the subclass type rather than ApolloCache.\n update(cache: TCache): TUpdateResult;\n\n // Passing a string for this option creates a new optimistic layer, with the\n // given string as its layer.id, just like passing a string for the\n // optimisticId parameter of performTransaction. Passing true is the same as\n // passing undefined to performTransaction (running the batch operation\n // against the current top layer of the cache), and passing false is the\n // same as passing null (running the operation against root/non-optimistic\n // cache data).\n optimistic?: string | boolean;\n\n // If you specify the ID of an optimistic layer using this option, that\n // layer will be removed as part of the batch transaction, triggering at\n // most one broadcast for both the transaction and the removal of the layer.\n // Note: this option is needed because calling cache.removeOptimistic during\n // the transaction function may not be not safe, since any modifications to\n // cache layers may be discarded after the transaction finishes.\n removeOptimistic?: string;\n\n // If you want to find out which watched queries were invalidated during\n // this batch operation, pass this optional callback function. Returning\n // false from the callback will prevent broadcasting this result.\n onWatchUpdated?: (\n this: TCache,\n watch: Cache.WatchOptions,\n diff: Cache.DiffResult,\n lastDiff?: Cache.DiffResult | undefined\n ) => any;\n }\n\n export import DiffResult = DataProxy.DiffResult;\n export import ReadQueryOptions = DataProxy.ReadQueryOptions;\n export import ReadFragmentOptions = DataProxy.ReadFragmentOptions;\n export import WriteQueryOptions = DataProxy.WriteQueryOptions;\n export import WriteFragmentOptions = DataProxy.WriteFragmentOptions;\n export import UpdateQueryOptions = DataProxy.UpdateQueryOptions;\n export import UpdateFragmentOptions = DataProxy.UpdateFragmentOptions;\n export import Fragment = DataProxy.Fragment;\n}\n","import { invariant, newInvariantError } from \"../utilities/globals/index.js\";\n\nimport type { ExecutionResult, DocumentNode } from \"graphql\";\n\nimport type { FetchResult, GraphQLRequest } from \"../link/core/index.js\";\nimport { ApolloLink, execute } from \"../link/core/index.js\";\nimport type { ApolloCache, DataProxy, Reference } from \"../cache/index.js\";\nimport type { DocumentTransform, Observable } from \"../utilities/index.js\";\nimport { version } from \"../version.js\";\nimport type { UriFunction } from \"../link/http/index.js\";\nimport { HttpLink } from \"../link/http/index.js\";\n\nimport { QueryManager } from \"./QueryManager.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\n\nimport type {\n ApolloQueryResult,\n DefaultContext,\n OperationVariables,\n Resolvers,\n RefetchQueriesOptions,\n RefetchQueriesResult,\n InternalRefetchQueriesResult,\n RefetchQueriesInclude,\n} from \"./types.js\";\n\nimport type {\n QueryOptions,\n WatchQueryOptions,\n MutationOptions,\n SubscriptionOptions,\n WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\n\nimport type { FragmentMatcher } from \"./LocalState.js\";\nimport { LocalState } from \"./LocalState.js\";\n\nexport interface DefaultOptions {\n watchQuery?: Partial>;\n query?: Partial>;\n mutate?: Partial>;\n}\n\nlet hasSuggestedDevtools = false;\n\nexport interface ApolloClientOptions {\n /**\n * The URI of the GraphQL endpoint that Apollo Client will communicate with.\n *\n * One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.\n */\n uri?: string | UriFunction;\n credentials?: string;\n /**\n * An object representing headers to include in every HTTP request, such as `{Authorization: 'Bearer 1234'}`\n *\n * This value will be ignored when using the `link` option.\n */\n headers?: Record;\n /**\n * You can provide an `ApolloLink` instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).\n *\n * One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.\n */\n link?: ApolloLink;\n /**\n * The cache that Apollo Client should use to store query results locally. The recommended cache is `InMemoryCache`, which is provided by the `@apollo/client` package.\n *\n * For more information, see [Configuring the cache](https://www.apollographql.com/docs/react/caching/cache-configuration/).\n */\n cache: ApolloCache;\n /**\n * The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.\n *\n * @defaultValue `0` (no delay)\n */\n ssrForceFetchDelay?: number;\n /**\n * When using Apollo Client for [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/), set this to `true` so that the [`getDataFromTree` function](../react/ssr/#getdatafromtree) can work effectively.\n *\n * @defaultValue `false`\n */\n ssrMode?: boolean;\n /**\n * If `true`, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to Apollo Client.\n *\n * The default value is `false` in production and `true` in development (if there is a `window` object).\n */\n connectToDevTools?: boolean;\n /**\n * If `false`, Apollo Client sends every created query to the server, even if a _completely_ identical query (identical in terms of query string, variable values, and operationName) is already in flight.\n *\n * @defaultValue `true`\n */\n queryDeduplication?: boolean;\n /**\n * Provide this object to set application-wide default values for options you can provide to the `watchQuery`, `query`, and `mutate` functions. See below for an example object.\n *\n * See this [example object](https://www.apollographql.com/docs/react/api/core/ApolloClient#example-defaultoptions-object).\n */\n defaultOptions?: DefaultOptions;\n defaultContext?: Partial;\n /**\n * If `true`, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.\n *\n * @defaultValue `false`\n */\n assumeImmutableResults?: boolean;\n resolvers?: Resolvers | Resolvers[];\n typeDefs?: string | string[] | DocumentNode | DocumentNode[];\n fragmentMatcher?: FragmentMatcher;\n /**\n * A custom name (e.g., `iOS`) that identifies this particular client among your set of clients. Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.\n */\n name?: string;\n /**\n * A custom version that identifies the current version of this particular client (e.g., `1.2`). Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.\n *\n * This is **not** the version of Apollo Client that you are using, but rather any version string that helps you differentiate between versions of your client.\n */\n version?: string;\n documentTransform?: DocumentTransform;\n}\n\n// Though mergeOptions now resides in @apollo/client/utilities, it was\n// previously declared and exported from this module, and then reexported from\n// @apollo/client/core. Since we need to preserve that API anyway, the easiest\n// solution is to reexport mergeOptions where it was previously declared (here).\nimport { mergeOptions } from \"../utilities/index.js\";\nimport { getApolloClientMemoryInternals } from \"../utilities/caching/getMemoryInternals.js\";\nimport type {\n WatchFragmentOptions,\n WatchFragmentResult,\n} from \"../cache/core/cache.js\";\nexport { mergeOptions };\n\n/**\n * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries\n * and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,\n * receive results from the server and cache the results in a store. It also delivers updates\n * to GraphQL queries through `Observable` instances.\n */\nexport class ApolloClient implements DataProxy {\n public link: ApolloLink;\n public cache: ApolloCache;\n public disableNetworkFetches: boolean;\n public version: string;\n public queryDeduplication: boolean;\n public defaultOptions: DefaultOptions;\n public readonly typeDefs: ApolloClientOptions[\"typeDefs\"];\n\n private queryManager: QueryManager;\n private devToolsHookCb?: Function;\n private resetStoreCallbacks: Array<() => Promise> = [];\n private clearStoreCallbacks: Array<() => Promise> = [];\n private localState: LocalState;\n\n /**\n * Constructs an instance of `ApolloClient`.\n *\n * @example\n * ```js\n * import { ApolloClient, InMemoryCache } from '@apollo/client';\n *\n * const cache = new InMemoryCache();\n *\n * const client = new ApolloClient({\n * // Provide required constructor fields\n * cache: cache,\n * uri: 'http://localhost:4000/',\n *\n * // Provide some optional constructor fields\n * name: 'react-web-client',\n * version: '1.3',\n * queryDeduplication: false,\n * defaultOptions: {\n * watchQuery: {\n * fetchPolicy: 'cache-and-network',\n * },\n * },\n * });\n * ```\n */\n constructor(options: ApolloClientOptions) {\n if (!options.cache) {\n throw newInvariantError(\n \"To initialize Apollo Client, you must specify a 'cache' property \" +\n \"in the options object. \\n\" +\n \"For more information, please visit: https://go.apollo.dev/c/docs\"\n );\n }\n\n const {\n uri,\n credentials,\n headers,\n cache,\n documentTransform,\n ssrMode = false,\n ssrForceFetchDelay = 0,\n // Expose the client instance as window.__APOLLO_CLIENT__ and call\n // onBroadcast in queryManager.broadcastQueries to enable browser\n // devtools, but disable them by default in production.\n connectToDevTools = typeof window === \"object\" &&\n !(window as any).__APOLLO_CLIENT__ &&\n __DEV__,\n queryDeduplication = true,\n defaultOptions,\n defaultContext,\n assumeImmutableResults = cache.assumeImmutableResults,\n resolvers,\n typeDefs,\n fragmentMatcher,\n name: clientAwarenessName,\n version: clientAwarenessVersion,\n } = options;\n\n let { link } = options;\n\n if (!link) {\n link =\n uri ? new HttpLink({ uri, credentials, headers }) : ApolloLink.empty();\n }\n\n this.link = link;\n this.cache = cache;\n this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;\n this.queryDeduplication = queryDeduplication;\n this.defaultOptions = defaultOptions || Object.create(null);\n this.typeDefs = typeDefs;\n\n if (ssrForceFetchDelay) {\n setTimeout(\n () => (this.disableNetworkFetches = false),\n ssrForceFetchDelay\n );\n }\n\n this.watchQuery = this.watchQuery.bind(this);\n this.query = this.query.bind(this);\n this.mutate = this.mutate.bind(this);\n this.watchFragment = this.watchFragment.bind(this);\n this.resetStore = this.resetStore.bind(this);\n this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);\n\n this.version = version;\n\n this.localState = new LocalState({\n cache,\n client: this,\n resolvers,\n fragmentMatcher,\n });\n\n this.queryManager = new QueryManager({\n cache: this.cache,\n link: this.link,\n defaultOptions: this.defaultOptions,\n defaultContext,\n documentTransform,\n queryDeduplication,\n ssrMode,\n clientAwareness: {\n name: clientAwarenessName!,\n version: clientAwarenessVersion!,\n },\n localState: this.localState,\n assumeImmutableResults,\n onBroadcast:\n connectToDevTools ?\n () => {\n if (this.devToolsHookCb) {\n this.devToolsHookCb({\n action: {},\n state: {\n queries: this.queryManager.getQueryStore(),\n mutations: this.queryManager.mutationStore || {},\n },\n dataWithOptimisticResults: this.cache.extract(true),\n });\n }\n }\n : void 0,\n });\n\n if (connectToDevTools) this.connectToDevTools();\n }\n\n private connectToDevTools() {\n if (typeof window === \"object\") {\n type DevToolsConnector = {\n push(client: ApolloClient): void;\n };\n const windowWithDevTools = window as Window & {\n [devtoolsSymbol]?: DevToolsConnector;\n __APOLLO_CLIENT__?: ApolloClient;\n };\n const devtoolsSymbol = Symbol.for(\"apollo.devtools\");\n (windowWithDevTools[devtoolsSymbol] =\n windowWithDevTools[devtoolsSymbol] || ([] as DevToolsConnector)).push(\n this\n );\n windowWithDevTools.__APOLLO_CLIENT__ = this;\n }\n\n /**\n * Suggest installing the devtools for developers who don't have them\n */\n if (!hasSuggestedDevtools && __DEV__) {\n hasSuggestedDevtools = true;\n setTimeout(() => {\n if (\n typeof window !== \"undefined\" &&\n window.document &&\n window.top === window.self &&\n !(window as any).__APOLLO_DEVTOOLS_GLOBAL_HOOK__ &&\n /^(https?|file):$/.test(window.location.protocol)\n ) {\n const nav = window.navigator;\n const ua = nav && nav.userAgent;\n let url: string | undefined;\n if (typeof ua === \"string\") {\n if (ua.indexOf(\"Chrome/\") > -1) {\n url =\n \"https://chrome.google.com/webstore/detail/\" +\n \"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm\";\n } else if (ua.indexOf(\"Firefox/\") > -1) {\n url =\n \"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/\";\n }\n }\n if (url) {\n invariant.log(\n \"Download the Apollo DevTools for a better development \" +\n \"experience: %s\",\n url\n );\n }\n }\n }, 10000);\n }\n }\n\n /**\n * The `DocumentTransform` used to modify GraphQL documents before a request\n * is made. If a custom `DocumentTransform` is not provided, this will be the\n * default document transform.\n */\n get documentTransform() {\n return this.queryManager.documentTransform;\n }\n\n /**\n * Call this method to terminate any active client processes, making it safe\n * to dispose of this `ApolloClient` instance.\n */\n public stop() {\n this.queryManager.stop();\n }\n\n /**\n * This watches the cache store of the query according to the options specified and\n * returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and\n * receive updated results through an observer when the cache store changes.\n *\n * Note that this method is not an implementation of GraphQL subscriptions. Rather,\n * it uses Apollo's store in order to reactively deliver updates to your query results.\n *\n * For example, suppose you call watchQuery on a GraphQL query that fetches a person's\n * first and last name and this person has a particular object identifier, provided by\n * dataIdFromObject. Later, a different query fetches that same person's\n * first and last name and the first name has now changed. Then, any observers associated\n * with the results of the first query will be updated with a new result object.\n *\n * Note that if the cache does not change, the subscriber will *not* be notified.\n *\n * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for\n * a description of store reactivity.\n */\n public watchQuery<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions): ObservableQuery {\n if (this.defaultOptions.watchQuery) {\n options = mergeOptions(this.defaultOptions.watchQuery, options);\n }\n\n // XXX Overwriting options is probably not the best way to do this long term...\n if (\n this.disableNetworkFetches &&\n (options.fetchPolicy === \"network-only\" ||\n options.fetchPolicy === \"cache-and-network\")\n ) {\n options = { ...options, fetchPolicy: \"cache-first\" };\n }\n\n return this.queryManager.watchQuery(options);\n }\n\n /**\n * This resolves a single query according to the options specified and\n * returns a `Promise` which is either resolved with the resulting data\n * or rejected with an error.\n *\n * @param options - An object of type `QueryOptions` that allows us to\n * describe how this query should be treated e.g. whether it should hit the\n * server at all or just resolve from the cache, etc.\n */\n public query<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: QueryOptions): Promise> {\n if (this.defaultOptions.query) {\n options = mergeOptions(this.defaultOptions.query, options);\n }\n\n invariant(\n (options.fetchPolicy as WatchQueryFetchPolicy) !== \"cache-and-network\",\n \"The cache-and-network fetchPolicy does not work with client.query, because \" +\n \"client.query can only return a single result. Please use client.watchQuery \" +\n \"to receive multiple results from the cache and the network, or consider \" +\n \"using a different fetchPolicy, such as cache-first or network-only.\"\n );\n\n if (this.disableNetworkFetches && options.fetchPolicy === \"network-only\") {\n options = { ...options, fetchPolicy: \"cache-first\" };\n }\n\n return this.queryManager.query(options);\n }\n\n /**\n * This resolves a single mutation according to the options specified and returns a\n * Promise which is either resolved with the resulting data or rejected with an\n * error. In some cases both `data` and `errors` might be undefined, for example\n * when `errorPolicy` is set to `'ignore'`.\n *\n * It takes options as an object with the following keys and values:\n */\n public mutate<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n TContext extends Record = DefaultContext,\n TCache extends ApolloCache = ApolloCache,\n >(\n options: MutationOptions\n ): Promise> {\n if (this.defaultOptions.mutate) {\n options = mergeOptions(this.defaultOptions.mutate, options);\n }\n return this.queryManager.mutate(\n options\n );\n }\n\n /**\n * This subscribes to a graphql subscription according to the options specified and returns an\n * `Observable` which either emits received data or an error.\n */\n public subscribe<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: SubscriptionOptions): Observable> {\n return this.queryManager.startGraphQLSubscription(options);\n }\n\n /**\n * Tries to read some data from the store in the shape of the provided\n * GraphQL query without making a network request. This method will start at\n * the root query. To start at a specific id returned by `dataIdFromObject`\n * use `readFragment`.\n *\n * @param optimistic - Set to `true` to allow `readQuery` to return\n * optimistic results. Is `false` by default.\n */\n public readQuery(\n options: DataProxy.Query,\n optimistic: boolean = false\n ): T | null {\n return this.cache.readQuery(options, optimistic);\n }\n\n /**\n * Watches the cache store of the fragment according to the options specified\n * and returns an `Observable`. We can subscribe to this\n * `Observable` and receive updated results through an\n * observer when the cache store changes.\n *\n * You must pass in a GraphQL document with a single fragment or a document\n * with multiple fragments that represent what you are reading. If you pass\n * in a document with multiple fragments then you must also specify a\n * `fragmentName`.\n *\n * @since 3.10.0\n * @param options - An object of type `WatchFragmentOptions` that allows\n * the cache to identify the fragment and optionally specify whether to react\n * to optimistic updates.\n */\n\n public watchFragment<\n TFragmentData = unknown,\n TVariables = OperationVariables,\n >(\n options: WatchFragmentOptions\n ): Observable> {\n return this.cache.watchFragment(options);\n }\n\n /**\n * Tries to read some data from the store in the shape of the provided\n * GraphQL fragment without making a network request. This method will read a\n * GraphQL fragment from any arbitrary id that is currently cached, unlike\n * `readQuery` which will only read from the root query.\n *\n * You must pass in a GraphQL document with a single fragment or a document\n * with multiple fragments that represent what you are reading. If you pass\n * in a document with multiple fragments then you must also specify a\n * `fragmentName`.\n *\n * @param optimistic - Set to `true` to allow `readFragment` to return\n * optimistic results. Is `false` by default.\n */\n public readFragment(\n options: DataProxy.Fragment,\n optimistic: boolean = false\n ): T | null {\n return this.cache.readFragment(options, optimistic);\n }\n\n /**\n * Writes some data in the shape of the provided GraphQL query directly to\n * the store. This method will start at the root query. To start at a\n * specific id returned by `dataIdFromObject` then use `writeFragment`.\n */\n public writeQuery(\n options: DataProxy.WriteQueryOptions\n ): Reference | undefined {\n const ref = this.cache.writeQuery(options);\n\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n\n return ref;\n }\n\n /**\n * Writes some data in the shape of the provided GraphQL fragment directly to\n * the store. This method will write to a GraphQL fragment from any arbitrary\n * id that is currently cached, unlike `writeQuery` which will only write\n * from the root query.\n *\n * You must pass in a GraphQL document with a single fragment or a document\n * with multiple fragments that represent what you are writing. If you pass\n * in a document with multiple fragments then you must also specify a\n * `fragmentName`.\n */\n public writeFragment(\n options: DataProxy.WriteFragmentOptions\n ): Reference | undefined {\n const ref = this.cache.writeFragment(options);\n\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n\n return ref;\n }\n\n public __actionHookForDevTools(cb: () => any) {\n this.devToolsHookCb = cb;\n }\n\n public __requestRaw(payload: GraphQLRequest): Observable {\n return execute(this.link, payload);\n }\n\n /**\n * Resets your entire store by clearing out your cache and then re-executing\n * all of your active queries. This makes it so that you may guarantee that\n * there is no data left in your store from a time before you called this\n * method.\n *\n * `resetStore()` is useful when your user just logged out. You’ve removed the\n * user session, and you now want to make sure that any references to data you\n * might have fetched while the user session was active is gone.\n *\n * It is important to remember that `resetStore()` *will* refetch any active\n * queries. This means that any components that might be mounted will execute\n * their queries again using your network interface. If you do not want to\n * re-execute any queries then you should make sure to stop watching any\n * active queries.\n */\n public resetStore(): Promise[] | null> {\n return Promise.resolve()\n .then(() =>\n this.queryManager.clearStore({\n discardWatches: false,\n })\n )\n .then(() => Promise.all(this.resetStoreCallbacks.map((fn) => fn())))\n .then(() => this.reFetchObservableQueries());\n }\n\n /**\n * Remove all data from the store. Unlike `resetStore`, `clearStore` will\n * not refetch any active queries.\n */\n public clearStore(): Promise {\n return Promise.resolve()\n .then(() =>\n this.queryManager.clearStore({\n discardWatches: true,\n })\n )\n .then(() => Promise.all(this.clearStoreCallbacks.map((fn) => fn())));\n }\n\n /**\n * Allows callbacks to be registered that are executed when the store is\n * reset. `onResetStore` returns an unsubscribe function that can be used\n * to remove registered callbacks.\n */\n public onResetStore(cb: () => Promise): () => void {\n this.resetStoreCallbacks.push(cb);\n return () => {\n this.resetStoreCallbacks = this.resetStoreCallbacks.filter(\n (c) => c !== cb\n );\n };\n }\n\n /**\n * Allows callbacks to be registered that are executed when the store is\n * cleared. `onClearStore` returns an unsubscribe function that can be used\n * to remove registered callbacks.\n */\n public onClearStore(cb: () => Promise): () => void {\n this.clearStoreCallbacks.push(cb);\n return () => {\n this.clearStoreCallbacks = this.clearStoreCallbacks.filter(\n (c) => c !== cb\n );\n };\n }\n\n /**\n * Refetches all of your active queries.\n *\n * `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage\n *\n * It is important to remember that `reFetchObservableQueries()` *will* refetch any active\n * queries. This means that any components that might be mounted will execute\n * their queries again using your network interface. If you do not want to\n * re-execute any queries then you should make sure to stop watching any\n * active queries.\n * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.\n */\n public reFetchObservableQueries(\n includeStandby?: boolean\n ): Promise[]> {\n return this.queryManager.reFetchObservableQueries(includeStandby);\n }\n\n /**\n * Refetches specified active queries. Similar to \"reFetchObservableQueries()\" but with a specific list of queries.\n *\n * `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.\n *\n * It is important to remember that `refetchQueries()` *will* refetch specified active\n * queries. This means that any components that might be mounted will execute\n * their queries again using your network interface. If you do not want to\n * re-execute any queries then you should make sure to stop watching any\n * active queries.\n */\n public refetchQueries<\n TCache extends ApolloCache = ApolloCache,\n TResult = Promise>,\n >(\n options: RefetchQueriesOptions\n ): RefetchQueriesResult {\n const map = this.queryManager.refetchQueries(\n options as RefetchQueriesOptions, TResult>\n );\n const queries: ObservableQuery[] = [];\n const results: InternalRefetchQueriesResult[] = [];\n\n map.forEach((result, obsQuery) => {\n queries.push(obsQuery);\n results.push(result);\n });\n\n const result = Promise.all(\n results as TResult[]\n ) as RefetchQueriesResult;\n\n // In case you need the raw results immediately, without awaiting\n // Promise.all(results):\n result.queries = queries;\n result.results = results;\n\n // If you decide to ignore the result Promise because you're using\n // result.queries and result.results instead, you shouldn't have to worry\n // about preventing uncaught rejections for the Promise.all result.\n result.catch((error) => {\n invariant.debug(\n `In client.refetchQueries, Promise.all promise rejected with error %o`,\n error\n );\n });\n\n return result;\n }\n\n /**\n * Get all currently active `ObservableQuery` objects, in a `Map` keyed by\n * query ID strings.\n *\n * An \"active\" query is one that has observers and a `fetchPolicy` other than\n * \"standby\" or \"cache-only\".\n *\n * You can include all `ObservableQuery` objects (including the inactive ones)\n * by passing \"all\" instead of \"active\", or you can include just a subset of\n * active queries by passing an array of query names or DocumentNode objects.\n */\n public getObservableQueries(\n include: RefetchQueriesInclude = \"active\"\n ): Map> {\n return this.queryManager.getObservableQueries(include);\n }\n\n /**\n * Exposes the cache's complete state, in a serializable format for later restoration.\n */\n public extract(optimistic?: boolean): TCacheShape {\n return this.cache.extract(optimistic);\n }\n\n /**\n * Replaces existing state in the cache (if any) with the values expressed by\n * `serializedState`.\n *\n * Called when hydrating a cache (server side rendering, or offline storage),\n * and also (potentially) during hot reloads.\n */\n public restore(serializedState: TCacheShape): ApolloCache {\n return this.cache.restore(serializedState);\n }\n\n /**\n * Add additional local resolvers.\n */\n public addResolvers(resolvers: Resolvers | Resolvers[]) {\n this.localState.addResolvers(resolvers);\n }\n\n /**\n * Set (override existing) local resolvers.\n */\n public setResolvers(resolvers: Resolvers | Resolvers[]) {\n this.localState.setResolvers(resolvers);\n }\n\n /**\n * Get all registered local resolvers.\n */\n public getResolvers() {\n return this.localState.getResolvers();\n }\n\n /**\n * Set a custom local state fragment matcher.\n */\n public setLocalStateFragmentMatcher(fragmentMatcher: FragmentMatcher) {\n this.localState.setFragmentMatcher(fragmentMatcher);\n }\n\n /**\n * Define a new ApolloLink (or link chain) that Apollo Client will use.\n */\n public setLink(newLink: ApolloLink) {\n this.link = this.queryManager.link = newLink;\n }\n\n public get defaultContext() {\n return this.queryManager.defaultContext;\n }\n\n /**\n * @experimental\n * This is not a stable API - it is used in development builds to expose\n * information to the DevTools.\n * Use at your own risk!\n * For more details, see [Memory Management](https://www.apollographql.com/docs/react/caching/memory-management/#measuring-cache-usage)\n *\n * @example\n * ```ts\n * console.log(client.getMemoryInternals())\n * ```\n * Logs output in the following JSON format:\n * @example\n * ```json\n *{\n * limits: {\n * parser: 1000,\n * canonicalStringify: 1000,\n * print: 2000,\n * 'documentTransform.cache': 2000,\n * 'queryManager.getDocumentInfo': 2000,\n * 'PersistedQueryLink.persistedQueryHashes': 2000,\n * 'fragmentRegistry.transform': 2000,\n * 'fragmentRegistry.lookup': 1000,\n * 'fragmentRegistry.findFragmentSpreads': 4000,\n * 'cache.fragmentQueryDocuments': 1000,\n * 'removeTypenameFromVariables.getVariableDefinitions': 2000,\n * 'inMemoryCache.maybeBroadcastWatch': 5000,\n * 'inMemoryCache.executeSelectionSet': 10000,\n * 'inMemoryCache.executeSubSelectedArray': 5000\n * },\n * sizes: {\n * parser: 26,\n * canonicalStringify: 4,\n * print: 14,\n * addTypenameDocumentTransform: [\n * {\n * cache: 14,\n * },\n * ],\n * queryManager: {\n * getDocumentInfo: 14,\n * documentTransforms: [\n * {\n * cache: 14,\n * },\n * {\n * cache: 14,\n * },\n * ],\n * },\n * fragmentRegistry: {\n * findFragmentSpreads: 34,\n * lookup: 20,\n * transform: 14,\n * },\n * cache: {\n * fragmentQueryDocuments: 22,\n * },\n * inMemoryCache: {\n * executeSelectionSet: 4345,\n * executeSubSelectedArray: 1206,\n * maybeBroadcastWatch: 32,\n * },\n * links: [\n * {\n * PersistedQueryLink: {\n * persistedQueryHashes: 14,\n * },\n * },\n * {\n * removeTypenameFromVariables: {\n * getVariableDefinitions: 14,\n * },\n * },\n * ],\n * },\n * }\n *```\n */\n public getMemoryInternals?: typeof getApolloClientMemoryInternals;\n}\n\nif (__DEV__) {\n ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;\n}\n","import type { DocumentNode } from \"graphql\";\nimport { wrap } from \"optimism\";\n\nimport type {\n StoreObject,\n Reference,\n DeepPartial,\n} from \"../../utilities/index.js\";\nimport {\n Observable,\n cacheSizes,\n defaultCacheSizes,\n getFragmentQueryDocument,\n mergeDeepArray,\n} from \"../../utilities/index.js\";\nimport type { DataProxy } from \"./types/DataProxy.js\";\nimport type { Cache } from \"./types/Cache.js\";\nimport { WeakCache } from \"@wry/caches\";\nimport { getApolloCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nimport type {\n OperationVariables,\n TypedDocumentNode,\n} from \"../../core/types.js\";\nimport type { MissingTree } from \"./types/common.js\";\nimport { equalByQuery } from \"../../core/equalByQuery.js\";\n\nexport type Transaction = (c: ApolloCache) => void;\n\n/**\n * Watched fragment options.\n */\nexport interface WatchFragmentOptions {\n /**\n * A GraphQL fragment document parsed into an AST with the `gql`\n * template literal.\n *\n * @docGroup 1. Required options\n */\n fragment: DocumentNode | TypedDocumentNode;\n /**\n * An object containing a `__typename` and primary key fields\n * (such as `id`) identifying the entity object from which the fragment will\n * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID\n * (uncommon).\n *\n * @docGroup 1. Required options\n */\n from: StoreObject | Reference | string;\n /**\n * Any variables that the GraphQL fragment may depend on.\n *\n * @docGroup 2. Cache options\n */\n variables?: TVars;\n /**\n * The name of the fragment defined in the fragment document.\n *\n * Required if the fragment document includes more than one fragment,\n * optional otherwise.\n *\n * @docGroup 2. Cache options\n */\n fragmentName?: string;\n /**\n * If `true`, `watchFragment` returns optimistic results.\n *\n * The default value is `true`.\n *\n * @docGroup 2. Cache options\n */\n optimistic?: boolean;\n /**\n * @deprecated\n * Using `canonizeResults` can result in memory leaks so we generally do not\n * recommend using this option anymore.\n * A future version of Apollo Client will contain a similar feature.\n *\n * Whether to canonize cache results before returning them. Canonization\n * takes some extra time, but it speeds up future deep equality comparisons.\n * Defaults to false.\n */\n canonizeResults?: boolean;\n}\n\n/**\n * Watched fragment results.\n */\nexport type WatchFragmentResult =\n | {\n data: TData;\n complete: true;\n missing?: never;\n }\n | {\n data: DeepPartial;\n complete: false;\n missing: MissingTree;\n };\n\nexport abstract class ApolloCache implements DataProxy {\n public readonly assumeImmutableResults: boolean = false;\n\n // required to implement\n // core API\n public abstract read(\n query: Cache.ReadOptions\n ): TData | null;\n public abstract write(\n write: Cache.WriteOptions\n ): Reference | undefined;\n public abstract diff(query: Cache.DiffOptions): Cache.DiffResult;\n public abstract watch(\n watch: Cache.WatchOptions\n ): () => void;\n\n // Empty the cache and restart all current watches (unless\n // options.discardWatches is true).\n public abstract reset(options?: Cache.ResetOptions): Promise;\n\n // Remove whole objects from the cache by passing just options.id, or\n // specific fields by passing options.field and/or options.args. If no\n // options.args are provided, all fields matching options.field (even\n // those with arguments) will be removed. Returns true iff any data was\n // removed from the cache.\n public abstract evict(options: Cache.EvictOptions): boolean;\n\n // initializer / offline / ssr API\n /**\n * Replaces existing state in the cache (if any) with the values expressed by\n * `serializedState`.\n *\n * Called when hydrating a cache (server side rendering, or offline storage),\n * and also (potentially) during hot reloads.\n */\n public abstract restore(\n serializedState: TSerialized\n ): ApolloCache;\n\n /**\n * Exposes the cache's complete state, in a serializable format for later restoration.\n */\n public abstract extract(optimistic?: boolean): TSerialized;\n\n // Optimistic API\n\n public abstract removeOptimistic(id: string): void;\n\n // Transactional API\n\n // The batch method is intended to replace/subsume both performTransaction\n // and recordOptimisticTransaction, but performTransaction came first, so we\n // provide a default batch implementation that's just another way of calling\n // performTransaction. Subclasses of ApolloCache (such as InMemoryCache) can\n // override the batch method to do more interesting things with its options.\n public batch(options: Cache.BatchOptions): U {\n const optimisticId =\n typeof options.optimistic === \"string\" ? options.optimistic\n : options.optimistic === false ? null\n : void 0;\n let updateResult: U;\n this.performTransaction(\n () => (updateResult = options.update(this)),\n optimisticId\n );\n return updateResult!;\n }\n\n public abstract performTransaction(\n transaction: Transaction,\n // Although subclasses may implement recordOptimisticTransaction\n // however they choose, the default implementation simply calls\n // performTransaction with a string as the second argument, allowing\n // performTransaction to handle both optimistic and non-optimistic\n // (broadcast-batching) transactions. Passing null for optimisticId is\n // also allowed, and indicates that performTransaction should apply\n // the transaction non-optimistically (ignoring optimistic data).\n optimisticId?: string | null\n ): void;\n\n public recordOptimisticTransaction(\n transaction: Transaction,\n optimisticId: string\n ) {\n this.performTransaction(transaction, optimisticId);\n }\n\n // Optional API\n\n // Called once per input document, allowing the cache to make static changes\n // to the query, such as adding __typename fields.\n public transformDocument(document: DocumentNode): DocumentNode {\n return document;\n }\n\n // Called before each ApolloLink request, allowing the cache to make dynamic\n // changes to the query, such as filling in missing fragment definitions.\n public transformForLink(document: DocumentNode): DocumentNode {\n return document;\n }\n\n public identify(object: StoreObject | Reference): string | undefined {\n return;\n }\n\n public gc(): string[] {\n return [];\n }\n\n public modify = Record>(\n options: Cache.ModifyOptions\n ): boolean {\n return false;\n }\n\n // DataProxy API\n public readQuery(\n options: Cache.ReadQueryOptions,\n optimistic = !!options.optimistic\n ): QueryType | null {\n return this.read({\n ...options,\n rootId: options.id || \"ROOT_QUERY\",\n optimistic,\n });\n }\n\n /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n public watchFragment(\n options: WatchFragmentOptions\n ): Observable> {\n const { fragment, fragmentName, from, optimistic = true } = options;\n const query = this.getFragmentDoc(fragment, fragmentName);\n\n const diffOptions: Cache.DiffOptions = {\n returnPartialData: true,\n id: typeof from === \"string\" ? from : this.identify(from),\n query,\n optimistic,\n };\n\n let latestDiff: DataProxy.DiffResult | undefined;\n\n return new Observable((observer) => {\n return this.watch({\n ...diffOptions,\n immediate: true,\n callback(diff) {\n if (\n // Always ensure we deliver the first result\n latestDiff &&\n equalByQuery(\n query,\n { data: latestDiff?.result },\n { data: diff.result }\n )\n ) {\n return;\n }\n\n const result = {\n data: diff.result as DeepPartial,\n complete: !!diff.complete,\n } as WatchFragmentResult;\n\n if (diff.missing) {\n result.missing = mergeDeepArray(\n diff.missing.map((error) => error.missing)\n );\n }\n\n latestDiff = diff;\n observer.next(result);\n },\n });\n });\n }\n\n // Make sure we compute the same (===) fragment query document every\n // time we receive the same fragment in readFragment.\n private getFragmentDoc = wrap(getFragmentQueryDocument, {\n max:\n cacheSizes[\"cache.fragmentQueryDocuments\"] ||\n defaultCacheSizes[\"cache.fragmentQueryDocuments\"],\n cache: WeakCache,\n });\n\n public readFragment(\n options: Cache.ReadFragmentOptions,\n optimistic = !!options.optimistic\n ): FragmentType | null {\n return this.read({\n ...options,\n query: this.getFragmentDoc(options.fragment, options.fragmentName),\n rootId: options.id,\n optimistic,\n });\n }\n\n public writeQuery({\n id,\n data,\n ...options\n }: Cache.WriteQueryOptions): Reference | undefined {\n return this.write(\n Object.assign(options, {\n dataId: id || \"ROOT_QUERY\",\n result: data,\n })\n );\n }\n\n public writeFragment({\n id,\n data,\n fragment,\n fragmentName,\n ...options\n }: Cache.WriteFragmentOptions): Reference | undefined {\n return this.write(\n Object.assign(options, {\n query: this.getFragmentDoc(fragment, fragmentName),\n dataId: id,\n result: data,\n })\n );\n }\n\n public updateQuery(\n options: Cache.UpdateQueryOptions,\n update: (data: TData | null) => TData | null | void\n ): TData | null {\n return this.batch({\n update(cache) {\n const value = cache.readQuery(options);\n const data = update(value);\n if (data === void 0 || data === null) return value;\n cache.writeQuery({ ...options, data });\n return data;\n },\n });\n }\n\n public updateFragment(\n options: Cache.UpdateFragmentOptions,\n update: (data: TData | null) => TData | null | void\n ): TData | null {\n return this.batch({\n update(cache) {\n const value = cache.readFragment(options);\n const data = update(value);\n if (data === void 0 || data === null) return value;\n cache.writeFragment({ ...options, data });\n return data;\n },\n });\n }\n\n /**\n * @experimental\n * @internal\n * This is not a stable API - it is used in development builds to expose\n * information to the DevTools.\n * Use at your own risk!\n */\n public getMemoryInternals?: typeof getApolloCacheMemoryInternals;\n}\n\nif (__DEV__) {\n ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;\n}\n","import type { DocumentNode, FieldNode } from \"graphql\";\n\nimport type {\n Reference,\n StoreObject,\n StoreValue,\n isReference,\n AsStoreObject,\n} from \"../../../utilities/index.js\";\n\nimport type { StorageType } from \"../../inmemory/policies.js\";\n\n// The Readonly type only really works for object types, since it marks\n// all of the object's properties as readonly, but there are many cases when\n// a generic type parameter like TExisting might be a string or some other\n// primitive type, in which case we need to avoid wrapping it with Readonly.\n// SafeReadonly collapses to just string, which makes string\n// assignable to SafeReadonly, whereas string is not assignable to\n// Readonly, somewhat surprisingly.\nexport type SafeReadonly = T extends object ? Readonly : T;\n\nexport type MissingTree =\n | string\n | {\n readonly [key: string]: MissingTree;\n };\n\nexport class MissingFieldError extends Error {\n constructor(\n public readonly message: string,\n public readonly path: MissingTree | Array,\n public readonly query: DocumentNode,\n public readonly variables?: Record\n ) {\n // 'Error' breaks prototype chain here\n super(message);\n\n if (Array.isArray(this.path)) {\n this.missing = this.message;\n for (let i = this.path.length - 1; i >= 0; --i) {\n this.missing = { [this.path[i]]: this.missing };\n }\n } else {\n this.missing = this.path;\n }\n\n // We're not using `Object.setPrototypeOf` here as it isn't fully supported\n // on Android (see issue #3236).\n (this as any).__proto__ = MissingFieldError.prototype;\n }\n\n public readonly missing: MissingTree;\n}\n\nexport interface FieldSpecifier {\n typename?: string;\n fieldName: string;\n field?: FieldNode;\n args?: Record;\n variables?: Record;\n}\n\nexport interface ReadFieldOptions extends FieldSpecifier {\n from?: StoreObject | Reference;\n}\n\nexport interface ReadFieldFunction {\n (options: ReadFieldOptions): SafeReadonly | undefined;\n (\n fieldName: string,\n from?: StoreObject | Reference\n ): SafeReadonly | undefined;\n}\n\nexport type ToReferenceFunction = (\n objOrIdOrRef: StoreObject | string | Reference,\n mergeIntoStore?: boolean\n) => Reference | undefined;\n\nexport type CanReadFunction = (value: StoreValue) => boolean;\n\ndeclare const _deleteModifier: unique symbol;\nexport interface DeleteModifier {\n [_deleteModifier]: true;\n}\ndeclare const _invalidateModifier: unique symbol;\nexport interface InvalidateModifier {\n [_invalidateModifier]: true;\n}\ndeclare const _ignoreModifier: unique symbol;\nexport interface IgnoreModifier {\n [_ignoreModifier]: true;\n}\n\nexport type ModifierDetails = {\n DELETE: DeleteModifier;\n INVALIDATE: InvalidateModifier;\n fieldName: string;\n storeFieldName: string;\n readField: ReadFieldFunction;\n canRead: CanReadFunction;\n isReference: typeof isReference;\n toReference: ToReferenceFunction;\n storage: StorageType;\n};\n\nexport type Modifier = (\n value: T,\n details: ModifierDetails\n) => T | DeleteModifier | InvalidateModifier;\n\ntype StoreObjectValueMaybeReference =\n StoreVal extends Array> ?\n StoreVal extends Array ?\n Item extends Record ?\n ReadonlyArray | Reference>\n : never\n : never\n : StoreVal extends Record ? AsStoreObject | Reference\n : StoreVal;\n\nexport type AllFieldsModifier> = Modifier<\n Entity[keyof Entity] extends infer Value ?\n StoreObjectValueMaybeReference>\n : never\n>;\n\nexport type Modifiers = Record> =\n Partial<{\n [FieldName in keyof T]: Modifier<\n StoreObjectValueMaybeReference>\n >;\n }>;\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport type { OptimisticDependencyFunction } from \"optimism\";\nimport { dep } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\n\nimport type {\n StoreValue,\n StoreObject,\n Reference,\n} from \"../../utilities/index.js\";\nimport {\n isReference,\n makeReference,\n DeepMerger,\n maybeDeepFreeze,\n canUseWeakMap,\n isNonNullObject,\n} from \"../../utilities/index.js\";\nimport type { NormalizedCache, NormalizedCacheObject } from \"./types.js\";\nimport { hasOwn, fieldNameFromStoreName } from \"./helpers.js\";\nimport type { Policies, StorageType } from \"./policies.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\nimport type {\n SafeReadonly,\n Modifier,\n Modifiers,\n ReadFieldOptions,\n ToReferenceFunction,\n CanReadFunction,\n InvalidateModifier,\n DeleteModifier,\n ModifierDetails,\n} from \"../core/types/common.js\";\nimport type { DocumentNode, FieldNode, SelectionSetNode } from \"graphql\";\n\nconst DELETE: DeleteModifier = Object.create(null);\nconst delModifier: Modifier = () => DELETE;\nconst INVALIDATE: InvalidateModifier = Object.create(null);\n\nexport abstract class EntityStore implements NormalizedCache {\n protected data: NormalizedCacheObject = Object.create(null);\n\n constructor(\n public readonly policies: Policies,\n public readonly group: CacheGroup\n ) {}\n\n public abstract addLayer(\n layerId: string,\n replay: (layer: EntityStore) => any\n ): Layer;\n\n public abstract removeLayer(layerId: string): EntityStore;\n\n // Although the EntityStore class is abstract, it contains concrete\n // implementations of the various NormalizedCache interface methods that\n // are inherited by the Root and Layer subclasses.\n\n public toObject(): NormalizedCacheObject {\n return { ...this.data };\n }\n\n public has(dataId: string): boolean {\n return this.lookup(dataId, true) !== void 0;\n }\n\n public get(dataId: string, fieldName: string): StoreValue {\n this.group.depend(dataId, fieldName);\n if (hasOwn.call(this.data, dataId)) {\n const storeObject = this.data[dataId];\n if (storeObject && hasOwn.call(storeObject, fieldName)) {\n return storeObject[fieldName];\n }\n }\n if (\n fieldName === \"__typename\" &&\n hasOwn.call(this.policies.rootTypenamesById, dataId)\n ) {\n return this.policies.rootTypenamesById[dataId];\n }\n if (this instanceof Layer) {\n return this.parent.get(dataId, fieldName);\n }\n }\n\n protected lookup(\n dataId: string,\n dependOnExistence?: boolean\n ): StoreObject | undefined {\n // The has method (above) calls lookup with dependOnExistence = true, so\n // that it can later be invalidated when we add or remove a StoreObject for\n // this dataId. Any consumer who cares about the contents of the StoreObject\n // should not rely on this dependency, since the contents could change\n // without the object being added or removed.\n if (dependOnExistence) this.group.depend(dataId, \"__exists\");\n\n if (hasOwn.call(this.data, dataId)) {\n return this.data[dataId];\n }\n\n if (this instanceof Layer) {\n return this.parent.lookup(dataId, dependOnExistence);\n }\n\n if (this.policies.rootTypenamesById[dataId]) {\n return Object.create(null);\n }\n }\n\n public merge(older: string | StoreObject, newer: StoreObject | string): void {\n let dataId: string | undefined;\n\n // Convert unexpected references to ID strings.\n if (isReference(older)) older = older.__ref;\n if (isReference(newer)) newer = newer.__ref;\n\n const existing: StoreObject | undefined =\n typeof older === \"string\" ? this.lookup((dataId = older)) : older;\n\n const incoming: StoreObject | undefined =\n typeof newer === \"string\" ? this.lookup((dataId = newer)) : newer;\n\n // If newer was a string ID, but that ID was not defined in this store,\n // then there are no fields to be merged, so we're done.\n if (!incoming) return;\n\n invariant(typeof dataId === \"string\", \"store.merge expects a string ID\");\n\n const merged: StoreObject = new DeepMerger(storeObjectReconciler).merge(\n existing,\n incoming\n );\n\n // Even if merged === existing, existing may have come from a lower\n // layer, so we always need to set this.data[dataId] on this level.\n this.data[dataId] = merged;\n\n if (merged !== existing) {\n delete this.refs[dataId];\n if (this.group.caching) {\n const fieldsToDirty: Record = Object.create(null);\n\n // If we added a new StoreObject where there was previously none, dirty\n // anything that depended on the existence of this dataId, such as the\n // EntityStore#has method.\n if (!existing) fieldsToDirty.__exists = 1;\n\n // Now invalidate dependents who called getFieldValue for any fields\n // that are changing as a result of this merge.\n Object.keys(incoming).forEach((storeFieldName) => {\n if (\n !existing ||\n existing[storeFieldName] !== merged[storeFieldName]\n ) {\n // Always dirty the full storeFieldName, which may include\n // serialized arguments following the fieldName prefix.\n fieldsToDirty[storeFieldName] = 1;\n\n // Also dirty fieldNameFromStoreName(storeFieldName) if it's\n // different from storeFieldName and this field does not have\n // keyArgs configured, because that means the cache can't make\n // any assumptions about how field values with the same field\n // name but different arguments might be interrelated, so it\n // must err on the side of invalidating all field values that\n // share the same short fieldName, regardless of arguments.\n const fieldName = fieldNameFromStoreName(storeFieldName);\n if (\n fieldName !== storeFieldName &&\n !this.policies.hasKeyArgs(merged.__typename, fieldName)\n ) {\n fieldsToDirty[fieldName] = 1;\n }\n\n // If merged[storeFieldName] has become undefined, and this is the\n // Root layer, actually delete the property from the merged object,\n // which is guaranteed to have been created fresh in this method.\n if (merged[storeFieldName] === void 0 && !(this instanceof Layer)) {\n delete merged[storeFieldName];\n }\n }\n });\n\n if (\n fieldsToDirty.__typename &&\n !(existing && existing.__typename) &&\n // Since we return default root __typename strings\n // automatically from store.get, we don't need to dirty the\n // ROOT_QUERY.__typename field if merged.__typename is equal\n // to the default string (usually \"Query\").\n this.policies.rootTypenamesById[dataId] === merged.__typename\n ) {\n delete fieldsToDirty.__typename;\n }\n\n Object.keys(fieldsToDirty).forEach((fieldName) =>\n this.group.dirty(dataId as string, fieldName)\n );\n }\n }\n }\n\n public modify(\n dataId: string,\n fields: Modifier | Modifiers>\n ): boolean {\n const storeObject = this.lookup(dataId);\n\n if (storeObject) {\n const changedFields: Record = Object.create(null);\n let needToMerge = false;\n let allDeleted = true;\n\n const sharedDetails = {\n DELETE,\n INVALIDATE,\n isReference,\n toReference: this.toReference,\n canRead: this.canRead,\n readField: (\n fieldNameOrOptions: string | ReadFieldOptions,\n from?: StoreObject | Reference\n ) =>\n this.policies.readField(\n typeof fieldNameOrOptions === \"string\" ?\n {\n fieldName: fieldNameOrOptions,\n from: from || makeReference(dataId),\n }\n : fieldNameOrOptions,\n { store: this }\n ),\n } satisfies Partial;\n\n Object.keys(storeObject).forEach((storeFieldName) => {\n const fieldName = fieldNameFromStoreName(storeFieldName);\n let fieldValue = storeObject[storeFieldName];\n if (fieldValue === void 0) return;\n const modify: Modifier | undefined =\n typeof fields === \"function\" ? fields : (\n fields[storeFieldName] || fields[fieldName]\n );\n if (modify) {\n let newValue =\n modify === delModifier ? DELETE : (\n modify(maybeDeepFreeze(fieldValue), {\n ...sharedDetails,\n fieldName,\n storeFieldName,\n storage: this.getStorage(dataId, storeFieldName),\n })\n );\n if (newValue === INVALIDATE) {\n this.group.dirty(dataId, storeFieldName);\n } else {\n if (newValue === DELETE) newValue = void 0;\n if (newValue !== fieldValue) {\n changedFields[storeFieldName] = newValue;\n needToMerge = true;\n fieldValue = newValue;\n\n if (__DEV__) {\n const checkReference = (ref: Reference) => {\n if (this.lookup(ref.__ref) === undefined) {\n invariant.warn(\n \"cache.modify: You are trying to write a Reference that is not part of the store: %o\\n\" +\n \"Please make sure to set the `mergeIntoStore` parameter to `true` when creating a Reference that is not part of the store yet:\\n\" +\n \"`toReference(object, true)`\",\n ref\n );\n return true;\n }\n };\n if (isReference(newValue)) {\n checkReference(newValue);\n } else if (Array.isArray(newValue)) {\n // Warn about writing \"mixed\" arrays of Reference and non-Reference objects\n let seenReference: boolean = false;\n let someNonReference: unknown;\n for (const value of newValue) {\n if (isReference(value)) {\n seenReference = true;\n if (checkReference(value)) break;\n } else {\n // Do not warn on primitive values, since those could never be represented\n // by a reference. This is a valid (albeit uncommon) use case.\n if (typeof value === \"object\" && !!value) {\n const [id] = this.policies.identify(value);\n // check if object could even be referenced, otherwise we are not interested in it for this warning\n if (id) {\n someNonReference = value;\n }\n }\n }\n if (seenReference && someNonReference !== undefined) {\n invariant.warn(\n \"cache.modify: Writing an array with a mix of both References and Objects will not result in the Objects being normalized correctly.\\n\" +\n \"Please convert the object instance %o to a Reference before writing it to the cache by calling `toReference(object, true)`.\",\n someNonReference\n );\n break;\n }\n }\n }\n }\n }\n }\n }\n if (fieldValue !== void 0) {\n allDeleted = false;\n }\n });\n\n if (needToMerge) {\n this.merge(dataId, changedFields);\n\n if (allDeleted) {\n if (this instanceof Layer) {\n this.data[dataId] = void 0;\n } else {\n delete this.data[dataId];\n }\n this.group.dirty(dataId, \"__exists\");\n }\n\n return true;\n }\n }\n\n return false;\n }\n\n // If called with only one argument, removes the entire entity\n // identified by dataId. If called with a fieldName as well, removes all\n // fields of that entity whose names match fieldName according to the\n // fieldNameFromStoreName helper function. If called with a fieldName\n // and variables, removes all fields of that entity whose names match fieldName\n // and whose arguments when cached exactly match the variables passed.\n public delete(\n dataId: string,\n fieldName?: string,\n args?: Record\n ) {\n const storeObject = this.lookup(dataId);\n if (storeObject) {\n const typename = this.getFieldValue(storeObject, \"__typename\");\n const storeFieldName =\n fieldName && args ?\n this.policies.getStoreFieldName({ typename, fieldName, args })\n : fieldName;\n return this.modify(\n dataId,\n storeFieldName ?\n {\n [storeFieldName]: delModifier,\n }\n : delModifier\n );\n }\n return false;\n }\n\n public evict(options: Cache.EvictOptions, limit: EntityStore): boolean {\n let evicted = false;\n if (options.id) {\n if (hasOwn.call(this.data, options.id)) {\n evicted = this.delete(options.id, options.fieldName, options.args);\n }\n if (this instanceof Layer && this !== limit) {\n evicted = this.parent.evict(options, limit) || evicted;\n }\n // Always invalidate the field to trigger rereading of watched\n // queries, even if no cache data was modified by the eviction,\n // because queries may depend on computed fields with custom read\n // functions, whose values are not stored in the EntityStore.\n if (options.fieldName || evicted) {\n this.group.dirty(options.id, options.fieldName || \"__exists\");\n }\n }\n return evicted;\n }\n\n public clear(): void {\n this.replace(null);\n }\n\n public extract(): NormalizedCacheObject {\n const obj = this.toObject();\n const extraRootIds: string[] = [];\n this.getRootIdSet().forEach((id) => {\n if (!hasOwn.call(this.policies.rootTypenamesById, id)) {\n extraRootIds.push(id);\n }\n });\n if (extraRootIds.length) {\n obj.__META = { extraRootIds: extraRootIds.sort() };\n }\n return obj;\n }\n\n public replace(newData: NormalizedCacheObject | null): void {\n Object.keys(this.data).forEach((dataId) => {\n if (!(newData && hasOwn.call(newData, dataId))) {\n this.delete(dataId);\n }\n });\n if (newData) {\n const { __META, ...rest } = newData;\n Object.keys(rest).forEach((dataId) => {\n this.merge(dataId, rest[dataId] as StoreObject);\n });\n if (__META) {\n __META.extraRootIds.forEach(this.retain, this);\n }\n }\n }\n\n public abstract getStorage(\n idOrObj: string | StoreObject,\n ...storeFieldNames: (string | number)[]\n ): StorageType;\n\n // Maps root entity IDs to the number of times they have been retained, minus\n // the number of times they have been released. Retained entities keep other\n // entities they reference (even indirectly) from being garbage collected.\n private rootIds: {\n [rootId: string]: number;\n } = Object.create(null);\n\n public retain(rootId: string): number {\n return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);\n }\n\n public release(rootId: string): number {\n if (this.rootIds[rootId] > 0) {\n const count = --this.rootIds[rootId];\n if (!count) delete this.rootIds[rootId];\n return count;\n }\n return 0;\n }\n\n // Return a Set of all the ID strings that have been retained by\n // this layer/root *and* any layers/roots beneath it.\n public getRootIdSet(ids = new Set()) {\n Object.keys(this.rootIds).forEach(ids.add, ids);\n if (this instanceof Layer) {\n this.parent.getRootIdSet(ids);\n } else {\n // Official singleton IDs like ROOT_QUERY and ROOT_MUTATION are\n // always considered roots for garbage collection, regardless of\n // their retainment counts in this.rootIds.\n Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);\n }\n return ids;\n }\n\n // The goal of garbage collection is to remove IDs from the Root layer of the\n // store that are no longer reachable starting from any IDs that have been\n // explicitly retained (see retain and release, above). Returns an array of\n // dataId strings that were removed from the store.\n public gc() {\n const ids = this.getRootIdSet();\n const snapshot = this.toObject();\n ids.forEach((id) => {\n if (hasOwn.call(snapshot, id)) {\n // Because we are iterating over an ECMAScript Set, the IDs we add here\n // will be visited in later iterations of the forEach loop only if they\n // were not previously contained by the Set.\n Object.keys(this.findChildRefIds(id)).forEach(ids.add, ids);\n // By removing IDs from the snapshot object here, we protect them from\n // getting removed from the root store layer below.\n delete snapshot[id];\n }\n });\n const idsToRemove = Object.keys(snapshot);\n if (idsToRemove.length) {\n let root: EntityStore = this;\n while (root instanceof Layer) root = root.parent;\n idsToRemove.forEach((id) => root.delete(id));\n }\n return idsToRemove;\n }\n\n // Lazily tracks { __ref: } strings contained by this.data[dataId].\n private refs: {\n [dataId: string]: Record;\n } = Object.create(null);\n\n public findChildRefIds(dataId: string): Record {\n if (!hasOwn.call(this.refs, dataId)) {\n const found = (this.refs[dataId] = Object.create(null));\n const root = this.data[dataId];\n if (!root) return found;\n\n const workSet = new Set>([root]);\n // Within the store, only arrays and objects can contain child entity\n // references, so we can prune the traversal using this predicate:\n workSet.forEach((obj) => {\n if (isReference(obj)) {\n found[obj.__ref] = true;\n // In rare cases, a { __ref } Reference object may have other fields.\n // This often indicates a mismerging of References with StoreObjects,\n // but garbage collection should not be fooled by a stray __ref\n // property in a StoreObject (ignoring all the other fields just\n // because the StoreObject looks like a Reference). To avoid this\n // premature termination of findChildRefIds recursion, we fall through\n // to the code below, which will handle any other properties of obj.\n }\n if (isNonNullObject(obj)) {\n Object.keys(obj).forEach((key) => {\n const child = obj[key];\n // No need to add primitive values to the workSet, since they cannot\n // contain reference objects.\n if (isNonNullObject(child)) {\n workSet.add(child);\n }\n });\n }\n });\n }\n return this.refs[dataId];\n }\n\n // Used to compute cache keys specific to this.group.\n /** overload for `InMemoryCache.maybeBroadcastWatch` */\n public makeCacheKey(\n document: DocumentNode,\n callback: Cache.WatchCallback,\n details: string\n ): object;\n /** overload for `StoreReader.executeSelectionSet` */\n public makeCacheKey(\n selectionSet: SelectionSetNode,\n parent: string /* = ( Reference.__ref ) */ | StoreObject,\n varString: string | undefined,\n canonizeResults: boolean\n ): object;\n /** overload for `StoreReader.executeSubSelectedArray` */\n public makeCacheKey(\n field: FieldNode,\n array: readonly any[],\n varString: string | undefined\n ): object;\n /** @deprecated This is only meant for internal usage,\n * in your own code please use a `Trie` instance instead. */\n public makeCacheKey(...args: any[]): object;\n public makeCacheKey() {\n return this.group.keyMaker.lookupArray(arguments);\n }\n\n // Bound function that can be passed around to provide easy access to fields\n // of Reference objects as well as ordinary objects.\n public getFieldValue = (\n objectOrReference: StoreObject | Reference | undefined,\n storeFieldName: string\n ) =>\n maybeDeepFreeze(\n isReference(objectOrReference) ?\n this.get(objectOrReference.__ref, storeFieldName)\n : objectOrReference && objectOrReference[storeFieldName]\n ) as SafeReadonly;\n\n // Returns true for non-normalized StoreObjects and non-dangling\n // References, indicating that readField(name, objOrRef) has a chance of\n // working. Useful for filtering out dangling references from lists.\n public canRead: CanReadFunction = (objOrRef) => {\n return isReference(objOrRef) ?\n this.has(objOrRef.__ref)\n : typeof objOrRef === \"object\";\n };\n\n // Bound function that converts an id or an object with a __typename and\n // primary key fields to a Reference object. If called with a Reference object,\n // that same Reference object is returned. Pass true for mergeIntoStore to persist\n // an object into the store.\n public toReference: ToReferenceFunction = (objOrIdOrRef, mergeIntoStore) => {\n if (typeof objOrIdOrRef === \"string\") {\n return makeReference(objOrIdOrRef);\n }\n\n if (isReference(objOrIdOrRef)) {\n return objOrIdOrRef;\n }\n\n const [id] = this.policies.identify(objOrIdOrRef);\n\n if (id) {\n const ref = makeReference(id);\n if (mergeIntoStore) {\n this.merge(id, objOrIdOrRef);\n }\n return ref;\n }\n };\n}\n\nexport type FieldValueGetter = EntityStore[\"getFieldValue\"];\n\n// A single CacheGroup represents a set of one or more EntityStore objects,\n// typically the Root store in a CacheGroup by itself, and all active Layer\n// stores in a group together. A single EntityStore object belongs to only\n// one CacheGroup, store.group. The CacheGroup is responsible for tracking\n// dependencies, so store.group is helpful for generating unique keys for\n// cached results that need to be invalidated when/if those dependencies\n// change. If we used the EntityStore objects themselves as cache keys (that\n// is, store rather than store.group), the cache would become unnecessarily\n// fragmented by all the different Layer objects. Instead, the CacheGroup\n// approach allows all optimistic Layer objects in the same linked list to\n// belong to one CacheGroup, with the non-optimistic Root object belonging\n// to another CacheGroup, allowing resultCaching dependencies to be tracked\n// separately for optimistic and non-optimistic entity data.\nclass CacheGroup {\n private d: OptimisticDependencyFunction | null = null;\n\n // Used by the EntityStore#makeCacheKey method to compute cache keys\n // specific to this CacheGroup.\n public keyMaker!: Trie;\n\n constructor(\n public readonly caching: boolean,\n private parent: CacheGroup | null = null\n ) {\n this.resetCaching();\n }\n\n public resetCaching() {\n this.d = this.caching ? dep() : null;\n this.keyMaker = new Trie(canUseWeakMap);\n }\n\n public depend(dataId: string, storeFieldName: string) {\n if (this.d) {\n this.d(makeDepKey(dataId, storeFieldName));\n const fieldName = fieldNameFromStoreName(storeFieldName);\n if (fieldName !== storeFieldName) {\n // Fields with arguments that contribute extra identifying\n // information to the fieldName (thus forming the storeFieldName)\n // depend not only on the full storeFieldName but also on the\n // short fieldName, so the field can be invalidated using either\n // level of specificity.\n this.d(makeDepKey(dataId, fieldName));\n }\n if (this.parent) {\n this.parent.depend(dataId, storeFieldName);\n }\n }\n }\n\n public dirty(dataId: string, storeFieldName: string) {\n if (this.d) {\n this.d.dirty(\n makeDepKey(dataId, storeFieldName),\n // When storeFieldName === \"__exists\", that means the entity identified\n // by dataId has either disappeared from the cache or was newly added,\n // so the result caching system would do well to \"forget everything it\n // knows\" about that object. To achieve that kind of invalidation, we\n // not only dirty the associated result cache entry, but also remove it\n // completely from the dependency graph. For the optimism implementation\n // details, see https://github.com/benjamn/optimism/pull/195.\n storeFieldName === \"__exists\" ? \"forget\" : \"setDirty\"\n );\n }\n }\n}\n\nfunction makeDepKey(dataId: string, storeFieldName: string) {\n // Since field names cannot have '#' characters in them, this method\n // of joining the field name and the ID should be unambiguous, and much\n // cheaper than JSON.stringify([dataId, fieldName]).\n return storeFieldName + \"#\" + dataId;\n}\n\nexport function maybeDependOnExistenceOfEntity(\n store: NormalizedCache,\n entityId: string\n) {\n if (supportsResultCaching(store)) {\n // We use this pseudo-field __exists elsewhere in the EntityStore code to\n // represent changes in the existence of the entity object identified by\n // entityId. This dependency gets reliably dirtied whenever an object with\n // this ID is deleted (or newly created) within this group, so any result\n // cache entries (for example, StoreReader#executeSelectionSet results) that\n // depend on __exists for this entityId will get dirtied as well, leading to\n // the eventual recomputation (instead of reuse) of those result objects the\n // next time someone reads them from the cache.\n store.group.depend(entityId, \"__exists\");\n }\n}\n\nexport namespace EntityStore {\n // Refer to this class as EntityStore.Root outside this namespace.\n export class Root extends EntityStore {\n constructor({\n policies,\n resultCaching = true,\n seed,\n }: {\n policies: Policies;\n resultCaching?: boolean;\n seed?: NormalizedCacheObject;\n }) {\n super(policies, new CacheGroup(resultCaching));\n if (seed) this.replace(seed);\n }\n\n public readonly stump = new Stump(this);\n\n public addLayer(\n layerId: string,\n replay: (layer: EntityStore) => any\n ): Layer {\n // Adding an optimistic Layer on top of the Root actually adds the Layer\n // on top of the Stump, so the Stump always comes between the Root and\n // any Layer objects that we've added.\n return this.stump.addLayer(layerId, replay);\n }\n\n public removeLayer(): Root {\n // Never remove the root layer.\n return this;\n }\n\n public readonly storageTrie = new Trie(canUseWeakMap);\n public getStorage(): StorageType {\n return this.storageTrie.lookupArray(arguments);\n }\n }\n}\n\n// Not exported, since all Layer instances are created by the addLayer method\n// of the EntityStore.Root class.\nclass Layer extends EntityStore {\n constructor(\n public readonly id: string,\n public readonly parent: EntityStore,\n public readonly replay: (layer: EntityStore) => any,\n public readonly group: CacheGroup\n ) {\n super(parent.policies, group);\n replay(this);\n }\n\n public addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer {\n return new Layer(layerId, this, replay, this.group);\n }\n\n public removeLayer(layerId: string): EntityStore {\n // Remove all instances of the given id, not just the first one.\n const parent = this.parent.removeLayer(layerId);\n\n if (layerId === this.id) {\n if (this.group.caching) {\n // Dirty every ID we're removing. Technically we might be able to avoid\n // dirtying fields that have values in higher layers, but we don't have\n // easy access to higher layers here, and we're about to recreate those\n // layers anyway (see parent.addLayer below).\n Object.keys(this.data).forEach((dataId) => {\n const ownStoreObject = this.data[dataId];\n const parentStoreObject = parent[\"lookup\"](dataId);\n if (!parentStoreObject) {\n // The StoreObject identified by dataId was defined in this layer\n // but will be undefined in the parent layer, so we can delete the\n // whole entity using this.delete(dataId). Since we're about to\n // throw this layer away, the only goal of this deletion is to dirty\n // the removed fields.\n this.delete(dataId);\n } else if (!ownStoreObject) {\n // This layer had an entry for dataId but it was undefined, which\n // means the entity was deleted in this layer, and it's about to\n // become undeleted when we remove this layer, so we need to dirty\n // all fields that are about to be reexposed.\n this.group.dirty(dataId, \"__exists\");\n Object.keys(parentStoreObject).forEach((storeFieldName) => {\n this.group.dirty(dataId, storeFieldName);\n });\n } else if (ownStoreObject !== parentStoreObject) {\n // If ownStoreObject is not exactly the same as parentStoreObject,\n // dirty any fields whose values will change as a result of this\n // removal.\n Object.keys(ownStoreObject).forEach((storeFieldName) => {\n if (\n !equal(\n ownStoreObject[storeFieldName],\n parentStoreObject[storeFieldName]\n )\n ) {\n this.group.dirty(dataId, storeFieldName);\n }\n });\n }\n });\n }\n\n return parent;\n }\n\n // No changes are necessary if the parent chain remains identical.\n if (parent === this.parent) return this;\n\n // Recreate this layer on top of the new parent.\n return parent.addLayer(this.id, this.replay);\n }\n\n public toObject(): NormalizedCacheObject {\n return {\n ...this.parent.toObject(),\n ...this.data,\n };\n }\n\n public findChildRefIds(dataId: string): Record {\n const fromParent = this.parent.findChildRefIds(dataId);\n return hasOwn.call(this.data, dataId) ?\n {\n ...fromParent,\n ...super.findChildRefIds(dataId),\n }\n : fromParent;\n }\n\n public getStorage(): StorageType {\n let p: EntityStore = this.parent;\n while ((p as Layer).parent) p = (p as Layer).parent;\n return p.getStorage.apply(\n p,\n // @ts-expect-error\n arguments\n );\n }\n}\n\n// Represents a Layer permanently installed just above the Root, which allows\n// reading optimistically (and registering optimistic dependencies) even when\n// no optimistic layers are currently active. The stump.group CacheGroup object\n// is shared by any/all Layer objects added on top of the Stump.\nclass Stump extends Layer {\n constructor(root: EntityStore.Root) {\n super(\n \"EntityStore.Stump\",\n root,\n () => {},\n new CacheGroup(root.group.caching, root.group)\n );\n }\n\n public removeLayer() {\n // Never remove the Stump layer.\n return this;\n }\n\n public merge(older: string | StoreObject, newer: string | StoreObject) {\n // We never want to write any data into the Stump, so we forward any merge\n // calls to the Root instead. Another option here would be to throw an\n // exception, but the toReference(object, true) function can sometimes\n // trigger Stump writes (which used to be Root writes, before the Stump\n // concept was introduced).\n return this.parent.merge(older, newer);\n }\n}\n\nfunction storeObjectReconciler(\n existingObject: StoreObject,\n incomingObject: StoreObject,\n property: string | number\n): StoreValue {\n const existingValue = existingObject[property];\n const incomingValue = incomingObject[property];\n // Wherever there is a key collision, prefer the incoming value, unless\n // it is deeply equal to the existing value. It's worth checking deep\n // equality here (even though blindly returning incoming would be\n // logically correct) because preserving the referential identity of\n // existing data can prevent needless rereading and rerendering.\n return equal(existingValue, incomingValue) ? existingValue : incomingValue;\n}\n\nexport function supportsResultCaching(store: any): store is EntityStore {\n // When result caching is disabled, store.depend will be null.\n return !!(store instanceof EntityStore && store.group.caching);\n}\n","import { Trie } from \"@wry/trie\";\nimport {\n canUseWeakMap,\n canUseWeakSet,\n isNonNullObject as isObjectOrArray,\n} from \"../../utilities/index.js\";\nimport { isArray } from \"./helpers.js\";\n\nfunction shallowCopy(value: T): T {\n if (isObjectOrArray(value)) {\n return isArray(value) ?\n (value.slice(0) as any as T)\n : { __proto__: Object.getPrototypeOf(value), ...value };\n }\n return value;\n}\n\n// When programmers talk about the \"canonical form\" of an object, they\n// usually have the following meaning in mind, which I've copied from\n// https://en.wiktionary.org/wiki/canonical_form:\n//\n// 1. A standard or normal presentation of a mathematical entity [or\n// object]. A canonical form is an element of a set of representatives\n// of equivalence classes of forms such that there is a function or\n// procedure which projects every element of each equivalence class\n// onto that one element, the canonical form of that equivalence\n// class. The canonical form is expected to be simpler than the rest of\n// the forms in some way.\n//\n// That's a long-winded way of saying any two objects that have the same\n// canonical form may be considered equivalent, even if they are !==,\n// which usually means the objects are structurally equivalent (deeply\n// equal), but don't necessarily use the same memory.\n//\n// Like a literary or musical canon, this ObjectCanon class represents a\n// collection of unique canonical items (JavaScript objects), with the\n// important property that canon.admit(a) === canon.admit(b) if a and b\n// are deeply equal to each other. In terms of the definition above, the\n// canon.admit method is the \"function or procedure which projects every\"\n// object \"onto that one element, the canonical form.\"\n//\n// In the worst case, the canonicalization process may involve looking at\n// every property in the provided object tree, so it takes the same order\n// of time as deep equality checking. Fortunately, already-canonicalized\n// objects are returned immediately from canon.admit, so the presence of\n// canonical subtrees tends to speed up canonicalization.\n//\n// Since consumers of canonical objects can check for deep equality in\n// constant time, canonicalizing cache results can massively improve the\n// performance of application code that skips re-rendering unchanged\n// results, such as \"pure\" UI components in a framework like React.\n//\n// Of course, since canonical objects may be shared widely between\n// unrelated consumers, it's important to think of them as immutable, even\n// though they are not actually frozen with Object.freeze in production,\n// due to the extra performance overhead that comes with frozen objects.\n//\n// Custom scalar objects whose internal class name is neither Array nor\n// Object can be included safely in the admitted tree, but they will not\n// be replaced with a canonical version (to put it another way, they are\n// assumed to be canonical already).\n//\n// If we ignore custom objects, no detection of cycles or repeated object\n// references is currently required by the StoreReader class, since\n// GraphQL result objects are JSON-serializable trees (and thus contain\n// neither cycles nor repeated subtrees), so we can avoid the complexity\n// of keeping track of objects we've already seen during the recursion of\n// the admit method.\n//\n// In the future, we may consider adding additional cases to the switch\n// statement to handle other common object types, such as \"[object Date]\"\n// objects, as needed.\nexport class ObjectCanon {\n // Set of all canonical objects this ObjectCanon has admitted, allowing\n // canon.admit to return previously-canonicalized objects immediately.\n private known = new (canUseWeakSet ? WeakSet : Set)();\n\n // Efficient storage/lookup structure for canonical objects.\n private pool = new Trie<{\n array?: any[];\n object?: Record;\n keys?: SortedKeysInfo;\n }>(canUseWeakMap);\n\n public isKnown(value: any): boolean {\n return isObjectOrArray(value) && this.known.has(value);\n }\n\n // Make the ObjectCanon assume this value has already been\n // canonicalized.\n private passes = new WeakMap();\n public pass(value: T): T;\n public pass(value: any) {\n if (isObjectOrArray(value)) {\n const copy = shallowCopy(value);\n this.passes.set(copy, value);\n return copy;\n }\n return value;\n }\n\n // Returns the canonical version of value.\n public admit(value: T): T;\n public admit(value: any) {\n if (isObjectOrArray(value)) {\n const original = this.passes.get(value);\n if (original) return original;\n\n const proto = Object.getPrototypeOf(value);\n switch (proto) {\n case Array.prototype: {\n if (this.known.has(value)) return value;\n const array: any[] = (value as any[]).map(this.admit, this);\n // Arrays are looked up in the Trie using their recursively\n // canonicalized elements, and the known version of the array is\n // preserved as node.array.\n const node = this.pool.lookupArray(array);\n if (!node.array) {\n this.known.add((node.array = array));\n // Since canonical arrays may be shared widely between\n // unrelated consumers, it's important to regard them as\n // immutable, even if they are not frozen in production.\n if (__DEV__) {\n Object.freeze(array);\n }\n }\n return node.array;\n }\n\n case null:\n case Object.prototype: {\n if (this.known.has(value)) return value;\n const proto = Object.getPrototypeOf(value);\n const array = [proto];\n const keys = this.sortedKeys(value);\n array.push(keys.json);\n const firstValueIndex = array.length;\n keys.sorted.forEach((key) => {\n array.push(this.admit((value as any)[key]));\n });\n // Objects are looked up in the Trie by their prototype (which\n // is *not* recursively canonicalized), followed by a JSON\n // representation of their (sorted) keys, followed by the\n // sequence of recursively canonicalized values corresponding to\n // those keys. To keep the final results unambiguous with other\n // sequences (such as arrays that just happen to contain [proto,\n // keys.json, value1, value2, ...]), the known version of the\n // object is stored as node.object.\n const node = this.pool.lookupArray(array);\n if (!node.object) {\n const obj = (node.object = Object.create(proto));\n this.known.add(obj);\n keys.sorted.forEach((key, i) => {\n obj[key] = array[firstValueIndex + i];\n });\n // Since canonical objects may be shared widely between\n // unrelated consumers, it's important to regard them as\n // immutable, even if they are not frozen in production.\n if (__DEV__) {\n Object.freeze(obj);\n }\n }\n return node.object;\n }\n }\n }\n return value;\n }\n\n // It's worthwhile to cache the sorting of arrays of strings, since the\n // same initial unsorted arrays tend to be encountered many times.\n // Fortunately, we can reuse the Trie machinery to look up the sorted\n // arrays in linear time (which is faster than sorting large arrays).\n private sortedKeys(obj: object) {\n const keys = Object.keys(obj);\n const node = this.pool.lookupArray(keys);\n if (!node.keys) {\n keys.sort();\n const json = JSON.stringify(keys);\n if (!(node.keys = this.keysByJSON.get(json))) {\n this.keysByJSON.set(json, (node.keys = { sorted: keys, json }));\n }\n }\n return node.keys;\n }\n // Arrays that contain the same elements in a different order can share\n // the same SortedKeysInfo object, to save memory.\n private keysByJSON = new Map();\n\n // This has to come last because it depends on keysByJSON.\n public readonly empty = this.admit({});\n}\n\ntype SortedKeysInfo = {\n sorted: string[];\n json: string;\n};\n","import { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\n\nimport type { DocumentNode, FieldNode, SelectionSetNode } from \"graphql\";\nimport { Kind } from \"graphql\";\nimport type { OptimisticWrapperFunction } from \"optimism\";\nimport { wrap } from \"optimism\";\n\nimport type {\n Reference,\n StoreObject,\n FragmentMap,\n FragmentMapFunction,\n} from \"../../utilities/index.js\";\nimport {\n isField,\n resultKeyNameFromField,\n isReference,\n makeReference,\n shouldInclude,\n addTypenameToDocument,\n getDefaultValues,\n getMainDefinition,\n getQueryDefinition,\n getFragmentFromSelection,\n maybeDeepFreeze,\n mergeDeepArray,\n DeepMerger,\n isNonNullObject,\n canUseWeakMap,\n compact,\n canonicalStringify,\n cacheSizes,\n defaultCacheSizes,\n} from \"../../utilities/index.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\nimport type {\n DiffQueryAgainstStoreOptions,\n InMemoryCacheConfig,\n NormalizedCache,\n ReadMergeModifyContext,\n} from \"./types.js\";\nimport {\n maybeDependOnExistenceOfEntity,\n supportsResultCaching,\n} from \"./entityStore.js\";\nimport {\n isArray,\n extractFragmentContext,\n getTypenameFromStoreObject,\n shouldCanonizeResults,\n} from \"./helpers.js\";\nimport type { Policies } from \"./policies.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type { MissingTree } from \"../core/types/common.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { ObjectCanon } from \"./object-canon.js\";\n\nexport type VariableMap = { [name: string]: any };\n\ninterface ReadContext extends ReadMergeModifyContext {\n query: DocumentNode;\n policies: Policies;\n canonizeResults: boolean;\n fragmentMap: FragmentMap;\n lookupFragment: FragmentMapFunction;\n}\n\nexport type ExecResult = {\n result: R;\n missing?: MissingTree;\n};\n\ntype ExecSelectionSetOptions = {\n selectionSet: SelectionSetNode;\n objectOrReference: StoreObject | Reference;\n enclosingRef: Reference;\n context: ReadContext;\n};\n\ntype ExecSubSelectedArrayOptions = {\n field: FieldNode;\n array: readonly any[];\n enclosingRef: Reference;\n context: ReadContext;\n};\n\nexport interface StoreReaderConfig {\n cache: InMemoryCache;\n addTypename?: boolean;\n resultCacheMaxSize?: number;\n canonizeResults?: boolean;\n canon?: ObjectCanon;\n fragments?: InMemoryCacheConfig[\"fragments\"];\n}\n\n// Arguments type after keyArgs translation.\ntype ExecSelectionSetKeyArgs = [\n SelectionSetNode,\n StoreObject | Reference,\n ReadMergeModifyContext,\n boolean,\n];\n\nfunction execSelectionSetKeyArgs(\n options: ExecSelectionSetOptions\n): ExecSelectionSetKeyArgs {\n return [\n options.selectionSet,\n options.objectOrReference,\n options.context,\n // We split out this property so we can pass different values\n // independently without modifying options.context itself.\n options.context.canonizeResults,\n ];\n}\n\nexport class StoreReader {\n // cached version of executeSelectionSet\n private executeSelectionSet: OptimisticWrapperFunction<\n [ExecSelectionSetOptions], // Actual arguments tuple type.\n ExecResult, // Actual return type.\n ExecSelectionSetKeyArgs\n >;\n\n // cached version of executeSubSelectedArray\n private executeSubSelectedArray: OptimisticWrapperFunction<\n [ExecSubSelectedArrayOptions],\n ExecResult,\n [ExecSubSelectedArrayOptions]\n >;\n\n private config: {\n cache: InMemoryCache;\n addTypename: boolean;\n resultCacheMaxSize?: number;\n canonizeResults: boolean;\n fragments?: InMemoryCacheConfig[\"fragments\"];\n };\n\n private knownResults = new (canUseWeakMap ? WeakMap : Map)<\n Record,\n SelectionSetNode\n >();\n\n public canon: ObjectCanon;\n public resetCanon() {\n this.canon = new ObjectCanon();\n }\n\n constructor(config: StoreReaderConfig) {\n this.config = compact(config, {\n addTypename: config.addTypename !== false,\n canonizeResults: shouldCanonizeResults(config),\n });\n\n this.canon = config.canon || new ObjectCanon();\n\n // memoized functions in this class will be \"garbage-collected\"\n // by recreating the whole `StoreReader` in\n // `InMemoryCache.resetResultsCache`\n // (triggered from `InMemoryCache.gc` with `resetResultCache: true`)\n this.executeSelectionSet = wrap(\n (options) => {\n const { canonizeResults } = options.context;\n\n const peekArgs = execSelectionSetKeyArgs(options);\n\n // Negate this boolean option so we can find out if we've already read\n // this result using the other boolean value.\n peekArgs[3] = !canonizeResults;\n\n const other = this.executeSelectionSet.peek(...peekArgs);\n\n if (other) {\n if (canonizeResults) {\n return {\n ...other,\n // If we previously read this result without canonizing it, we can\n // reuse that result simply by canonizing it now.\n result: this.canon.admit(other.result),\n };\n }\n // If we previously read this result with canonization enabled, we can\n // return that canonized result as-is.\n return other;\n }\n\n maybeDependOnExistenceOfEntity(\n options.context.store,\n options.enclosingRef.__ref\n );\n\n // Finally, if we didn't find any useful previous results, run the real\n // execSelectionSetImpl method with the given options.\n return this.execSelectionSetImpl(options);\n },\n {\n max:\n this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSelectionSet\"] ||\n defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"],\n keyArgs: execSelectionSetKeyArgs,\n // Note that the parameters of makeCacheKey are determined by the\n // array returned by keyArgs.\n makeCacheKey(selectionSet, parent, context, canonizeResults) {\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(\n selectionSet,\n isReference(parent) ? parent.__ref : parent,\n context.varString,\n canonizeResults\n );\n }\n },\n }\n );\n\n this.executeSubSelectedArray = wrap(\n (options: ExecSubSelectedArrayOptions) => {\n maybeDependOnExistenceOfEntity(\n options.context.store,\n options.enclosingRef.__ref\n );\n return this.execSubSelectedArrayImpl(options);\n },\n {\n max:\n this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSubSelectedArray\"] ||\n defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"],\n makeCacheKey({ field, array, context }) {\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(field, array, context.varString);\n }\n },\n }\n );\n }\n\n /**\n * Given a store and a query, return as much of the result as possible and\n * identify if any data was missing from the store.\n */\n public diffQueryAgainstStore({\n store,\n query,\n rootId = \"ROOT_QUERY\",\n variables,\n returnPartialData = true,\n canonizeResults = this.config.canonizeResults,\n }: DiffQueryAgainstStoreOptions): Cache.DiffResult {\n const policies = this.config.cache.policies;\n\n variables = {\n ...getDefaultValues(getQueryDefinition(query)),\n ...variables!,\n };\n\n const rootRef = makeReference(rootId);\n const execResult = this.executeSelectionSet({\n selectionSet: getMainDefinition(query).selectionSet,\n objectOrReference: rootRef,\n enclosingRef: rootRef,\n context: {\n store,\n query,\n policies,\n variables,\n varString: canonicalStringify(variables),\n canonizeResults,\n ...extractFragmentContext(query, this.config.fragments),\n },\n });\n\n let missing: MissingFieldError[] | undefined;\n if (execResult.missing) {\n // For backwards compatibility we still report an array of\n // MissingFieldError objects, even though there will only ever be at most\n // one of them, now that all missing field error messages are grouped\n // together in the execResult.missing tree.\n missing = [\n new MissingFieldError(\n firstMissing(execResult.missing)!,\n execResult.missing,\n query,\n variables\n ),\n ];\n if (!returnPartialData) {\n throw missing[0];\n }\n }\n\n return {\n result: execResult.result,\n complete: !missing,\n missing,\n };\n }\n\n public isFresh(\n result: Record,\n parent: StoreObject | Reference,\n selectionSet: SelectionSetNode,\n context: ReadMergeModifyContext\n ): boolean {\n if (\n supportsResultCaching(context.store) &&\n this.knownResults.get(result) === selectionSet\n ) {\n const latest = this.executeSelectionSet.peek(\n selectionSet,\n parent,\n context,\n // If result is canonical, then it could only have been previously\n // cached by the canonizing version of executeSelectionSet, so we can\n // avoid checking both possibilities here.\n this.canon.isKnown(result)\n );\n if (latest && result === latest.result) {\n return true;\n }\n }\n return false;\n }\n\n // Uncached version of executeSelectionSet.\n private execSelectionSetImpl({\n selectionSet,\n objectOrReference,\n enclosingRef,\n context,\n }: ExecSelectionSetOptions): ExecResult {\n if (\n isReference(objectOrReference) &&\n !context.policies.rootTypenamesById[objectOrReference.__ref] &&\n !context.store.has(objectOrReference.__ref)\n ) {\n return {\n result: this.canon.empty,\n missing: `Dangling reference to missing ${objectOrReference.__ref} object`,\n };\n }\n\n const { variables, policies, store } = context;\n const typename = store.getFieldValue(\n objectOrReference,\n \"__typename\"\n );\n\n const objectsToMerge: Record[] = [];\n let missing: MissingTree | undefined;\n const missingMerger = new DeepMerger();\n\n if (\n this.config.addTypename &&\n typeof typename === \"string\" &&\n !policies.rootIdsByTypename[typename]\n ) {\n // Ensure we always include a default value for the __typename\n // field, if we have one, and this.config.addTypename is true. Note\n // that this field can be overridden by other merged objects.\n objectsToMerge.push({ __typename: typename });\n }\n\n function handleMissing(result: ExecResult, resultName: string): T {\n if (result.missing) {\n missing = missingMerger.merge(missing, {\n [resultName]: result.missing,\n });\n }\n return result.result;\n }\n\n const workSet = new Set(selectionSet.selections);\n\n workSet.forEach((selection) => {\n // Omit fields with directives @skip(if: ) or\n // @include(if: ).\n if (!shouldInclude(selection, variables)) return;\n\n if (isField(selection)) {\n let fieldValue = policies.readField(\n {\n fieldName: selection.name.value,\n field: selection,\n variables: context.variables,\n from: objectOrReference,\n },\n context\n );\n\n const resultName = resultKeyNameFromField(selection);\n\n if (fieldValue === void 0) {\n if (!addTypenameToDocument.added(selection)) {\n missing = missingMerger.merge(missing, {\n [resultName]: `Can't find field '${selection.name.value}' on ${\n isReference(objectOrReference) ?\n objectOrReference.__ref + \" object\"\n : \"object \" + JSON.stringify(objectOrReference, null, 2)\n }`,\n });\n }\n } else if (isArray(fieldValue)) {\n if (fieldValue.length > 0) {\n fieldValue = handleMissing(\n this.executeSubSelectedArray({\n field: selection,\n array: fieldValue,\n enclosingRef,\n context,\n }),\n resultName\n );\n }\n } else if (!selection.selectionSet) {\n // If the field does not have a selection set, then we handle it\n // as a scalar value. To keep this.canon from canonicalizing\n // this value, we use this.canon.pass to wrap fieldValue in a\n // Pass object that this.canon.admit will later unwrap as-is.\n if (context.canonizeResults) {\n fieldValue = this.canon.pass(fieldValue);\n }\n } else if (fieldValue != null) {\n // In this case, because we know the field has a selection set,\n // it must be trying to query a GraphQLObjectType, which is why\n // fieldValue must be != null.\n fieldValue = handleMissing(\n this.executeSelectionSet({\n selectionSet: selection.selectionSet,\n objectOrReference: fieldValue as StoreObject | Reference,\n enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,\n context,\n }),\n resultName\n );\n }\n\n if (fieldValue !== void 0) {\n objectsToMerge.push({ [resultName]: fieldValue });\n }\n } else {\n const fragment = getFragmentFromSelection(\n selection,\n context.lookupFragment\n );\n\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(`No fragment named %s`, selection.name.value);\n }\n\n if (fragment && policies.fragmentMatches(fragment, typename)) {\n fragment.selectionSet.selections.forEach(workSet.add, workSet);\n }\n }\n });\n\n const result = mergeDeepArray(objectsToMerge);\n const finalResult: ExecResult = { result, missing };\n const frozen =\n context.canonizeResults ?\n this.canon.admit(finalResult)\n // Since this.canon is normally responsible for freezing results (only in\n // development), freeze them manually if canonization is disabled.\n : maybeDeepFreeze(finalResult);\n\n // Store this result with its selection set so that we can quickly\n // recognize it again in the StoreReader#isFresh method.\n if (frozen.result) {\n this.knownResults.set(frozen.result, selectionSet);\n }\n\n return frozen;\n }\n\n // Uncached version of executeSubSelectedArray.\n private execSubSelectedArrayImpl({\n field,\n array,\n enclosingRef,\n context,\n }: ExecSubSelectedArrayOptions): ExecResult {\n let missing: MissingTree | undefined;\n let missingMerger = new DeepMerger();\n\n function handleMissing(childResult: ExecResult, i: number): T {\n if (childResult.missing) {\n missing = missingMerger.merge(missing, { [i]: childResult.missing });\n }\n return childResult.result;\n }\n\n if (field.selectionSet) {\n array = array.filter(context.store.canRead);\n }\n\n array = array.map((item, i) => {\n // null value in array\n if (item === null) {\n return null;\n }\n\n // This is a nested array, recurse\n if (isArray(item)) {\n return handleMissing(\n this.executeSubSelectedArray({\n field,\n array: item,\n enclosingRef,\n context,\n }),\n i\n );\n }\n\n // This is an object, run the selection set on it\n if (field.selectionSet) {\n return handleMissing(\n this.executeSelectionSet({\n selectionSet: field.selectionSet,\n objectOrReference: item,\n enclosingRef: isReference(item) ? item : enclosingRef,\n context,\n }),\n i\n );\n }\n\n if (__DEV__) {\n assertSelectionSetForIdValue(context.store, field, item);\n }\n\n return item;\n });\n\n return {\n result: context.canonizeResults ? this.canon.admit(array) : array,\n missing,\n };\n }\n}\n\nfunction firstMissing(tree: MissingTree): string | undefined {\n try {\n JSON.stringify(tree, (_, value) => {\n if (typeof value === \"string\") throw value;\n return value;\n });\n } catch (result) {\n return result as string;\n }\n}\n\nfunction assertSelectionSetForIdValue(\n store: NormalizedCache,\n field: FieldNode,\n fieldValue: any\n) {\n if (!field.selectionSet) {\n const workSet = new Set([fieldValue]);\n workSet.forEach((value) => {\n if (isNonNullObject(value)) {\n invariant(\n !isReference(value),\n `Missing selection set for object of type %s returned for query field %s`,\n getTypenameFromStoreObject(store, value),\n field.name.value\n );\n Object.values(value).forEach(workSet.add, workSet);\n }\n });\n }\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport {\n argumentsObjectFromField,\n DeepMerger,\n isNonEmptyArray,\n isNonNullObject,\n} from \"../../utilities/index.js\";\n\nimport { hasOwn, isArray } from \"./helpers.js\";\nimport type {\n KeySpecifier,\n KeyFieldsFunction,\n KeyArgsFunction,\n} from \"./policies.js\";\n\n// Mapping from JSON-encoded KeySpecifier strings to associated information.\nconst specifierInfoCache: Record<\n string,\n {\n paths?: string[][];\n keyFieldsFn?: KeyFieldsFunction;\n keyArgsFn?: KeyArgsFunction;\n }\n> = Object.create(null);\n\nfunction lookupSpecifierInfo(spec: KeySpecifier) {\n // It's safe to encode KeySpecifier arrays with JSON.stringify, since they're\n // just arrays of strings or nested KeySpecifier arrays, and the order of the\n // array elements is important (and suitably preserved by JSON.stringify).\n const cacheKey = JSON.stringify(spec);\n return (\n specifierInfoCache[cacheKey] ||\n (specifierInfoCache[cacheKey] = Object.create(null))\n );\n}\n\nexport function keyFieldsFnFromSpecifier(\n specifier: KeySpecifier\n): KeyFieldsFunction {\n const info = lookupSpecifierInfo(specifier);\n\n return (\n info.keyFieldsFn ||\n (info.keyFieldsFn = (object, context) => {\n const extract: typeof extractKey = (from, key) =>\n context.readField(key, from);\n\n const keyObject = (context.keyObject = collectSpecifierPaths(\n specifier,\n (schemaKeyPath) => {\n let extracted = extractKeyPath(\n context.storeObject,\n schemaKeyPath,\n // Using context.readField to extract paths from context.storeObject\n // allows the extraction to see through Reference objects and respect\n // custom read functions.\n extract\n );\n\n if (\n extracted === void 0 &&\n object !== context.storeObject &&\n hasOwn.call(object, schemaKeyPath[0])\n ) {\n // If context.storeObject fails to provide a value for the requested\n // path, fall back to the raw result object, if it has a top-level key\n // matching the first key in the path (schemaKeyPath[0]). This allows\n // key fields included in the written data to be saved in the cache\n // even if they are not selected explicitly in context.selectionSet.\n // Not being mentioned by context.selectionSet is convenient here,\n // since it means these extra fields cannot be affected by field\n // aliasing, which is why we can use extractKey instead of\n // context.readField for this extraction.\n extracted = extractKeyPath(object, schemaKeyPath, extractKey);\n }\n\n invariant(\n extracted !== void 0,\n `Missing field '%s' while extracting keyFields from %s`,\n schemaKeyPath.join(\".\"),\n object\n );\n\n return extracted;\n }\n ));\n\n return `${context.typename}:${JSON.stringify(keyObject)}`;\n })\n );\n}\n\n// The keyArgs extraction process is roughly analogous to keyFields extraction,\n// but there are no aliases involved, missing fields are tolerated (by merely\n// omitting them from the key), and drawing from field.directives or variables\n// is allowed (in addition to drawing from the field's arguments object).\n// Concretely, these differences mean passing a different key path extractor\n// function to collectSpecifierPaths, reusing the shared extractKeyPath helper\n// wherever possible.\nexport function keyArgsFnFromSpecifier(\n specifier: KeySpecifier\n): KeyArgsFunction {\n const info = lookupSpecifierInfo(specifier);\n\n return (\n info.keyArgsFn ||\n (info.keyArgsFn = (args, { field, variables, fieldName }) => {\n const collected = collectSpecifierPaths(specifier, (keyPath) => {\n const firstKey = keyPath[0];\n const firstChar = firstKey.charAt(0);\n\n if (firstChar === \"@\") {\n if (field && isNonEmptyArray(field.directives)) {\n const directiveName = firstKey.slice(1);\n // If the directive appears multiple times, only the first\n // occurrence's arguments will be used. TODO Allow repetition?\n // TODO Cache this work somehow, a la aliasMap?\n const d = field.directives.find(\n (d) => d.name.value === directiveName\n );\n // Fortunately argumentsObjectFromField works for DirectiveNode!\n const directiveArgs = d && argumentsObjectFromField(d, variables);\n // For directives without arguments (d defined, but directiveArgs ===\n // null), the presence or absence of the directive still counts as\n // part of the field key, so we return null in those cases. If no\n // directive with this name was found for this field (d undefined and\n // thus directiveArgs undefined), we return undefined, which causes\n // this value to be omitted from the key object returned by\n // collectSpecifierPaths.\n return (\n directiveArgs &&\n extractKeyPath(\n directiveArgs,\n // If keyPath.length === 1, this code calls extractKeyPath with an\n // empty path, which works because it uses directiveArgs as the\n // extracted value.\n keyPath.slice(1)\n )\n );\n }\n // If the key started with @ but there was no corresponding directive,\n // we want to omit this value from the key object, not fall through to\n // treating @whatever as a normal argument name.\n return;\n }\n\n if (firstChar === \"$\") {\n const variableName = firstKey.slice(1);\n if (variables && hasOwn.call(variables, variableName)) {\n const varKeyPath = keyPath.slice(0);\n varKeyPath[0] = variableName;\n return extractKeyPath(variables, varKeyPath);\n }\n // If the key started with $ but there was no corresponding variable, we\n // want to omit this value from the key object, not fall through to\n // treating $whatever as a normal argument name.\n return;\n }\n\n if (args) {\n return extractKeyPath(args, keyPath);\n }\n });\n\n const suffix = JSON.stringify(collected);\n\n // If no arguments were passed to this field, and it didn't have any other\n // field key contributions from directives or variables, hide the empty\n // :{} suffix from the field key. However, a field passed no arguments can\n // still end up with a non-empty :{...} suffix if its key configuration\n // refers to directives or variables.\n if (args || suffix !== \"{}\") {\n fieldName += \":\" + suffix;\n }\n\n return fieldName;\n })\n );\n}\n\nexport function collectSpecifierPaths(\n specifier: KeySpecifier,\n extractor: (path: string[]) => any\n): Record {\n // For each path specified by specifier, invoke the extractor, and repeatedly\n // merge the results together, with appropriate ancestor context.\n const merger = new DeepMerger();\n return getSpecifierPaths(specifier).reduce((collected, path) => {\n let toMerge = extractor(path);\n if (toMerge !== void 0) {\n // This path is not expected to contain array indexes, so the toMerge\n // reconstruction will not contain arrays. TODO Fix this?\n for (let i = path.length - 1; i >= 0; --i) {\n toMerge = { [path[i]]: toMerge };\n }\n collected = merger.merge(collected, toMerge);\n }\n return collected;\n }, Object.create(null));\n}\n\nexport function getSpecifierPaths(spec: KeySpecifier): string[][] {\n const info = lookupSpecifierInfo(spec);\n\n if (!info.paths) {\n const paths: string[][] = (info.paths = []);\n const currentPath: string[] = [];\n\n spec.forEach((s, i) => {\n if (isArray(s)) {\n getSpecifierPaths(s).forEach((p) => paths.push(currentPath.concat(p)));\n currentPath.length = 0;\n } else {\n currentPath.push(s);\n if (!isArray(spec[i + 1])) {\n paths.push(currentPath.slice(0));\n currentPath.length = 0;\n }\n }\n });\n }\n\n return info.paths!;\n}\n\nfunction extractKey, TKey extends string>(\n object: TObj,\n key: TKey\n): TObj[TKey] | undefined {\n return object[key];\n}\n\nexport function extractKeyPath(\n object: Record,\n path: string[],\n extract?: typeof extractKey\n): any {\n // For each key in path, extract the corresponding child property from obj,\n // flattening arrays if encountered (uncommon for keyFields and keyArgs, but\n // possible). The final result of path.reduce is normalized so unexpected leaf\n // objects have their keys safely sorted. That final result is difficult to\n // type as anything other than any. You're welcome to try to improve the\n // return type, but keep in mind extractKeyPath is not a public function\n // (exported only for testing), so the effort may not be worthwhile unless the\n // limited set of actual callers (see above) pass arguments that TypeScript\n // can statically type. If we know only that path is some array of strings\n // (and not, say, a specific tuple of statically known strings), any (or\n // possibly unknown) is the honest answer.\n extract = extract || extractKey;\n return normalize(\n path.reduce(function reducer(obj, key): any {\n return isArray(obj) ?\n obj.map((child) => reducer(child, key))\n : obj && extract!(obj, key);\n }, object)\n );\n}\n\nfunction normalize(value: T): T {\n // Usually the extracted value will be a scalar value, since most primary\n // key fields are scalar, but just in case we get an object or an array, we\n // need to do some normalization of the order of (nested) keys.\n if (isNonNullObject(value)) {\n if (isArray(value)) {\n return value.map(normalize) as any;\n }\n return collectSpecifierPaths(Object.keys(value).sort(), (path) =>\n extractKeyPath(value, path)\n ) as T;\n }\n return value;\n}\n","import { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\n\nimport type {\n InlineFragmentNode,\n FragmentDefinitionNode,\n SelectionSetNode,\n FieldNode,\n} from \"graphql\";\n\nimport type {\n FragmentMap,\n StoreValue,\n StoreObject,\n Reference,\n} from \"../../utilities/index.js\";\nimport {\n storeKeyNameFromField,\n argumentsObjectFromField,\n isReference,\n getStoreKeyName,\n isNonNullObject,\n stringifyForDisplay,\n} from \"../../utilities/index.js\";\nimport type {\n IdGetter,\n MergeInfo,\n NormalizedCache,\n ReadMergeModifyContext,\n} from \"./types.js\";\nimport {\n hasOwn,\n fieldNameFromStoreName,\n storeValueIsStoreObject,\n selectionSetMatchesResult,\n TypeOrFieldNameRegExp,\n defaultDataIdFromObject,\n isArray,\n} from \"./helpers.js\";\nimport { cacheSlot } from \"./reactiveVars.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type {\n SafeReadonly,\n FieldSpecifier,\n ToReferenceFunction,\n ReadFieldFunction,\n ReadFieldOptions,\n CanReadFunction,\n} from \"../core/types/common.js\";\nimport type { WriteContext } from \"./writeToStore.js\";\n\nimport {\n keyArgsFnFromSpecifier,\n keyFieldsFnFromSpecifier,\n} from \"./key-extractor.js\";\n\nexport type TypePolicies = {\n [__typename: string]: TypePolicy;\n};\n\n// TypeScript 3.7 will allow recursive type aliases, so this should work:\n// type KeySpecifier = (string | KeySpecifier)[]\nexport type KeySpecifier = ReadonlyArray;\n\nexport type KeyFieldsContext = {\n // The __typename of the incoming object, even if the __typename field was\n // aliased to another name in the raw result object. May be undefined when\n // dataIdFromObject is called for objects without __typename fields.\n typename: string | undefined;\n\n // The object to be identified, after processing to remove aliases and\n // normalize identifiable child objects with references.\n storeObject: StoreObject;\n\n // Handy tool for reading additional fields from context.storeObject, either\n // readField(\"fieldName\") to read storeObject[fieldName], or readField(\"name\",\n // objectOrReference) to read from another object or Reference. If you read a\n // field with a read function, that function will be invoked.\n readField: ReadFieldFunction;\n\n // If you are writing a custom keyFields function, and you plan to use the raw\n // result object passed as the first argument, you may also need access to the\n // selection set and available fragments for this object, just in case any\n // fields have aliases. Since this logic is tricky to get right, and these\n // context properties are not even always provided (for example, they are\n // omitted when calling cache.identify(object), where object is assumed to be\n // a StoreObject), we recommend you use context.storeObject (which has already\n // been de-aliased) and context.readField (which can read from references as\n // well as objects) instead of the raw result object in your keyFields\n // functions, or just rely on the internal implementation of keyFields:[...]\n // syntax to get these details right for you.\n selectionSet?: SelectionSetNode;\n fragmentMap?: FragmentMap;\n\n // Internal. May be set by the KeyFieldsFunction to report fields that were\n // involved in computing the ID. Never passed in by the caller.\n keyObject?: Record;\n};\n\nexport type KeyFieldsFunction = (\n object: Readonly,\n context: KeyFieldsContext\n) => KeySpecifier | false | ReturnType;\n\ntype KeyFieldsResult = Exclude, KeySpecifier>;\n\n// TODO Should TypePolicy be a generic type, with a TObject or TEntity\n// type parameter?\nexport type TypePolicy = {\n // Allows defining the primary key fields for this type, either using an\n // array of field names or a function that returns an arbitrary string.\n keyFields?: KeySpecifier | KeyFieldsFunction | false;\n\n // Allows defining a merge function (or merge:true/false shorthand) to\n // be used for merging objects of this type wherever they appear, unless\n // the parent field also defines a merge function/boolean (that is,\n // parent field merge functions take precedence over type policy merge\n // functions). In many cases, defining merge:true for a given type\n // policy can save you from specifying merge:true for all the field\n // policies where that type might be encountered.\n merge?: FieldMergeFunction | boolean;\n\n // In the rare event that your schema happens to use a different\n // __typename for the root Query, Mutation, and/or Schema types, you can\n // express your deviant preferences by enabling one of these options.\n queryType?: true;\n mutationType?: true;\n subscriptionType?: true;\n\n fields?: {\n [fieldName: string]: FieldPolicy | FieldReadFunction;\n };\n};\n\nexport type KeyArgsFunction = (\n args: Record | null,\n context: {\n typename: string;\n fieldName: string;\n field: FieldNode | null;\n variables?: Record;\n }\n) => KeySpecifier | false | ReturnType;\n\nexport type FieldPolicy<\n // The internal representation used to store the field's data in the\n // cache. Must be JSON-serializable if you plan to serialize the result\n // of cache.extract() using JSON.\n TExisting = any,\n // The type of the incoming parameter passed to the merge function,\n // typically matching the GraphQL response format, but with Reference\n // objects substituted for any identifiable child objects. Often the\n // same as TExisting, but not necessarily.\n TIncoming = TExisting,\n // The type that the read function actually returns, using TExisting\n // data and options.args as input. Usually the same as TIncoming.\n TReadResult = TIncoming,\n // Allows FieldFunctionOptions definition to be overwritten by the\n // developer\n TOptions extends FieldFunctionOptions = FieldFunctionOptions,\n> = {\n keyArgs?: KeySpecifier | KeyArgsFunction | false;\n read?: FieldReadFunction;\n merge?: FieldMergeFunction | boolean;\n};\n\nexport type StorageType = Record;\n\nfunction argsFromFieldSpecifier(spec: FieldSpecifier) {\n return (\n spec.args !== void 0 ? spec.args\n : spec.field ? argumentsObjectFromField(spec.field, spec.variables)\n : null\n );\n}\n\nexport interface FieldFunctionOptions<\n TArgs = Record,\n TVars = Record,\n> {\n args: TArgs | null;\n\n // The name of the field, equal to options.field.name.value when\n // options.field is available. Useful if you reuse the same function for\n // multiple fields, and you need to know which field you're currently\n // processing. Always a string, even when options.field is null.\n fieldName: string;\n\n // The full field key used internally, including serialized key arguments.\n storeFieldName: string;\n\n // The FieldNode object used to read this field. Useful if you need to\n // know about other attributes of the field, such as its directives. This\n // option will be null when a string was passed to options.readField.\n field: FieldNode | null;\n\n variables?: TVars;\n\n // Utilities for dealing with { __ref } objects.\n isReference: typeof isReference;\n toReference: ToReferenceFunction;\n\n // A handy place to put field-specific data that you want to survive\n // across multiple read function calls. Useful for field-level caching,\n // if your read function does any expensive work.\n storage: StorageType;\n\n cache: InMemoryCache;\n\n // Helper function for reading other fields within the current object.\n // If a foreign object or reference is provided, the field will be read\n // from that object instead of the current object, so this function can\n // be used (together with isReference) to examine the cache outside the\n // current object. If a FieldNode is passed instead of a string, and\n // that FieldNode has arguments, the same options.variables will be used\n // to compute the argument values. Note that this function will invoke\n // custom read functions for other fields, if defined. Always returns\n // immutable data (enforced with Object.freeze in development).\n readField: ReadFieldFunction;\n\n // Returns true for non-normalized StoreObjects and non-dangling\n // References, indicating that readField(name, objOrRef) has a chance of\n // working. Useful for filtering out dangling references from lists.\n canRead: CanReadFunction;\n\n // Instead of just merging objects with { ...existing, ...incoming }, this\n // helper function can be used to merge objects in a way that respects any\n // custom merge functions defined for their fields.\n mergeObjects: MergeObjectsFunction;\n}\n\ntype MergeObjectsFunction = (\n existing: T,\n incoming: T\n) => T;\n\nexport type FieldReadFunction<\n TExisting = any,\n TReadResult = TExisting,\n TOptions extends FieldFunctionOptions = FieldFunctionOptions,\n> = (\n // When reading a field, one often needs to know about any existing\n // value stored for that field. If the field is read before any value\n // has been written to the cache, this existing parameter will be\n // undefined, which makes it easy to use a default parameter expression\n // to supply the initial value. This parameter is positional (rather\n // than one of the named options) because that makes it possible for the\n // developer to annotate it with a type, without also having to provide\n // a whole new type for the options object.\n existing: SafeReadonly | undefined,\n options: TOptions\n) => TReadResult | undefined;\n\nexport type FieldMergeFunction<\n TExisting = any,\n TIncoming = TExisting,\n // Passing the whole FieldFunctionOptions makes the current definition\n // independent from its implementation\n TOptions extends FieldFunctionOptions = FieldFunctionOptions,\n> = (\n existing: SafeReadonly | undefined,\n // The incoming parameter needs to be positional as well, for the same\n // reasons discussed in FieldReadFunction above.\n incoming: SafeReadonly,\n options: TOptions\n) => SafeReadonly;\n\nconst nullKeyFieldsFn: KeyFieldsFunction = () => void 0;\nconst simpleKeyArgsFn: KeyArgsFunction = (_args, context) => context.fieldName;\n\n// These merge functions can be selected by specifying merge:true or\n// merge:false in a field policy.\nconst mergeTrueFn: FieldMergeFunction = (\n existing,\n incoming,\n { mergeObjects }\n) => mergeObjects(existing, incoming);\nconst mergeFalseFn: FieldMergeFunction = (_, incoming) => incoming;\n\nexport type PossibleTypesMap = {\n [supertype: string]: string[];\n};\n\nexport class Policies {\n private typePolicies: {\n [__typename: string]: {\n keyFn?: KeyFieldsFunction;\n merge?: FieldMergeFunction;\n fields: {\n [fieldName: string]: {\n keyFn?: KeyArgsFunction;\n read?: FieldReadFunction;\n merge?: FieldMergeFunction;\n };\n };\n };\n } = Object.create(null);\n\n private toBeAdded: {\n [__typename: string]: TypePolicy[];\n } = Object.create(null);\n\n // Map from subtype names to sets of supertype names. Note that this\n // representation inverts the structure of possibleTypes (whose keys are\n // supertypes and whose values are arrays of subtypes) because it tends\n // to be much more efficient to search upwards than downwards.\n private supertypeMap = new Map>();\n\n // Any fuzzy subtypes specified by possibleTypes will be converted to\n // RegExp objects and recorded here. Every key of this map can also be\n // found in supertypeMap. In many cases this Map will be empty, which\n // means no fuzzy subtype checking will happen in fragmentMatches.\n private fuzzySubtypes = new Map();\n\n public readonly cache: InMemoryCache;\n\n public readonly rootIdsByTypename: Record =\n Object.create(null);\n public readonly rootTypenamesById: Record =\n Object.create(null);\n\n public readonly usingPossibleTypes = false;\n\n constructor(\n private config: {\n cache: InMemoryCache;\n dataIdFromObject?: KeyFieldsFunction;\n possibleTypes?: PossibleTypesMap;\n typePolicies?: TypePolicies;\n }\n ) {\n this.config = {\n dataIdFromObject: defaultDataIdFromObject,\n ...config,\n };\n\n this.cache = this.config.cache;\n\n this.setRootTypename(\"Query\");\n this.setRootTypename(\"Mutation\");\n this.setRootTypename(\"Subscription\");\n\n if (config.possibleTypes) {\n this.addPossibleTypes(config.possibleTypes);\n }\n\n if (config.typePolicies) {\n this.addTypePolicies(config.typePolicies);\n }\n }\n\n public identify(\n object: StoreObject,\n partialContext?: Partial\n ): [string?, StoreObject?] {\n const policies = this;\n\n const typename =\n (partialContext &&\n (partialContext.typename || partialContext.storeObject?.__typename)) ||\n object.__typename;\n\n // It should be possible to write root Query fields with writeFragment,\n // using { __typename: \"Query\", ... } as the data, but it does not make\n // sense to allow the same identification behavior for the Mutation and\n // Subscription types, since application code should never be writing\n // directly to (or reading directly from) those root objects.\n if (typename === this.rootTypenamesById.ROOT_QUERY) {\n return [\"ROOT_QUERY\"];\n }\n\n // Default context.storeObject to object if not otherwise provided.\n const storeObject =\n (partialContext && partialContext.storeObject) || object;\n\n const context: KeyFieldsContext = {\n ...partialContext,\n typename,\n storeObject,\n readField:\n (partialContext && partialContext.readField) ||\n function () {\n const options = normalizeReadFieldOptions(arguments, storeObject);\n return policies.readField(options, {\n store: policies.cache[\"data\"],\n variables: options.variables,\n });\n },\n };\n\n let id: KeyFieldsResult;\n\n const policy = typename && this.getTypePolicy(typename);\n let keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;\n while (keyFn) {\n const specifierOrId = keyFn({ ...object, ...storeObject }, context);\n if (isArray(specifierOrId)) {\n keyFn = keyFieldsFnFromSpecifier(specifierOrId);\n } else {\n id = specifierOrId;\n break;\n }\n }\n\n id = id ? String(id) : void 0;\n return context.keyObject ? [id, context.keyObject] : [id];\n }\n\n public addTypePolicies(typePolicies: TypePolicies) {\n Object.keys(typePolicies).forEach((typename) => {\n const { queryType, mutationType, subscriptionType, ...incoming } =\n typePolicies[typename];\n\n // Though {query,mutation,subscription}Type configurations are rare,\n // it's important to call setRootTypename as early as possible,\n // since these configurations should apply consistently for the\n // entire lifetime of the cache. Also, since only one __typename can\n // qualify as one of these root types, these three properties cannot\n // be inherited, unlike the rest of the incoming properties. That\n // restriction is convenient, because the purpose of this.toBeAdded\n // is to delay the processing of type/field policies until the first\n // time they're used, allowing policies to be added in any order as\n // long as all relevant policies (including policies for supertypes)\n // have been added by the time a given policy is used for the first\n // time. In other words, since inheritance doesn't matter for these\n // properties, there's also no need to delay their processing using\n // the this.toBeAdded queue.\n if (queryType) this.setRootTypename(\"Query\", typename);\n if (mutationType) this.setRootTypename(\"Mutation\", typename);\n if (subscriptionType) this.setRootTypename(\"Subscription\", typename);\n\n if (hasOwn.call(this.toBeAdded, typename)) {\n this.toBeAdded[typename].push(incoming);\n } else {\n this.toBeAdded[typename] = [incoming];\n }\n });\n }\n\n private updateTypePolicy(typename: string, incoming: TypePolicy) {\n const existing = this.getTypePolicy(typename);\n const { keyFields, fields } = incoming;\n\n function setMerge(\n existing: { merge?: FieldMergeFunction | boolean },\n merge?: FieldMergeFunction | boolean\n ) {\n existing.merge =\n typeof merge === \"function\" ? merge\n // Pass merge:true as a shorthand for a merge implementation\n // that returns options.mergeObjects(existing, incoming).\n : merge === true ? mergeTrueFn\n // Pass merge:false to make incoming always replace existing\n // without any warnings about data clobbering.\n : merge === false ? mergeFalseFn\n : existing.merge;\n }\n\n // Type policies can define merge functions, as an alternative to\n // using field policies to merge child objects.\n setMerge(existing, incoming.merge);\n\n existing.keyFn =\n // Pass false to disable normalization for this typename.\n keyFields === false ? nullKeyFieldsFn\n // Pass an array of strings to use those fields to compute a\n // composite ID for objects of this typename.\n : isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)\n // Pass a function to take full control over identification.\n : typeof keyFields === \"function\" ? keyFields\n // Leave existing.keyFn unchanged if above cases fail.\n : existing.keyFn;\n\n if (fields) {\n Object.keys(fields).forEach((fieldName) => {\n const existing = this.getFieldPolicy(typename, fieldName, true)!;\n const incoming = fields[fieldName];\n\n if (typeof incoming === \"function\") {\n existing.read = incoming;\n } else {\n const { keyArgs, read, merge } = incoming;\n\n existing.keyFn =\n // Pass false to disable argument-based differentiation of\n // field identities.\n keyArgs === false ? simpleKeyArgsFn\n // Pass an array of strings to use named arguments to\n // compute a composite identity for the field.\n : isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)\n // Pass a function to take full control over field identity.\n : typeof keyArgs === \"function\" ? keyArgs\n // Leave existing.keyFn unchanged if above cases fail.\n : existing.keyFn;\n\n if (typeof read === \"function\") {\n existing.read = read;\n }\n\n setMerge(existing, merge);\n }\n\n if (existing.read && existing.merge) {\n // If we have both a read and a merge function, assume\n // keyArgs:false, because read and merge together can take\n // responsibility for interpreting arguments in and out. This\n // default assumption can always be overridden by specifying\n // keyArgs explicitly in the FieldPolicy.\n existing.keyFn = existing.keyFn || simpleKeyArgsFn;\n }\n });\n }\n }\n\n private setRootTypename(\n which: \"Query\" | \"Mutation\" | \"Subscription\",\n typename: string = which\n ) {\n const rootId = \"ROOT_\" + which.toUpperCase();\n const old = this.rootTypenamesById[rootId];\n if (typename !== old) {\n invariant(\n !old || old === which,\n `Cannot change root %s __typename more than once`,\n which\n );\n // First, delete any old __typename associated with this rootId from\n // rootIdsByTypename.\n if (old) delete this.rootIdsByTypename[old];\n // Now make this the only __typename that maps to this rootId.\n this.rootIdsByTypename[typename] = rootId;\n // Finally, update the __typename associated with this rootId.\n this.rootTypenamesById[rootId] = typename;\n }\n }\n\n public addPossibleTypes(possibleTypes: PossibleTypesMap) {\n (this.usingPossibleTypes as boolean) = true;\n Object.keys(possibleTypes).forEach((supertype) => {\n // Make sure all types have an entry in this.supertypeMap, even if\n // their supertype set is empty, so we can return false immediately\n // from policies.fragmentMatches for unknown supertypes.\n this.getSupertypeSet(supertype, true);\n\n possibleTypes[supertype].forEach((subtype) => {\n this.getSupertypeSet(subtype, true)!.add(supertype);\n const match = subtype.match(TypeOrFieldNameRegExp);\n if (!match || match[0] !== subtype) {\n // TODO Don't interpret just any invalid typename as a RegExp.\n this.fuzzySubtypes.set(subtype, new RegExp(subtype));\n }\n });\n });\n }\n\n private getTypePolicy(typename: string): Policies[\"typePolicies\"][string] {\n if (!hasOwn.call(this.typePolicies, typename)) {\n const policy: Policies[\"typePolicies\"][string] = (this.typePolicies[\n typename\n ] = Object.create(null));\n policy.fields = Object.create(null);\n\n // When the TypePolicy for typename is first accessed, instead of\n // starting with an empty policy object, inherit any properties or\n // fields from the type policies of the supertypes of typename.\n //\n // Any properties or fields defined explicitly within the TypePolicy\n // for typename will take precedence, and if there are multiple\n // supertypes, the properties of policies whose types were added\n // later via addPossibleTypes will take precedence over those of\n // earlier supertypes. TODO Perhaps we should warn about these\n // conflicts in development, and recommend defining the property\n // explicitly in the subtype policy?\n //\n // Field policy inheritance is atomic/shallow: you can't inherit a\n // field policy and then override just its read function, since read\n // and merge functions often need to cooperate, so changing only one\n // of them would be a recipe for inconsistency.\n //\n // Once the TypePolicy for typename has been accessed, its properties can\n // still be updated directly using addTypePolicies, but future changes to\n // inherited supertype policies will not be reflected in this subtype\n // policy, because this code runs at most once per typename.\n let supertypes = this.supertypeMap.get(typename);\n if (!supertypes && this.fuzzySubtypes.size) {\n // To make the inheritance logic work for unknown typename strings that\n // may have fuzzy supertypes, we give this typename an empty supertype\n // set and then populate it with any fuzzy supertypes that match.\n supertypes = this.getSupertypeSet(typename, true)!;\n // This only works for typenames that are directly matched by a fuzzy\n // supertype. What if there is an intermediate chain of supertypes?\n // While possible, that situation can only be solved effectively by\n // specifying the intermediate relationships via possibleTypes, manually\n // and in a non-fuzzy way.\n this.fuzzySubtypes.forEach((regExp, fuzzy) => {\n if (regExp.test(typename)) {\n // The fuzzy parameter is just the original string version of regExp\n // (not a valid __typename string), but we can look up the\n // associated supertype(s) in this.supertypeMap.\n const fuzzySupertypes = this.supertypeMap.get(fuzzy);\n if (fuzzySupertypes) {\n fuzzySupertypes.forEach((supertype) =>\n supertypes!.add(supertype)\n );\n }\n }\n });\n }\n if (supertypes && supertypes.size) {\n supertypes.forEach((supertype) => {\n const { fields, ...rest } = this.getTypePolicy(supertype);\n Object.assign(policy, rest);\n Object.assign(policy.fields, fields);\n });\n }\n }\n\n const inbox = this.toBeAdded[typename];\n if (inbox && inbox.length) {\n // Merge the pending policies into this.typePolicies, in the order they\n // were originally passed to addTypePolicy.\n inbox.splice(0).forEach((policy) => {\n this.updateTypePolicy(typename, policy);\n });\n }\n\n return this.typePolicies[typename];\n }\n\n private getFieldPolicy(\n typename: string | undefined,\n fieldName: string,\n createIfMissing: boolean\n ):\n | {\n keyFn?: KeyArgsFunction;\n read?: FieldReadFunction;\n merge?: FieldMergeFunction;\n }\n | undefined {\n if (typename) {\n const fieldPolicies = this.getTypePolicy(typename).fields;\n return (\n fieldPolicies[fieldName] ||\n (createIfMissing && (fieldPolicies[fieldName] = Object.create(null)))\n );\n }\n }\n\n private getSupertypeSet(\n subtype: string,\n createIfMissing: boolean\n ): Set | undefined {\n let supertypeSet = this.supertypeMap.get(subtype);\n if (!supertypeSet && createIfMissing) {\n this.supertypeMap.set(subtype, (supertypeSet = new Set()));\n }\n return supertypeSet;\n }\n\n public fragmentMatches(\n fragment: InlineFragmentNode | FragmentDefinitionNode,\n typename: string | undefined,\n result?: Record,\n variables?: Record\n ): boolean {\n if (!fragment.typeCondition) return true;\n\n // If the fragment has a type condition but the object we're matching\n // against does not have a __typename, the fragment cannot match.\n if (!typename) return false;\n\n const supertype = fragment.typeCondition.name.value;\n // Common case: fragment type condition and __typename are the same.\n if (typename === supertype) return true;\n\n if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {\n const typenameSupertypeSet = this.getSupertypeSet(typename, true)!;\n const workQueue = [typenameSupertypeSet];\n const maybeEnqueue = (subtype: string) => {\n const supertypeSet = this.getSupertypeSet(subtype, false);\n if (\n supertypeSet &&\n supertypeSet.size &&\n workQueue.indexOf(supertypeSet) < 0\n ) {\n workQueue.push(supertypeSet);\n }\n };\n\n // We need to check fuzzy subtypes only if we encountered fuzzy\n // subtype strings in addPossibleTypes, and only while writing to\n // the cache, since that's when selectionSetMatchesResult gives a\n // strong signal of fragment matching. The StoreReader class calls\n // policies.fragmentMatches without passing a result object, so\n // needToCheckFuzzySubtypes is always false while reading.\n let needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);\n let checkingFuzzySubtypes = false;\n\n // It's important to keep evaluating workQueue.length each time through\n // the loop, because the queue can grow while we're iterating over it.\n for (let i = 0; i < workQueue.length; ++i) {\n const supertypeSet = workQueue[i];\n\n if (supertypeSet.has(supertype)) {\n if (!typenameSupertypeSet.has(supertype)) {\n if (checkingFuzzySubtypes) {\n invariant.warn(\n `Inferring subtype %s of supertype %s`,\n typename,\n supertype\n );\n }\n // Record positive results for faster future lookup.\n // Unfortunately, we cannot safely cache negative results,\n // because new possibleTypes data could always be added to the\n // Policies class.\n typenameSupertypeSet.add(supertype);\n }\n return true;\n }\n\n supertypeSet.forEach(maybeEnqueue);\n\n if (\n needToCheckFuzzySubtypes &&\n // Start checking fuzzy subtypes only after exhausting all\n // non-fuzzy subtypes (after the final iteration of the loop).\n i === workQueue.length - 1 &&\n // We could wait to compare fragment.selectionSet to result\n // after we verify the supertype, but this check is often less\n // expensive than that search, and we will have to do the\n // comparison anyway whenever we find a potential match.\n selectionSetMatchesResult(fragment.selectionSet, result!, variables)\n ) {\n // We don't always need to check fuzzy subtypes (if no result\n // was provided, or !this.fuzzySubtypes.size), but, when we do,\n // we only want to check them once.\n needToCheckFuzzySubtypes = false;\n checkingFuzzySubtypes = true;\n\n // If we find any fuzzy subtypes that match typename, extend the\n // workQueue to search through the supertypes of those fuzzy\n // subtypes. Otherwise the for-loop will terminate and we'll\n // return false below.\n this.fuzzySubtypes.forEach((regExp, fuzzyString) => {\n const match = typename.match(regExp);\n if (match && match[0] === typename) {\n maybeEnqueue(fuzzyString);\n }\n });\n }\n }\n }\n\n return false;\n }\n\n public hasKeyArgs(typename: string | undefined, fieldName: string) {\n const policy = this.getFieldPolicy(typename, fieldName, false);\n return !!(policy && policy.keyFn);\n }\n\n public getStoreFieldName(fieldSpec: FieldSpecifier): string {\n const { typename, fieldName } = fieldSpec;\n const policy = this.getFieldPolicy(typename, fieldName, false);\n let storeFieldName: Exclude, KeySpecifier>;\n\n let keyFn = policy && policy.keyFn;\n if (keyFn && typename) {\n const context: Parameters[1] = {\n typename,\n fieldName,\n field: fieldSpec.field || null,\n variables: fieldSpec.variables,\n };\n const args = argsFromFieldSpecifier(fieldSpec);\n while (keyFn) {\n const specifierOrString = keyFn(args, context);\n if (isArray(specifierOrString)) {\n keyFn = keyArgsFnFromSpecifier(specifierOrString);\n } else {\n // If the custom keyFn returns a falsy value, fall back to\n // fieldName instead.\n storeFieldName = specifierOrString || fieldName;\n break;\n }\n }\n }\n\n if (storeFieldName === void 0) {\n storeFieldName =\n fieldSpec.field ?\n storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)\n : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));\n }\n\n // Returning false from a keyArgs function is like configuring\n // keyArgs: false, but more dynamic.\n if (storeFieldName === false) {\n return fieldName;\n }\n\n // Make sure custom field names start with the actual field.name.value\n // of the field, so we can always figure out which properties of a\n // StoreObject correspond to which original field names.\n return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName\n : fieldName + \":\" + storeFieldName;\n }\n\n public readField(\n options: ReadFieldOptions,\n context: ReadMergeModifyContext\n ): SafeReadonly | undefined {\n const objectOrReference = options.from;\n if (!objectOrReference) return;\n\n const nameOrField = options.field || options.fieldName;\n if (!nameOrField) return;\n\n if (options.typename === void 0) {\n const typename = context.store.getFieldValue(\n objectOrReference,\n \"__typename\"\n );\n if (typename) options.typename = typename;\n }\n\n const storeFieldName = this.getStoreFieldName(options);\n const fieldName = fieldNameFromStoreName(storeFieldName);\n const existing = context.store.getFieldValue(\n objectOrReference,\n storeFieldName\n );\n const policy = this.getFieldPolicy(options.typename, fieldName, false);\n const read = policy && policy.read;\n\n if (read) {\n const readOptions = makeFieldFunctionOptions(\n this,\n objectOrReference,\n options,\n context,\n context.store.getStorage(\n isReference(objectOrReference) ?\n objectOrReference.__ref\n : objectOrReference,\n storeFieldName\n )\n );\n\n // Call read(existing, readOptions) with cacheSlot holding this.cache.\n return cacheSlot.withValue(this.cache, read, [\n existing,\n readOptions,\n ]) as SafeReadonly;\n }\n\n return existing;\n }\n\n public getReadFunction(\n typename: string | undefined,\n fieldName: string\n ): FieldReadFunction | undefined {\n const policy = this.getFieldPolicy(typename, fieldName, false);\n return policy && policy.read;\n }\n\n public getMergeFunction(\n parentTypename: string | undefined,\n fieldName: string,\n childTypename: string | undefined\n ): FieldMergeFunction | undefined {\n let policy:\n | Policies[\"typePolicies\"][string]\n | Policies[\"typePolicies\"][string][\"fields\"][string]\n | undefined = this.getFieldPolicy(parentTypename, fieldName, false);\n let merge = policy && policy.merge;\n if (!merge && childTypename) {\n policy = this.getTypePolicy(childTypename);\n merge = policy && policy.merge;\n }\n return merge;\n }\n\n public runMergeFunction(\n existing: StoreValue,\n incoming: StoreValue,\n { field, typename, merge }: MergeInfo,\n context: WriteContext,\n storage?: StorageType\n ) {\n if (merge === mergeTrueFn) {\n // Instead of going to the trouble of creating a full\n // FieldFunctionOptions object and calling mergeTrueFn, we can\n // simply call mergeObjects, as mergeTrueFn would.\n return makeMergeObjectsFunction(context.store)(\n existing as StoreObject,\n incoming as StoreObject\n );\n }\n\n if (merge === mergeFalseFn) {\n // Likewise for mergeFalseFn, whose implementation is even simpler.\n return incoming;\n }\n\n // If cache.writeQuery or cache.writeFragment was called with\n // options.overwrite set to true, we still call merge functions, but\n // the existing data is always undefined, so the merge function will\n // not attempt to combine the incoming data with the existing data.\n if (context.overwrite) {\n existing = void 0;\n }\n\n return merge(\n existing,\n incoming,\n makeFieldFunctionOptions(\n this,\n // Unlike options.readField for read functions, we do not fall\n // back to the current object if no foreignObjOrRef is provided,\n // because it's not clear what the current object should be for\n // merge functions: the (possibly undefined) existing object, or\n // the incoming object? If you think your merge function needs\n // to read sibling fields in order to produce a new value for\n // the current field, you might want to rethink your strategy,\n // because that's a recipe for making merge behavior sensitive\n // to the order in which fields are written into the cache.\n // However, readField(name, ref) is useful for merge functions\n // that need to deduplicate child objects and references.\n void 0,\n {\n typename,\n fieldName: field.name.value,\n field,\n variables: context.variables,\n },\n context,\n storage || Object.create(null)\n )\n );\n }\n}\n\nfunction makeFieldFunctionOptions(\n policies: Policies,\n objectOrReference: StoreObject | Reference | undefined,\n fieldSpec: FieldSpecifier,\n context: ReadMergeModifyContext,\n storage: StorageType\n): FieldFunctionOptions {\n const storeFieldName = policies.getStoreFieldName(fieldSpec);\n const fieldName = fieldNameFromStoreName(storeFieldName);\n const variables = fieldSpec.variables || context.variables;\n const { toReference, canRead } = context.store;\n\n return {\n args: argsFromFieldSpecifier(fieldSpec),\n field: fieldSpec.field || null,\n fieldName,\n storeFieldName,\n variables,\n isReference,\n toReference,\n storage,\n cache: policies.cache,\n canRead,\n readField() {\n return policies.readField(\n normalizeReadFieldOptions(arguments, objectOrReference, variables),\n context\n );\n },\n mergeObjects: makeMergeObjectsFunction(context.store),\n };\n}\n\nexport function normalizeReadFieldOptions(\n readFieldArgs: IArguments,\n objectOrReference: StoreObject | Reference | undefined,\n variables?: ReadMergeModifyContext[\"variables\"]\n): ReadFieldOptions {\n const { 0: fieldNameOrOptions, 1: from, length: argc } = readFieldArgs;\n\n let options: ReadFieldOptions;\n\n if (typeof fieldNameOrOptions === \"string\") {\n options = {\n fieldName: fieldNameOrOptions,\n // Default to objectOrReference only when no second argument was\n // passed for the from parameter, not when undefined is explicitly\n // passed as the second argument.\n from: argc > 1 ? from : objectOrReference,\n };\n } else {\n options = { ...fieldNameOrOptions };\n // Default to objectOrReference only when fieldNameOrOptions.from is\n // actually omitted, rather than just undefined.\n if (!hasOwn.call(options, \"from\")) {\n options.from = objectOrReference;\n }\n }\n\n if (__DEV__ && options.from === void 0) {\n invariant.warn(\n `Undefined 'from' passed to readField with arguments %s`,\n stringifyForDisplay(Array.from(readFieldArgs))\n );\n }\n\n if (void 0 === options.variables) {\n options.variables = variables;\n }\n\n return options;\n}\n\nfunction makeMergeObjectsFunction(\n store: NormalizedCache\n): MergeObjectsFunction {\n return function mergeObjects(existing, incoming) {\n if (isArray(existing) || isArray(incoming)) {\n throw newInvariantError(\"Cannot automatically merge arrays\");\n }\n\n // These dynamic checks are necessary because the parameters of a\n // custom merge function can easily have the any type, so the type\n // system cannot always enforce the StoreObject | Reference parameter\n // types of options.mergeObjects.\n if (isNonNullObject(existing) && isNonNullObject(incoming)) {\n const eType = store.getFieldValue(existing, \"__typename\");\n const iType = store.getFieldValue(incoming, \"__typename\");\n const typesDiffer = eType && iType && eType !== iType;\n\n if (typesDiffer) {\n return incoming;\n }\n\n if (isReference(existing) && storeValueIsStoreObject(incoming)) {\n // Update the normalized EntityStore for the entity identified by\n // existing.__ref, preferring/overwriting any fields contributed by the\n // newer incoming StoreObject.\n store.merge(existing.__ref, incoming);\n return existing;\n }\n\n if (storeValueIsStoreObject(existing) && isReference(incoming)) {\n // Update the normalized EntityStore for the entity identified by\n // incoming.__ref, taking fields from the older existing object only if\n // those fields are not already present in the newer StoreObject\n // identified by incoming.__ref.\n store.merge(existing, incoming.__ref);\n return incoming;\n }\n\n if (\n storeValueIsStoreObject(existing) &&\n storeValueIsStoreObject(incoming)\n ) {\n return { ...existing, ...incoming };\n }\n }\n\n return incoming;\n };\n}\n","import { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport type { SelectionSetNode, FieldNode } from \"graphql\";\nimport { Kind } from \"graphql\";\n\nimport type {\n FragmentMap,\n FragmentMapFunction,\n StoreValue,\n StoreObject,\n Reference,\n} from \"../../utilities/index.js\";\nimport {\n getFragmentFromSelection,\n getDefaultValues,\n getOperationDefinition,\n getTypenameFromResult,\n makeReference,\n isField,\n resultKeyNameFromField,\n isReference,\n shouldInclude,\n cloneDeep,\n addTypenameToDocument,\n isNonEmptyArray,\n argumentsObjectFromField,\n canonicalStringify,\n} from \"../../utilities/index.js\";\n\nimport type {\n NormalizedCache,\n ReadMergeModifyContext,\n MergeTree,\n InMemoryCacheConfig,\n} from \"./types.js\";\nimport {\n isArray,\n makeProcessedFieldsMerger,\n fieldNameFromStoreName,\n storeValueIsStoreObject,\n extractFragmentContext,\n} from \"./helpers.js\";\nimport type { StoreReader } from \"./readFromStore.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type { EntityStore } from \"./entityStore.js\";\nimport type { Cache } from \"../../core/index.js\";\nimport { normalizeReadFieldOptions } from \"./policies.js\";\nimport type { ReadFieldFunction } from \"../core/types/common.js\";\n\nexport interface WriteContext extends ReadMergeModifyContext {\n readonly written: {\n [dataId: string]: SelectionSetNode[];\n };\n readonly fragmentMap: FragmentMap;\n lookupFragment: FragmentMapFunction;\n // General-purpose deep-merge function for use during writes.\n merge(existing: T, incoming: T): T;\n // If true, merge functions will be called with undefined existing data.\n overwrite: boolean;\n incomingById: Map<\n string,\n {\n storeObject: StoreObject;\n mergeTree?: MergeTree;\n fieldNodeSet: Set;\n }\n >;\n // Directive metadata for @client and @defer. We could use a bitfield for this\n // information to save some space, and use that bitfield number as the keys in\n // the context.flavors Map.\n clientOnly: boolean;\n deferred: boolean;\n flavors: Map;\n}\n\ntype FlavorableWriteContext = Pick<\n WriteContext,\n \"clientOnly\" | \"deferred\" | \"flavors\"\n>;\n\n// Since there are only four possible combinations of context.clientOnly and\n// context.deferred values, we should need at most four \"flavors\" of any given\n// WriteContext. To avoid creating multiple copies of the same context, we cache\n// the contexts in the context.flavors Map (shared by all flavors) according to\n// their clientOnly and deferred values (always in that order).\nfunction getContextFlavor(\n context: TContext,\n clientOnly: TContext[\"clientOnly\"],\n deferred: TContext[\"deferred\"]\n): TContext {\n const key = `${clientOnly}${deferred}`;\n let flavored = context.flavors.get(key);\n if (!flavored) {\n context.flavors.set(\n key,\n (flavored =\n context.clientOnly === clientOnly && context.deferred === deferred ?\n context\n : {\n ...context,\n clientOnly,\n deferred,\n })\n );\n }\n return flavored as TContext;\n}\n\ninterface ProcessSelectionSetOptions {\n dataId?: string;\n result: Record;\n selectionSet: SelectionSetNode;\n context: WriteContext;\n mergeTree: MergeTree;\n}\n\nexport class StoreWriter {\n constructor(\n public readonly cache: InMemoryCache,\n private reader?: StoreReader,\n private fragments?: InMemoryCacheConfig[\"fragments\"]\n ) {}\n\n public writeToStore(\n store: NormalizedCache,\n { query, result, dataId, variables, overwrite }: Cache.WriteOptions\n ): Reference | undefined {\n const operationDefinition = getOperationDefinition(query)!;\n const merger = makeProcessedFieldsMerger();\n\n variables = {\n ...getDefaultValues(operationDefinition),\n ...variables!,\n };\n\n const context: WriteContext = {\n store,\n written: Object.create(null),\n merge(existing: T, incoming: T) {\n return merger.merge(existing, incoming) as T;\n },\n variables,\n varString: canonicalStringify(variables),\n ...extractFragmentContext(query, this.fragments),\n overwrite: !!overwrite,\n incomingById: new Map(),\n clientOnly: false,\n deferred: false,\n flavors: new Map(),\n };\n\n const ref = this.processSelectionSet({\n result: result || Object.create(null),\n dataId,\n selectionSet: operationDefinition.selectionSet,\n mergeTree: { map: new Map() },\n context,\n });\n\n if (!isReference(ref)) {\n throw newInvariantError(`Could not identify object %s`, result);\n }\n\n // So far, the store has not been modified, so now it's time to process\n // context.incomingById and merge those incoming fields into context.store.\n context.incomingById.forEach(\n ({ storeObject, mergeTree, fieldNodeSet }, dataId) => {\n const entityRef = makeReference(dataId);\n\n if (mergeTree && mergeTree.map.size) {\n const applied = this.applyMerges(\n mergeTree,\n entityRef,\n storeObject,\n context\n );\n if (isReference(applied)) {\n // Assume References returned by applyMerges have already been merged\n // into the store. See makeMergeObjectsFunction in policies.ts for an\n // example of how this can happen.\n return;\n }\n // Otherwise, applyMerges returned a StoreObject, whose fields we should\n // merge into the store (see store.merge statement below).\n storeObject = applied;\n }\n\n if (__DEV__ && !context.overwrite) {\n const fieldsWithSelectionSets: Record =\n Object.create(null);\n fieldNodeSet.forEach((field) => {\n if (field.selectionSet) {\n fieldsWithSelectionSets[field.name.value] = true;\n }\n });\n\n const hasSelectionSet = (storeFieldName: string) =>\n fieldsWithSelectionSets[fieldNameFromStoreName(storeFieldName)] ===\n true;\n\n const hasMergeFunction = (storeFieldName: string) => {\n const childTree = mergeTree && mergeTree.map.get(storeFieldName);\n return Boolean(childTree && childTree.info && childTree.info.merge);\n };\n\n Object.keys(storeObject).forEach((storeFieldName) => {\n // If a merge function was defined for this field, trust that it\n // did the right thing about (not) clobbering data. If the field\n // has no selection set, it's a scalar field, so it doesn't need\n // a merge function (even if it's an object, like JSON data).\n if (\n hasSelectionSet(storeFieldName) &&\n !hasMergeFunction(storeFieldName)\n ) {\n warnAboutDataLoss(\n entityRef,\n storeObject,\n storeFieldName,\n context.store\n );\n }\n });\n }\n\n store.merge(dataId, storeObject);\n }\n );\n\n // Any IDs written explicitly to the cache will be retained as\n // reachable root IDs for garbage collection purposes. Although this\n // logic includes root IDs like ROOT_QUERY and ROOT_MUTATION, their\n // retainment counts are effectively ignored because cache.gc() always\n // includes them in its root ID set.\n store.retain(ref.__ref);\n\n return ref;\n }\n\n private processSelectionSet({\n dataId,\n result,\n selectionSet,\n context,\n // This object allows processSelectionSet to report useful information\n // to its callers without explicitly returning that information.\n mergeTree,\n }: ProcessSelectionSetOptions): StoreObject | Reference {\n const { policies } = this.cache;\n\n // This variable will be repeatedly updated using context.merge to\n // accumulate all fields that need to be written into the store.\n let incoming: StoreObject = Object.create(null);\n\n // If typename was not passed in, infer it. Note that typename is\n // always passed in for tricky-to-infer cases such as \"Query\" for\n // ROOT_QUERY.\n const typename: string | undefined =\n (dataId && policies.rootTypenamesById[dataId]) ||\n getTypenameFromResult(result, selectionSet, context.fragmentMap) ||\n (dataId && (context.store.get(dataId, \"__typename\") as string));\n\n if (\"string\" === typeof typename) {\n incoming.__typename = typename;\n }\n\n // This readField function will be passed as context.readField in the\n // KeyFieldsContext object created within policies.identify (called below).\n // In addition to reading from the existing context.store (thanks to the\n // policies.readField(options, context) line at the very bottom), this\n // version of readField can read from Reference objects that are currently\n // pending in context.incomingById, which is important whenever keyFields\n // need to be extracted from a child object that processSelectionSet has\n // turned into a Reference.\n const readField: ReadFieldFunction = function (this: void) {\n const options = normalizeReadFieldOptions(\n arguments,\n incoming,\n context.variables\n );\n\n if (isReference(options.from)) {\n const info = context.incomingById.get(options.from.__ref);\n if (info) {\n const result = policies.readField(\n {\n ...options,\n from: info.storeObject,\n },\n context\n );\n\n if (result !== void 0) {\n return result;\n }\n }\n }\n\n return policies.readField(options, context);\n };\n\n const fieldNodeSet = new Set();\n\n this.flattenFields(\n selectionSet,\n result,\n // This WriteContext will be the default context value for fields returned\n // by the flattenFields method, but some fields may be assigned a modified\n // context, depending on the presence of @client and other directives.\n context,\n typename\n ).forEach((context, field) => {\n const resultFieldKey = resultKeyNameFromField(field);\n const value = result[resultFieldKey];\n\n fieldNodeSet.add(field);\n\n if (value !== void 0) {\n const storeFieldName = policies.getStoreFieldName({\n typename,\n fieldName: field.name.value,\n field,\n variables: context.variables,\n });\n\n const childTree = getChildMergeTree(mergeTree, storeFieldName);\n\n let incomingValue = this.processFieldValue(\n value,\n field,\n // Reset context.clientOnly and context.deferred to their default\n // values before processing nested selection sets.\n field.selectionSet ?\n getContextFlavor(context, false, false)\n : context,\n childTree\n );\n\n // To determine if this field holds a child object with a merge function\n // defined in its type policy (see PR #7070), we need to figure out the\n // child object's __typename.\n let childTypename: string | undefined;\n\n // The field's value can be an object that has a __typename only if the\n // field has a selection set. Otherwise incomingValue is scalar.\n if (\n field.selectionSet &&\n (isReference(incomingValue) || storeValueIsStoreObject(incomingValue))\n ) {\n childTypename = readField(\"__typename\", incomingValue);\n }\n\n const merge = policies.getMergeFunction(\n typename,\n field.name.value,\n childTypename\n );\n\n if (merge) {\n childTree.info = {\n // TODO Check compatibility against any existing childTree.field?\n field,\n typename,\n merge,\n };\n } else {\n maybeRecycleChildMergeTree(mergeTree, storeFieldName);\n }\n\n incoming = context.merge(incoming, {\n [storeFieldName]: incomingValue,\n });\n } else if (\n __DEV__ &&\n !context.clientOnly &&\n !context.deferred &&\n !addTypenameToDocument.added(field) &&\n // If the field has a read function, it may be a synthetic field or\n // provide a default value, so its absence from the written data should\n // not be cause for alarm.\n !policies.getReadFunction(typename, field.name.value)\n ) {\n invariant.error(\n `Missing field '%s' while writing result %o`,\n resultKeyNameFromField(field),\n result\n );\n }\n });\n\n // Identify the result object, even if dataId was already provided,\n // since we always need keyObject below.\n try {\n const [id, keyObject] = policies.identify(result, {\n typename,\n selectionSet,\n fragmentMap: context.fragmentMap,\n storeObject: incoming,\n readField,\n });\n\n // If dataId was not provided, fall back to the id just generated by\n // policies.identify.\n dataId = dataId || id;\n\n // Write any key fields that were used during identification, even if\n // they were not mentioned in the original query.\n if (keyObject) {\n // TODO Reverse the order of the arguments?\n incoming = context.merge(incoming, keyObject);\n }\n } catch (e) {\n // If dataId was provided, tolerate failure of policies.identify.\n if (!dataId) throw e;\n }\n\n if (\"string\" === typeof dataId) {\n const dataRef = makeReference(dataId);\n\n // Avoid processing the same entity object using the same selection\n // set more than once. We use an array instead of a Set since most\n // entity IDs will be written using only one selection set, so the\n // size of this array is likely to be very small, meaning indexOf is\n // likely to be faster than Set.prototype.has.\n const sets = context.written[dataId] || (context.written[dataId] = []);\n if (sets.indexOf(selectionSet) >= 0) return dataRef;\n sets.push(selectionSet);\n\n // If we're about to write a result object into the store, but we\n // happen to know that the exact same (===) result object would be\n // returned if we were to reread the result with the same inputs,\n // then we can skip the rest of the processSelectionSet work for\n // this object, and immediately return a Reference to it.\n if (\n this.reader &&\n this.reader.isFresh(result, dataRef, selectionSet, context)\n ) {\n return dataRef;\n }\n\n const previous = context.incomingById.get(dataId);\n if (previous) {\n previous.storeObject = context.merge(previous.storeObject, incoming);\n previous.mergeTree = mergeMergeTrees(previous.mergeTree, mergeTree);\n fieldNodeSet.forEach((field) => previous.fieldNodeSet.add(field));\n } else {\n context.incomingById.set(dataId, {\n storeObject: incoming,\n // Save a reference to mergeTree only if it is not empty, because\n // empty MergeTrees may be recycled by maybeRecycleChildMergeTree and\n // reused for entirely different parts of the result tree.\n mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,\n fieldNodeSet,\n });\n }\n\n return dataRef;\n }\n\n return incoming;\n }\n\n private processFieldValue(\n value: any,\n field: FieldNode,\n context: WriteContext,\n mergeTree: MergeTree\n ): StoreValue {\n if (!field.selectionSet || value === null) {\n // In development, we need to clone scalar values so that they can be\n // safely frozen with maybeDeepFreeze in readFromStore.ts. In production,\n // it's cheaper to store the scalar values directly in the cache.\n return __DEV__ ? cloneDeep(value) : value;\n }\n\n if (isArray(value)) {\n return value.map((item, i) => {\n const value = this.processFieldValue(\n item,\n field,\n context,\n getChildMergeTree(mergeTree, i)\n );\n maybeRecycleChildMergeTree(mergeTree, i);\n return value;\n });\n }\n\n return this.processSelectionSet({\n result: value,\n selectionSet: field.selectionSet,\n context,\n mergeTree,\n });\n }\n\n // Implements https://spec.graphql.org/draft/#sec-Field-Collection, but with\n // some additions for tracking @client and @defer directives.\n private flattenFields<\n TContext extends Pick<\n WriteContext,\n | \"clientOnly\"\n | \"deferred\"\n | \"flavors\"\n | \"fragmentMap\"\n | \"lookupFragment\"\n | \"variables\"\n >,\n >(\n selectionSet: SelectionSetNode,\n result: Record,\n context: TContext,\n typename = getTypenameFromResult(result, selectionSet, context.fragmentMap)\n ): Map {\n const fieldMap = new Map();\n const { policies } = this.cache;\n\n const limitingTrie = new Trie<{\n // Tracks whether (selectionSet, clientOnly, deferred) has been flattened\n // before. The GraphQL specification only uses the fragment name for\n // skipping previously visited fragments, but the top-level fragment\n // selection set corresponds 1:1 with the fagment name (and is slightly\n // easier too work with), and we need to consider clientOnly and deferred\n // values as well, potentially revisiting selection sets that were\n // previously visited with different inherited configurations of those\n // directives.\n visited?: boolean;\n }>(false); // No need for WeakMap, since limitingTrie does not escape.\n\n (function flatten(\n this: void,\n selectionSet: SelectionSetNode,\n inheritedContext: TContext\n ) {\n const visitedNode = limitingTrie.lookup(\n selectionSet,\n // Because we take inheritedClientOnly and inheritedDeferred into\n // consideration here (in addition to selectionSet), it's possible for\n // the same selection set to be flattened more than once, if it appears\n // in the query with different @client and/or @directive configurations.\n inheritedContext.clientOnly,\n inheritedContext.deferred\n );\n if (visitedNode.visited) return;\n visitedNode.visited = true;\n\n selectionSet.selections.forEach((selection) => {\n if (!shouldInclude(selection, context.variables)) return;\n\n let { clientOnly, deferred } = inheritedContext;\n if (\n // Since the presence of @client or @defer on this field can only\n // cause clientOnly or deferred to become true, we can skip the\n // forEach loop if both clientOnly and deferred are already true.\n !(clientOnly && deferred) &&\n isNonEmptyArray(selection.directives)\n ) {\n selection.directives.forEach((dir) => {\n const name = dir.name.value;\n if (name === \"client\") clientOnly = true;\n if (name === \"defer\") {\n const args = argumentsObjectFromField(dir, context.variables);\n // The @defer directive takes an optional args.if boolean\n // argument, similar to @include(if: boolean). Note that\n // @defer(if: false) does not make context.deferred false, but\n // instead behaves as if there was no @defer directive.\n if (!args || (args as { if?: boolean }).if !== false) {\n deferred = true;\n }\n // TODO In the future, we may want to record args.label using\n // context.deferred, if a label is specified.\n }\n });\n }\n\n if (isField(selection)) {\n const existing = fieldMap.get(selection);\n if (existing) {\n // If this field has been visited along another recursive path\n // before, the final context should have clientOnly or deferred set\n // to true only if *all* paths have the directive (hence the &&).\n clientOnly = clientOnly && existing.clientOnly;\n deferred = deferred && existing.deferred;\n }\n\n fieldMap.set(\n selection,\n getContextFlavor(context, clientOnly, deferred)\n );\n } else {\n const fragment = getFragmentFromSelection(\n selection,\n context.lookupFragment\n );\n\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(\n `No fragment named %s`,\n selection.name.value\n );\n }\n\n if (\n fragment &&\n policies.fragmentMatches(\n fragment,\n typename,\n result,\n context.variables\n )\n ) {\n flatten(\n fragment.selectionSet,\n getContextFlavor(context, clientOnly, deferred)\n );\n }\n }\n });\n })(selectionSet, context);\n\n return fieldMap;\n }\n\n private applyMerges(\n mergeTree: MergeTree,\n existing: StoreValue,\n incoming: T,\n context: WriteContext,\n getStorageArgs?: Parameters\n ): T | Reference {\n if (mergeTree.map.size && !isReference(incoming)) {\n const e: StoreObject | Reference | undefined =\n // Items in the same position in different arrays are not\n // necessarily related to each other, so when incoming is an array\n // we process its elements as if there was no existing data.\n (\n !isArray(incoming) &&\n // Likewise, existing must be either a Reference or a StoreObject\n // in order for its fields to be safe to merge with the fields of\n // the incoming object.\n (isReference(existing) || storeValueIsStoreObject(existing))\n ) ?\n existing\n : void 0;\n\n // This narrowing is implied by mergeTree.map.size > 0 and\n // !isReference(incoming), though TypeScript understandably cannot\n // hope to infer this type.\n const i = incoming as StoreObject | StoreValue[];\n\n // The options.storage objects provided to read and merge functions\n // are derived from the identity of the parent object plus a\n // sequence of storeFieldName strings/numbers identifying the nested\n // field name path of each field value to be merged.\n if (e && !getStorageArgs) {\n getStorageArgs = [isReference(e) ? e.__ref : e];\n }\n\n // It's possible that applying merge functions to this subtree will\n // not change the incoming data, so this variable tracks the fields\n // that did change, so we can create a new incoming object when (and\n // only when) at least one incoming field has changed. We use a Map\n // to preserve the type of numeric keys.\n let changedFields: Map | undefined;\n\n const getValue = (\n from: typeof e | typeof i,\n name: string | number\n ): StoreValue => {\n return (\n isArray(from) ?\n typeof name === \"number\" ?\n from[name]\n : void 0\n : context.store.getFieldValue(from, String(name))\n );\n };\n\n mergeTree.map.forEach((childTree, storeFieldName) => {\n const eVal = getValue(e, storeFieldName);\n const iVal = getValue(i, storeFieldName);\n // If we have no incoming data, leave any existing data untouched.\n if (void 0 === iVal) return;\n if (getStorageArgs) {\n getStorageArgs.push(storeFieldName);\n }\n const aVal = this.applyMerges(\n childTree,\n eVal,\n iVal,\n context,\n getStorageArgs\n );\n if (aVal !== iVal) {\n changedFields = changedFields || new Map();\n changedFields.set(storeFieldName, aVal);\n }\n if (getStorageArgs) {\n invariant(getStorageArgs.pop() === storeFieldName);\n }\n });\n\n if (changedFields) {\n // Shallow clone i so we can add changed fields to it.\n incoming = (isArray(i) ? i.slice(0) : { ...i }) as T;\n changedFields.forEach((value, name) => {\n (incoming as any)[name] = value;\n });\n }\n }\n\n if (mergeTree.info) {\n return this.cache.policies.runMergeFunction(\n existing,\n incoming,\n mergeTree.info,\n context,\n getStorageArgs && context.store.getStorage(...getStorageArgs)\n );\n }\n\n return incoming;\n }\n}\n\nconst emptyMergeTreePool: MergeTree[] = [];\n\nfunction getChildMergeTree(\n { map }: MergeTree,\n name: string | number\n): MergeTree {\n if (!map.has(name)) {\n map.set(name, emptyMergeTreePool.pop() || { map: new Map() });\n }\n return map.get(name)!;\n}\n\nfunction mergeMergeTrees(\n left: MergeTree | undefined,\n right: MergeTree | undefined\n): MergeTree {\n if (left === right || !right || mergeTreeIsEmpty(right)) return left!;\n if (!left || mergeTreeIsEmpty(left)) return right;\n\n const info =\n left.info && right.info ?\n {\n ...left.info,\n ...right.info,\n }\n : left.info || right.info;\n\n const needToMergeMaps = left.map.size && right.map.size;\n const map =\n needToMergeMaps ? new Map()\n : left.map.size ? left.map\n : right.map;\n\n const merged = { info, map };\n\n if (needToMergeMaps) {\n const remainingRightKeys = new Set(right.map.keys());\n\n left.map.forEach((leftTree, key) => {\n merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));\n remainingRightKeys.delete(key);\n });\n\n remainingRightKeys.forEach((key) => {\n merged.map.set(\n key,\n mergeMergeTrees(right.map.get(key), left.map.get(key))\n );\n });\n }\n\n return merged;\n}\n\nfunction mergeTreeIsEmpty(tree: MergeTree | undefined): boolean {\n return !tree || !(tree.info || tree.map.size);\n}\n\nfunction maybeRecycleChildMergeTree({ map }: MergeTree, name: string | number) {\n const childTree = map.get(name);\n if (childTree && mergeTreeIsEmpty(childTree)) {\n emptyMergeTreePool.push(childTree);\n map.delete(name);\n }\n}\n\nconst warnings = new Set();\n\n// Note that this function is unused in production, and thus should be\n// pruned by any well-configured minifier.\nfunction warnAboutDataLoss(\n existingRef: Reference,\n incomingObj: StoreObject,\n storeFieldName: string,\n store: NormalizedCache\n) {\n const getChild = (objOrRef: StoreObject | Reference): StoreObject | false => {\n const child = store.getFieldValue(objOrRef, storeFieldName);\n return typeof child === \"object\" && child;\n };\n\n const existing = getChild(existingRef);\n if (!existing) return;\n\n const incoming = getChild(incomingObj);\n if (!incoming) return;\n\n // It's always safe to replace a reference, since it refers to data\n // safely stored elsewhere.\n if (isReference(existing)) return;\n\n // If the values are structurally equivalent, we do not need to worry\n // about incoming replacing existing.\n if (equal(existing, incoming)) return;\n\n // If we're replacing every key of the existing object, then the\n // existing data would be overwritten even if the objects were\n // normalized, so warning would not be helpful here.\n if (\n Object.keys(existing).every(\n (key) => store.getFieldValue(incoming, key) !== void 0\n )\n ) {\n return;\n }\n\n const parentType =\n store.getFieldValue(existingRef, \"__typename\") ||\n store.getFieldValue(incomingObj, \"__typename\");\n const fieldName = fieldNameFromStoreName(storeFieldName);\n const typeDotName = `${parentType}.${fieldName}`;\n // Avoid warning more than once for the same type and field name.\n if (warnings.has(typeDotName)) return;\n warnings.add(typeDotName);\n\n const childTypenames: string[] = [];\n // Arrays do not have __typename fields, and always need a custom merge\n // function, even if their elements are normalized entities.\n if (!isArray(existing) && !isArray(incoming)) {\n [existing, incoming].forEach((child) => {\n const typename = store.getFieldValue(child, \"__typename\");\n if (typeof typename === \"string\" && !childTypenames.includes(typename)) {\n childTypenames.push(typename);\n }\n });\n }\n\n invariant.warn(\n `Cache data may be lost when replacing the %s field of a %s object.\n\nThis could cause additional (usually avoidable) network requests to fetch data that were otherwise cached.\n\nTo address this problem (which is not a bug in Apollo Client), %sdefine a custom merge function for the %s field, so InMemoryCache can safely merge these objects:\n\n existing: %o\n incoming: %o\n\nFor more information about these options, please refer to the documentation:\n\n * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n`,\n fieldName,\n parentType,\n childTypenames.length ?\n \"either ensure all objects of type \" +\n childTypenames.join(\" and \") +\n \" have an ID or a custom merge function, or \"\n : \"\",\n typeDotName,\n { ...existing },\n { ...incoming }\n );\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\n\n// Make builtins like Map and Set safe to use with non-extensible objects.\nimport \"./fixPolyfills.js\";\n\nimport type { DocumentNode } from \"graphql\";\nimport type { OptimisticWrapperFunction } from \"optimism\";\nimport { wrap } from \"optimism\";\nimport { equal } from \"@wry/equality\";\n\nimport { ApolloCache } from \"../core/cache.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport type { StoreObject, Reference } from \"../../utilities/index.js\";\nimport {\n addTypenameToDocument,\n isReference,\n DocumentTransform,\n canonicalStringify,\n print,\n cacheSizes,\n defaultCacheSizes,\n} from \"../../utilities/index.js\";\nimport type { InMemoryCacheConfig, NormalizedCacheObject } from \"./types.js\";\nimport { StoreReader } from \"./readFromStore.js\";\nimport { StoreWriter } from \"./writeToStore.js\";\nimport { EntityStore, supportsResultCaching } from \"./entityStore.js\";\nimport { makeVar, forgetCache, recallCache } from \"./reactiveVars.js\";\nimport { Policies } from \"./policies.js\";\nimport { hasOwn, normalizeConfig, shouldCanonizeResults } from \"./helpers.js\";\nimport type { OperationVariables } from \"../../core/index.js\";\nimport { getInMemoryCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\n\ntype BroadcastOptions = Pick<\n Cache.BatchOptions,\n \"optimistic\" | \"onWatchUpdated\"\n>;\n\nexport class InMemoryCache extends ApolloCache {\n private data!: EntityStore;\n private optimisticData!: EntityStore;\n\n protected config: InMemoryCacheConfig;\n private watches = new Set();\n private addTypename: boolean;\n\n private storeReader!: StoreReader;\n private storeWriter!: StoreWriter;\n private addTypenameTransform = new DocumentTransform(addTypenameToDocument);\n\n private maybeBroadcastWatch!: OptimisticWrapperFunction<\n [Cache.WatchOptions, BroadcastOptions?],\n any,\n [Cache.WatchOptions]\n >;\n\n // Override the default value, since InMemoryCache result objects are frozen\n // in development and expected to remain logically immutable in production.\n public readonly assumeImmutableResults = true;\n\n // Dynamically imported code can augment existing typePolicies or\n // possibleTypes by calling cache.policies.addTypePolicies or\n // cache.policies.addPossibletypes.\n public readonly policies: Policies;\n\n public readonly makeVar = makeVar;\n\n constructor(config: InMemoryCacheConfig = {}) {\n super();\n this.config = normalizeConfig(config);\n this.addTypename = !!this.config.addTypename;\n\n this.policies = new Policies({\n cache: this,\n dataIdFromObject: this.config.dataIdFromObject,\n possibleTypes: this.config.possibleTypes,\n typePolicies: this.config.typePolicies,\n });\n\n this.init();\n }\n\n private init() {\n // Passing { resultCaching: false } in the InMemoryCache constructor options\n // will completely disable dependency tracking, which will improve memory\n // usage but worsen the performance of repeated reads.\n const rootStore = (this.data = new EntityStore.Root({\n policies: this.policies,\n resultCaching: this.config.resultCaching,\n }));\n\n // When no optimistic writes are currently active, cache.optimisticData ===\n // cache.data, so there are no additional layers on top of the actual data.\n // When an optimistic update happens, this.optimisticData will become a\n // linked list of EntityStore Layer objects that terminates with the\n // original this.data cache object.\n this.optimisticData = rootStore.stump;\n\n this.resetResultCache();\n }\n\n private resetResultCache(resetResultIdentities?: boolean) {\n const previousReader = this.storeReader;\n const { fragments } = this.config;\n\n // The StoreWriter is mostly stateless and so doesn't really need to be\n // reset, but it does need to have its writer.storeReader reference updated,\n // so it's simpler to update this.storeWriter as well.\n this.storeWriter = new StoreWriter(\n this,\n (this.storeReader = new StoreReader({\n cache: this,\n addTypename: this.addTypename,\n resultCacheMaxSize: this.config.resultCacheMaxSize,\n canonizeResults: shouldCanonizeResults(this.config),\n canon:\n resetResultIdentities ? void 0 : (\n previousReader && previousReader.canon\n ),\n fragments,\n })),\n fragments\n );\n\n this.maybeBroadcastWatch = wrap(\n (c: Cache.WatchOptions, options?: BroadcastOptions) => {\n return this.broadcastWatch(c, options);\n },\n {\n max:\n this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] ||\n defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"],\n makeCacheKey: (c: Cache.WatchOptions) => {\n // Return a cache key (thus enabling result caching) only if we're\n // currently using a data store that can track cache dependencies.\n const store = c.optimistic ? this.optimisticData : this.data;\n if (supportsResultCaching(store)) {\n const { optimistic, id, variables } = c;\n return store.makeCacheKey(\n c.query,\n // Different watches can have the same query, optimistic\n // status, rootId, and variables, but if their callbacks are\n // different, the (identical) result needs to be delivered to\n // each distinct callback. The easiest way to achieve that\n // separation is to include c.callback in the cache key for\n // maybeBroadcastWatch calls. See issue #5733.\n c.callback,\n canonicalStringify({ optimistic, id, variables })\n );\n }\n },\n }\n );\n\n // Since we have thrown away all the cached functions that depend on the\n // CacheGroup dependencies maintained by EntityStore, we should also reset\n // all CacheGroup dependency information.\n new Set([this.data.group, this.optimisticData.group]).forEach((group) =>\n group.resetCaching()\n );\n }\n\n public restore(data: NormalizedCacheObject): this {\n this.init();\n // Since calling this.init() discards/replaces the entire StoreReader, along\n // with the result caches it maintains, this.data.replace(data) won't have\n // to bother deleting the old data.\n if (data) this.data.replace(data);\n return this;\n }\n\n public extract(optimistic: boolean = false): NormalizedCacheObject {\n return (optimistic ? this.optimisticData : this.data).extract();\n }\n\n public read(options: Cache.ReadOptions): T | null {\n const {\n // Since read returns data or null, without any additional metadata\n // about whether/where there might have been missing fields, the\n // default behavior cannot be returnPartialData = true (like it is\n // for the diff method), since defaulting to true would violate the\n // integrity of the T in the return type. However, partial data may\n // be useful in some cases, so returnPartialData:true may be\n // specified explicitly.\n returnPartialData = false,\n } = options;\n try {\n return (\n this.storeReader.diffQueryAgainstStore({\n ...options,\n store: options.optimistic ? this.optimisticData : this.data,\n config: this.config,\n returnPartialData,\n }).result || null\n );\n } catch (e) {\n if (e instanceof MissingFieldError) {\n // Swallow MissingFieldError and return null, so callers do not need to\n // worry about catching \"normal\" exceptions resulting from incomplete\n // cache data. Unexpected errors will be re-thrown. If you need more\n // information about which fields were missing, use cache.diff instead,\n // and examine diffResult.missing.\n return null;\n }\n throw e;\n }\n }\n\n public write(options: Cache.WriteOptions): Reference | undefined {\n try {\n ++this.txCount;\n return this.storeWriter.writeToStore(this.data, options);\n } finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n }\n\n public modify = Record>(\n options: Cache.ModifyOptions\n ): boolean {\n if (hasOwn.call(options, \"id\") && !options.id) {\n // To my knowledge, TypeScript does not currently provide a way to\n // enforce that an optional property?:type must *not* be undefined\n // when present. That ability would be useful here, because we want\n // options.id to default to ROOT_QUERY only when no options.id was\n // provided. If the caller attempts to pass options.id with a\n // falsy/undefined value (perhaps because cache.identify failed), we\n // should not assume the goal was to modify the ROOT_QUERY object.\n // We could throw, but it seems natural to return false to indicate\n // that nothing was modified.\n return false;\n }\n const store =\n (\n options.optimistic // Defaults to false.\n ) ?\n this.optimisticData\n : this.data;\n try {\n ++this.txCount;\n return store.modify(options.id || \"ROOT_QUERY\", options.fields);\n } finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n }\n\n public diff(\n options: Cache.DiffOptions\n ): Cache.DiffResult {\n return this.storeReader.diffQueryAgainstStore({\n ...options,\n store: options.optimistic ? this.optimisticData : this.data,\n rootId: options.id || \"ROOT_QUERY\",\n config: this.config,\n });\n }\n\n public watch(\n watch: Cache.WatchOptions\n ): () => void {\n if (!this.watches.size) {\n // In case we previously called forgetCache(this) because\n // this.watches became empty (see below), reattach this cache to any\n // reactive variables on which it previously depended. It might seem\n // paradoxical that we're able to recall something we supposedly\n // forgot, but the point of calling forgetCache(this) is to silence\n // useless broadcasts while this.watches is empty, and to allow the\n // cache to be garbage collected. If, however, we manage to call\n // recallCache(this) here, this cache object must not have been\n // garbage collected yet, and should resume receiving updates from\n // reactive variables, now that it has a watcher to notify.\n recallCache(this);\n }\n this.watches.add(watch);\n if (watch.immediate) {\n this.maybeBroadcastWatch(watch);\n }\n return () => {\n // Once we remove the last watch from this.watches, cache.broadcastWatches\n // no longer does anything, so we preemptively tell the reactive variable\n // system to exclude this cache from future broadcasts.\n if (this.watches.delete(watch) && !this.watches.size) {\n forgetCache(this);\n }\n // Remove this watch from the LRU cache managed by the\n // maybeBroadcastWatch OptimisticWrapperFunction, to prevent memory\n // leaks involving the closure of watch.callback.\n this.maybeBroadcastWatch.forget(watch);\n };\n }\n\n public gc(options?: {\n // If true, also free non-essential result cache memory by bulk-releasing\n // this.{store{Reader,Writer},maybeBroadcastWatch}. Defaults to false.\n resetResultCache?: boolean;\n // If resetResultCache is true, this.storeReader.canon will be preserved by\n // default, but can also be discarded by passing resetResultIdentities:true.\n // Defaults to false.\n resetResultIdentities?: boolean;\n }) {\n canonicalStringify.reset();\n print.reset();\n this.addTypenameTransform.resetCache();\n this.config.fragments?.resetCaches();\n const ids = this.optimisticData.gc();\n if (options && !this.txCount) {\n if (options.resetResultCache) {\n this.resetResultCache(options.resetResultIdentities);\n } else if (options.resetResultIdentities) {\n this.storeReader.resetCanon();\n }\n }\n return ids;\n }\n\n // Call this method to ensure the given root ID remains in the cache after\n // garbage collection, along with its transitive child entities. Note that\n // the cache automatically retains all directly written entities. By default,\n // the retainment persists after optimistic updates are removed. Pass true\n // for the optimistic argument if you would prefer for the retainment to be\n // discarded when the top-most optimistic layer is removed. Returns the\n // resulting (non-negative) retainment count.\n public retain(rootId: string, optimistic?: boolean): number {\n return (optimistic ? this.optimisticData : this.data).retain(rootId);\n }\n\n // Call this method to undo the effect of the retain method, above. Once the\n // retainment count falls to zero, the given ID will no longer be preserved\n // during garbage collection, though it may still be preserved by other safe\n // entities that refer to it. Returns the resulting (non-negative) retainment\n // count, in case that's useful.\n public release(rootId: string, optimistic?: boolean): number {\n return (optimistic ? this.optimisticData : this.data).release(rootId);\n }\n\n // Returns the canonical ID for a given StoreObject, obeying typePolicies\n // and keyFields (and dataIdFromObject, if you still use that). At minimum,\n // the object must contain a __typename and any primary key fields required\n // to identify entities of that type. If you pass a query result object, be\n // sure that none of the primary key fields have been renamed by aliasing.\n // If you pass a Reference object, its __ref ID string will be returned.\n public identify(object: StoreObject | Reference): string | undefined {\n if (isReference(object)) return object.__ref;\n try {\n return this.policies.identify(object)[0];\n } catch (e) {\n invariant.warn(e);\n }\n }\n\n public evict(options: Cache.EvictOptions): boolean {\n if (!options.id) {\n if (hasOwn.call(options, \"id\")) {\n // See comment in modify method about why we return false when\n // options.id exists but is falsy/undefined.\n return false;\n }\n options = { ...options, id: \"ROOT_QUERY\" };\n }\n try {\n // It's unlikely that the eviction will end up invoking any other\n // cache update operations while it's running, but {in,de}crementing\n // this.txCount still seems like a good idea, for uniformity with\n // the other update methods.\n ++this.txCount;\n // Pass this.data as a limit on the depth of the eviction, so evictions\n // during optimistic updates (when this.data is temporarily set equal to\n // this.optimisticData) do not escape their optimistic Layer.\n return this.optimisticData.evict(options, this.data);\n } finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n }\n\n public reset(options?: Cache.ResetOptions): Promise {\n this.init();\n\n canonicalStringify.reset();\n\n if (options && options.discardWatches) {\n // Similar to what happens in the unsubscribe function returned by\n // cache.watch, applied to all current watches.\n this.watches.forEach((watch) => this.maybeBroadcastWatch.forget(watch));\n this.watches.clear();\n forgetCache(this);\n } else {\n // Calling this.init() above unblocks all maybeBroadcastWatch caching, so\n // this.broadcastWatches() triggers a broadcast to every current watcher\n // (letting them know their data is now missing). This default behavior is\n // convenient because it means the watches do not have to be manually\n // reestablished after resetting the cache. To prevent this broadcast and\n // cancel all watches, pass true for options.discardWatches.\n this.broadcastWatches();\n }\n\n return Promise.resolve();\n }\n\n public removeOptimistic(idToRemove: string) {\n const newOptimisticData = this.optimisticData.removeLayer(idToRemove);\n if (newOptimisticData !== this.optimisticData) {\n this.optimisticData = newOptimisticData;\n this.broadcastWatches();\n }\n }\n\n private txCount = 0;\n\n public batch(\n options: Cache.BatchOptions\n ): TUpdateResult {\n const {\n update,\n optimistic = true,\n removeOptimistic,\n onWatchUpdated,\n } = options;\n\n let updateResult: TUpdateResult;\n const perform = (layer?: EntityStore): TUpdateResult => {\n const { data, optimisticData } = this;\n ++this.txCount;\n if (layer) {\n this.data = this.optimisticData = layer;\n }\n try {\n return (updateResult = update(this));\n } finally {\n --this.txCount;\n this.data = data;\n this.optimisticData = optimisticData;\n }\n };\n\n const alreadyDirty = new Set();\n\n if (onWatchUpdated && !this.txCount) {\n // If an options.onWatchUpdated callback is provided, we want to call it\n // with only the Cache.WatchOptions objects affected by options.update,\n // but there might be dirty watchers already waiting to be broadcast that\n // have nothing to do with the update. To prevent including those watchers\n // in the post-update broadcast, we perform this initial broadcast to\n // collect the dirty watchers, so we can re-dirty them later, after the\n // post-update broadcast, allowing them to receive their pending\n // broadcasts the next time broadcastWatches is called, just as they would\n // if we never called cache.batch.\n this.broadcastWatches({\n ...options,\n onWatchUpdated(watch) {\n alreadyDirty.add(watch);\n return false;\n },\n });\n }\n\n if (typeof optimistic === \"string\") {\n // Note that there can be multiple layers with the same optimistic ID.\n // When removeOptimistic(id) is called for that id, all matching layers\n // will be removed, and the remaining layers will be reapplied.\n this.optimisticData = this.optimisticData.addLayer(optimistic, perform);\n } else if (optimistic === false) {\n // Ensure both this.data and this.optimisticData refer to the root\n // (non-optimistic) layer of the cache during the update. Note that\n // this.data could be a Layer if we are currently executing an optimistic\n // update function, but otherwise will always be an EntityStore.Root\n // instance.\n perform(this.data);\n } else {\n // Otherwise, leave this.data and this.optimisticData unchanged and run\n // the update with broadcast batching.\n perform();\n }\n\n if (typeof removeOptimistic === \"string\") {\n this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);\n }\n\n // Note: if this.txCount > 0, then alreadyDirty.size === 0, so this code\n // takes the else branch and calls this.broadcastWatches(options), which\n // does nothing when this.txCount > 0.\n if (onWatchUpdated && alreadyDirty.size) {\n this.broadcastWatches({\n ...options,\n onWatchUpdated(watch, diff) {\n const result = onWatchUpdated.call(this, watch, diff);\n if (result !== false) {\n // Since onWatchUpdated did not return false, this diff is\n // about to be broadcast to watch.callback, so we don't need\n // to re-dirty it with the other alreadyDirty watches below.\n alreadyDirty.delete(watch);\n }\n return result;\n },\n });\n // Silently re-dirty any watches that were already dirty before the update\n // was performed, and were not broadcast just now.\n if (alreadyDirty.size) {\n alreadyDirty.forEach((watch) => this.maybeBroadcastWatch.dirty(watch));\n }\n } else {\n // If alreadyDirty is empty or we don't have an onWatchUpdated\n // function, we don't need to go to the trouble of wrapping\n // options.onWatchUpdated.\n this.broadcastWatches(options);\n }\n\n return updateResult!;\n }\n\n public performTransaction(\n update: (cache: InMemoryCache) => any,\n optimisticId?: string | null\n ) {\n return this.batch({\n update,\n optimistic: optimisticId || optimisticId !== null,\n });\n }\n\n public transformDocument(document: DocumentNode): DocumentNode {\n return this.addTypenameToDocument(this.addFragmentsToDocument(document));\n }\n\n protected broadcastWatches(options?: BroadcastOptions) {\n if (!this.txCount) {\n this.watches.forEach((c) => this.maybeBroadcastWatch(c, options));\n }\n }\n\n private addFragmentsToDocument(document: DocumentNode) {\n const { fragments } = this.config;\n return fragments ? fragments.transform(document) : document;\n }\n\n private addTypenameToDocument(document: DocumentNode) {\n if (this.addTypename) {\n return this.addTypenameTransform.transformDocument(document);\n }\n return document;\n }\n\n // This method is wrapped by maybeBroadcastWatch, which is called by\n // broadcastWatches, so that we compute and broadcast results only when\n // the data that would be broadcast might have changed. It would be\n // simpler to check for changes after recomputing a result but before\n // broadcasting it, but this wrapping approach allows us to skip both\n // the recomputation and the broadcast, in most cases.\n private broadcastWatch(c: Cache.WatchOptions, options?: BroadcastOptions) {\n const { lastDiff } = c;\n\n // Both WatchOptions and DiffOptions extend ReadOptions, and DiffOptions\n // currently requires no additional properties, so we can use c (a\n // WatchOptions object) as DiffOptions, without having to allocate a new\n // object, and without having to enumerate the relevant properties (query,\n // variables, etc.) explicitly. There will be some additional properties\n // (lastDiff, callback, etc.), but cache.diff ignores them.\n const diff = this.diff(c);\n\n if (options) {\n if (c.optimistic && typeof options.optimistic === \"string\") {\n diff.fromOptimisticTransaction = true;\n }\n\n if (\n options.onWatchUpdated &&\n options.onWatchUpdated.call(this, c, diff, lastDiff) === false\n ) {\n // Returning false from the onWatchUpdated callback will prevent\n // calling c.callback(diff) for this watcher.\n return;\n }\n }\n\n if (!lastDiff || !equal(lastDiff.result, diff.result)) {\n c.callback((c.lastDiff = diff), lastDiff);\n }\n }\n\n /**\n * @experimental\n * @internal\n * This is not a stable API - it is used in development builds to expose\n * information to the DevTools.\n * Use at your own risk!\n */\n public getMemoryInternals?: typeof getInMemoryCacheMemoryInternals;\n}\n\nif (__DEV__) {\n InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;\n}\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const empty = ApolloLink.empty;\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const from = ApolloLink.from;\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const split = ApolloLink.split;\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const concat = ApolloLink.concat;\n","/**\n * @deprecated\n * This is not used internally any more and will be removed in\n * the next major version of Apollo Client.\n */\nexport const createSignalIfSupported = () => {\n if (typeof AbortController === \"undefined\")\n return { controller: false, signal: false };\n\n const controller = new AbortController();\n const signal = controller.signal;\n return { controller, signal };\n};\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport type { Observable } from \"../../utilities/index.js\";\n\nexport function toPromise(observable: Observable): Promise {\n let completed = false;\n return new Promise((resolve, reject) => {\n observable.subscribe({\n next: (data) => {\n if (completed) {\n invariant.warn(\n `Promise Wrapper does not support multiple results from Observable`\n );\n } else {\n completed = true;\n resolve(data);\n }\n },\n error: reject,\n });\n });\n}\n","import { Observable } from \"../../utilities/index.js\";\n\nexport function fromPromise(promise: Promise): Observable {\n return new Observable((observer) => {\n promise\n .then((value: T) => {\n observer.next(value);\n observer.complete();\n })\n .catch(observer.error.bind(observer));\n });\n}\n","import { parse } from 'graphql';\n\nimport {\n DocumentNode,\n DefinitionNode,\n Location,\n} from 'graphql/language/ast';\n\n// A map docString -> graphql document\nconst docCache = new Map();\n\n// A map fragmentName -> [normalized source]\nconst fragmentSourceMap = new Map>();\n\nlet printFragmentWarnings = true;\nlet experimentalFragmentVariables = false;\n\n// Strip insignificant whitespace\n// Note that this could do a lot more, such as reorder fields etc.\nfunction normalize(string: string) {\n return string.replace(/[\\s,]+/g, ' ').trim();\n}\n\nfunction cacheKeyFromLoc(loc: Location) {\n return normalize(loc.source.body.substring(loc.start, loc.end));\n}\n\n// Take a unstripped parsed document (query/mutation or even fragment), and\n// check all fragment definitions, checking for name->source uniqueness.\n// We also want to make sure only unique fragments exist in the document.\nfunction processFragments(ast: DocumentNode) {\n const seenKeys = new Set();\n const definitions: DefinitionNode[] = [];\n\n ast.definitions.forEach(fragmentDefinition => {\n if (fragmentDefinition.kind === 'FragmentDefinition') {\n var fragmentName = fragmentDefinition.name.value;\n var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc!);\n\n // We know something about this fragment\n let sourceKeySet = fragmentSourceMap.get(fragmentName)!;\n if (sourceKeySet && !sourceKeySet.has(sourceKey)) {\n // this is a problem because the app developer is trying to register another fragment with\n // the same name as one previously registered. So, we tell them about it.\n if (printFragmentWarnings) {\n console.warn(\"Warning: fragment with name \" + fragmentName + \" already exists.\\n\"\n + \"graphql-tag enforces all fragment names across your application to be unique; read more about\\n\"\n + \"this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names\");\n }\n } else if (!sourceKeySet) {\n fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);\n }\n\n sourceKeySet.add(sourceKey);\n\n if (!seenKeys.has(sourceKey)) {\n seenKeys.add(sourceKey);\n definitions.push(fragmentDefinition);\n }\n } else {\n definitions.push(fragmentDefinition);\n }\n });\n\n return {\n ...ast,\n definitions,\n };\n}\n\nfunction stripLoc(doc: DocumentNode) {\n const workSet = new Set>(doc.definitions);\n\n workSet.forEach(node => {\n if (node.loc) delete node.loc;\n Object.keys(node).forEach(key => {\n const value = node[key];\n if (value && typeof value === 'object') {\n workSet.add(value);\n }\n });\n });\n\n const loc = doc.loc as Record;\n if (loc) {\n delete loc.startToken;\n delete loc.endToken;\n }\n\n return doc;\n}\n\nfunction parseDocument(source: string) {\n var cacheKey = normalize(source);\n if (!docCache.has(cacheKey)) {\n const parsed = parse(source, {\n experimentalFragmentVariables,\n allowLegacyFragmentVariables: experimentalFragmentVariables,\n } as any);\n if (!parsed || parsed.kind !== 'Document') {\n throw new Error('Not a valid GraphQL document.');\n }\n docCache.set(\n cacheKey,\n // check that all \"new\" fragments inside the documents are consistent with\n // existing fragments of the same name\n stripLoc(processFragments(parsed)),\n );\n }\n return docCache.get(cacheKey)!;\n}\n\n// XXX This should eventually disallow arbitrary string interpolation, like Relay does\nexport function gql(\n literals: string | readonly string[],\n ...args: any[]\n) {\n\n if (typeof literals === 'string') {\n literals = [literals];\n }\n\n let result = literals[0];\n\n args.forEach((arg, i) => {\n if (arg && arg.kind === 'Document') {\n result += arg.loc.source.body;\n } else {\n result += arg;\n }\n result += literals[i + 1];\n });\n\n return parseDocument(result);\n}\n\nexport function resetCaches() {\n docCache.clear();\n fragmentSourceMap.clear();\n}\n\nexport function disableFragmentWarnings() {\n printFragmentWarnings = false;\n}\n\nexport function enableExperimentalFragmentVariables() {\n experimentalFragmentVariables = true;\n}\n\nexport function disableExperimentalFragmentVariables() {\n experimentalFragmentVariables = false;\n}\n\nconst extras = {\n gql,\n resetCaches,\n disableFragmentWarnings,\n enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables,\n};\n\nexport namespace gql {\n export const {\n gql,\n resetCaches,\n disableFragmentWarnings,\n enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables,\n } = extras;\n}\n\ngql.default = gql;\n\nexport default gql;\n","/* Core */\n\nexport type { ApolloClientOptions, DefaultOptions } from \"./ApolloClient.js\";\nexport { ApolloClient, mergeOptions } from \"./ApolloClient.js\";\nexport type {\n FetchMoreOptions,\n UpdateQueryOptions,\n} from \"./ObservableQuery.js\";\nexport { ObservableQuery } from \"./ObservableQuery.js\";\nexport type {\n QueryOptions,\n WatchQueryOptions,\n MutationOptions,\n SubscriptionOptions,\n FetchPolicy,\n WatchQueryFetchPolicy,\n MutationFetchPolicy,\n RefetchWritePolicy,\n ErrorPolicy,\n FetchMoreQueryOptions,\n SubscribeToMoreOptions,\n} from \"./watchQueryOptions.js\";\nexport { NetworkStatus, isNetworkRequestSettled } from \"./networkStatus.js\";\nexport * from \"./types.js\";\nexport type { Resolver, FragmentMatcher } from \"./LocalState.js\";\nexport { isApolloError, ApolloError } from \"../errors/index.js\";\n/* Cache */\n\nexport type {\n // All the exports (types) from ../cache, minus cacheSlot,\n // which we want to keep semi-private.\n Transaction,\n DataProxy,\n InMemoryCacheConfig,\n ReactiveVar,\n TypePolicies,\n TypePolicy,\n FieldPolicy,\n FieldReadFunction,\n FieldMergeFunction,\n FieldFunctionOptions,\n PossibleTypesMap,\n WatchFragmentOptions,\n WatchFragmentResult,\n} from \"../cache/index.js\";\nexport {\n Cache,\n ApolloCache,\n InMemoryCache,\n MissingFieldError,\n defaultDataIdFromObject,\n makeVar,\n} from \"../cache/index.js\";\n\nexport * from \"../cache/inmemory/types.js\";\n\n/* Link */\n\nexport * from \"../link/core/index.js\";\nexport * from \"../link/http/index.js\";\nexport type { ServerError } from \"../link/utils/index.js\";\nexport {\n fromError,\n toPromise,\n fromPromise,\n throwServerError,\n} from \"../link/utils/index.js\";\n\n/* Utilities */\n\nexport type {\n DocumentTransformCacheKey,\n Observer,\n ObservableSubscription,\n Reference,\n StoreObject,\n} from \"../utilities/index.js\";\nexport {\n DocumentTransform,\n Observable,\n isReference,\n makeReference,\n} from \"../utilities/index.js\";\n\n/* Supporting */\n\n// The verbosity of invariant.{log,warn,error} can be controlled globally\n// (for anyone using the same ts-invariant package) by passing \"log\",\n// \"warn\", \"error\", or \"silent\" to setVerbosity (\"log\" is the default).\n// Note that all invariant.* logging is hidden in production.\nimport { setVerbosity } from \"ts-invariant\";\nexport { setVerbosity as setLogVerbosity };\nsetVerbosity(__DEV__ ? \"log\" : \"silent\");\n\n// Note that importing `gql` by itself, then destructuring\n// additional properties separately before exporting, is intentional.\n// Due to the way the `graphql-tag` library is setup, certain bundlers\n// can't find the properties added to the exported `gql` function without\n// additional guidance (e.g. Rollup - see\n// https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module).\n// Instead of having people that are using bundlers with `@apollo/client` add\n// extra bundler config to help `graphql-tag` exports be found (which would be\n// awkward since they aren't importing `graphql-tag` themselves), this\n// workaround of pulling the extra properties off the `gql` function,\n// then re-exporting them separately, helps keeps bundlers happy without any\n// additional config changes.\nexport {\n gql,\n resetCaches,\n disableFragmentWarnings,\n enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables,\n} from \"graphql-tag\";\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport * as React from \"rehackt\";\nimport type * as ReactTypes from \"react\";\n\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { getApolloContext } from \"./ApolloContext.js\";\n\nexport interface ApolloProviderProps {\n client: ApolloClient;\n children: ReactTypes.ReactNode | ReactTypes.ReactNode[] | null;\n}\n\nexport const ApolloProvider: ReactTypes.FC> = ({\n client,\n children,\n}) => {\n const ApolloContext = getApolloContext();\n const parentContext = React.useContext(ApolloContext);\n\n const context = React.useMemo(() => {\n return {\n ...parentContext,\n client: client || parentContext.client,\n };\n }, [parentContext, client]);\n\n invariant(\n context.client,\n \"ApolloProvider was not passed a client instance. Make \" +\n 'sure you pass in your client via the \"client\" prop.'\n );\n\n return (\n {children}\n );\n};\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport * as React from \"rehackt\";\nimport type * as ReactTypes from \"react\";\n\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { getApolloContext } from \"./ApolloContext.js\";\n\nexport interface ApolloConsumerProps {\n children: (client: ApolloClient) => ReactTypes.ReactNode;\n}\n\nexport const ApolloConsumer: ReactTypes.FC = (props) => {\n const ApolloContext = getApolloContext();\n return (\n \n {(context: any) => {\n invariant(\n context && context.client,\n 'Could not find \"client\" in the context of ApolloConsumer. ' +\n \"Wrap the root component in an .\"\n );\n return props.children(context.client);\n }}\n \n );\n};\n","import type { DocumentNode } from \"graphql\";\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport * as React from \"rehackt\";\n\nimport type { OperationVariables } from \"../../core/index.js\";\nimport { mergeOptions } from \"../../utilities/index.js\";\nimport type {\n LazyQueryHookExecOptions,\n LazyQueryHookOptions,\n LazyQueryResultTuple,\n NoInfer,\n QueryResult,\n} from \"../types/types.js\";\nimport { useInternalState } from \"./useQuery.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n\n// The following methods, when called will execute the query, regardless of\n// whether the useLazyQuery execute function was called before.\nconst EAGER_METHODS = [\n \"refetch\",\n \"reobserve\",\n \"fetchMore\",\n \"updateQuery\",\n \"startPolling\",\n \"subscribeToMore\",\n] as const;\n\n/**\n * A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.\n *\n * > Refer to the [Queries - Manual execution with useLazyQuery](https://www.apollographql.com/docs/react/data/queries#manual-execution-with-uselazyquery) section for a more in-depth overview of `useLazyQuery`.\n *\n * @example\n * ```jsx\n * import { gql, useLazyQuery } from \"@apollo/client\";\n *\n * const GET_GREETING = gql`\n * query GetGreeting($language: String!) {\n * greeting(language: $language) {\n * message\n * }\n * }\n * `;\n *\n * function Hello() {\n * const [loadGreeting, { called, loading, data }] = useLazyQuery(\n * GET_GREETING,\n * { variables: { language: \"english\" } }\n * );\n * if (called && loading) return

Loading ...

\n * if (!called) {\n * return \n * }\n * return

Hello {data.greeting.message}!

;\n * }\n * ```\n * @since 3.0.0\n *\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Default options to control how the query is executed.\n * @returns A tuple in the form of `[execute, result]`\n */\nexport function useLazyQuery<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: LazyQueryHookOptions, NoInfer>\n): LazyQueryResultTuple {\n const execOptionsRef =\n React.useRef>>();\n const optionsRef = React.useRef>();\n const queryRef = React.useRef<\n DocumentNode | TypedDocumentNode\n >();\n const merged = mergeOptions(options, execOptionsRef.current || {});\n const document = merged?.query ?? query;\n\n // Use refs to track options and the used query to ensure the `execute`\n // function remains referentially stable between renders.\n optionsRef.current = options;\n queryRef.current = document;\n\n const internalState = useInternalState(\n useApolloClient(options && options.client),\n document\n );\n\n const useQueryResult = internalState.useQuery({\n ...merged,\n skip: !execOptionsRef.current,\n });\n\n const initialFetchPolicy =\n useQueryResult.observable.options.initialFetchPolicy ||\n internalState.getDefaultFetchPolicy();\n\n const result: QueryResult = Object.assign(useQueryResult, {\n called: !!execOptionsRef.current,\n });\n\n // We use useMemo here to make sure the eager methods have a stable identity.\n const eagerMethods = React.useMemo(() => {\n const eagerMethods: Record = {};\n for (const key of EAGER_METHODS) {\n const method = result[key];\n eagerMethods[key] = function () {\n if (!execOptionsRef.current) {\n execOptionsRef.current = Object.create(null);\n // Only the first time populating execOptionsRef.current matters here.\n internalState.forceUpdateState();\n }\n // @ts-expect-error this is just too generic to type\n return method.apply(this, arguments);\n };\n }\n\n return eagerMethods;\n }, []);\n\n Object.assign(result, eagerMethods);\n\n const execute = React.useCallback[0]>(\n (executeOptions) => {\n execOptionsRef.current =\n executeOptions ?\n {\n ...executeOptions,\n fetchPolicy: executeOptions.fetchPolicy || initialFetchPolicy,\n }\n : {\n fetchPolicy: initialFetchPolicy,\n };\n\n const options = mergeOptions(optionsRef.current, {\n query: queryRef.current,\n ...execOptionsRef.current,\n });\n\n const promise = internalState\n .executeQuery({ ...options, skip: false })\n .then((queryResult) => Object.assign(queryResult, eagerMethods));\n\n // Because the return value of `useLazyQuery` is usually floated, we need\n // to catch the promise to prevent unhandled rejections.\n promise.catch(() => {});\n\n return promise;\n },\n []\n );\n\n return [execute, result];\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport * as React from \"rehackt\";\nimport type { DocumentNode } from \"graphql\";\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport { equal } from \"@wry/equality\";\n\nimport { DocumentType, verifyDocumentType } from \"../parser/index.js\";\nimport type {\n NoInfer,\n SubscriptionHookOptions,\n SubscriptionResult,\n} from \"../types/types.js\";\nimport type { OperationVariables } from \"../../core/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n/**\n * > Refer to the [Subscriptions](https://www.apollographql.com/docs/react/data/subscriptions/) section for a more in-depth overview of `useSubscription`.\n *\n * @example\n * ```jsx\n * const COMMENTS_SUBSCRIPTION = gql`\n * subscription OnCommentAdded($repoFullName: String!) {\n * commentAdded(repoFullName: $repoFullName) {\n * id\n * content\n * }\n * }\n * `;\n *\n * function DontReadTheComments({ repoFullName }) {\n * const {\n * data: { commentAdded },\n * loading,\n * } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });\n * return

New comment: {!loading && commentAdded.content}

;\n * }\n * ```\n * @remarks\n * #### Subscriptions and React 18 Automatic Batching\n *\n * With React 18's [automatic batching](https://react.dev/blog/2022/03/29/react-v18#new-feature-automatic-batching), multiple state updates may be grouped into a single re-render for better performance.\n *\n * If your subscription API sends multiple messages at the same time or in very fast succession (within fractions of a millisecond), it is likely that only the last message received in that narrow time frame will result in a re-render.\n *\n * Consider the following component:\n *\n * ```jsx\n * export function Subscriptions() {\n * const { data, error, loading } = useSubscription(query);\n * const [accumulatedData, setAccumulatedData] = useState([]);\n *\n * useEffect(() => {\n * setAccumulatedData((prev) => [...prev, data]);\n * }, [data]);\n *\n * return (\n * <>\n * {loading &&

Loading...

}\n * {JSON.stringify(accumulatedData, undefined, 2)}\n * \n * );\n * }\n * ```\n *\n * If your subscription back-end emits two messages with the same timestamp, only the last message received by Apollo Client will be rendered. This is because React 18 will batch these two state updates into a single re-render.\n *\n * Since the component above is using `useEffect` to push `data` into a piece of local state on each `Subscriptions` re-render, the first message will never be added to the `accumulatedData` array since its render was skipped.\n *\n * Instead of using `useEffect` here, we can re-write this component to use the `onData` callback function accepted in `useSubscription`'s `options` object:\n *\n * ```jsx\n * export function Subscriptions() {\n * const [accumulatedData, setAccumulatedData] = useState([]);\n * const { data, error, loading } = useSubscription(\n * query,\n * {\n * onData({ data }) {\n * setAccumulatedData((prev) => [...prev, data])\n * }\n * }\n * );\n *\n * return (\n * <>\n * {loading &&

Loading...

}\n * {JSON.stringify(accumulatedData, undefined, 2)}\n * \n * );\n * }\n * ```\n *\n * > ⚠️ **Note:** The `useSubscription` option `onData` is available in Apollo Client >= 3.7. In previous versions, the equivalent option is named `onSubscriptionData`.\n *\n * Now, the first message will be added to the `accumulatedData` array since `onData` is called _before_ the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but with `onData` we can guarantee each message received after the component mounts is added to `accumulatedData`.\n *\n * @since 3.0.0\n * @param subscription - A GraphQL subscription document parsed into an AST by `gql`.\n * @param options - Options to control how the subscription is executed.\n * @returns Query result object\n */\nexport function useSubscription<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n subscription: DocumentNode | TypedDocumentNode,\n options?: SubscriptionHookOptions, NoInfer>\n) {\n const hasIssuedDeprecationWarningRef = React.useRef(false);\n const client = useApolloClient(options?.client);\n verifyDocumentType(subscription, DocumentType.Subscription);\n const [result, setResult] = React.useState<\n SubscriptionResult\n >({\n loading: !options?.skip,\n error: void 0,\n data: void 0,\n variables: options?.variables,\n });\n\n if (!hasIssuedDeprecationWarningRef.current) {\n hasIssuedDeprecationWarningRef.current = true;\n\n if (options?.onSubscriptionData) {\n invariant.warn(\n options.onData ?\n \"'useSubscription' supports only the 'onSubscriptionData' or 'onData' option, but not both. Only the 'onData' option will be used.\"\n : \"'onSubscriptionData' is deprecated and will be removed in a future major version. Please use the 'onData' option instead.\"\n );\n }\n\n if (options?.onSubscriptionComplete) {\n invariant.warn(\n options.onComplete ?\n \"'useSubscription' supports only the 'onSubscriptionComplete' or 'onComplete' option, but not both. Only the 'onComplete' option will be used.\"\n : \"'onSubscriptionComplete' is deprecated and will be removed in a future major version. Please use the 'onComplete' option instead.\"\n );\n }\n }\n\n const [observable, setObservable] = React.useState(() => {\n if (options?.skip) {\n return null;\n }\n\n return client.subscribe({\n query: subscription,\n variables: options?.variables,\n fetchPolicy: options?.fetchPolicy,\n context: options?.context,\n });\n });\n\n const canResetObservableRef = React.useRef(false);\n React.useEffect(() => {\n return () => {\n canResetObservableRef.current = true;\n };\n }, []);\n\n const ref = React.useRef({ client, subscription, options });\n React.useEffect(() => {\n let shouldResubscribe = options?.shouldResubscribe;\n if (typeof shouldResubscribe === \"function\") {\n shouldResubscribe = !!shouldResubscribe(options!);\n }\n\n if (options?.skip) {\n if (\n !options?.skip !== !ref.current.options?.skip ||\n canResetObservableRef.current\n ) {\n setResult({\n loading: false,\n data: void 0,\n error: void 0,\n variables: options?.variables,\n });\n setObservable(null);\n canResetObservableRef.current = false;\n }\n } else if (\n (shouldResubscribe !== false &&\n (client !== ref.current.client ||\n subscription !== ref.current.subscription ||\n options?.fetchPolicy !== ref.current.options?.fetchPolicy ||\n !options?.skip !== !ref.current.options?.skip ||\n !equal(options?.variables, ref.current.options?.variables))) ||\n canResetObservableRef.current\n ) {\n setResult({\n loading: true,\n data: void 0,\n error: void 0,\n variables: options?.variables,\n });\n setObservable(\n client.subscribe({\n query: subscription,\n variables: options?.variables,\n fetchPolicy: options?.fetchPolicy,\n context: options?.context,\n })\n );\n canResetObservableRef.current = false;\n }\n\n Object.assign(ref.current, { client, subscription, options });\n }, [client, subscription, options, canResetObservableRef.current]);\n\n React.useEffect(() => {\n if (!observable) {\n return;\n }\n\n let subscriptionStopped = false;\n const subscription = observable.subscribe({\n next(fetchResult) {\n if (subscriptionStopped) {\n return;\n }\n\n const result = {\n loading: false,\n // TODO: fetchResult.data can be null but SubscriptionResult.data\n // expects TData | undefined only\n data: fetchResult.data!,\n error: void 0,\n variables: options?.variables,\n };\n setResult(result);\n\n if (ref.current.options?.onData) {\n ref.current.options.onData({\n client,\n data: result,\n });\n } else if (ref.current.options?.onSubscriptionData) {\n ref.current.options.onSubscriptionData({\n client,\n subscriptionData: result,\n });\n }\n },\n error(error) {\n if (!subscriptionStopped) {\n setResult({\n loading: false,\n data: void 0,\n error,\n variables: options?.variables,\n });\n ref.current.options?.onError?.(error);\n }\n },\n complete() {\n if (!subscriptionStopped) {\n if (ref.current.options?.onComplete) {\n ref.current.options.onComplete();\n } else if (ref.current.options?.onSubscriptionComplete) {\n ref.current.options.onSubscriptionComplete();\n }\n }\n },\n });\n\n return () => {\n // immediately stop receiving subscription values, but do not unsubscribe\n // until after a short delay in case another useSubscription hook is\n // reusing the same underlying observable and is about to subscribe\n subscriptionStopped = true;\n setTimeout(() => {\n subscription.unsubscribe();\n });\n };\n }, [observable]);\n\n return result;\n}\n","import * as React from \"rehackt\";\nimport type { ReactiveVar } from \"../../core/index.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\n/**\n * Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the `useQuery` hook.\n *\n * @example\n * ```jsx\n * import { makeVar, useReactiveVar } from \"@apollo/client\";\n * export const cartItemsVar = makeVar([]);\n *\n * export function Cart() {\n * const cartItems = useReactiveVar(cartItemsVar);\n * // ...\n * }\n * ```\n * @since 3.2.0\n * @param rv - A reactive variable.\n * @returns The current value of the reactive variable.\n */\nexport function useReactiveVar(rv: ReactiveVar): T {\n return useSyncExternalStore(\n React.useCallback(\n (update) => {\n // By reusing the same onNext function in the nested call to\n // rv.onNextChange(onNext), we can keep using the initial clean-up function\n // returned by rv.onNextChange(function onNext(v){...}), without having to\n // register the new clean-up function (returned by the nested\n // rv.onNextChange(onNext)) with yet another callback.\n return rv.onNextChange(function onNext() {\n update();\n rv.onNextChange(onNext);\n });\n },\n [rv]\n ),\n rv,\n rv\n );\n}\n","import type { DependencyList } from \"react\";\nimport * as React from \"rehackt\";\nimport { equal } from \"@wry/equality\";\n\nexport function useDeepMemo(\n memoFn: () => TValue,\n deps: DependencyList\n) {\n const ref = React.useRef<{ deps: DependencyList; value: TValue }>();\n\n if (!ref.current || !equal(ref.current.deps, deps)) {\n ref.current = { value: memoFn(), deps };\n }\n\n return ref.current.value;\n}\n","import * as React from \"rehackt\";\n\nconst INIT = {};\n\nexport function useLazyRef(getInitialValue: () => T) {\n const ref = React.useRef(INIT as unknown as T);\n\n if (ref.current === INIT) {\n ref.current = getInitialValue();\n }\n\n return ref;\n}\n","import * as React from \"rehackt\";\nimport type { DeepPartial } from \"../../utilities/index.js\";\nimport { mergeDeepArray } from \"../../utilities/index.js\";\nimport type {\n Cache,\n Reference,\n StoreObject,\n MissingTree,\n} from \"../../cache/index.js\";\n\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport type { ApolloClient, OperationVariables } from \"../../core/index.js\";\nimport type { NoInfer } from \"../types/types.js\";\nimport { useDeepMemo, useLazyRef, wrapHook } from \"./internal/index.js\";\nimport equal from \"@wry/equality\";\n\nexport interface UseFragmentOptions\n extends Omit<\n Cache.DiffOptions, NoInfer>,\n \"id\" | \"query\" | \"optimistic\" | \"previousResult\" | \"returnPartialData\"\n >,\n Omit<\n Cache.ReadFragmentOptions,\n \"id\" | \"variables\" | \"returnPartialData\"\n > {\n from: StoreObject | Reference | string;\n // Override this field to make it optional (default: true).\n optimistic?: boolean;\n /**\n * The instance of `ApolloClient` to use to look up the fragment.\n *\n * By default, the instance that's passed down via context is used, but you\n * can provide a different instance here.\n *\n * @docGroup 1. Operation options\n */\n client?: ApolloClient;\n}\n\nexport type UseFragmentResult =\n | {\n data: TData;\n complete: true;\n missing?: never;\n }\n | {\n data: DeepPartial;\n complete: false;\n missing?: MissingTree;\n };\n\nexport function useFragment(\n options: UseFragmentOptions\n): UseFragmentResult {\n return wrapHook(\n \"useFragment\",\n _useFragment,\n useApolloClient(options.client)\n )(options);\n}\n\nfunction _useFragment(\n options: UseFragmentOptions\n): UseFragmentResult {\n const { cache } = useApolloClient(options.client);\n\n const diffOptions = useDeepMemo>(() => {\n const {\n fragment,\n fragmentName,\n from,\n optimistic = true,\n ...rest\n } = options;\n\n return {\n ...rest,\n returnPartialData: true,\n id: typeof from === \"string\" ? from : cache.identify(from),\n query: cache[\"getFragmentDoc\"](fragment, fragmentName),\n optimistic,\n };\n }, [options]);\n\n const resultRef = useLazyRef>(() =>\n diffToResult(cache.diff(diffOptions))\n );\n\n const stableOptions = useDeepMemo(() => options, [options]);\n\n // Since .next is async, we need to make sure that we\n // get the correct diff on the next render given new diffOptions\n React.useMemo(() => {\n resultRef.current = diffToResult(cache.diff(diffOptions));\n }, [diffOptions, cache]);\n\n // Used for both getSnapshot and getServerSnapshot\n const getSnapshot = React.useCallback(() => resultRef.current, []);\n\n return useSyncExternalStore(\n React.useCallback(\n (forceUpdate) => {\n let lastTimeout = 0;\n const subscription = cache.watchFragment(stableOptions).subscribe({\n next: (result) => {\n if (equal(result, resultRef.current)) return;\n resultRef.current = result;\n // If we get another update before we've re-rendered, bail out of\n // the update and try again. This ensures that the relative timing\n // between useQuery and useFragment stays roughly the same as\n // fixed in https://github.com/apollographql/apollo-client/pull/11083\n clearTimeout(lastTimeout);\n lastTimeout = setTimeout(forceUpdate) as any;\n },\n });\n return () => {\n subscription.unsubscribe();\n clearTimeout(lastTimeout);\n };\n },\n [cache, stableOptions]\n ),\n getSnapshot,\n getSnapshot\n );\n}\n\nfunction diffToResult(\n diff: Cache.DiffResult\n): UseFragmentResult {\n const result = {\n data: diff.result!,\n complete: !!diff.complete,\n } as UseFragmentResult;\n\n if (diff.missing) {\n result.missing = mergeDeepArray(diff.missing.map((error) => error.missing));\n }\n\n return result;\n}\n","export interface PendingPromise extends Promise {\n status: \"pending\";\n}\n\nexport interface FulfilledPromise extends Promise {\n status: \"fulfilled\";\n value: TValue;\n}\n\nexport interface RejectedPromise extends Promise {\n status: \"rejected\";\n reason: unknown;\n}\n\nexport type PromiseWithState =\n | PendingPromise\n | FulfilledPromise\n | RejectedPromise;\n\nexport function createFulfilledPromise(value: TValue) {\n const promise = Promise.resolve(value) as FulfilledPromise;\n\n promise.status = \"fulfilled\";\n promise.value = value;\n\n return promise;\n}\n\nexport function createRejectedPromise(reason: unknown) {\n const promise = Promise.reject(reason) as RejectedPromise;\n\n // prevent potential edge cases leaking unhandled error rejections\n promise.catch(() => {});\n\n promise.status = \"rejected\";\n promise.reason = reason;\n\n return promise;\n}\n\nexport function isStatefulPromise(\n promise: Promise\n): promise is PromiseWithState {\n return \"status\" in promise;\n}\n\nexport function wrapPromiseWithState(\n promise: Promise\n): PromiseWithState {\n if (isStatefulPromise(promise)) {\n return promise;\n }\n\n const pendingPromise = promise as PendingPromise;\n pendingPromise.status = \"pending\";\n\n pendingPromise.then(\n (value) => {\n if (pendingPromise.status === \"pending\") {\n const fulfilledPromise =\n pendingPromise as unknown as FulfilledPromise;\n\n fulfilledPromise.status = \"fulfilled\";\n fulfilledPromise.value = value;\n }\n },\n (reason: unknown) => {\n if (pendingPromise.status === \"pending\") {\n const rejectedPromise =\n pendingPromise as unknown as RejectedPromise;\n\n rejectedPromise.status = \"rejected\";\n rejectedPromise.reason = reason;\n }\n }\n );\n\n return promise as PromiseWithState;\n}\n","import { wrapPromiseWithState } from \"../../../utilities/index.js\";\nimport * as React from \"rehackt\";\n\ntype Use = (promise: Promise) => T;\n// Prevent webpack from complaining about our feature detection of the\n// use property of the React namespace, which is expected not\n// to exist when using current stable versions, and that's fine.\nconst useKey = \"use\" as keyof typeof React;\nconst realHook = React[useKey] as Use | undefined;\n\n// This is named with two underscores to allow this hook to evade typical rules of\n// hooks (i.e. it can be used conditionally)\nexport const __use =\n realHook ||\n function __use(promise: Promise) {\n const statefulPromise = wrapPromiseWithState(promise);\n\n switch (statefulPromise.status) {\n case \"pending\":\n throw statefulPromise;\n case \"rejected\":\n throw statefulPromise.reason;\n case \"fulfilled\":\n return statefulPromise.value;\n }\n };\n","import { equal } from \"@wry/equality\";\nimport type {\n ApolloError,\n ApolloQueryResult,\n ObservableQuery,\n OperationVariables,\n WatchQueryOptions,\n} from \"../../../core/index.js\";\nimport type {\n ObservableSubscription,\n PromiseWithState,\n} from \"../../../utilities/index.js\";\nimport {\n createFulfilledPromise,\n createRejectedPromise,\n} from \"../../../utilities/index.js\";\nimport type { QueryKey } from \"./types.js\";\nimport { wrapPromiseWithState } from \"../../../utilities/index.js\";\nimport { invariant } from \"../../../utilities/globals/invariantWrappers.js\";\n\ntype QueryRefPromise = PromiseWithState>;\n\ntype Listener = (promise: QueryRefPromise) => void;\n\ntype FetchMoreOptions = Parameters<\n ObservableQuery[\"fetchMore\"]\n>[0];\n\nconst QUERY_REFERENCE_SYMBOL: unique symbol = Symbol();\nconst PROMISE_SYMBOL: unique symbol = Symbol();\ndeclare const QUERY_REF_BRAND: unique symbol;\n/**\n * A `QueryReference` is an opaque object returned by `useBackgroundQuery`.\n * A child component reading the `QueryReference` via `useReadQuery` will\n * suspend until the promise resolves.\n */\nexport interface QueryRef {\n /** @internal */\n [QUERY_REF_BRAND]?(variables: TVariables): TData;\n}\n\n/**\n * @internal\n * For usage in internal helpers only.\n */\ninterface WrappedQueryRef\n extends QueryRef {\n /** @internal */\n readonly [QUERY_REFERENCE_SYMBOL]: InternalQueryReference;\n /** @internal */\n [PROMISE_SYMBOL]: QueryRefPromise;\n /** @internal */\n toPromise?(): Promise;\n}\n\n/**\n * @deprecated Please use the `QueryRef` interface instead of `QueryReference`.\n *\n * {@inheritDoc @apollo/client!QueryRef:interface}\n */\nexport interface QueryReference\n extends QueryRef {\n /**\n * @deprecated Please use the `QueryRef` interface instead of `QueryReference`.\n *\n * {@inheritDoc @apollo/client!PreloadedQueryRef#toPromise:member(1)}\n */\n toPromise?: unknown;\n}\n\n/**\n * {@inheritDoc @apollo/client!QueryRef:interface}\n */\nexport interface PreloadedQueryRef\n extends QueryRef {\n /**\n * A function that returns a promise that resolves when the query has finished\n * loading. The promise resolves with the `QueryReference` itself.\n *\n * @remarks\n * This method is useful for preloading queries in data loading routers, such\n * as [React Router](https://reactrouter.com/en/main) or [TanStack Router](https://tanstack.com/router),\n * to prevent routes from transitioning until the query has finished loading.\n * `data` is not exposed on the promise to discourage using the data in\n * `loader` functions and exposing it to your route components. Instead, we\n * prefer you rely on `useReadQuery` to access the data to ensure your\n * component can rerender with cache updates. If you need to access raw query\n * data, use `client.query()` directly.\n *\n * @example\n * Here's an example using React Router's `loader` function:\n * ```ts\n * import { createQueryPreloader } from \"@apollo/client\";\n *\n * const preloadQuery = createQueryPreloader(client);\n *\n * export async function loader() {\n * const queryRef = preloadQuery(GET_DOGS_QUERY);\n *\n * return queryRef.toPromise();\n * }\n *\n * export function RouteComponent() {\n * const queryRef = useLoaderData();\n * const { data } = useReadQuery(queryRef);\n *\n * // ...\n * }\n * ```\n *\n * @since 3.9.0\n */\n toPromise(): Promise>;\n}\n\ninterface InternalQueryReferenceOptions {\n onDispose?: () => void;\n autoDisposeTimeoutMs?: number;\n}\n\nexport function wrapQueryRef(\n internalQueryRef: InternalQueryReference\n) {\n const ref: WrappedQueryRef = {\n toPromise() {\n // We avoid resolving this promise with the query data because we want to\n // discourage using the server data directly from the queryRef. Instead,\n // the data should be accessed through `useReadQuery`. When the server\n // data is needed, its better to use `client.query()` directly.\n //\n // Here we resolve with the ref itself to make using this in React Router\n // or TanStack Router `loader` functions a bit more ergonomic e.g.\n //\n // function loader() {\n // return { queryRef: await preloadQuery(query).toPromise() }\n // }\n return getWrappedPromise(ref).then(() => ref);\n },\n [QUERY_REFERENCE_SYMBOL]: internalQueryRef,\n [PROMISE_SYMBOL]: internalQueryRef.promise,\n };\n\n return ref;\n}\n\nexport function assertWrappedQueryRef(\n queryRef: QueryRef\n): asserts queryRef is WrappedQueryRef;\nexport function assertWrappedQueryRef(\n queryRef: QueryRef | undefined | null\n): asserts queryRef is WrappedQueryRef | undefined | null;\nexport function assertWrappedQueryRef(\n queryRef: QueryRef | undefined | null\n) {\n invariant(\n !queryRef || QUERY_REFERENCE_SYMBOL in queryRef,\n \"Expected a QueryRef object, but got something else instead.\"\n );\n}\n\nexport function getWrappedPromise(\n queryRef: WrappedQueryRef\n) {\n const internalQueryRef = unwrapQueryRef(queryRef);\n\n return internalQueryRef.promise.status === \"fulfilled\" ?\n internalQueryRef.promise\n : queryRef[PROMISE_SYMBOL];\n}\n\nexport function unwrapQueryRef(\n queryRef: WrappedQueryRef\n): InternalQueryReference;\nexport function unwrapQueryRef(\n queryRef: Partial>\n): undefined | InternalQueryReference;\nexport function unwrapQueryRef(\n queryRef: Partial>\n) {\n return queryRef[QUERY_REFERENCE_SYMBOL];\n}\n\nexport function updateWrappedQueryRef(\n queryRef: WrappedQueryRef,\n promise: QueryRefPromise\n) {\n queryRef[PROMISE_SYMBOL] = promise;\n}\n\nconst OBSERVED_CHANGED_OPTIONS = [\n \"canonizeResults\",\n \"context\",\n \"errorPolicy\",\n \"fetchPolicy\",\n \"refetchWritePolicy\",\n \"returnPartialData\",\n] as const;\n\ntype ObservedOptions = Pick<\n WatchQueryOptions,\n (typeof OBSERVED_CHANGED_OPTIONS)[number]\n>;\n\nexport class InternalQueryReference {\n public result!: ApolloQueryResult;\n public readonly key: QueryKey = {};\n public readonly observable: ObservableQuery;\n\n public promise!: QueryRefPromise;\n\n private subscription!: ObservableSubscription;\n private listeners = new Set>();\n private autoDisposeTimeoutId?: NodeJS.Timeout;\n\n private resolve: ((result: ApolloQueryResult) => void) | undefined;\n private reject: ((error: unknown) => void) | undefined;\n\n private references = 0;\n private softReferences = 0;\n\n constructor(\n observable: ObservableQuery,\n options: InternalQueryReferenceOptions\n ) {\n this.handleNext = this.handleNext.bind(this);\n this.handleError = this.handleError.bind(this);\n this.dispose = this.dispose.bind(this);\n this.observable = observable;\n\n if (options.onDispose) {\n this.onDispose = options.onDispose;\n }\n\n this.setResult();\n this.subscribeToQuery();\n\n // Start a timer that will automatically dispose of the query if the\n // suspended resource does not use this queryRef in the given time. This\n // helps prevent memory leaks when a component has unmounted before the\n // query has finished loading.\n const startDisposeTimer = () => {\n if (!this.references) {\n this.autoDisposeTimeoutId = setTimeout(\n this.dispose,\n options.autoDisposeTimeoutMs ?? 30_000\n );\n }\n };\n\n // We wait until the request has settled to ensure we don't dispose of the\n // query ref before the request finishes, otherwise we would leave the\n // promise in a pending state rendering the suspense boundary indefinitely.\n this.promise.then(startDisposeTimer, startDisposeTimer);\n }\n\n get disposed() {\n return this.subscription.closed;\n }\n\n get watchQueryOptions() {\n return this.observable.options;\n }\n\n reinitialize() {\n const { observable } = this;\n\n const originalFetchPolicy = this.watchQueryOptions.fetchPolicy;\n const avoidNetworkRequests =\n originalFetchPolicy === \"no-cache\" || originalFetchPolicy === \"standby\";\n\n try {\n if (avoidNetworkRequests) {\n observable.silentSetOptions({ fetchPolicy: \"standby\" });\n } else {\n observable.resetLastResults();\n observable.silentSetOptions({ fetchPolicy: \"cache-first\" });\n }\n\n this.subscribeToQuery();\n\n if (avoidNetworkRequests) {\n return;\n }\n\n observable.resetDiff();\n this.setResult();\n } finally {\n observable.silentSetOptions({ fetchPolicy: originalFetchPolicy });\n }\n }\n\n retain() {\n this.references++;\n clearTimeout(this.autoDisposeTimeoutId);\n let disposed = false;\n\n return () => {\n if (disposed) {\n return;\n }\n\n disposed = true;\n this.references--;\n\n setTimeout(() => {\n if (!this.references) {\n this.dispose();\n }\n });\n };\n }\n\n softRetain() {\n this.softReferences++;\n let disposed = false;\n\n return () => {\n // Tracking if this has already been called helps ensure that\n // multiple calls to this function won't decrement the reference\n // counter more than it should. Subsequent calls just result in a noop.\n if (disposed) {\n return;\n }\n\n disposed = true;\n this.softReferences--;\n setTimeout(() => {\n if (!this.softReferences && !this.references) {\n this.dispose();\n }\n });\n };\n }\n\n didChangeOptions(watchQueryOptions: ObservedOptions) {\n return OBSERVED_CHANGED_OPTIONS.some(\n (option) =>\n option in watchQueryOptions &&\n !equal(this.watchQueryOptions[option], watchQueryOptions[option])\n );\n }\n\n applyOptions(watchQueryOptions: ObservedOptions) {\n const {\n fetchPolicy: currentFetchPolicy,\n canonizeResults: currentCanonizeResults,\n } = this.watchQueryOptions;\n\n // \"standby\" is used when `skip` is set to `true`. Detect when we've\n // enabled the query (i.e. `skip` is `false`) to execute a network request.\n if (\n currentFetchPolicy === \"standby\" &&\n currentFetchPolicy !== watchQueryOptions.fetchPolicy\n ) {\n this.initiateFetch(this.observable.reobserve(watchQueryOptions));\n } else {\n this.observable.silentSetOptions(watchQueryOptions);\n\n if (currentCanonizeResults !== watchQueryOptions.canonizeResults) {\n this.result = { ...this.result, ...this.observable.getCurrentResult() };\n this.promise = createFulfilledPromise(this.result);\n }\n }\n\n return this.promise;\n }\n\n listen(listener: Listener) {\n this.listeners.add(listener);\n\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n refetch(variables: OperationVariables | undefined) {\n return this.initiateFetch(this.observable.refetch(variables));\n }\n\n fetchMore(options: FetchMoreOptions) {\n return this.initiateFetch(this.observable.fetchMore(options));\n }\n\n private dispose() {\n this.subscription.unsubscribe();\n this.onDispose();\n }\n\n private onDispose() {\n // noop. overridable by options\n }\n\n private handleNext(result: ApolloQueryResult) {\n switch (this.promise.status) {\n case \"pending\": {\n // Maintain the last successful `data` value if the next result does not\n // have one.\n if (result.data === void 0) {\n result.data = this.result.data;\n }\n this.result = result;\n this.resolve?.(result);\n break;\n }\n default: {\n // This occurs when switching to a result that is fully cached when this\n // class is instantiated. ObservableQuery will run reobserve when\n // subscribing, which delivers a result from the cache.\n if (\n result.data === this.result.data &&\n result.networkStatus === this.result.networkStatus\n ) {\n return;\n }\n\n // Maintain the last successful `data` value if the next result does not\n // have one.\n if (result.data === void 0) {\n result.data = this.result.data;\n }\n\n this.result = result;\n this.promise = createFulfilledPromise(result);\n this.deliver(this.promise);\n break;\n }\n }\n }\n\n private handleError(error: ApolloError) {\n this.subscription.unsubscribe();\n this.subscription = this.observable.resubscribeAfterError(\n this.handleNext,\n this.handleError\n );\n\n switch (this.promise.status) {\n case \"pending\": {\n this.reject?.(error);\n break;\n }\n default: {\n this.promise = createRejectedPromise>(error);\n this.deliver(this.promise);\n }\n }\n }\n\n private deliver(promise: QueryRefPromise) {\n this.listeners.forEach((listener) => listener(promise));\n }\n\n private initiateFetch(returnedPromise: Promise>) {\n this.promise = this.createPendingPromise();\n this.promise.catch(() => {});\n\n // If the data returned from the fetch is deeply equal to the data already\n // in the cache, `handleNext` will not be triggered leaving the promise we\n // created in a pending state forever. To avoid this situtation, we attempt\n // to resolve the promise if `handleNext` hasn't been run to ensure the\n // promise is resolved correctly.\n returnedPromise\n .then(() => {\n // In the case of `fetchMore`, this promise is resolved before a cache\n // result is emitted due to the fact that `fetchMore` sets a `no-cache`\n // fetch policy and runs `cache.batch` in its `.then` handler. Because\n // the timing is different, we accidentally run this update twice\n // causing an additional re-render with the `fetchMore` result by\n // itself. By wrapping in `setTimeout`, this should provide a short\n // delay to allow the `QueryInfo.notify` handler to run before this\n // promise is checked.\n // See https://github.com/apollographql/apollo-client/issues/11315 for\n // more information\n setTimeout(() => {\n if (this.promise.status === \"pending\") {\n // Use the current result from the observable instead of the value\n // resolved from the promise. This avoids issues in some cases where\n // the raw resolved value should not be the emitted value, such as\n // when a `fetchMore` call returns an empty array after it has\n // reached the end of the list.\n //\n // See the following for more information:\n // https://github.com/apollographql/apollo-client/issues/11642\n this.result = this.observable.getCurrentResult();\n this.resolve?.(this.result);\n }\n });\n })\n .catch(() => {});\n\n return returnedPromise;\n }\n\n private subscribeToQuery() {\n this.subscription = this.observable\n .filter(\n (result) => !equal(result.data, {}) && !equal(result, this.result)\n )\n .subscribe(this.handleNext, this.handleError);\n }\n\n private setResult() {\n // Don't save this result as last result to prevent delivery of last result\n // when first subscribing\n const result = this.observable.getCurrentResult(false);\n\n if (equal(result, this.result)) {\n return;\n }\n\n this.result = result;\n this.promise =\n (\n result.data &&\n (!result.partial || this.watchQueryOptions.returnPartialData)\n ) ?\n createFulfilledPromise(result)\n : this.createPendingPromise();\n }\n\n private createPendingPromise() {\n return wrapPromiseWithState(\n new Promise>((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n })\n );\n }\n}\n","import { Trie } from \"@wry/trie\";\nimport type { ObservableQuery } from \"../../../core/index.js\";\nimport { canUseWeakMap } from \"../../../utilities/index.js\";\nimport { InternalQueryReference } from \"./QueryReference.js\";\nimport type { CacheKey } from \"./types.js\";\n\nexport interface SuspenseCacheOptions {\n /**\n * Specifies the amount of time, in milliseconds, the suspense cache will wait\n * for a suspended component to read from the suspense cache before it\n * automatically disposes of the query. This prevents memory leaks when a\n * component unmounts before a suspended resource finishes loading. Increase\n * the timeout if your queries take longer than than the specified time to\n * prevent your queries from suspending over and over.\n *\n * Defaults to 30 seconds.\n */\n autoDisposeTimeoutMs?: number;\n}\n\nexport class SuspenseCache {\n private queryRefs = new Trie<{ current?: InternalQueryReference }>(\n canUseWeakMap\n );\n private options: SuspenseCacheOptions;\n\n constructor(options: SuspenseCacheOptions = Object.create(null)) {\n this.options = options;\n }\n\n getQueryRef(\n cacheKey: CacheKey,\n createObservable: () => ObservableQuery\n ) {\n const ref = this.queryRefs.lookupArray(cacheKey) as {\n current?: InternalQueryReference;\n };\n\n if (!ref.current) {\n ref.current = new InternalQueryReference(createObservable(), {\n autoDisposeTimeoutMs: this.options.autoDisposeTimeoutMs,\n onDispose: () => {\n delete ref.current;\n },\n });\n }\n\n return ref.current;\n }\n\n add(cacheKey: CacheKey, queryRef: InternalQueryReference) {\n const ref = this.queryRefs.lookupArray(cacheKey);\n ref.current = queryRef;\n }\n}\n","import type { SuspenseCacheOptions } from \"../index.js\";\nimport { SuspenseCache } from \"./SuspenseCache.js\";\nimport type { ApolloClient } from \"../../../core/ApolloClient.js\";\n\ndeclare module \"../../../core/ApolloClient.js\" {\n interface DefaultOptions {\n react?: {\n suspense?: Readonly;\n };\n }\n}\n\nconst suspenseCacheSymbol = Symbol.for(\"apollo.suspenseCache\");\n\nexport function getSuspenseCache(\n client: ApolloClient & {\n [suspenseCacheSymbol]?: SuspenseCache;\n }\n) {\n if (!client[suspenseCacheSymbol]) {\n client[suspenseCacheSymbol] = new SuspenseCache(\n client.defaultOptions.react?.suspense\n );\n }\n\n return client[suspenseCacheSymbol];\n}\n","export const skipToken = Symbol.for(\"apollo.skipToken\");\nexport type SkipToken = typeof skipToken;\n","import * as React from \"rehackt\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport type {\n ApolloClient,\n ApolloQueryResult,\n DocumentNode,\n OperationVariables,\n TypedDocumentNode,\n WatchQueryFetchPolicy,\n FetchMoreQueryOptions,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport { ApolloError, NetworkStatus } from \"../../core/index.js\";\nimport type { DeepPartial } from \"../../utilities/index.js\";\nimport { isNonEmptyArray } from \"../../utilities/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { DocumentType, verifyDocumentType } from \"../parser/index.js\";\nimport type {\n SuspenseQueryHookOptions,\n ObservableQueryFields,\n NoInfer,\n} from \"../types/types.js\";\nimport { __use, useDeepMemo, wrapHook } from \"./internal/index.js\";\nimport { getSuspenseCache } from \"../internal/index.js\";\nimport { canonicalStringify } from \"../../cache/index.js\";\nimport { skipToken } from \"./constants.js\";\nimport type { SkipToken } from \"./constants.js\";\nimport type { CacheKey, QueryKey } from \"../internal/index.js\";\n\nexport interface UseSuspenseQueryResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> {\n client: ApolloClient;\n data: TData;\n error: ApolloError | undefined;\n fetchMore: FetchMoreFunction;\n networkStatus: NetworkStatus;\n refetch: RefetchFunction;\n subscribeToMore: SubscribeToMoreFunction;\n}\n\nexport type FetchMoreFunction = (\n fetchMoreOptions: FetchMoreQueryOptions & {\n updateQuery?: (\n previousQueryResult: TData,\n options: {\n fetchMoreResult: TData;\n variables: TVariables;\n }\n ) => TData;\n }\n) => Promise>;\n\nexport type RefetchFunction<\n TData,\n TVariables extends OperationVariables,\n> = ObservableQueryFields[\"refetch\"];\n\nexport type SubscribeToMoreFunction<\n TData,\n TVariables extends OperationVariables,\n> = ObservableQueryFields[\"subscribeToMore\"];\n\nexport function useSuspenseQuery<\n TData,\n TVariables extends OperationVariables,\n TOptions extends Omit, \"variables\">,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: SuspenseQueryHookOptions, NoInfer> &\n TOptions\n): UseSuspenseQueryResult<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ?\n TOptions[\"skip\"] extends boolean ?\n DeepPartial | undefined\n : DeepPartial\n : TOptions[\"skip\"] extends boolean ? TData | undefined\n : TData,\n TVariables\n>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseSuspenseQueryResult | undefined, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n skip: boolean;\n returnPartialData: true;\n }\n): UseSuspenseQueryResult | undefined, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n returnPartialData: true;\n }\n): UseSuspenseQueryResult, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n skip: boolean;\n }\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: SuspenseQueryHookOptions, NoInfer>\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | SkipToken\n | (SuspenseQueryHookOptions, NoInfer> & {\n returnPartialData: true;\n })\n): UseSuspenseQueryResult | undefined, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?:\n | SkipToken\n | SuspenseQueryHookOptions, NoInfer>\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken & Partial>)\n | SuspenseQueryHookOptions = Object.create(null)\n): UseSuspenseQueryResult {\n return wrapHook(\n \"useSuspenseQuery\",\n _useSuspenseQuery,\n useApolloClient(typeof options === \"object\" ? options.client : undefined)\n )(query, options);\n}\n\nfunction _useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken & Partial>)\n | SuspenseQueryHookOptions\n): UseSuspenseQueryResult {\n const client = useApolloClient(options.client);\n const suspenseCache = getSuspenseCache(client);\n const watchQueryOptions = useWatchQueryOptions({\n client,\n query,\n options,\n });\n const { fetchPolicy, variables } = watchQueryOptions;\n const { queryKey = [] } = options;\n\n const cacheKey: CacheKey = [\n query,\n canonicalStringify(variables),\n ...([] as any[]).concat(queryKey),\n ];\n\n const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n client.watchQuery(watchQueryOptions)\n );\n\n let [current, setPromise] = React.useState<\n [QueryKey, Promise>]\n >([queryRef.key, queryRef.promise]);\n\n // This saves us a re-execution of the render function when a variable changed.\n if (current[0] !== queryRef.key) {\n current[0] = queryRef.key;\n current[1] = queryRef.promise;\n }\n let promise = current[1];\n\n if (queryRef.didChangeOptions(watchQueryOptions)) {\n current[1] = promise = queryRef.applyOptions(watchQueryOptions);\n }\n\n React.useEffect(() => {\n const dispose = queryRef.retain();\n\n const removeListener = queryRef.listen((promise) => {\n setPromise([queryRef.key, promise]);\n });\n\n return () => {\n removeListener();\n dispose();\n };\n }, [queryRef]);\n\n const skipResult = React.useMemo(() => {\n const error = toApolloError(queryRef.result);\n\n return {\n loading: false,\n data: queryRef.result.data,\n networkStatus: error ? NetworkStatus.error : NetworkStatus.ready,\n error,\n };\n }, [queryRef.result]);\n\n const result = fetchPolicy === \"standby\" ? skipResult : __use(promise);\n const fetchMore = React.useCallback(\n ((options) => {\n const promise = queryRef.fetchMore(options);\n setPromise([queryRef.key, queryRef.promise]);\n\n return promise;\n }) satisfies FetchMoreFunction<\n unknown,\n OperationVariables\n > as FetchMoreFunction,\n [queryRef]\n );\n\n const refetch: RefetchFunction = React.useCallback(\n (variables) => {\n const promise = queryRef.refetch(variables);\n setPromise([queryRef.key, queryRef.promise]);\n\n return promise;\n },\n [queryRef]\n );\n\n const subscribeToMore: SubscribeToMoreFunction<\n TData | undefined,\n TVariables\n > = React.useCallback(\n (options) => queryRef.observable.subscribeToMore(options),\n [queryRef]\n );\n\n return React.useMemo<\n UseSuspenseQueryResult\n >(() => {\n return {\n client,\n data: result.data,\n error: toApolloError(result),\n networkStatus: result.networkStatus,\n fetchMore,\n refetch,\n subscribeToMore,\n };\n }, [client, fetchMore, refetch, result, subscribeToMore]);\n}\n\nfunction validateOptions(options: WatchQueryOptions) {\n const { query, fetchPolicy, returnPartialData } = options;\n\n verifyDocumentType(query, DocumentType.Query);\n validateFetchPolicy(fetchPolicy);\n validatePartialDataReturn(fetchPolicy, returnPartialData);\n}\n\nfunction validateFetchPolicy(\n fetchPolicy: WatchQueryFetchPolicy = \"cache-first\"\n) {\n const supportedFetchPolicies: WatchQueryFetchPolicy[] = [\n \"cache-first\",\n \"network-only\",\n \"no-cache\",\n \"cache-and-network\",\n ];\n\n invariant(\n supportedFetchPolicies.includes(fetchPolicy),\n `The fetch policy \\`%s\\` is not supported with suspense.`,\n fetchPolicy\n );\n}\n\nfunction validatePartialDataReturn(\n fetchPolicy: WatchQueryFetchPolicy | undefined,\n returnPartialData: boolean | undefined\n) {\n if (fetchPolicy === \"no-cache\" && returnPartialData) {\n invariant.warn(\n \"Using `returnPartialData` with a `no-cache` fetch policy has no effect. To read partial data from the cache, consider using an alternate fetch policy.\"\n );\n }\n}\n\nexport function toApolloError(result: ApolloQueryResult) {\n return isNonEmptyArray(result.errors) ?\n new ApolloError({ graphQLErrors: result.errors })\n : result.error;\n}\n\ninterface UseWatchQueryOptionsHookOptions<\n TData,\n TVariables extends OperationVariables,\n> {\n client: ApolloClient;\n query: DocumentNode | TypedDocumentNode;\n options: SkipToken | SuspenseQueryHookOptions;\n}\n\nexport function useWatchQueryOptions<\n TData,\n TVariables extends OperationVariables,\n>({\n client,\n query,\n options,\n}: UseWatchQueryOptionsHookOptions): WatchQueryOptions<\n TVariables,\n TData\n> {\n return useDeepMemo>(() => {\n if (options === skipToken) {\n return { query, fetchPolicy: \"standby\" };\n }\n\n const fetchPolicy =\n options.fetchPolicy ||\n client.defaultOptions.watchQuery?.fetchPolicy ||\n \"cache-first\";\n\n const watchQueryOptions = {\n ...options,\n fetchPolicy,\n query,\n notifyOnNetworkStatusChange: false,\n nextFetchPolicy: void 0,\n };\n\n if (__DEV__) {\n validateOptions(watchQueryOptions);\n }\n\n // Assign the updated fetch policy after our validation since `standby` is\n // not a supported fetch policy on its own without the use of `skip`.\n if (options.skip) {\n watchQueryOptions.fetchPolicy = \"standby\";\n }\n\n return watchQueryOptions;\n }, [client, options, query]);\n}\n","import * as React from \"rehackt\";\nimport type {\n DocumentNode,\n FetchMoreQueryOptions,\n OperationVariables,\n TypedDocumentNode,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport {\n getSuspenseCache,\n unwrapQueryRef,\n updateWrappedQueryRef,\n wrapQueryRef,\n} from \"../internal/index.js\";\nimport type { CacheKey, QueryRef } from \"../internal/index.js\";\nimport type { BackgroundQueryHookOptions, NoInfer } from \"../types/types.js\";\nimport { wrapHook } from \"./internal/index.js\";\nimport { useWatchQueryOptions } from \"./useSuspenseQuery.js\";\nimport type { FetchMoreFunction, RefetchFunction } from \"./useSuspenseQuery.js\";\nimport { canonicalStringify } from \"../../cache/index.js\";\nimport type { DeepPartial } from \"../../utilities/index.js\";\nimport type { SkipToken } from \"./constants.js\";\n\nexport type UseBackgroundQueryResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> = {\n fetchMore: FetchMoreFunction;\n refetch: RefetchFunction;\n};\n\ntype BackgroundQueryHookOptionsNoInfer<\n TData,\n TVariables extends OperationVariables,\n> = BackgroundQueryHookOptions, NoInfer>;\n\nexport function useBackgroundQuery<\n TData,\n TVariables extends OperationVariables,\n TOptions extends Omit, \"variables\">,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: BackgroundQueryHookOptionsNoInfer & TOptions\n): [\n (\n | QueryRef<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ? DeepPartial\n : TData,\n TVariables\n >\n | (TOptions[\"skip\"] extends boolean ? undefined : never)\n ),\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n): [\n QueryRef | undefined, TVariables>,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n errorPolicy: \"ignore\" | \"all\";\n }\n): [\n QueryRef,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n skip: boolean;\n returnPartialData: true;\n }\n): [\n QueryRef, TVariables> | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n returnPartialData: true;\n }\n): [\n QueryRef, TVariables>,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n skip: boolean;\n }\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: BackgroundQueryHookOptionsNoInfer\n): [QueryRef, UseBackgroundQueryResult];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SkipToken\n): [undefined, UseBackgroundQueryResult];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | SkipToken\n | (BackgroundQueryHookOptionsNoInfer & {\n returnPartialData: true;\n })\n): [\n QueryRef, TVariables> | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: SkipToken | BackgroundQueryHookOptionsNoInfer\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken &\n Partial>)\n | BackgroundQueryHookOptionsNoInfer = Object.create(null)\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n] {\n return wrapHook(\n \"useBackgroundQuery\",\n _useBackgroundQuery,\n useApolloClient(typeof options === \"object\" ? options.client : undefined)\n )(query, options);\n}\n\nfunction _useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken &\n Partial>)\n | BackgroundQueryHookOptionsNoInfer\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n] {\n const client = useApolloClient(options.client);\n const suspenseCache = getSuspenseCache(client);\n const watchQueryOptions = useWatchQueryOptions({ client, query, options });\n const { fetchPolicy, variables } = watchQueryOptions;\n const { queryKey = [] } = options;\n\n // This ref tracks the first time query execution is enabled to determine\n // whether to return a query ref or `undefined`. When initialized\n // in a skipped state (either via `skip: true` or `skipToken`) we return\n // `undefined` for the `queryRef` until the query has been enabled. Once\n // enabled, a query ref is always returned regardless of whether the query is\n // skipped again later.\n const didFetchResult = React.useRef(fetchPolicy !== \"standby\");\n didFetchResult.current ||= fetchPolicy !== \"standby\";\n\n const cacheKey: CacheKey = [\n query,\n canonicalStringify(variables),\n ...([] as any[]).concat(queryKey),\n ];\n\n const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n client.watchQuery(watchQueryOptions as WatchQueryOptions)\n );\n\n const [wrappedQueryRef, setWrappedQueryRef] = React.useState(\n wrapQueryRef(queryRef)\n );\n if (unwrapQueryRef(wrappedQueryRef) !== queryRef) {\n setWrappedQueryRef(wrapQueryRef(queryRef));\n }\n if (queryRef.didChangeOptions(watchQueryOptions)) {\n const promise = queryRef.applyOptions(watchQueryOptions);\n updateWrappedQueryRef(wrappedQueryRef, promise);\n }\n\n // This prevents issues where rerendering useBackgroundQuery after the\n // queryRef has been disposed would cause the hook to return a new queryRef\n // instance since disposal also removes it from the suspense cache. We add\n // the queryRef back in the suspense cache so that the next render will reuse\n // this queryRef rather than initializing a new instance.\n React.useEffect(() => {\n // Since the queryRef is disposed async via `setTimeout`, we have to wait a\n // tick before checking it and adding back to the suspense cache.\n const id = setTimeout(() => {\n if (queryRef.disposed) {\n suspenseCache.add(cacheKey, queryRef);\n }\n });\n\n return () => clearTimeout(id);\n // Omitting the deps is intentional. This avoids stale closures and the\n // conditional ensures we aren't running the logic on each render.\n });\n\n const fetchMore: FetchMoreFunction = React.useCallback(\n (options) => {\n const promise = queryRef.fetchMore(options as FetchMoreQueryOptions);\n\n setWrappedQueryRef(wrapQueryRef(queryRef));\n\n return promise;\n },\n [queryRef]\n );\n\n const refetch: RefetchFunction = React.useCallback(\n (variables) => {\n const promise = queryRef.refetch(variables);\n\n setWrappedQueryRef(wrapQueryRef(queryRef));\n\n return promise;\n },\n [queryRef]\n );\n\n React.useEffect(() => queryRef.softRetain(), [queryRef]);\n\n return [\n didFetchResult.current ? wrappedQueryRef : void 0,\n { fetchMore, refetch },\n ];\n}\n","import * as React from \"rehackt\";\n\nfunction getRenderDispatcher() {\n return (React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n ?.ReactCurrentDispatcher?.current;\n}\n\nlet RenderDispatcher: unknown = null;\n\n/*\nRelay does this too, so we hope this is safe.\nhttps://github.com/facebook/relay/blob/8651fbca19adbfbb79af7a3bc40834d105fd7747/packages/react-relay/relay-hooks/loadQuery.js#L90-L98\n*/\nexport function useRenderGuard() {\n RenderDispatcher = getRenderDispatcher();\n\n return React.useCallback(() => {\n return (\n RenderDispatcher != null && RenderDispatcher === getRenderDispatcher()\n );\n }, []);\n}\n","import * as React from \"rehackt\";\nimport type {\n DocumentNode,\n FetchMoreQueryOptions,\n OperationVariables,\n TypedDocumentNode,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport {\n assertWrappedQueryRef,\n getSuspenseCache,\n unwrapQueryRef,\n updateWrappedQueryRef,\n wrapQueryRef,\n} from \"../internal/index.js\";\nimport type { CacheKey, QueryRef } from \"../internal/index.js\";\nimport type { LoadableQueryHookOptions } from \"../types/types.js\";\nimport { __use, useRenderGuard } from \"./internal/index.js\";\nimport { useWatchQueryOptions } from \"./useSuspenseQuery.js\";\nimport type { FetchMoreFunction, RefetchFunction } from \"./useSuspenseQuery.js\";\nimport { canonicalStringify } from \"../../cache/index.js\";\nimport type {\n DeepPartial,\n OnlyRequiredProperties,\n} from \"../../utilities/index.js\";\nimport { invariant } from \"../../utilities/globals/index.js\";\n\nexport type LoadQueryFunction = (\n // Use variadic args to handle cases where TVariables is type `never`, in\n // which case we don't want to allow a variables argument. In other\n // words, we don't want to allow variables to be passed as an argument to this\n // function if the query does not expect variables in the document.\n ...args: [TVariables] extends [never] ? []\n : {} extends OnlyRequiredProperties ? [variables?: TVariables]\n : [variables: TVariables]\n) => void;\n\ntype ResetFunction = () => void;\n\nexport type UseLoadableQueryResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> = [\n loadQuery: LoadQueryFunction,\n queryRef: QueryRef | null,\n {\n /** {@inheritDoc @apollo/client!QueryResultDocumentation#fetchMore:member} */\n fetchMore: FetchMoreFunction;\n /** {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member} */\n refetch: RefetchFunction;\n /**\n * A function that resets the `queryRef` back to `null`.\n */\n reset: ResetFunction;\n },\n];\n\nexport function useLoadableQuery<\n TData,\n TVariables extends OperationVariables,\n TOptions extends LoadableQueryHookOptions,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: LoadableQueryHookOptions & TOptions\n): UseLoadableQueryResult<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ? DeepPartial\n : TData,\n TVariables\n>;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseLoadableQueryResult | undefined, TVariables>;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions & {\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseLoadableQueryResult;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions & {\n returnPartialData: true;\n }\n): UseLoadableQueryResult, TVariables>;\n\n/**\n * A hook for imperatively loading a query, such as responding to a user\n * interaction.\n *\n * > Refer to the [Suspense - Fetching in response to user interaction](https://www.apollographql.com/docs/react/data/suspense#fetching-in-response-to-user-interaction) section for a more in-depth overview of `useLoadableQuery`.\n *\n * @example\n * ```jsx\n * import { gql, useLoadableQuery } from \"@apollo/client\";\n *\n * const GET_GREETING = gql`\n * query GetGreeting($language: String!) {\n * greeting(language: $language) {\n * message\n * }\n * }\n * `;\n *\n * function App() {\n * const [loadGreeting, queryRef] = useLoadableQuery(GET_GREETING);\n *\n * return (\n * <>\n * \n * Loading...}>\n * {queryRef && }\n * \n * \n * );\n * }\n *\n * function Hello({ queryRef }) {\n * const { data } = useReadQuery(queryRef);\n *\n * return
{data.greeting.message}
;\n * }\n * ```\n *\n * @since 3.9.0\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Options to control how the query is executed.\n * @returns A tuple in the form of `[loadQuery, queryRef, handlers]`\n */\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: LoadableQueryHookOptions\n): UseLoadableQueryResult;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions = Object.create(null)\n): UseLoadableQueryResult {\n const client = useApolloClient(options.client);\n const suspenseCache = getSuspenseCache(client);\n const watchQueryOptions = useWatchQueryOptions({ client, query, options });\n const { queryKey = [] } = options;\n\n const [queryRef, setQueryRef] = React.useState | null>(null);\n\n assertWrappedQueryRef(queryRef);\n\n const internalQueryRef = queryRef && unwrapQueryRef(queryRef);\n\n if (queryRef && internalQueryRef?.didChangeOptions(watchQueryOptions)) {\n const promise = internalQueryRef.applyOptions(watchQueryOptions);\n updateWrappedQueryRef(queryRef, promise);\n }\n\n const calledDuringRender = useRenderGuard();\n\n const fetchMore: FetchMoreFunction = React.useCallback(\n (options) => {\n if (!internalQueryRef) {\n throw new Error(\n \"The query has not been loaded. Please load the query.\"\n );\n }\n\n const promise = internalQueryRef.fetchMore(\n options as FetchMoreQueryOptions\n );\n\n setQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n const refetch: RefetchFunction = React.useCallback(\n (options) => {\n if (!internalQueryRef) {\n throw new Error(\n \"The query has not been loaded. Please load the query.\"\n );\n }\n\n const promise = internalQueryRef.refetch(options);\n\n setQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n const loadQuery: LoadQueryFunction = React.useCallback(\n (...args) => {\n invariant(\n !calledDuringRender(),\n \"useLoadableQuery: 'loadQuery' should not be called during render. To start a query during render, use the 'useBackgroundQuery' hook.\"\n );\n\n const [variables] = args;\n\n const cacheKey: CacheKey = [\n query,\n canonicalStringify(variables),\n ...([] as any[]).concat(queryKey),\n ];\n\n const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n client.watchQuery({\n ...watchQueryOptions,\n variables,\n } as WatchQueryOptions)\n );\n\n setQueryRef(wrapQueryRef(queryRef));\n },\n [query, queryKey, suspenseCache, watchQueryOptions, calledDuringRender]\n );\n\n const reset: ResetFunction = React.useCallback(() => {\n setQueryRef(null);\n }, [queryRef]);\n\n return [loadQuery, queryRef, { fetchMore, refetch, reset }];\n}\n","import * as React from \"rehackt\";\nimport {\n assertWrappedQueryRef,\n getWrappedPromise,\n unwrapQueryRef,\n updateWrappedQueryRef,\n wrapQueryRef,\n} from \"../internal/index.js\";\nimport type { QueryRef } from \"../internal/index.js\";\nimport type { OperationVariables } from \"../../core/types.js\";\nimport type { RefetchFunction, FetchMoreFunction } from \"./useSuspenseQuery.js\";\nimport type { FetchMoreQueryOptions } from \"../../core/watchQueryOptions.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { wrapHook } from \"./internal/index.js\";\n\nexport interface UseQueryRefHandlersResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> {\n /** {@inheritDoc @apollo/client!ObservableQuery#refetch:member(1)} */\n refetch: RefetchFunction;\n /** {@inheritDoc @apollo/client!ObservableQuery#fetchMore:member(1)} */\n fetchMore: FetchMoreFunction;\n}\n\n/**\n * A React hook that returns a `refetch` and `fetchMore` function for a given\n * `queryRef`.\n *\n * This is useful to get access to handlers for a `queryRef` that was created by\n * `createQueryPreloader` or when the handlers for a `queryRef` produced in\n * a different component are inaccessible.\n *\n * @example\n * ```tsx\n * const MyComponent({ queryRef }) {\n * const { refetch, fetchMore } = useQueryRefHandlers(queryRef);\n *\n * // ...\n * }\n * ```\n * @since 3.9.0\n * @param queryRef - A `QueryRef` returned from `useBackgroundQuery`, `useLoadableQuery`, or `createQueryPreloader`.\n */\nexport function useQueryRefHandlers<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n queryRef: QueryRef\n): UseQueryRefHandlersResult {\n const unwrapped = unwrapQueryRef(queryRef);\n\n return wrapHook(\n \"useQueryRefHandlers\",\n _useQueryRefHandlers,\n unwrapped ?\n unwrapped[\"observable\"]\n // in the case of a \"transported\" queryRef object, we need to use the\n // client that's available to us at the current position in the React tree\n // that ApolloClient will then have the job to recreate a real queryRef from\n // the transported object\n : useApolloClient()\n )(queryRef);\n}\n\nfunction _useQueryRefHandlers<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n queryRef: QueryRef\n): UseQueryRefHandlersResult {\n assertWrappedQueryRef(queryRef);\n const [previousQueryRef, setPreviousQueryRef] = React.useState(queryRef);\n const [wrappedQueryRef, setWrappedQueryRef] = React.useState(queryRef);\n const internalQueryRef = unwrapQueryRef(queryRef);\n\n // To ensure we can support React transitions, this hook needs to manage the\n // queryRef state and apply React's state value immediately to the existing\n // queryRef since this hook doesn't return the queryRef directly\n if (previousQueryRef !== queryRef) {\n setPreviousQueryRef(queryRef);\n setWrappedQueryRef(queryRef);\n } else {\n updateWrappedQueryRef(queryRef, getWrappedPromise(wrappedQueryRef));\n }\n\n const refetch: RefetchFunction = React.useCallback(\n (variables) => {\n const promise = internalQueryRef.refetch(variables);\n\n setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n const fetchMore: FetchMoreFunction = React.useCallback(\n (options) => {\n const promise = internalQueryRef.fetchMore(\n options as FetchMoreQueryOptions\n );\n\n setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n return { refetch, fetchMore };\n}\n","import * as React from \"rehackt\";\nimport {\n assertWrappedQueryRef,\n getWrappedPromise,\n unwrapQueryRef,\n updateWrappedQueryRef,\n} from \"../internal/index.js\";\nimport type { QueryRef } from \"../internal/index.js\";\nimport { __use, wrapHook } from \"./internal/index.js\";\nimport { toApolloError } from \"./useSuspenseQuery.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport type { ApolloError } from \"../../errors/index.js\";\nimport type { NetworkStatus } from \"../../core/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n\nexport interface UseReadQueryResult {\n /**\n * An object containing the result of your GraphQL query after it completes.\n *\n * This value might be `undefined` if a query results in one or more errors\n * (depending on the query's `errorPolicy`).\n */\n data: TData;\n /**\n * If the query produces one or more errors, this object contains either an\n * array of `graphQLErrors` or a single `networkError`. Otherwise, this value\n * is `undefined`.\n *\n * This property can be ignored when using the default `errorPolicy` or an\n * `errorPolicy` of `none`. The hook will throw the error instead of setting\n * this property.\n */\n error: ApolloError | undefined;\n /**\n * A number indicating the current network state of the query's associated\n * request. {@link https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/core/networkStatus.ts#L4 | See possible values}.\n */\n networkStatus: NetworkStatus;\n}\n\nexport function useReadQuery(\n queryRef: QueryRef\n): UseReadQueryResult {\n const unwrapped = unwrapQueryRef(queryRef);\n\n return wrapHook(\n \"useReadQuery\",\n _useReadQuery,\n unwrapped ?\n unwrapped[\"observable\"]\n // in the case of a \"transported\" queryRef object, we need to use the\n // client that's available to us at the current position in the React tree\n // that ApolloClient will then have the job to recreate a real queryRef from\n // the transported object\n : useApolloClient()\n )(queryRef);\n}\n\nfunction _useReadQuery(\n queryRef: QueryRef\n): UseReadQueryResult {\n assertWrappedQueryRef(queryRef);\n const internalQueryRef = React.useMemo(\n () => unwrapQueryRef(queryRef),\n [queryRef]\n );\n\n const getPromise = React.useCallback(\n () => getWrappedPromise(queryRef),\n [queryRef]\n );\n\n if (internalQueryRef.disposed) {\n internalQueryRef.reinitialize();\n updateWrappedQueryRef(queryRef, internalQueryRef.promise);\n }\n\n React.useEffect(() => internalQueryRef.retain(), [internalQueryRef]);\n\n const promise = useSyncExternalStore(\n React.useCallback(\n (forceUpdate) => {\n return internalQueryRef.listen((promise) => {\n updateWrappedQueryRef(queryRef, promise);\n forceUpdate();\n });\n },\n [internalQueryRef]\n ),\n getPromise,\n getPromise\n );\n\n const result = __use(promise);\n\n return React.useMemo(() => {\n return {\n data: result.data,\n networkStatus: result.networkStatus,\n error: toApolloError(result),\n };\n }, [result]);\n}\n","import type {\n ApolloClient,\n DefaultContext,\n DocumentNode,\n ErrorPolicy,\n OperationVariables,\n RefetchWritePolicy,\n TypedDocumentNode,\n WatchQueryFetchPolicy,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport type {\n DeepPartial,\n OnlyRequiredProperties,\n} from \"../../utilities/index.js\";\nimport { InternalQueryReference, wrapQueryRef } from \"../internal/index.js\";\nimport type { PreloadedQueryRef } from \"../internal/index.js\";\nimport type { NoInfer } from \"../index.js\";\n\ntype VariablesOption =\n [TVariables] extends [never] ?\n {\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n variables?: Record;\n }\n : {} extends OnlyRequiredProperties ?\n {\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n variables?: TVariables;\n }\n : {\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n variables: TVariables;\n };\n\nexport type PreloadQueryFetchPolicy = Extract<\n WatchQueryFetchPolicy,\n \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\"\n>;\n\nexport type PreloadQueryOptions<\n TVariables extends OperationVariables = OperationVariables,\n> = {\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#canonizeResults:member} */\n canonizeResults?: boolean;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n context?: DefaultContext;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n errorPolicy?: ErrorPolicy;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n fetchPolicy?: PreloadQueryFetchPolicy;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n returnPartialData?: boolean;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n refetchWritePolicy?: RefetchWritePolicy;\n} & VariablesOption;\n\ntype PreloadQueryOptionsArg<\n TVariables extends OperationVariables,\n TOptions = unknown,\n> = [TVariables] extends [never] ?\n [options?: PreloadQueryOptions & TOptions]\n: {} extends OnlyRequiredProperties ?\n [\n options?: PreloadQueryOptions> &\n Omit,\n ]\n: [\n options: PreloadQueryOptions> &\n Omit,\n ];\n\n/**\n * A function that will begin loading a query when called. It's result can be\n * read by `useReadQuery` which will suspend until the query is loaded.\n * This is useful when you want to start loading a query as early as possible\n * outside of a React component.\n *\n * @example\n * ```js\n * const preloadQuery = createQueryPreloader(client);\n * const queryRef = preloadQuery(query, { variables, ...otherOptions });\n *\n * function App() {\n * return (\n * Loading}>\n * \n * \n * );\n * }\n *\n * function MyQuery() {\n * const { data } = useReadQuery(queryRef);\n *\n * // do something with `data`\n * }\n * ```\n */\nexport interface PreloadQueryFunction {\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n <\n TData,\n TVariables extends OperationVariables,\n TOptions extends Omit,\n >(\n query: DocumentNode | TypedDocumentNode,\n ...[options]: PreloadQueryOptionsArg, TOptions>\n ): PreloadedQueryRef<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ? DeepPartial\n : TData,\n TVariables\n >;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n ): PreloadedQueryRef | undefined, TVariables>;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> & {\n errorPolicy: \"ignore\" | \"all\";\n }\n ): PreloadedQueryRef;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> & {\n returnPartialData: true;\n }\n ): PreloadedQueryRef, TVariables>;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n ...[options]: PreloadQueryOptionsArg>\n ): PreloadedQueryRef;\n}\n\n/**\n * A higher order function that returns a `preloadQuery` function which\n * can be used to begin loading a query with the given `client`. This is useful\n * when you want to start loading a query as early as possible outside of a\n * React component.\n *\n * > Refer to the [Suspense - Initiating queries outside React](https://www.apollographql.com/docs/react/data/suspense#initiating-queries-outside-react) section for a more in-depth overview.\n *\n * @param client - The `ApolloClient` instance that will be used to load queries\n * from the returned `preloadQuery` function.\n * @returns The `preloadQuery` function.\n *\n * @example\n * ```js\n * const preloadQuery = createQueryPreloader(client);\n * ```\n * @since 3.9.0\n */\nexport function createQueryPreloader(\n client: ApolloClient\n): PreloadQueryFunction {\n return function preloadQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n >(\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> &\n VariablesOption = Object.create(null)\n ): PreloadedQueryRef {\n const queryRef = new InternalQueryReference(\n client.watchQuery({\n ...options,\n query,\n } as WatchQueryOptions),\n {\n autoDisposeTimeoutMs:\n client.defaultOptions.react?.suspense?.autoDisposeTimeoutMs,\n }\n );\n\n return wrapQueryRef(queryRef) as PreloadedQueryRef;\n };\n}\n"],"names":["execute","ApolloLink","serializeFetchParameter","p","label","serialized","JSON","stringify","e","parseError","selectURI","operation","fallbackURI","getContext","uri","readerIterator","reader","iterator","next","read","canUse","Symbol","asyncIterator","this","responseIterator","response","value","body","getReader","isReadableStream","stream","isStreamableBlob","arrayBuffer","isBlob","promise","resolved","Promise","resolve","undefined","done","reject","then","catch","promiseIterator","pipe","isNodeReadableStream","cleanup","error","data","waiting","onData","chunk","length","shiftedArr","shift","Array","isArray","push","onError","err","slice","forEach","pair","onEnd","removeListener","on","nodeStreamIterator","Error","throwServerError","result","message","name","statusCode","status","isExecutionPatchIncrementalResult","isApolloPayloadResult","mergeIncrementalData","prevResult","mergedData","merger","incremental","path","i","key","isNaN","merge","Object","prototype","parseHeaders","headerText","headersInit","split","line","indexOf","trim","toLowerCase","parseJsonBody","bodyText","parse","getResult","parseAndCheckHttpResponse","operations","text","call","map","op","operationName","printCache","checkFetcher","fetcher","fetch","print","assign","ast","get","set","reset","A","size","fallbackHttpConfig","http","includeQuery","includeExtensions","preserveHeaderCase","headers","accept","options","method","defaultPrinter","printer","selectHttpOptionsAndBody","fallbackConfig","configs","unshift","selectHttpOptionsAndBodyInternal","config","credentials","create","keys","headerData","originalName","normalizedHeaders","removeDuplicateHeaders","extensions","variables","query","rewriteURIForGET","chosenURI","queryParams","addQueryParam","encodeURIComponent","serializedVariables","serializedExtensions","fragment","preFragment","fragmentStart","substr","queryParamsPrefix","newURI","join","fromError","errorValue","observer","TYPENAME_FIELD","kind","Kind","FIELD","NAME","isEmpty","fragmentMap","selectionSet","selections","every","selection","FRAGMENT_SPREAD","nullIfDocIsEmpty","doc","makeInUseGetterFunction","defaultKey","Map","inUse","Set","fragmentSpreads","removeDirectivesFromDocument","directives","getInUseByOperationName","getInUseByFragmentName","getInUse","ancestors","ancestor","OPERATION_DEFINITION","FRAGMENT_DEFINITION","operationCount","definitions","names","tests","directiveMatcher","directive","test","testConfig","shouldRemoveField","nodeDirectives","some","remove","originalFragmentDefsByPath","firstVisitMadeChanges","fieldOrInlineFragmentVisitor","enter","node","docWithoutDirectiveSubtrees","visit","Field","InlineFragment","VariableDefinition","Variable","_key","_parent","_path","add","FragmentSpread","FragmentDefinition","leave","removed","Directive","populateTransitiveVars","transitiveVars","childFragmentName","varName","allFragmentNamesUsed","def","fragmentName","enterVisitor","has","OperationDefinition","variableDefinitions","filter","varDef","variable","addTypenameToDocument","SelectionSet","parent","lastIndexOf","field","d","added","backupFetch","createHttpLink","linkOptions","preferredFetch","useGETForQueries","includeUnusedVariables","requestOptions","linkConfig","fetchOptions","context","clientAwarenessHeaders","clientAwareness","version","contextHeaders","contextConfig","transformedQuery","removeClientSetsFromDocument","unusedNames","controller","delete","signal","AbortController","isSubscription","hasDefer","acceptHeader","currentFetch","observerNext","bind","setContext","ctype","nextValue","TextDecoder","decoder","contentType","delimiter","boundaryVal","includes","substring","replace","boundary","buffer","running","decode","searchFrom","bi","payload","errors","hasNext","readMultipartBody","complete","handleError","abort","request","defaultMakeData","hasOwnProperty","Trie","constructor","weakness","makeData","lookup","lookupArray","arguments","array","getChildTrie","peek","peekArray","len","mapFor","removeArray","head","child","weak","strong","isObjRef","WeakMap","currentContext","MISSING_VALUE","idCounter","maybe","fn","ignored","globalKey","globalHost","globalThis","global","Slot","defineProperty","enumerable","writable","configurable","id","Date","now","Math","random","toString","hasValue","slots","getValue","withValue","callback","args","thisArg","__proto__","apply","saved","noContext","parentEntrySlot","arrayFromSet","from","item","maybeUnsubscribe","entryOrDep","unsubscribe","emptySetPool","POOL_TARGET_SIZE","assert","condition","optionalMessage","valueIs","a","b","valueGet","valueCopy","Entry","parents","childValues","dirtyChildren","dirty","recomputing","deps","count","mightBeDirty","rememberParent","recompute","entry","forgetChildren","recomputeNewValue","subscribe","setDirty","maybeSubscribe","reportClean","setClean","reallyRecompute","reportDirty","dispose","eachParent","forgetChild","forget","dependOn","dep","pop","forgetDeps","clear","reportDirtyChild","reportCleanChild","normalizeResult","oldValueCopy","parentCount","parentWasClean","childValue","removeDirtyChild","dc","_value","EntryMethods","depsByKey","depend","entryMethodName","m","defaultKeyTrie","defaultMakeCacheKey","wrap","originalFunction","max","pow","keyArgs","makeCacheKey","cache","cacheOption","optimistic","clean","dirtyKey","peekKey","forgetKey","freeze","getKey","identity","document","transform","resultCache","WeakSet","getCacheKey","cached","resetCache","DocumentTransform","predicate","left","right","transformDocument","performWork","cacheKeys","transformedDocument","concat","otherTransform","asyncMap","observable","mapFn","catchFn","promiseQueue","makeCallback","examiner","arg","both","closed","handler","sub","graphQLResultHasError","getGraphQLErrorsFromResult","graphQLErrors","incrementalResult","iterateObserversSafely","observers","argument","observersWithMethod","obs","fixObservableSubclass","subclass","species","sources","addObserver","removeObserver","handlers","latest","notify","setTimeout","nextResultListeners","cancel","reason","_","iterable","start","deliverLastMessage","nextOrError","listener","beforeNext","called","Concast","cloneDeep","cloneDeepHelper","val","seen","getPrototypeOf","equalByQuery","aData","aRest","bData","bRest","equalBySelectionSet","aResult","bResult","seenSelections","selectionHasNonreactiveDirective","resultKey","aResultChild","bResultChild","childSelectionSet","aChildIsArray","bChildIsArray","directiveIsNonreactive","dir","queryManager","queryInfo","subObserver","_subscription","_observer","defaultSubscriptionObserverErrorCallback","first","last","reobserve","tearDownQuery","subscriptions","waitForOwnResult","skipCacheDataFor","fetchPolicy","isTornDown","defaultOptions","defaultFetchPolicy","initialFetchPolicy","queryId","generateQueryId","opDef","queryName","lastQuery","removeQuery","subscription","resetDiff","getCurrentResult","saveAsLastResult","lastResult","getLastResult","networkStatus","ready","loading","getDocumentInfo","hasForcedResolvers","diff","getDiff","returnPartialData","partial","partialRefetch","logMissingFieldErrors","missing","updateLastResult","isDifferentFromLastResult","newResult","hasNonreactiveDirective","getLast","variablesMustMatch","getLastError","resetLastResults","resetQueryStoreErrors","resetErrors","refetch","reobserveOptions","pollInterval","queryDef","vars","v","newOptions","pollingInfo","mergedOptions","concast","nextFetchPolicy","cacheSlot","cacheInfoMap","getCacheInfo","info","forgetCache","rv","makeVar","caches","listeners","newValue","broadcastWatches","broadcast","oldListeners","attach","onNextChange","attachCache","client","resolvers","fragmentMatcher","selectionsToResolveCache","addResolvers","setFragmentMatcher","resolverGroup","mergeDeep","setResolvers","getResolvers","runResolvers","remoteResult","onlyRunForcedResolvers","resolveDocument","localResult","getFragmentMatcher","clientQuery","serverQuery","prepareContext","obj","identify","addExportedVariables","buildRootValueFromCache","exportedVariables","shouldForceResolvers","forceResolvers","BREAK","buildQueryFromSelectionSet","rootValue","mainDefinition","fragments","selectionsToResolve","collectSelectionsToResolve","definitionOperation","defaultOperationType","charAt","toUpperCase","execContext","resolveSelectionSet","isClientFieldDescendant","resultsToMerge","resolveField","fieldResult","typeCondition","fragmentResult","all","fieldName","aliasedFieldName","aliasUsed","defaultResult","resultPromise","resolverType","__typename","resolverMap","isClientField","resolveSubSelectedArray","isSingleASTNode","collectByDefinition","definitionNode","__","___","isSelectionNode","spread","fragmentSelections","destructiveMethodCounts","wrapDestructiveCacheMethod","methodName","original","cancelNotifyTimeout","clearTimeout","lastRequestId","stopped","observableQuery","init","setVariables","lastDiff","networkError","setObservableQuery","getDiffOptions","updateWatch","oq","updateLastDiff","canonizeResults","setDiff","oldDiff","notifyTimeout","oqListener","fromOptimisticTransaction","reobserveCacheFirst","shouldNotify","stop","QueryInfo","stopPolling","watchOptions","watcher","lastWatch","watch","resetLastWrite","lastWrite","shouldWrite","dmCount","markResult","cacheWriteBehavior","shouldWriteResult","errorPolicy","performTransaction","writeQuery","overwrite","diffOptions","markReady","markError","ignoreErrors","writeWithErrors","Cache","IGNORE","link","documentTransform","queryDeduplication","onBroadcast","ssrMode","localState","assumeImmutableResults","defaultContext","queries","fetchCancelFns","transformCache","queryIdCounter","requestIdCounter","mutationIdCounter","inFlightLinkObservables","defaultDocumentTransform","LocalState","mutationStore","_info","stopQueryNoBroadcast","cancelPendingFetches","mutate","mutation","optimisticResponse","updateQueries","refetchQueries","awaitRefetchQueries","updateWithProxyFn","onQueryUpdated","keepRootFields","mutationId","generateMutationId","transformForLink","hasClientExports","getVariables","mutationStoreValue","isOptimistic","markMutationOptimistic","update","broadcastQueries","self","getObservableFromLink","storeResult","markMutationResult","removeOptimistic","cacheWrites","skipCache","dataId","asQuery","updater","currentQueryResult","nextQueryResult","mutationResult","queryVariables","updateCache","write","isFinalResult","isExecutionPatchInitialResult","modify","fields","DELETE","include","recordOptimisticTransaction","fetchQuery","fetchConcastWithInfo","getQueryStore","store","cacheEntry","defaultVars","watchQuery","notifyOnNetworkStatusChange","ObservableQuery","desc","legacyQueryOptions","deduplication","includedQueriesById","hasSuggestedDevtools","resetStoreCallbacks","clearStoreCallbacks","connectToDevTools","window","getFragmentDoc","batch","updateResult","optimisticId","transaction","object","gc","readQuery","rootId","watchFragment","latestDiff","immediate","readFragment","writeFragment","updateQuery","updateFragment","ApolloCache","getMemoryInternals","MissingFieldError","delModifier","INVALIDATE","policies","group","rootIds","refs","getFieldValue","objectOrReference","storeFieldName","maybeDeepFreeze","__ref","canRead","objOrRef","toReference","objOrIdOrRef","mergeIntoStore","ref","toObject","storeObject","rootTypenamesById","Layer","dependOnExistence","older","newer","existing","incoming","merged","storeObjectReconciler","caching","__exists","hasKeyArgs","isReference","readField","fieldNameOrOptions","fieldValue","storage","getStorage","checkReference","evicted","extraRootIds","ids","layerId","known","pool","passes","keysByJSON","empty","admit","isKnown","pass","copy","shallowCopy","sortedKeys","json","sorted","sort","execSelectionSetKeyArgs","knownResults","compact","addTypename","canon","ObjectCanon","executeSelectionSet","peekArgs","other","maybeDependOnExistenceOfEntity","enclosingRef","execSelectionSetImpl","resultCacheMaxSize","supportsResultCaching","varString","executeSubSelectedArray","execSubSelectedArrayImpl","resetCanon","diffQueryAgainstStore","rootRef","execResult","canonicalStringify","firstMissing","isFresh","typename","objectsToMerge","missingMerger","handleMissing","resultName","rootIdsByTypename","workSet","lookupFragment","fragmentMatches","finalResult","frozen","childResult","assertSelectionSetForIdValue","tree","specifierInfoCache","lookupSpecifierInfo","spec","cacheKey","keyFieldsFnFromSpecifier","specifier","keyFieldsFn","firstChar","directiveArgs","toMerge","s","c","argsFromFieldSpecifier","nullKeyFieldsFn","simpleKeyArgsFn","_args","mergeTrueFn","mergeObjects","mergeFalseFn","typePolicies","toBeAdded","supertypeMap","fuzzySubtypes","usingPossibleTypes","dataIdFromObject","setRootTypename","possibleTypes","addPossibleTypes","addTypePolicies","partialContext","ROOT_QUERY","normalizeReadFieldOptions","policy","getTypePolicy","keyFn","specifierOrId","String","keyObject","queryType","mutationType","subscriptionType","updateTypePolicy","keyFields","setMerge","getFieldPolicy","keyArgsFnFromSpecifier","which","old","supertype","getSupertypeSet","subtype","match","RegExp","regExp","fuzzy","fuzzySupertypes","rest","inbox","splice","createIfMissing","fieldPolicies","supertypeSet","typenameSupertypeSet","needToCheckFuzzySubtypes","checkingFuzzySubtypes","fuzzyString","getStoreFieldName","fieldSpec","specifierOrString","readOptions","makeFieldFunctionOptions","getReadFunction","getMergeFunction","parentTypename","childTypename","runMergeFunction","makeMergeObjectsFunction","readFieldArgs","argc","eType","iType","getContextFlavor","clientOnly","deferred","flavored","flavors","writeToStore","operationDefinition","written","incomingById","processSelectionSet","mergeTree","fieldNodeSet","entityRef","applied","applyMerges","childTree","Boolean","existingRef","incomingObj","getChild","parentType","typeDotName","warnings","childTypenames","warnAboutDataLoss","retain","flattenFields","resultFieldKey","getChildMergeTree","incomingValue","processFieldValue","maybeRecycleChildMergeTree","dataRef","sets","mergeMergeTrees","mergeTreeIsEmpty","fieldMap","limitingTrie","flatten","inheritedContext","visitedNode","visited","if","getStorageArgs","eVal","iVal","aVal","emptyMergeTreePool","needToMergeMaps","leftTree","watches","addTypenameTransform","txCount","Policies","rootStore","EntityStore","Root","resultCaching","optimisticData","stump","resetResultCache","resetResultIdentities","previousReader","storeReader","storeWriter","StoreWriter","StoreReader","maybeBroadcastWatch","broadcastWatch","resetCaching","restore","extract","resetCaches","release","evict","discardWatches","idToRemove","newOptimisticData","removeLayer","onWatchUpdated","perform","layer","alreadyDirty","addLayer","addFragmentsToDocument","InMemoryCache","createSignalIfSupported","toPromise","completed","fromPromise","docCache","fragmentSourceMap","printFragmentWarnings","experimentalFragmentVariables","string","parseDocument","source","seenKeys","parsed","allowLegacyFragmentVariables","loc","startToken","endToken","stripLoc","fragmentDefinition","sourceKey","end","sourceKeySet","console","warn","gql","literals","disableFragmentWarnings","enableExperimentalFragmentVariables","disableExperimentalFragmentVariables","extras","ApolloProvider","children","ApolloContext","parentContext","ApolloConsumer","props","Consumer","EAGER_METHODS","useLazyQuery","execOptionsRef","optionsRef","queryRef","mergeOptions","current","internalState","useApolloClient","useQueryResult","useQuery","skip","getDefaultFetchPolicy","eagerMethods","forceUpdateState","executeOptions","executeQuery","queryResult","useSubscription","hasIssuedDeprecationWarningRef","Subscription","setResult","onSubscriptionData","subscriptionStopped","useReactiveVar","useSyncExternalStore","onNext","useDeepMemo","memoFn","INIT","useFragment","wrapHook","_useFragment","getInitialValue","resultRef","diffToResult","stableOptions","getSnapshot","forceUpdate","lastTimeout","createFulfilledPromise","wrapPromiseWithState","isStatefulPromise","pendingPromise","fulfilledPromise","rejectedPromise","__use","statefulPromise","QUERY_REFERENCE_SYMBOL","PROMISE_SYMBOL","wrapQueryRef","internalQueryRef","getWrappedPromise","assertWrappedQueryRef","unwrapQueryRef","updateWrappedQueryRef","OBSERVED_CHANGED_OPTIONS","references","softReferences","handleNext","onDispose","subscribeToQuery","startDisposeTimer","autoDisposeTimeoutId","autoDisposeTimeoutMs","reinitialize","originalFetchPolicy","watchQueryOptions","avoidNetworkRequests","silentSetOptions","disposed","softRetain","didChangeOptions","option","applyOptions","currentFetchPolicy","currentCanonizeResults","initiateFetch","listen","fetchMore","deliver","resubscribeAfterError","returnedPromise","createPendingPromise","queryRefs","getQueryRef","createObservable","InternalQueryReference","suspenseCacheSymbol","for","getSuspenseCache","SuspenseCache","react","suspense","skipToken","useSuspenseQuery","_useSuspenseQuery","suspenseCache","useWatchQueryOptions","queryKey","setPromise","skipResult","toApolloError","subscribeToMore","Query","validateFetchPolicy","validatePartialDataReturn","validateOptions","useBackgroundQuery","_useBackgroundQuery","didFetchResult","wrappedQueryRef","setWrappedQueryRef","getRenderDispatcher","ReactCurrentDispatcher","RenderDispatcher","useLoadableQuery","setQueryRef","calledDuringRender","loadQuery","useQueryRefHandlers","unwrapped","_useQueryRefHandlers","previousQueryRef","setPreviousQueryRef","useReadQuery","_useReadQuery","getPromise","createQueryPreloader"],"sourceRoot":""}