{
  "version": 3,
  "sources": ["../../../../../node_modules/is-plain-obj/index.js", "../../../node_modules/@contentful/rich-text-types/src/blocks.ts", "../../../node_modules/@contentful/rich-text-types/src/inlines.ts", "../../../node_modules/@contentful/rich-text-types/src/marks.ts", "../../../node_modules/@contentful/rich-text-types/src/schemaConstraints.ts", "../../../node_modules/@contentful/rich-text-types/src/emptyDocument.ts", "../../../node_modules/@contentful/rich-text-types/src/helpers.ts", "../../../node_modules/@contentful/rich-text-types/src/validator/errors.ts", "../../../node_modules/@contentful/rich-text-types/src/validator/assert.ts", "../../../node_modules/@contentful/rich-text-types/src/validator/node.ts", "../../../node_modules/@contentful/rich-text-types/src/validator/path.ts", "../../../node_modules/@contentful/rich-text-types/src/validator/text.ts", "../../../node_modules/@contentful/rich-text-types/src/validator/index.ts", "../../../../../node_modules/@contentful/rich-text-plain-text-renderer/src/index.ts", "../../../../../node_modules/rehackt/index.js", "../../../node_modules/cross-fetch/dist/browser-ponyfill.js", "../../../../common/src/storage/TypedLocalStorage.ts", "../../../../common/src/constants/brands.ts", "../../../../common/src/constants/elastic.ts", "../../../../common/src/constants/ga4Properties.ts", "../../../../common/src/constants/gdprCountries.ts", "../../../../common/src/constants/localeMap.ts", "../../../../common/src/constants/networking.ts", "../../../../common/src/constants/productionDomains.ts", "../../../../common/src/constants/sitesToBrands.ts", "../../../../common/src/constants/stagingDomains.ts", "../../../../common/src/geoHeaders/parseGeoHeaders.ts", "../../../../common/src/utils/vod.ts", "../../../src/AppContext.tsx", "../../../../contentful-schema/src/charts/helpers.ts", "../../../../contentful-schema/src/constants/contentTokens.ts", "../../../../contentful-schema/src/extractPageText/getPlainText.ts", "../../../../contentful-schema/src/richtext/mergeRichText.ts", "../../../../contentful-schema/src/snapPersonas.ts", "../../../../../node_modules/lodash-es/_baseForOwn.js", "../../../../../node_modules/lodash-es/_baseInverter.js", "../../../../../node_modules/lodash-es/_createInverter.js", "../../../../../node_modules/lodash-es/invert.js", "../../../../contentful-schema/src/spaceIds.ts", "../../../../contentful-schema/src/tokenKeys.ts", "../../../../../node_modules/tslib/tslib.es6.mjs", "../../../../../node_modules/ts-invariant/src/invariant.ts", "../../../../../node_modules/@apollo/src/version.ts", "../../../../../node_modules/@apollo/src/utilities/globals/maybe.ts", "../../../../../node_modules/@apollo/src/utilities/globals/global.ts", "../../../../../node_modules/@apollo/src/utilities/common/makeUniqueId.ts", "../../../../../node_modules/@apollo/src/utilities/common/stringifyForDisplay.ts", "../../../../../node_modules/@apollo/src/utilities/globals/invariantWrappers.ts", "../../../../../node_modules/@apollo/src/utilities/globals/index.ts", "../../../../../node_modules/graphql/jsutils/isObjectLike.mjs", "../../../../../node_modules/graphql/polyfills/symbols.mjs", "../../../../../node_modules/graphql/language/location.mjs", "../../../../../node_modules/graphql/language/printLocation.mjs", "../../../../../node_modules/graphql/error/GraphQLError.mjs", "../../../../../node_modules/graphql/error/syntaxError.mjs", "../../../../../node_modules/graphql/language/kinds.mjs", "../../../../../node_modules/graphql/jsutils/invariant.mjs", "../../../../../node_modules/graphql/jsutils/nodejsCustomInspectSymbol.mjs", "../../../../../node_modules/graphql/jsutils/defineInspect.mjs", "../../../../../node_modules/graphql/language/ast.mjs", "../../../../../node_modules/graphql/language/tokenKind.mjs", "../../../../../node_modules/graphql/jsutils/inspect.mjs", "../../../../../node_modules/graphql/jsutils/devAssert.mjs", "../../../../../node_modules/graphql/jsutils/instanceOf.mjs", "../../../../../node_modules/graphql/language/source.mjs", "../../../../../node_modules/graphql/language/directiveLocation.mjs", "../../../../../node_modules/graphql/language/blockString.mjs", "../../../../../node_modules/graphql/language/lexer.mjs", "../../../../../node_modules/graphql/language/parser.mjs", "../../../../../node_modules/graphql/language/visitor.mjs", "../../../../../node_modules/graphql/language/printer.mjs", "../../../../../node_modules/graphql/language/predicates.mjs", "../../../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs", "../../../../../node_modules/@apollo/src/utilities/graphql/directives.ts", "../../../../../node_modules/@wry/trie/src/index.ts", "../../../../../node_modules/@apollo/src/utilities/common/canUse.ts", "../../../../../node_modules/@apollo/src/utilities/common/objects.ts", "../../../../../node_modules/@apollo/src/utilities/graphql/fragments.ts", "../../../../../node_modules/@wry/caches/src/strong.ts", "../../../../../node_modules/@wry/caches/src/weak.ts", "../../../../../node_modules/@apollo/src/utilities/caching/caches.ts", "../../../../../node_modules/@apollo/src/utilities/caching/sizes.ts", "../../../../../node_modules/@apollo/src/utilities/caching/getMemoryInternals.ts", "../../../../../node_modules/@apollo/src/utilities/common/canonicalStringify.ts", "../../../../../node_modules/@apollo/src/utilities/graphql/storeUtils.ts", "../../../../../node_modules/@apollo/src/utilities/graphql/getFromAST.ts", "../../../../../node_modules/@wry/context/src/slot.ts", "../../../../../node_modules/@wry/context/src/index.ts", "../../../../../node_modules/optimism/src/context.ts", "../../../../../node_modules/optimism/src/helpers.ts", "../../../../../node_modules/optimism/src/entry.ts", "../../../../../node_modules/optimism/src/dep.ts", "../../../../../node_modules/optimism/src/index.ts", "../../../../../node_modules/@apollo/src/utilities/graphql/DocumentTransform.ts", "../../../../../node_modules/@apollo/src/utilities/graphql/print.ts", "../../../../../node_modules/@apollo/src/utilities/common/arrays.ts", "../../../../../node_modules/@apollo/src/utilities/graphql/transform.ts", "../../../../../node_modules/@apollo/src/utilities/common/mergeDeep.ts", "../../../../../node_modules/zen-observable-ts/module.js", "../../../../../node_modules/symbol-observable/es/ponyfill.js", "../../../../../node_modules/symbol-observable/es/index.js", "../../../../../node_modules/@apollo/src/utilities/observables/Observable.ts", "../../../../../node_modules/@apollo/src/utilities/common/cloneDeep.ts", "../../../../../node_modules/@apollo/src/utilities/common/maybeDeepFreeze.ts", "../../../../../node_modules/@apollo/src/utilities/observables/iteration.ts", "../../../../../node_modules/@apollo/src/utilities/observables/asyncMap.ts", "../../../../../node_modules/@apollo/src/utilities/observables/subclassing.ts", "../../../../../node_modules/@apollo/src/utilities/observables/Concast.ts", "../../../../../node_modules/@apollo/src/utilities/common/incrementalResult.ts", "../../../../../node_modules/@apollo/src/utilities/common/errorHandling.ts", "../../../../../node_modules/@apollo/src/utilities/common/compact.ts", "../../../../../node_modules/@apollo/src/utilities/common/mergeOptions.ts", "../../../../../node_modules/@apollo/src/link/utils/fromError.ts", "../../../../../node_modules/@apollo/src/link/utils/throwServerError.ts", "../../../../../node_modules/@apollo/src/link/utils/validateOperation.ts", "../../../../../node_modules/@apollo/src/link/utils/createOperation.ts", "../../../../../node_modules/@apollo/src/link/utils/transformOperation.ts", "../../../../../node_modules/@apollo/src/link/utils/filterOperationVariables.ts", "../../../../../node_modules/@apollo/src/link/core/ApolloLink.ts", "../../../../../node_modules/@apollo/src/link/core/execute.ts", "../../../../../node_modules/@apollo/src/link/http/iterators/async.ts", "../../../../../node_modules/@apollo/src/link/http/iterators/nodeStream.ts", "../../../../../node_modules/@apollo/src/link/http/iterators/promise.ts", "../../../../../node_modules/@apollo/src/link/http/iterators/reader.ts", "../../../../../node_modules/@apollo/src/link/http/responseIterator.ts", "../../../../../node_modules/@apollo/src/errors/index.ts", "../../../../../node_modules/@apollo/src/link/http/parseAndCheckHttpResponse.ts", "../../../../../node_modules/@apollo/src/link/http/serializeFetchParameter.ts", "../../../../../node_modules/@apollo/src/link/http/selectHttpOptionsAndBody.ts", "../../../../../node_modules/@apollo/src/link/http/checkFetcher.ts", "../../../../../node_modules/@apollo/src/link/http/selectURI.ts", "../../../../../node_modules/@apollo/src/link/http/rewriteURIForGET.ts", "../../../../../node_modules/@apollo/src/link/http/createHttpLink.ts", "../../../../../node_modules/@apollo/src/link/http/HttpLink.ts", "../../../../../node_modules/@wry/equality/src/index.ts", "../../../../../node_modules/@apollo/src/cache/core/cache.ts", "../../../../../node_modules/@apollo/src/cache/core/types/common.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/helpers.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/entityStore.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/object-canon.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/readFromStore.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/reactiveVars.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/key-extractor.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/policies.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/writeToStore.ts", "../../../../../node_modules/@apollo/src/cache/inmemory/inMemoryCache.ts", "../../../../../node_modules/@apollo/src/core/networkStatus.ts", "../../../../../node_modules/@apollo/src/core/equalByQuery.ts", "../../../../../node_modules/@apollo/src/core/ObservableQuery.ts", "../../../../../node_modules/@apollo/src/core/LocalState.ts", "../../../../../node_modules/@apollo/src/core/QueryInfo.ts", "../../../../../node_modules/@apollo/src/core/QueryManager.ts", "../../../../../node_modules/@apollo/src/core/ApolloClient.ts", "../../../../../node_modules/graphql-tag/src/index.ts", "../../../../../node_modules/@apollo/src/core/index.ts", "../../../../../node_modules/@apollo/src/react/context/ApolloContext.ts", "../../../../../node_modules/@apollo/src/react/context/ApolloProvider.tsx", "../../../../../node_modules/@apollo/src/react/hooks/useApolloClient.ts", "../../../../../node_modules/@apollo/src/react/hooks/useQuery.ts", "../../../../../node_modules/@apollo/src/react/hooks/useSyncExternalStore.ts", "../../../../../node_modules/@apollo/src/react/parser/index.ts", "../../../../../node_modules/@apollo/src/react/hooks/internal/wrapHook.ts", "../../../../global-components-schema/src/contentful/apolloLink.ts", "../../../../global-components-schema/src/contentful/contentfulConstants.ts", "../../../../global-components-schema/src/hooks/useGlobalComponentsContentfulQuery.ts", "../../../../snap-design-system-marketing/src/components/Break/types.ts", "../../../../../node_modules/@snapchat/core/src/encoding/htmlEscape.ts", "../../../../../node_modules/@snapchat/core/src/encoding/htmlUnescape.ts", "../../../../../node_modules/@snapchat/core/src/encoding/jsonStringify.ts", "../../../../../node_modules/@snapchat/core/src/errors/SnapError.ts", "../../../../../node_modules/@snapchat/core/src/errors/parseError.ts", "../../../../../node_modules/@snapchat/core/src/sets.ts", "../../../../../node_modules/@snapchat/core/src/async/sleep.ts", "../../../../../node_modules/@snapchat/core/src/async/waitFor.ts", "../../../../../node_modules/@snapchat/core/src/async/promises.ts", "../../../../../node_modules/@snapchat/core/src/fetch/fetchHeaders.ts", "../../../../../node_modules/@snapchat/core/src/fetch/fetchWithTimeout.ts", "../../../../../node_modules/@snapchat/core/src/fetch/fetchWithRetries.ts", "../../../src/clientEnv.ts", "../../../src/constants/defaultFontSettings.ts", "../../../src/helpers/trackingCookies.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/utils/isInBrowser.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/logger.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/BaseClient.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/auth/constants.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/auth/Authenticator.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/collector/MetricCollector.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/network/BaseNetworkHandler.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/network/FetchNetworkHandler.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/utils/computeMetricKey.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/utils/getRandomIntFromRange.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/utils/reservoirSample.ts", "../../../../../node_modules/@snapchat/metrics-utils/src/utils/inlineBtoa.ts", "../../../../../node_modules/@snapchat/hash/dist/chunk-PAWJFY3S.mjs", "../../../../../node_modules/@snapchat/hash/src/hash.browser.ts", "../../../../../node_modules/@snapchat/graphene/src/index.ts", "../../../../../node_modules/@snapchat/graphene/src/partition.ts", "../../../../../node_modules/@snapchat/graphene/src/graphene.ts", "../../../../../node_modules/@snapchat/graphene/src/ActivityDetector.ts", "../../../../../node_modules/@snapchat/graphene/src/collector/WebMetricCollector.ts", "../../../../../node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js", "../../../../../node_modules/@bufbuild/protobuf/dist/esm/proto-int64.js", "../../../../../node_modules/@bufbuild/protobuf/dist/esm/wire/text-encoding.js", "../../../../../node_modules/@bufbuild/protobuf/dist/esm/wire/binary-encoding.js", "../../../../../node_modules/@snapchat/graphene/src/generated/graphene/metrics.ts", "../../../../../node_modules/@snapchat/graphene/src/config/web.ts", "../../../../../node_modules/@snapchat/graphene/src/auth/WebAuthenticator.ts", "../../../../../node_modules/@snapchat/graphene/src/auth/computeWebAttestation.ts", "../../../src/brands/snap/CustomLocaleDropdownButton/CustomLocaleDropdown.styles.ts", "../../../src/brands/snap/CustomLocaleDropdownButton/CustomLocaleDropdownButton.tsx", "../../../src/brands/snap/snapBrandConfigSharedSettings.ts", "../../../src/components/FeatureFlags/useFeatureFlags.ts", "../../../src/context/SitewideConfiguration/SitewideConfigurationContext.ts", "../../../src/sites/snap/snapConfig.ts", "../../../src/config.ts", "../../../src/constants/urlParameters.ts", "../../../../../node_modules/@snapchat/polyfills/src/requestIdleCallback.ts", "../../../../../node_modules/@snapchat/polyfills/src/structuredClone.ts", "../../../../../node_modules/lodash-es/isNil.js", "../../../../../node_modules/@snapchat/otel-otlp-logger/src/Batcher.ts", "../../../../../node_modules/@snapchat/otel-otlp-logger/src/LogLevel.ts", "../../../../../node_modules/@snapchat/otel-otlp-logger/src/simpleAttributes.ts", "../../../../../node_modules/@snapchat/otel-otlp-logger/src/OtlpJsonExporter.ts", "../../../../../node_modules/@snapchat/otel-otlp-logger/src/OpenTelemetryLogger.ts", "../../../../../node_modules/@snapchat/logging/src/AbstractEventListener.ts", "../../../../../node_modules/@snapchat/logging/src/AbstractDataLayerEventListener.ts", "../../../../../node_modules/@snapchat/logging/src/AbstractGrapheneEventListener.ts", "../../../../../node_modules/@snapchat/logging/src/loggingTypes.ts", "../../../../../node_modules/@snapchat/logging/src/AbstractSentryEventListener.ts", "../../../../../node_modules/@snapchat/logging/src/ConsoleEventListener.ts", "../../../../../node_modules/@snapchat/logging/src/LoggingEventBus.ts", "../../../../../node_modules/@snapchat/logging/src/OpenTelemetryEventListener.ts", "../../../../../node_modules/@snapchat/logging/src/withComponent.ts", "../../../../../node_modules/@snapchat/logging/src/testing/TestEventListener.ts", "../../../../../node_modules/@snapchat/logging/src/testing/testLogEvents.ts", "../../../src/helpers/logging/loggingInstance.ts"],
  "sourcesContent": ["'use strict';\n\nmodule.exports = value => {\n\tif (Object.prototype.toString.call(value) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || prototype === Object.prototype;\n};\n", "/**\n * Map of all Contentful block types. Blocks contain inline or block nodes.\n */\nexport enum BLOCKS {\n  DOCUMENT = 'document',\n  PARAGRAPH = 'paragraph',\n\n  HEADING_1 = 'heading-1',\n  HEADING_2 = 'heading-2',\n  HEADING_3 = 'heading-3',\n  HEADING_4 = 'heading-4',\n  HEADING_5 = 'heading-5',\n  HEADING_6 = 'heading-6',\n\n  OL_LIST = 'ordered-list',\n  UL_LIST = 'unordered-list',\n  LIST_ITEM = 'list-item',\n\n  HR = 'hr',\n  QUOTE = 'blockquote',\n\n  EMBEDDED_ENTRY = 'embedded-entry-block',\n  EMBEDDED_ASSET = 'embedded-asset-block',\n  EMBEDDED_RESOURCE = 'embedded-resource-block',\n\n  TABLE = 'table',\n  TABLE_ROW = 'table-row',\n  TABLE_CELL = 'table-cell',\n  TABLE_HEADER_CELL = 'table-header-cell',\n}\n", "/**\n * Map of all Contentful inline types. Inline contain inline or text nodes.\n *\n * @note This should be kept in alphabetical order since the\n * [validation package](https://github.com/contentful/content-stack/tree/master/packages/validation)\n *  relies on the values being in a predictable order.\n */\nexport enum INLINES {\n  ASSET_HYPERLINK = 'asset-hyperlink',\n  EMBEDDED_ENTRY = 'embedded-entry-inline',\n  EMBEDDED_RESOURCE = 'embedded-resource-inline',\n  ENTRY_HYPERLINK = 'entry-hyperlink',\n  HYPERLINK = 'hyperlink',\n  RESOURCE_HYPERLINK = 'resource-hyperlink',\n}\n", "/**\n * Map of all Contentful marks.\n */\nexport enum MARKS {\n  BOLD = 'bold',\n  ITALIC = 'italic',\n  UNDERLINE = 'underline',\n  CODE = 'code',\n  SUPERSCRIPT = 'superscript',\n  SUBSCRIPT = 'subscript',\n  STRIKETHROUGH = 'strikethrough',\n}\n", "import { BLOCKS } from './blocks';\nimport { INLINES } from './inlines';\nimport { MARKS } from './marks';\n\nexport type TopLevelBlockEnum =\n  | BLOCKS.PARAGRAPH\n  | BLOCKS.HEADING_1\n  | BLOCKS.HEADING_2\n  | BLOCKS.HEADING_3\n  | BLOCKS.HEADING_4\n  | BLOCKS.HEADING_5\n  | BLOCKS.HEADING_6\n  | BLOCKS.OL_LIST\n  | BLOCKS.UL_LIST\n  | BLOCKS.HR\n  | BLOCKS.QUOTE\n  | BLOCKS.EMBEDDED_ENTRY\n  | BLOCKS.EMBEDDED_ASSET\n  | BLOCKS.EMBEDDED_RESOURCE\n  | BLOCKS.TABLE;\n\n/**\n * Array of all top level block types.\n * Only these block types can be the direct children of the document.\n */\nexport const TOP_LEVEL_BLOCKS: TopLevelBlockEnum[] = [\n  BLOCKS.PARAGRAPH,\n  BLOCKS.HEADING_1,\n  BLOCKS.HEADING_2,\n  BLOCKS.HEADING_3,\n  BLOCKS.HEADING_4,\n  BLOCKS.HEADING_5,\n  BLOCKS.HEADING_6,\n  BLOCKS.OL_LIST,\n  BLOCKS.UL_LIST,\n  BLOCKS.HR,\n  BLOCKS.QUOTE,\n  BLOCKS.EMBEDDED_ENTRY,\n  BLOCKS.EMBEDDED_ASSET,\n  BLOCKS.EMBEDDED_RESOURCE,\n  BLOCKS.TABLE,\n];\n\nexport type ListItemBlockEnum =\n  | BLOCKS.PARAGRAPH\n  | BLOCKS.HEADING_1\n  | BLOCKS.HEADING_2\n  | BLOCKS.HEADING_3\n  | BLOCKS.HEADING_4\n  | BLOCKS.HEADING_5\n  | BLOCKS.HEADING_6\n  | BLOCKS.OL_LIST\n  | BLOCKS.UL_LIST\n  | BLOCKS.HR\n  | BLOCKS.QUOTE\n  | BLOCKS.EMBEDDED_ENTRY\n  | BLOCKS.EMBEDDED_ASSET\n  | BLOCKS.EMBEDDED_RESOURCE;\n\n/**\n * Array of all allowed block types inside list items\n */\nexport const LIST_ITEM_BLOCKS: TopLevelBlockEnum[] = [\n  BLOCKS.PARAGRAPH,\n  BLOCKS.HEADING_1,\n  BLOCKS.HEADING_2,\n  BLOCKS.HEADING_3,\n  BLOCKS.HEADING_4,\n  BLOCKS.HEADING_5,\n  BLOCKS.HEADING_6,\n  BLOCKS.OL_LIST,\n  BLOCKS.UL_LIST,\n  BLOCKS.HR,\n  BLOCKS.QUOTE,\n  BLOCKS.EMBEDDED_ENTRY,\n  BLOCKS.EMBEDDED_ASSET,\n  BLOCKS.EMBEDDED_RESOURCE,\n];\n\nexport const TABLE_BLOCKS = [\n  BLOCKS.TABLE,\n  BLOCKS.TABLE_ROW,\n  BLOCKS.TABLE_CELL,\n  BLOCKS.TABLE_HEADER_CELL,\n];\n\n/**\n * Array of all void block types\n */\nexport const VOID_BLOCKS = [\n  BLOCKS.HR,\n  BLOCKS.EMBEDDED_ENTRY,\n  BLOCKS.EMBEDDED_ASSET,\n  BLOCKS.EMBEDDED_RESOURCE,\n];\n\n/**\n * Dictionary of all container block types, and the set block types they accept as children.\n *\n * Note: This does not include `[BLOCKS.DOCUMENT]: TOP_LEVEL_BLOCKS`\n */\nexport const CONTAINERS = {\n  [BLOCKS.OL_LIST]: [BLOCKS.LIST_ITEM],\n  [BLOCKS.UL_LIST]: [BLOCKS.LIST_ITEM],\n  [BLOCKS.LIST_ITEM]: LIST_ITEM_BLOCKS,\n  [BLOCKS.QUOTE]: [BLOCKS.PARAGRAPH],\n  [BLOCKS.TABLE]: [BLOCKS.TABLE_ROW],\n  [BLOCKS.TABLE_ROW]: [BLOCKS.TABLE_CELL, BLOCKS.TABLE_HEADER_CELL],\n  [BLOCKS.TABLE_CELL]: [BLOCKS.PARAGRAPH, BLOCKS.UL_LIST, BLOCKS.OL_LIST],\n  [BLOCKS.TABLE_HEADER_CELL]: [BLOCKS.PARAGRAPH],\n};\n\n/**\n * Array of all heading levels\n */\nexport const HEADINGS = [\n  BLOCKS.HEADING_1,\n  BLOCKS.HEADING_2,\n  BLOCKS.HEADING_3,\n  BLOCKS.HEADING_4,\n  BLOCKS.HEADING_5,\n  BLOCKS.HEADING_6,\n];\n\n/**\n * Array of all block types that may contain text and inline nodes.\n */\nexport const TEXT_CONTAINERS = [BLOCKS.PARAGRAPH, ...HEADINGS];\n\n/**\n * Node types before `tables` release.\n */\nexport const V1_NODE_TYPES = [\n  BLOCKS.DOCUMENT,\n  BLOCKS.PARAGRAPH,\n  BLOCKS.HEADING_1,\n  BLOCKS.HEADING_2,\n  BLOCKS.HEADING_3,\n  BLOCKS.HEADING_4,\n  BLOCKS.HEADING_5,\n  BLOCKS.HEADING_6,\n  BLOCKS.OL_LIST,\n  BLOCKS.UL_LIST,\n  BLOCKS.LIST_ITEM,\n  BLOCKS.HR,\n  BLOCKS.QUOTE,\n  BLOCKS.EMBEDDED_ENTRY,\n  BLOCKS.EMBEDDED_ASSET,\n  INLINES.HYPERLINK,\n  INLINES.ENTRY_HYPERLINK,\n  INLINES.ASSET_HYPERLINK,\n  INLINES.EMBEDDED_ENTRY,\n  'text',\n];\n\n/**\n * Marks before `superscript` & `subscript` release.\n */\nexport const V1_MARKS = [MARKS.BOLD, MARKS.CODE, MARKS.ITALIC, MARKS.UNDERLINE];\n", "import { BLOCKS } from './blocks';\nimport { Document } from './types';\n\n/**\n * A rich text document considered to be empty.\n * Any other document structure than this is not considered empty.\n */\nexport const EMPTY_DOCUMENT: Document = {\n  nodeType: BLOCKS.DOCUMENT,\n  data: {},\n  content: [\n    {\n      nodeType: BLOCKS.PARAGRAPH,\n      data: {},\n      content: [\n        {\n          nodeType: 'text',\n          value: '',\n          marks: [],\n          data: {},\n        },\n      ],\n    },\n  ],\n};\n", "import { BLOCKS } from './blocks';\nimport { INLINES } from './inlines';\nimport { Block, Inline, Node, Text } from './types';\n\n/**\n * Tiny replacement for Object.values(object).includes(key) to\n * avoid including CoreJS polyfills\n */\nfunction hasValue(obj: Record<string, unknown>, value: unknown) {\n  for (const key of Object.keys(obj)) {\n    if (value === obj[key]) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n/**\n * Checks if the node is an instance of Inline.\n */\nexport function isInline(node: Node): node is Inline {\n  return hasValue(INLINES, node.nodeType);\n}\n\n/**\n * Checks if the node is an instance of Block.\n */\nexport function isBlock(node: Node): node is Block {\n  return hasValue(BLOCKS, node.nodeType);\n}\n\n/**\n * Checks if the node is an instance of Text.\n */\nexport function isText(node: Node): node is Text {\n  return node.nodeType === 'text';\n}\n", "import { ValidationError } from '.';\nimport type { Path } from './path';\n\nexport const typeMismatchError = ({\n  path,\n  property,\n  typeName,\n  value,\n}: {\n  path: Path;\n  property: string | number;\n  typeName: string;\n  value: any;\n}): ValidationError => {\n  return {\n    details: `The type of \"${property}\" is incorrect, expected type: ${typeName}`,\n    name: 'type',\n    path: path.toArray(),\n    type: typeName,\n    value,\n  };\n};\n\nexport const minSizeError = ({\n  min,\n  value,\n  path,\n}: {\n  min: number;\n  value: any;\n  path: Path;\n}): ValidationError => {\n  return {\n    name: 'size',\n    min,\n    path: path.toArray(),\n    details: `Size must be at least ${min}`,\n    value,\n  };\n};\n\nexport const maxSizeError = ({\n  max,\n  value,\n  path,\n}: {\n  max: number;\n  value: any;\n  path: Path;\n}): ValidationError => {\n  return {\n    name: 'size',\n    max,\n    path: path.toArray(),\n    details: `Size must be at most ${max}`,\n    value,\n  };\n};\n\nexport const enumError = ({\n  expected,\n  value,\n  path,\n}: {\n  expected: string[];\n  value: any;\n  path: Path;\n}): ValidationError => {\n  return {\n    details: `Value must be one of expected values`,\n    name: 'in',\n    expected: [...expected].sort(),\n    path: path.toArray(),\n    value,\n  };\n};\n\nexport const unknownPropertyError = ({\n  property,\n  path,\n}: {\n  property: string;\n  path: Path;\n}): ValidationError => {\n  return {\n    details: `The property \"${property}\" is not expected`,\n    name: 'unexpected',\n    path: path.toArray(),\n  };\n};\n\nexport const requiredPropertyError = ({\n  property,\n  path,\n}: {\n  property: string;\n  path: Path;\n}): ValidationError => {\n  return {\n    details: `The property \"${property}\" is required here`,\n    name: 'required',\n    path: path.toArray(),\n  };\n};\n", "import isPlainObject from 'is-plain-obj';\n\nimport { ValidationError } from '.';\nimport {\n  maxSizeError,\n  typeMismatchError,\n  enumError,\n  unknownPropertyError,\n  requiredPropertyError,\n  minSizeError,\n} from './errors';\nimport type { Path } from './path';\n\nexport class ObjectAssertion {\n  private _errors: ValidationError[] = [];\n\n  constructor(\n    private readonly obj: Record<string, any>,\n    private readonly path: Path,\n  ) {}\n\n  catch = (...errors: ValidationError[]): void => {\n    this._errors.push(...errors);\n  };\n\n  get errors(): ValidationError[] {\n    const serializeError = (error: ValidationError): string =>\n      JSON.stringify({\n        details: error.details,\n        path: error.path,\n      });\n\n    return this._errors.filter(\n      (error, index) =>\n        this._errors.findIndex((step) => serializeError(error) === serializeError(step)) === index,\n    );\n  }\n\n  /**\n   * Asserts the key exists in the object. You probably shouldn't call this\n   * function directly. Instead, use `$.object`, `$.number`, `$.string`, etc.\n   */\n  exists = (key: string): boolean => {\n    if (key in this.obj) {\n      return true;\n    }\n\n    this.catch(\n      requiredPropertyError({\n        property: key,\n        path: this.path.of(key),\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the key exists in the object and its value is a plain object. if\n   * no key is provided, it asserts the object itself.\n   */\n  public object = (key?: string): boolean => {\n    const value = key ? this.obj[key] : this.obj;\n\n    if (key) {\n      if (!this.exists(key)) {\n        return false;\n      }\n    }\n\n    if (isPlainObject(value)) {\n      return true;\n    }\n\n    const path = key ? this.path.of(key) : this.path;\n    const property = key ?? this.path.last() ?? 'value';\n\n    this.catch(\n      typeMismatchError({\n        typeName: 'Object',\n        property,\n        path,\n        value,\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the key exists in the object and its value is a string.\n   */\n  public string = (key: string): boolean => {\n    const value = this.obj[key];\n\n    if (key && !this.exists(key)) {\n      return false;\n    }\n\n    if (typeof value === 'string') {\n      return true;\n    }\n\n    this.catch(\n      typeMismatchError({\n        typeName: 'String',\n        property: key,\n        path: this.path.of(key),\n        value,\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the key exists in the object and its value is a number.\n   */\n  public number = (key: string, optional?: boolean): boolean => {\n    const value = this.obj[key];\n\n    if (optional && !(key in this.obj)) {\n      return true;\n    }\n\n    if (!this.exists(key)) {\n      return false;\n    }\n\n    if (typeof value === 'number' && !Number.isNaN(value)) {\n      return true;\n    }\n\n    this.catch(\n      typeMismatchError({\n        typeName: 'Number',\n        property: key,\n        path: this.path.of(key),\n        value,\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the key exists in the object and its value is an array. You don't\n   * need to manually call this function before `$.each` or `$.maxLength`.\n   */\n  public array = (key: string): boolean => {\n    const value = this.obj[key];\n\n    if (key && !this.exists(key)) {\n      return false;\n    }\n\n    if (Array.isArray(value)) {\n      return true;\n    }\n\n    this.catch(\n      typeMismatchError({\n        typeName: 'Array',\n        property: key,\n        path: this.path.of(key),\n        value,\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the value of the key is one of the expected values.\n   */\n  public enum = (key: string, expected: string[]): boolean => {\n    const value = this.obj[key];\n\n    if (typeof value === 'string' && expected.includes(value)) {\n      return true;\n    }\n\n    this.catch(\n      enumError({\n        expected,\n        value,\n        path: this.path.of(key),\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the array value of the object key is empty. If the value isn't an\n   * array, the function captures a type error and returns false.\n   */\n  public empty = (key: string): boolean => {\n    if (!this.array(key)) {\n      return false;\n    }\n\n    const value = this.obj[key] as Array<unknown>;\n\n    if (value.length === 0) {\n      return true;\n    }\n\n    this.catch(\n      maxSizeError({\n        max: 0,\n        value,\n        path: this.path.of(key),\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the length of the value of the object key is at least `min`. If the\n   * value isn't an array, the function captures a type error and returns false.\n   */\n  public minLength = (key: string, min: number): boolean => {\n    if (!this.array(key)) {\n      return false;\n    }\n\n    const value = this.obj[key] as Array<unknown>;\n\n    if (value.length >= min) {\n      return true;\n    }\n\n    this.catch(\n      minSizeError({\n        min,\n        value,\n        path: this.path.of(key),\n      }),\n    );\n\n    return false;\n  };\n\n  /**\n   * Asserts the object has no additional properties other than the ones\n   * specified\n   */\n  public noAdditionalProperties = (properties: string[]): boolean => {\n    const unknowns = Object.keys(this.obj)\n      .sort()\n      .filter((key) => !properties.includes(key));\n\n    unknowns.forEach((property) =>\n      this.catch(\n        unknownPropertyError({\n          property,\n          path: this.path.of(property),\n        }),\n      ),\n    );\n\n    return unknowns.length === 0;\n  };\n\n  /**\n   * Iterates over the value of the key and assert each item. If the value isn't\n   * an array, the function captures a type error and safely exits.\n   *\n   * To maintain compatibility with previous implementation, we stop early if we\n   * find any errors.\n   */\n  public each = (key: string, assert: (item: any, path: Path) => ValidationError[]): void => {\n    if (!this.array(key)) {\n      return;\n    }\n\n    const value = this.obj[key] as Array<any>;\n\n    let foundErrors = false;\n    value.forEach((item, index) => {\n      if (foundErrors) {\n        return;\n      }\n\n      const errors = assert(item, this.path.of(key).of(index));\n\n      if (errors.length > 0) {\n        foundErrors = true;\n      }\n\n      this.catch(...errors);\n    });\n  };\n}\n", "import { ValidationError } from '.';\nimport {\n  AssetHyperlink,\n  AssetLinkBlock,\n  EntryHyperlink,\n  EntryLinkBlock,\n  Hyperlink,\n  ResourceLinkBlock,\n  ResourceLinkInline,\n} from '../nodeTypes';\nimport { Block, Document, Inline } from '../types';\nimport { ObjectAssertion } from './assert';\nimport type { Path } from './path';\n\nexport type Node = Document | Block | Inline;\n\nexport type GetContentRule<T extends Node> =\n  | string[]\n  | ((\n      node: T,\n      path: Path,\n    ) => {\n      nodeTypes: string[];\n      min?: number;\n    });\n\nexport type ValidateData<T extends Node> = (data: T['data'], path: Path) => ValidationError[];\n\nexport const VOID_CONTENT: GetContentRule<Node> = [];\n\nexport class NodeAssertion<T extends Node = Node> {\n  constructor(\n    private contentRule: GetContentRule<T>,\n    private validateData?: ValidateData<T>,\n  ) {}\n\n  assert(node: T, path: Path): ValidationError[] {\n    const $ = new ObjectAssertion(node, path);\n\n    if (!$.object()) {\n      return $.errors;\n    }\n\n    $.noAdditionalProperties(['nodeType', 'data', 'content']);\n\n    const { nodeTypes, min = 0 } = Array.isArray(this.contentRule)\n      ? {\n          nodeTypes: this.contentRule,\n        }\n      : this.contentRule(node, path);\n\n    if (nodeTypes.length === 0 && min > 0) {\n      throw new Error(\n        `Invalid content rule. Cannot have enforce a 'min' of ${min} with no nodeTypes`,\n      );\n    }\n\n    $.minLength('content', min);\n\n    // Is void\n    if (nodeTypes.length === 0) {\n      $.empty('content');\n    }\n\n    // Ensure content nodes have valid nodeTypes without validating the full\n    // shape which is something that's only done later if the current node is\n    // valid.\n    else {\n      $.each('content', (item, path) => {\n        const item$ = new ObjectAssertion(item, path);\n\n        if (!item$.object()) {\n          return item$.errors;\n        }\n\n        item$.enum('nodeType', nodeTypes);\n\n        return item$.errors;\n      });\n    }\n\n    if ($.object('data')) {\n      const dataErrors = this.validateData?.(node.data, path.of('data')) ?? [];\n      $.catch(...dataErrors);\n    }\n\n    return $.errors;\n  }\n}\n\nexport class EntityLinkAssertion<\n  T extends\n    | EntryLinkBlock\n    | EntryHyperlink\n    | AssetLinkBlock\n    | AssetHyperlink\n    | ResourceLinkBlock\n    | ResourceLinkInline,\n> extends NodeAssertion<T> {\n  private type: 'ResourceLink' | 'Link';\n\n  constructor(\n    private linkType: 'Entry' | 'Asset' | 'Contentful:Entry',\n    contentNodeTypes: GetContentRule<T>,\n  ) {\n    super(contentNodeTypes, (data, path) => this.assertLink(data, path));\n    this.type = this.linkType.startsWith('Contentful:') ? 'ResourceLink' : 'Link';\n  }\n\n  private assertLink = (data: T['data'], path: Path): ValidationError[] => {\n    const $ = new ObjectAssertion(data, path);\n\n    if ($.object('target')) {\n      const sys$ = new ObjectAssertion(data.target.sys, path.of('target').of('sys'));\n\n      if (sys$.object()) {\n        sys$.enum('type', [this.type]);\n        sys$.enum('linkType', [this.linkType]);\n\n        if (this.type === 'Link') {\n          sys$.string('id');\n          sys$.noAdditionalProperties(['type', 'linkType', 'id']);\n        } else if (this.type === 'ResourceLink') {\n          sys$.string('urn');\n          sys$.noAdditionalProperties(['type', 'linkType', 'urn']);\n        }\n      }\n\n      $.catch(...sys$.errors);\n    }\n\n    $.noAdditionalProperties(['target']);\n\n    return $.errors;\n  };\n}\n\nexport class HyperLinkAssertion<T extends Hyperlink> extends NodeAssertion<T> {\n  constructor() {\n    super(['text'], (data, path) => this.assertLink(data, path));\n  }\n\n  private assertLink = (data: T['data'], path: Path): ValidationError[] => {\n    const $ = new ObjectAssertion(data, path);\n\n    $.string('uri');\n    $.noAdditionalProperties(['uri']);\n\n    return $.errors;\n  };\n}\n\nexport const assert = <T extends Node>(\n  contentRule: GetContentRule<T>,\n  validateData?: ValidateData<T>,\n): NodeAssertion<T> => {\n  return new NodeAssertion(contentRule, validateData);\n};\n\nexport const assertLink = <\n  T extends\n    | EntryLinkBlock\n    | EntryHyperlink\n    | AssetLinkBlock\n    | AssetHyperlink\n    | ResourceLinkBlock\n    | ResourceLinkInline,\n>(\n  linkType: 'Entry' | 'Asset' | 'Contentful:Entry',\n  contentRule: GetContentRule<T>,\n): EntityLinkAssertion<T> => {\n  return new EntityLinkAssertion(linkType, contentRule);\n};\n", "export class Path {\n  constructor(private readonly path: (string | number)[] = []) {}\n\n  of = (element: string | number): Path => {\n    return new Path([...this.path, element]);\n  };\n\n  isRoot = (): boolean => {\n    return this.path.length === 0;\n  };\n\n  last = (): string | number | undefined => {\n    return this.path[this.path.length - 1];\n  };\n\n  toArray = (): (string | number)[] => {\n    return this.path;\n  };\n}\n", "import { ValidationError } from '.';\nimport { Text } from '../types';\nimport { ObjectAssertion } from './assert';\nimport type { Path } from './path';\n\nexport function assertText(text: Text, path: Path): ValidationError[] {\n  const $ = new ObjectAssertion(text, path);\n\n  if (!$.object()) {\n    return $.errors;\n  }\n\n  $.noAdditionalProperties(['nodeType', 'data', 'value', 'marks']);\n\n  $.object('data');\n  $.each('marks', (mark, path) => {\n    const mark$ = new ObjectAssertion(mark, path);\n\n    if (!mark$.object()) {\n      return mark$.errors;\n    }\n\n    // For historical reasons, we don't explicitly check for supported marks\n    // e.g. bold, italic ..etc. This makes it possible for a customer to add\n    // custom marks\n    mark$.string('type');\n\n    return mark$.errors;\n  });\n\n  $.string('value');\n\n  return $.errors;\n}\n", "import { BLOCKS } from '../blocks';\nimport { INLINES } from '../inlines';\nimport { CONTAINERS, LIST_ITEM_BLOCKS, TOP_LEVEL_BLOCKS } from '../schemaConstraints';\nimport { Document, Text } from '../types';\nimport { ObjectAssertion } from './assert';\nimport { NodeAssertion, Node, HyperLinkAssertion, assert, assertLink, VOID_CONTENT } from './node';\nimport { Path } from './path';\nimport { assertText } from './text';\n\nexport type ValidationError = {\n  name: string;\n  type?: string;\n  value?: Record<string, any> | string | number | boolean | null;\n  min?: number | string;\n  max?: number | string;\n  details?: string | null;\n  path?: (string | number)[];\n  contentTypeId?: string | string[];\n  nodeType?: string;\n  customMessage?: string;\n  expected?: string[];\n};\n\nconst assertInlineOrText = assert([...Object.values(INLINES), 'text'].sort());\n\nconst assertList = assert([BLOCKS.LIST_ITEM]);\nconst assertVoidEntryLink = assertLink('Entry', VOID_CONTENT);\nconst assertTableCell = assert(\n  () => ({\n    nodeTypes: [BLOCKS.PARAGRAPH],\n    min: 1,\n  }),\n  (data, path) => {\n    const $ = new ObjectAssertion(data, path);\n\n    $.noAdditionalProperties(['colspan', 'rowspan']);\n    $.number('colspan', true);\n    $.number('rowspan', true);\n\n    return $.errors;\n  },\n);\n\nconst nodeValidator: Record<Node['nodeType'], NodeAssertion<any>> = {\n  [BLOCKS.DOCUMENT]: assert(TOP_LEVEL_BLOCKS),\n  [BLOCKS.PARAGRAPH]: assertInlineOrText,\n  [BLOCKS.HEADING_1]: assertInlineOrText,\n  [BLOCKS.HEADING_2]: assertInlineOrText,\n  [BLOCKS.HEADING_3]: assertInlineOrText,\n  [BLOCKS.HEADING_4]: assertInlineOrText,\n  [BLOCKS.HEADING_5]: assertInlineOrText,\n  [BLOCKS.HEADING_6]: assertInlineOrText,\n  [BLOCKS.QUOTE]: assert(CONTAINERS[BLOCKS.QUOTE]),\n  [BLOCKS.EMBEDDED_ENTRY]: assertVoidEntryLink,\n  [BLOCKS.EMBEDDED_ASSET]: assertLink('Asset', VOID_CONTENT),\n  [BLOCKS.EMBEDDED_RESOURCE]: assertLink('Contentful:Entry', VOID_CONTENT),\n  [BLOCKS.HR]: assert(VOID_CONTENT),\n  [BLOCKS.OL_LIST]: assertList,\n  [BLOCKS.UL_LIST]: assertList,\n  [BLOCKS.LIST_ITEM]: assert([...LIST_ITEM_BLOCKS].sort()),\n  [BLOCKS.TABLE]: assert(() => ({\n    nodeTypes: [BLOCKS.TABLE_ROW],\n    min: 1,\n  })),\n  [BLOCKS.TABLE_ROW]: assert(() => ({\n    nodeTypes: [BLOCKS.TABLE_CELL, BLOCKS.TABLE_HEADER_CELL],\n    min: 1,\n  })),\n  [BLOCKS.TABLE_CELL]: assertTableCell,\n  [BLOCKS.TABLE_HEADER_CELL]: assertTableCell,\n  [INLINES.HYPERLINK]: new HyperLinkAssertion(),\n  [INLINES.EMBEDDED_ENTRY]: assertVoidEntryLink,\n  [INLINES.EMBEDDED_RESOURCE]: assertLink('Contentful:Entry', VOID_CONTENT),\n  [INLINES.ENTRY_HYPERLINK]: assertLink('Entry', ['text']),\n  [INLINES.ASSET_HYPERLINK]: assertLink('Asset', ['text']),\n  [INLINES.RESOURCE_HYPERLINK]: assertLink('Contentful:Entry', ['text']),\n};\n\nfunction validateNode(node: Node | Text, path: Path): ValidationError[] {\n  if (node.nodeType === 'text') {\n    return assertText(node, path);\n  }\n\n  const errors = nodeValidator[node.nodeType].assert(node, path);\n\n  if (errors.length > 0) {\n    return errors;\n  }\n\n  const $ = new ObjectAssertion(node, path);\n\n  $.each('content', (item, path) => {\n    // We already know those are valid nodes thanks to the assertion done in\n    // the NodeAssertion class\n    return validateNode(item, path);\n  });\n\n  return $.errors;\n}\n\nexport const validateRichTextDocument = (document: Document): ValidationError[] => {\n  const path = new Path();\n  const $ = new ObjectAssertion(document, path);\n\n  if ($.object()) {\n    $.enum('nodeType', [BLOCKS.DOCUMENT]);\n  }\n\n  if ($.errors.length > 0) {\n    return $.errors;\n  }\n\n  return validateNode(document, path);\n};\n", "import { Block, Inline, Node, helpers } from '@contentful/rich-text-types';\n\n/**\n * Returns the text value of a rich text document.\n *\n * NB: This can be applied to non text node of a structured text document,\n * hence the flexible typing.\n */\nexport function documentToPlainTextString(\n  rootNode: Block | Inline,\n  blockDivisor: string = ' ',\n): string {\n  if (!rootNode || !rootNode.content || !Array.isArray(rootNode.content)) {\n    /**\n     * Handles edge cases, such as when the value is not set in the CMA or the\n     * field has not been properly validated, e.g. because of a user extension.\n     * Note that we are nevertheless strictly type-casting `rootNode` as\n     * Block | Inline. Valid rich text documents (and their branch block nodes)\n     * should never lack a Node[] `content` property.\n     */\n    return '';\n  }\n\n  /**\n   * Algorithm notes: We only want to apply spacing when a node is part of a\n   * sequence. This is tricky because nodes can often be deeply nested within\n   * non-semantic content arrays. For example, to get the text value of an\n   * unordered list, we have to traverse like so:\n   *\n   * {\n   *   nodeType: BLOCKS.UL_LIST,\n   *   data: {},\n   *   content: [\n   *     {\n   *       nodeType: BLOCKS.LIST_ITEM,\n   *       data: {},\n   *       content: [{\n   *         nodeType: BLOCKS.PARAGRAPH,\n   *         data: {},\n   *         content: [\n   *           { nodeType: 'text', data: {}, value: 'List ', marks: [] },\n   *           { nodeType: 'text', data: {}, value: 'item', marks: [{ type: 'bold' }] }\n   *         ]\n   *       }]\n   *     },\n   *     {\n   *       nodeType: BLOCKS.LIST_ITEM,\n   *       data: {},\n   *       content: [{\n   *         nodeType: BLOCKS.PARAGRAPH,\n   *         data: {},\n   *         content: [\n   *           { nodeType: 'text', data: {}, value: 'Another list item', marks: [] }\n   *         ]\n   *       }]\n   *     },\n   *     {\n   *       nodeType: BLOCKS.LIST_ITEM,\n   *       data: {},\n   *       content: [{\n   *         nodeType: BLOCKS.HR,\n   *         data: {},\n   *         content: [],\n   *       }]\n   *     },\n   *     {\n   *       nodeType: BLOCKS.LIST_ITEM,\n   *       data: {},\n   *       content: [{\n   *         nodeType: BLOCKS.PARAGRAPH,\n   *         data:\n   *         content: [\n   *           { nodeType: 'text', data: {}, value: 'Yet another list item', marks: [] }\n   *         ]\n   *       }]\n   *     },\n   *   }]\n   * }\n   *\n   * We want there to be a space between 'List item' and 'Another list item' (to\n   * denote a visual line break, which conventionally appears between non-text\n   * node sequences) but not a redundant space between 'List ' and 'item'.\n   * Moreover, we want just a _singular_ space between 'Another list item' and\n   * 'Yet another list item' - the non-semantic HR between the two nodes should\n   * not denote an additional space.\n   */\n  return (rootNode as Block).content.reduce((acc: string, node: Node, i: number): string => {\n    let nodeTextValue: string;\n\n    if (helpers.isText(node)) {\n      nodeTextValue = node.value;\n    } else if (helpers.isBlock(node) || helpers.isInline(node)) {\n      nodeTextValue = documentToPlainTextString(node, blockDivisor);\n      if (!nodeTextValue.length) {\n        return acc;\n      }\n    }\n\n    const nextNode = rootNode.content[i + 1];\n    const isNextNodeBlock = nextNode && helpers.isBlock(nextNode);\n    const divisor = isNextNodeBlock ? blockDivisor : '';\n    return acc + nodeTextValue + divisor;\n  }, '');\n}\n", "\"use strict\";\nif (0) {\n  // Trick cjs-module-lexer into adding named exports for all React exports.\n  // (if imported with `import()`, they will appear in `.default` as well.)\n  // This way, cjs-module-lexer will let all of react's (named) exports through unchanged.\n  module.exports = require(\"react\");\n}\n// We don't want bundlers to error when they encounter usage of any of these exports.\n// It's up to the package author to ensure that if they access React internals,\n// they do so in a safe way that won't break if React changes how they use these internals.\n// (e.g. only access them in development, and only in an optional way that won't\n// break if internals are not there or do not have the expected structure)\n// @ts-ignore\nmodule.exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = undefined;\n// @ts-ignore\nmodule.exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = undefined;\n// @ts-ignore\nmodule.exports.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = undefined;\n// Here we actually pull in the React library and add everything\n// it exports to our own `module.exports`.\n// If React suddenly were to add one of the above \"polyfilled\" exports,\n// the React version would overwrite our version, so this should be\n// future-proof.\nObject.assign(module.exports, require(\"react\"));\n", "// Save global object in a variable\nvar __global__ =\n(typeof globalThis !== 'undefined' && globalThis) ||\n(typeof self !== 'undefined' && self) ||\n(typeof global !== 'undefined' && global);\n// Create an object that extends from __global__ without the fetch function\nvar __globalThis__ = (function () {\nfunction F() {\nthis.fetch = false;\nthis.DOMException = __global__.DOMException\n}\nF.prototype = __global__; // Needed for feature detection on whatwg-fetch's code\nreturn new F();\n})();\n// Wraps whatwg-fetch with a function scope to hijack the global object\n// \"globalThis\" that's going to be patched\n(function(globalThis) {\n\nvar irrelevant = (function (exports) {\n\n  var global =\n    (typeof globalThis !== 'undefined' && globalThis) ||\n    (typeof self !== 'undefined' && self) ||\n    (typeof global !== 'undefined' && global);\n\n  var support = {\n    searchParams: 'URLSearchParams' in global,\n    iterable: 'Symbol' in global && 'iterator' in Symbol,\n    blob:\n      'FileReader' in global &&\n      'Blob' in global &&\n      (function() {\n        try {\n          new Blob();\n          return true\n        } catch (e) {\n          return false\n        }\n      })(),\n    formData: 'FormData' in global,\n    arrayBuffer: 'ArrayBuffer' in global\n  };\n\n  function isDataView(obj) {\n    return obj && DataView.prototype.isPrototypeOf(obj)\n  }\n\n  if (support.arrayBuffer) {\n    var viewClasses = [\n      '[object Int8Array]',\n      '[object Uint8Array]',\n      '[object Uint8ClampedArray]',\n      '[object Int16Array]',\n      '[object Uint16Array]',\n      '[object Int32Array]',\n      '[object Uint32Array]',\n      '[object Float32Array]',\n      '[object Float64Array]'\n    ];\n\n    var isArrayBufferView =\n      ArrayBuffer.isView ||\n      function(obj) {\n        return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n      };\n  }\n\n  function normalizeName(name) {\n    if (typeof name !== 'string') {\n      name = String(name);\n    }\n    if (/[^a-z0-9\\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {\n      throw new TypeError('Invalid character in header field name: \"' + name + '\"')\n    }\n    return name.toLowerCase()\n  }\n\n  function normalizeValue(value) {\n    if (typeof value !== 'string') {\n      value = String(value);\n    }\n    return value\n  }\n\n  // Build a destructive iterator for the value list\n  function iteratorFor(items) {\n    var iterator = {\n      next: function() {\n        var value = items.shift();\n        return {done: value === undefined, value: value}\n      }\n    };\n\n    if (support.iterable) {\n      iterator[Symbol.iterator] = function() {\n        return iterator\n      };\n    }\n\n    return iterator\n  }\n\n  function Headers(headers) {\n    this.map = {};\n\n    if (headers instanceof Headers) {\n      headers.forEach(function(value, name) {\n        this.append(name, value);\n      }, this);\n    } else if (Array.isArray(headers)) {\n      headers.forEach(function(header) {\n        this.append(header[0], header[1]);\n      }, this);\n    } else if (headers) {\n      Object.getOwnPropertyNames(headers).forEach(function(name) {\n        this.append(name, headers[name]);\n      }, this);\n    }\n  }\n\n  Headers.prototype.append = function(name, value) {\n    name = normalizeName(name);\n    value = normalizeValue(value);\n    var oldValue = this.map[name];\n    this.map[name] = oldValue ? oldValue + ', ' + value : value;\n  };\n\n  Headers.prototype['delete'] = function(name) {\n    delete this.map[normalizeName(name)];\n  };\n\n  Headers.prototype.get = function(name) {\n    name = normalizeName(name);\n    return this.has(name) ? this.map[name] : null\n  };\n\n  Headers.prototype.has = function(name) {\n    return this.map.hasOwnProperty(normalizeName(name))\n  };\n\n  Headers.prototype.set = function(name, value) {\n    this.map[normalizeName(name)] = normalizeValue(value);\n  };\n\n  Headers.prototype.forEach = function(callback, thisArg) {\n    for (var name in this.map) {\n      if (this.map.hasOwnProperty(name)) {\n        callback.call(thisArg, this.map[name], name, this);\n      }\n    }\n  };\n\n  Headers.prototype.keys = function() {\n    var items = [];\n    this.forEach(function(value, name) {\n      items.push(name);\n    });\n    return iteratorFor(items)\n  };\n\n  Headers.prototype.values = function() {\n    var items = [];\n    this.forEach(function(value) {\n      items.push(value);\n    });\n    return iteratorFor(items)\n  };\n\n  Headers.prototype.entries = function() {\n    var items = [];\n    this.forEach(function(value, name) {\n      items.push([name, value]);\n    });\n    return iteratorFor(items)\n  };\n\n  if (support.iterable) {\n    Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n  }\n\n  function consumed(body) {\n    if (body.bodyUsed) {\n      return Promise.reject(new TypeError('Already read'))\n    }\n    body.bodyUsed = true;\n  }\n\n  function fileReaderReady(reader) {\n    return new Promise(function(resolve, reject) {\n      reader.onload = function() {\n        resolve(reader.result);\n      };\n      reader.onerror = function() {\n        reject(reader.error);\n      };\n    })\n  }\n\n  function readBlobAsArrayBuffer(blob) {\n    var reader = new FileReader();\n    var promise = fileReaderReady(reader);\n    reader.readAsArrayBuffer(blob);\n    return promise\n  }\n\n  function readBlobAsText(blob) {\n    var reader = new FileReader();\n    var promise = fileReaderReady(reader);\n    reader.readAsText(blob);\n    return promise\n  }\n\n  function readArrayBufferAsText(buf) {\n    var view = new Uint8Array(buf);\n    var chars = new Array(view.length);\n\n    for (var i = 0; i < view.length; i++) {\n      chars[i] = String.fromCharCode(view[i]);\n    }\n    return chars.join('')\n  }\n\n  function bufferClone(buf) {\n    if (buf.slice) {\n      return buf.slice(0)\n    } else {\n      var view = new Uint8Array(buf.byteLength);\n      view.set(new Uint8Array(buf));\n      return view.buffer\n    }\n  }\n\n  function Body() {\n    this.bodyUsed = false;\n\n    this._initBody = function(body) {\n      /*\n        fetch-mock wraps the Response object in an ES6 Proxy to\n        provide useful test harness features such as flush. However, on\n        ES5 browsers without fetch or Proxy support pollyfills must be used;\n        the proxy-pollyfill is unable to proxy an attribute unless it exists\n        on the object before the Proxy is created. This change ensures\n        Response.bodyUsed exists on the instance, while maintaining the\n        semantic of setting Request.bodyUsed in the constructor before\n        _initBody is called.\n      */\n      this.bodyUsed = this.bodyUsed;\n      this._bodyInit = body;\n      if (!body) {\n        this._bodyText = '';\n      } else if (typeof body === 'string') {\n        this._bodyText = body;\n      } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n        this._bodyBlob = body;\n      } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n        this._bodyFormData = body;\n      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n        this._bodyText = body.toString();\n      } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n        this._bodyArrayBuffer = bufferClone(body.buffer);\n        // IE 10-11 can't handle a DataView body.\n        this._bodyInit = new Blob([this._bodyArrayBuffer]);\n      } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n        this._bodyArrayBuffer = bufferClone(body);\n      } else {\n        this._bodyText = body = Object.prototype.toString.call(body);\n      }\n\n      if (!this.headers.get('content-type')) {\n        if (typeof body === 'string') {\n          this.headers.set('content-type', 'text/plain;charset=UTF-8');\n        } else if (this._bodyBlob && this._bodyBlob.type) {\n          this.headers.set('content-type', this._bodyBlob.type);\n        } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n          this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n        }\n      }\n    };\n\n    if (support.blob) {\n      this.blob = function() {\n        var rejected = consumed(this);\n        if (rejected) {\n          return rejected\n        }\n\n        if (this._bodyBlob) {\n          return Promise.resolve(this._bodyBlob)\n        } else if (this._bodyArrayBuffer) {\n          return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n        } else if (this._bodyFormData) {\n          throw new Error('could not read FormData body as blob')\n        } else {\n          return Promise.resolve(new Blob([this._bodyText]))\n        }\n      };\n\n      this.arrayBuffer = function() {\n        if (this._bodyArrayBuffer) {\n          var isConsumed = consumed(this);\n          if (isConsumed) {\n            return isConsumed\n          }\n          if (ArrayBuffer.isView(this._bodyArrayBuffer)) {\n            return Promise.resolve(\n              this._bodyArrayBuffer.buffer.slice(\n                this._bodyArrayBuffer.byteOffset,\n                this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength\n              )\n            )\n          } else {\n            return Promise.resolve(this._bodyArrayBuffer)\n          }\n        } else {\n          return this.blob().then(readBlobAsArrayBuffer)\n        }\n      };\n    }\n\n    this.text = function() {\n      var rejected = consumed(this);\n      if (rejected) {\n        return rejected\n      }\n\n      if (this._bodyBlob) {\n        return readBlobAsText(this._bodyBlob)\n      } else if (this._bodyArrayBuffer) {\n        return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n      } else if (this._bodyFormData) {\n        throw new Error('could not read FormData body as text')\n      } else {\n        return Promise.resolve(this._bodyText)\n      }\n    };\n\n    if (support.formData) {\n      this.formData = function() {\n        return this.text().then(decode)\n      };\n    }\n\n    this.json = function() {\n      return this.text().then(JSON.parse)\n    };\n\n    return this\n  }\n\n  // HTTP methods whose capitalization should be normalized\n  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n  function normalizeMethod(method) {\n    var upcased = method.toUpperCase();\n    return methods.indexOf(upcased) > -1 ? upcased : method\n  }\n\n  function Request(input, options) {\n    if (!(this instanceof Request)) {\n      throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n    }\n\n    options = options || {};\n    var body = options.body;\n\n    if (input instanceof Request) {\n      if (input.bodyUsed) {\n        throw new TypeError('Already read')\n      }\n      this.url = input.url;\n      this.credentials = input.credentials;\n      if (!options.headers) {\n        this.headers = new Headers(input.headers);\n      }\n      this.method = input.method;\n      this.mode = input.mode;\n      this.signal = input.signal;\n      if (!body && input._bodyInit != null) {\n        body = input._bodyInit;\n        input.bodyUsed = true;\n      }\n    } else {\n      this.url = String(input);\n    }\n\n    this.credentials = options.credentials || this.credentials || 'same-origin';\n    if (options.headers || !this.headers) {\n      this.headers = new Headers(options.headers);\n    }\n    this.method = normalizeMethod(options.method || this.method || 'GET');\n    this.mode = options.mode || this.mode || null;\n    this.signal = options.signal || this.signal;\n    this.referrer = null;\n\n    if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n      throw new TypeError('Body not allowed for GET or HEAD requests')\n    }\n    this._initBody(body);\n\n    if (this.method === 'GET' || this.method === 'HEAD') {\n      if (options.cache === 'no-store' || options.cache === 'no-cache') {\n        // Search for a '_' parameter in the query string\n        var reParamSearch = /([?&])_=[^&]*/;\n        if (reParamSearch.test(this.url)) {\n          // If it already exists then set the value with the current time\n          this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime());\n        } else {\n          // Otherwise add a new '_' parameter to the end with the current time\n          var reQueryString = /\\?/;\n          this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime();\n        }\n      }\n    }\n  }\n\n  Request.prototype.clone = function() {\n    return new Request(this, {body: this._bodyInit})\n  };\n\n  function decode(body) {\n    var form = new FormData();\n    body\n      .trim()\n      .split('&')\n      .forEach(function(bytes) {\n        if (bytes) {\n          var split = bytes.split('=');\n          var name = split.shift().replace(/\\+/g, ' ');\n          var value = split.join('=').replace(/\\+/g, ' ');\n          form.append(decodeURIComponent(name), decodeURIComponent(value));\n        }\n      });\n    return form\n  }\n\n  function parseHeaders(rawHeaders) {\n    var headers = new Headers();\n    // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n    // https://tools.ietf.org/html/rfc7230#section-3.2\n    var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n    // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill\n    // https://github.com/github/fetch/issues/748\n    // https://github.com/zloirock/core-js/issues/751\n    preProcessedHeaders\n      .split('\\r')\n      .map(function(header) {\n        return header.indexOf('\\n') === 0 ? header.substr(1, header.length) : header\n      })\n      .forEach(function(line) {\n        var parts = line.split(':');\n        var key = parts.shift().trim();\n        if (key) {\n          var value = parts.join(':').trim();\n          headers.append(key, value);\n        }\n      });\n    return headers\n  }\n\n  Body.call(Request.prototype);\n\n  function Response(bodyInit, options) {\n    if (!(this instanceof Response)) {\n      throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n    }\n    if (!options) {\n      options = {};\n    }\n\n    this.type = 'default';\n    this.status = options.status === undefined ? 200 : options.status;\n    this.ok = this.status >= 200 && this.status < 300;\n    this.statusText = options.statusText === undefined ? '' : '' + options.statusText;\n    this.headers = new Headers(options.headers);\n    this.url = options.url || '';\n    this._initBody(bodyInit);\n  }\n\n  Body.call(Response.prototype);\n\n  Response.prototype.clone = function() {\n    return new Response(this._bodyInit, {\n      status: this.status,\n      statusText: this.statusText,\n      headers: new Headers(this.headers),\n      url: this.url\n    })\n  };\n\n  Response.error = function() {\n    var response = new Response(null, {status: 0, statusText: ''});\n    response.type = 'error';\n    return response\n  };\n\n  var redirectStatuses = [301, 302, 303, 307, 308];\n\n  Response.redirect = function(url, status) {\n    if (redirectStatuses.indexOf(status) === -1) {\n      throw new RangeError('Invalid status code')\n    }\n\n    return new Response(null, {status: status, headers: {location: url}})\n  };\n\n  exports.DOMException = global.DOMException;\n  try {\n    new exports.DOMException();\n  } catch (err) {\n    exports.DOMException = function(message, name) {\n      this.message = message;\n      this.name = name;\n      var error = Error(message);\n      this.stack = error.stack;\n    };\n    exports.DOMException.prototype = Object.create(Error.prototype);\n    exports.DOMException.prototype.constructor = exports.DOMException;\n  }\n\n  function fetch(input, init) {\n    return new Promise(function(resolve, reject) {\n      var request = new Request(input, init);\n\n      if (request.signal && request.signal.aborted) {\n        return reject(new exports.DOMException('Aborted', 'AbortError'))\n      }\n\n      var xhr = new XMLHttpRequest();\n\n      function abortXhr() {\n        xhr.abort();\n      }\n\n      xhr.onload = function() {\n        var options = {\n          status: xhr.status,\n          statusText: xhr.statusText,\n          headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n        };\n        options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n        var body = 'response' in xhr ? xhr.response : xhr.responseText;\n        setTimeout(function() {\n          resolve(new Response(body, options));\n        }, 0);\n      };\n\n      xhr.onerror = function() {\n        setTimeout(function() {\n          reject(new TypeError('Network request failed'));\n        }, 0);\n      };\n\n      xhr.ontimeout = function() {\n        setTimeout(function() {\n          reject(new TypeError('Network request failed'));\n        }, 0);\n      };\n\n      xhr.onabort = function() {\n        setTimeout(function() {\n          reject(new exports.DOMException('Aborted', 'AbortError'));\n        }, 0);\n      };\n\n      function fixUrl(url) {\n        try {\n          return url === '' && global.location.href ? global.location.href : url\n        } catch (e) {\n          return url\n        }\n      }\n\n      xhr.open(request.method, fixUrl(request.url), true);\n\n      if (request.credentials === 'include') {\n        xhr.withCredentials = true;\n      } else if (request.credentials === 'omit') {\n        xhr.withCredentials = false;\n      }\n\n      if ('responseType' in xhr) {\n        if (support.blob) {\n          xhr.responseType = 'blob';\n        } else if (\n          support.arrayBuffer &&\n          request.headers.get('Content-Type') &&\n          request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1\n        ) {\n          xhr.responseType = 'arraybuffer';\n        }\n      }\n\n      if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) {\n        Object.getOwnPropertyNames(init.headers).forEach(function(name) {\n          xhr.setRequestHeader(name, normalizeValue(init.headers[name]));\n        });\n      } else {\n        request.headers.forEach(function(value, name) {\n          xhr.setRequestHeader(name, value);\n        });\n      }\n\n      if (request.signal) {\n        request.signal.addEventListener('abort', abortXhr);\n\n        xhr.onreadystatechange = function() {\n          // DONE (success or failure)\n          if (xhr.readyState === 4) {\n            request.signal.removeEventListener('abort', abortXhr);\n          }\n        };\n      }\n\n      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n    })\n  }\n\n  fetch.polyfill = true;\n\n  if (!global.fetch) {\n    global.fetch = fetch;\n    global.Headers = Headers;\n    global.Request = Request;\n    global.Response = Response;\n  }\n\n  exports.Headers = Headers;\n  exports.Request = Request;\n  exports.Response = Response;\n  exports.fetch = fetch;\n\n  return exports;\n\n})({});\n})(__globalThis__);\n// This is a ponyfill, so...\n__globalThis__.fetch.ponyfill = true;\ndelete __globalThis__.fetch.polyfill;\n// Choose between native implementation (__global__) or custom implementation (__globalThis__)\nvar ctx = __global__.fetch ? __global__ : __globalThis__;\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n", "/**\n * Keys in the local storage that we set on a browser.\n *\n * These have to be CRAFTED because the data that's stored in them HAS NO EXPIRATION TIME. I.e. it's\n * important to not be too generic with words like \"key\" or \"array\", or get very specific with\n * applications like \"sps-2023-foo\" to make sure the same values aren't reused in 2024.\n */\nconst localStorageKeys = [\n  'mwp-shopify-cart', // Items in the shopify cart for websites with ecommerce\n  'mwp-snapkit-user-id', // SnapKit user id for SPS bitmoji reactions\n  'mwp-snapkit-access-token', // Snapkit access token for SPS bitmoji reactions\n  'sps-2023-firstName', // Stored first name of a person who's registered for SPS 2023\n  'sps-2023-registrationStatus', // Registration status for someone who's registered for SPS 2023\n  'sps-2023-interests', // Recorded interests for someone who's registeredf or SPS 2023\n  'sps-2024-firstName', // Stored first name of a person who's registered for SPS 2024\n  'sps-2024-registrationStatus', // Registration status for someone who's registered for SPS 2024\n  'sps-2024-interests', // Recorded interests for someone who's registered for SPS 2024\n  'experience-registration', // Registration data for experience site\n  'mwp-form-data', // Form data for MWP forms\n  'mwp-custom-motif', // When using custom debug mode to upload a motif from figma tokens\n  'templates-note-dismissed', // Dismissed state for contentful-app templates note\n] as const;\n\ntype LocalStorageKey = (typeof localStorageKeys)[number];\n\n/** Sets the local storage value for a given key. Type safe. */\nexport function setLocalStorageItem(key: LocalStorageKey, value: string): void {\n  // eslint-disable-next-line no-restricted-syntax\n  localStorage?.setItem(key, value);\n}\n\n/** Retrieves the local storage value for a given key. Type safe. */\nexport function getLocalStorageItem(key: LocalStorageKey): string | null {\n  // eslint-disable-next-line no-restricted-syntax\n  return localStorage?.getItem(key) ?? null;\n}\n\n/** Removes an item from local storage for a given key. Type safe. */\nexport function removeLocalStorageItem(key: LocalStorageKey): void {\n  // eslint-disable-next-line no-restricted-syntax\n  localStorage?.removeItem(key);\n}\n", "/**\n * A list of brands that we support on MWP.\n *\n * Shared to avoid other packages from maintaining separate lists.\n */\nexport enum Brand {\n  SNAP = 'snap',\n  SNAPCHAT = 'snapchat',\n  SPECTACLES = 'spectacles',\n}\n\nexport const brandNames: Record<Brand, string> = {\n  [Brand.SNAP]: 'Snap',\n  [Brand.SNAPCHAT]: 'Snapchat',\n  [Brand.SPECTACLES]: 'Spectacles',\n};\n\nexport const allBrands = [Brand.SNAP, Brand.SNAPCHAT, Brand.SPECTACLES] as const;\n", "import type { Site } from './sites';\n\n/** Returns elastic search index for the SEARCH functionality. */\nexport const getElasticSearchAliasName = (\n  site: Site,\n  environmentId: string,\n  isPreview: boolean,\n  prefix?: string\n): string => {\n  const suffix = isPreview ? 'staging' : 'production';\n\n  const baseName = `search_${site}_${environmentId}_${suffix}`;\n\n  if (prefix) {\n    return `${prefix}_${baseName}`;\n  }\n\n  return baseName;\n};\n\n/** Elastic Alias for the JOBS functionality */\nexport const elasticJobsAliasName = 'jobs_production';\n/** Development Elastic Alias for the JOBS functionality */\nexport const elasticJobsAliasNameDev = 'dev_jobs';\n/** Elastic index prefix for the jobs indexes. */\nexport const elasticJobsIndexPrefix = 'jobs_';\n\n/** Returns elastic search index for the GALLERY functionality */\nexport const getElasticGalleryAliasName = (\n  site: Site,\n  environmentId: string,\n  isPreview: boolean\n): string => {\n  const stagingOrProduction = isPreview ? 'staging' : 'production';\n  return `gallery_${site}_${environmentId}_${stagingOrProduction}`;\n};\n\n/** Serverless Elastic Staging Cloud ID (single source of truth for MWP packages). */\nexport const stagingElasticCloudId =\n  'mwp-serverless-elastic-staging:dXMtY2VudHJhbDEuZ2NwLmVsYXN0aWMuY2xvdWQkZGU5Y2UwMGNkNjNjNDEwYjkxN2Q3YWQ4ZjJiMTlkY2YuZXMkZGU5Y2UwMGNkNjNjNDEwYjkxN2Q3YWQ4ZjJiMTlkY2Yua2I=';\n\n/** Serverless Elastic Production Cloud ID. */\nexport const productionElasticCloudId =\n  'mwp-serverless-elastic-prod:dXMtY2VudHJhbDEuZ2NwLmVsYXN0aWMuY2xvdWQkYjM5N2NhYmFjNzNmNDNhOGE3YjZiZjRkZjU2MzgyZmYuZXMkYjM5N2NhYmFjNzNmNDNhOGE3YjZiZjRkZjU2MzgyZmYua2I=';\n\n/** Serverless Elastic Staging node URL. */\nexport const stagingElasticNode =\n  'https://mwp-serverless-elastic-staging-de9ce0.es.us-central1.gcp.elastic.cloud:443';\n\n/** Serverless Elastic Production node URL. */\nexport const productionElasticNode =\n  'https://mwp-serverless-elastic-prod-b397ca.es.us-central1.gcp.elastic.cloud:443';\n", "import { omit } from 'radashi';\n\nimport { Site } from './sites';\n\n/**\n * Definitive list of ga4 properties used by Marketing Web Platform.\n *\n * You can view a property by going to https://analytics.google.com/analytics/web/#/p<propertyId>\n *\n * Our policy is that every new site has a GA4 property, so you have to create one and add it to the\n * list when creating a site.\n */\nexport const googleAnalytics4Properties: Record<Site, number> = {\n  [Site.A523]: 292694174,\n  [Site.AR]: 265216064,\n  [Site.ARCADIA]: 287858207,\n  [Site.AVALON]: 327898756,\n  [Site.CAREERS]: 327730352,\n  [Site.CHEERIOS]: 327913877,\n  [Site.CITIZEN]: 327822562,\n  [Site.CREATORS]: 284037488,\n  [Site.DIVERSITY]: 327894680,\n  [Site.EDUCATORS]: 446196364,\n  [Site.ENG_BLOG]: 327879893,\n  [Site.EXPERIENCE]: 430935078,\n  [Site.FOR_BUSINESS]: 272999138,\n  [Site.NEWSROOM]: 327160579,\n  [Site.PARENTS]: 402936625,\n  [Site.SANDBOX]: 358873651,\n  [Site.TRUST]: 338421395,\n  [Site.SNAP]: 327913881,\n  [Site.STINSON]: 519909446,\n};\n\n/** List of MWP GA4 properties that receive production traffic. */\n// Remove Site.STINSON once Stinson has GA4 data so the release tests don't fail\n// https://jira.sc-corp.net/browse/WEBP-13714\nexport const productionMwpGa4Properties = omit(googleAnalytics4Properties, [\n  Site.SANDBOX,\n  Site.STINSON,\n]);\n", "/**\n * These are the ISO-3166 Alpha-2 codes for the countries in the GDPR region.\n *\n * The 'unknown country' code of ZZ is also included to default to showing the popup when the exact\n * country cannot be determined.\n */\nexport const gdprCountries = new Set([\n  'AT', // Austria\n  'BE', // Belgium\n  'BG', // Bulgaria\n  'CY', // Cyprus\n  'CZ', // Czechia\n  'DE', // Germany\n  'DK', // Denmark\n  'EE', // Estonia\n  'ES', // Spain\n  'FI', // Finland\n  'FR', // France\n  'GB', // Great Britain\n  'GR', // Greece\n  'HR', // Croatia\n  'HU', // Hungary\n  'IE', // Ireland\n  'IS', // Iceland\n  'IT', // Italy\n  'LI', // Liechtenstein\n  'LT', // Lithuania\n  'LU', // Luxembourg\n  'LV', // Latvia\n  'MT', // Malta\n  'NL', // Netherlands\n  'NO', // Norway\n  'PL', // Poland\n  'PT', // Portugal\n  'RO', // Romania\n  'SE', // Sweden\n  'SI', // Slovenia\n  'SK', // Slovakia\n  'ZZ', // Unknown\n]);\n", "/**\n * Maps a locale code to its native title\n *\n * Values are adopted from https://www.npmjs.com/package/langmap npm package and modified as needed.\n *\n * Note that this is the comprehensive list of locales supported by Web Platform regardless of any\n * l10n documentation. This is on purpose and this list IS the source of truth.\n */\nexport const localeMap: Record<string, string> = {\n  ar: '\u0627\u0644\u0639\u0631\u0628\u064A\u0629',\n  'bn-BD': '\u09AC\u09BE\u0982\u09B2\u09BE (\u09AC\u09BE\u0982\u09B2\u09BE\u09A6\u09C7\u09B6)',\n  'bn-IN': '\u09AC\u09BE\u0982\u09B2\u09BE (\u09AD\u09BE\u09B0\u09A4)',\n  'bg-BG': '\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438',\n  'zh-Hans': '\u4E2D\u6587\u7B80\u4F53',\n  'zh-Hant': '\u4E2D\u6587\u7E41\u9AD4',\n  'hr-HR': 'Hrvatski',\n  'cs-CZ': '\u010Ce\u0161tina',\n  'da-DK': 'Dansk',\n  'nl-NL': 'Nederlands (Nederland)',\n  'en-GB': 'English (UK)',\n  'en-US': 'English (US)',\n  'et-EE': 'Eesti',\n  'fil-PH': 'Filipino',\n  'fi-FI': 'Suomi',\n  'fr-FR': 'Fran\u00E7ais (France)',\n  'de-DE': 'Deutsch (Deutschland)',\n  'el-GR': '\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC',\n  'gu-IN': '\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0',\n  'hi-IN': '\u0939\u093F\u0928\u094D\u0926\u0940',\n  'hu-HU': 'Magyar',\n  'id-ID': 'Bahasa Indonesia',\n  'ga-IE': '\u00C9ireannach',\n  'it-IT': 'Italiano',\n  'ja-JP': '\u65E5\u672C\u8A9E',\n  'kn-IN': '\u0C95\u0CA8\u0CCD\u0CA8\u0CA1 (India)',\n  'ko-KR': '\uD55C\uAD6D\uC5B4',\n  'lv-LV': 'Latvie\u0161u',\n  'lt-LT': 'Lietuvi\u0173',\n  'ms-MY': 'Bahasa Melayu',\n  'ml-IN': '\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02',\n  'mt-MT': 'Malti',\n  'mr-IN': '\u092E\u0930\u093E\u0920\u0940',\n  'nb-NO': 'Norsk (bokm\u00E5l)',\n  'pl-PL': 'Polski',\n  'pt-BR': 'Portugu\u00EAs (Brasil)',\n  'pt-PT': 'Portugu\u00EAs (Portugal)',\n  pa: '\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40',\n  'ro-RO': 'Rom\u00E2n\u0103',\n  'ru-RU': '\u0420\u0443\u0441\u0441\u043A\u0438\u0439',\n  'sk-SK': 'Sloven\u010Dina',\n  'sl-SI': 'Sloven\u0161\u010Dina',\n  'es-AR': 'Espa\u00F1ol (Argentina)',\n  es: 'Espa\u00F1ol',\n  'es-MX': 'Espa\u00F1ol (M\u00E9xico)',\n  'es-ES': 'Espa\u00F1ol (Espa\u00F1a)',\n  'sv-SE': 'Svenska',\n  'ta-IN': '\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD',\n  'te-IN': '\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41',\n  'th-TH': '\u0E20\u0E32\u0E29\u0E32\u0E44\u0E17\u0E22 (\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28\u0E44\u0E17\u0E22)',\n  'tr-TR': 'T\u00FCrk\u00E7e',\n  'ur-PK': '\u0627\u0631\u062F\u0648',\n  'uk-UA': '\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430',\n  'vi-VN': 'Ti\u1EBFng Vi\u1EC7t',\n};\n", "// ============================================================================\n// Timeouts\n// ============================================================================\n\n/** Total server side response timeout in milliseconds */\nexport const connectionTimeoutMs = 30e3;\n\n/** Total sever side response timeout in seconds. */\nexport const connectionTimeoutS = Math.ceil(connectionTimeoutMs / 1e3);\n\n/**\n * Number of retries that are allowed for contentful.\n *\n * NOTE: 2023-07-07 We're changing this from 2 to 4 so that we can decrease the contentful request\n * timeout from ~11 seconds to ~6 seconds. This allows us to have green SLAs in a scenario where the\n * first request is slow and subsequent requests are fast. This way a 6 second + timeout, followed\n * by a <1s working query + a few more queries can return in under 10 seconds, which is our cutoff\n * for the uptime check to be considered a failure.\n */\nexport const contentfulRetryCount = 4;\n\n/**\n * Web SSR request to contentful timeout. This is set to fit the number of contentfulRetryCount\n * attempts in a single server side request. There's a little headroom added for other requests.\n * I.e. this only works if there's a single slow contentful request that can can be retried and even\n * if it fails contentfulRetryCount times SSR fails but we return a 200 code to let the client side\n * render the page.\n */\nexport const contentfulRequestTimeoutMs = Math.round(\n  (connectionTimeoutMs / contentfulRetryCount) * 0.75\n);\n", "import { Site } from './sites';\n\nexport const productionDomains: Record<Site, string> = {\n  [Site.A523]: '523.snap.com',\n  [Site.AR]: 'ar.snap.com',\n  [Site.ARCADIA]: 'www.arcadiacreativestudio.com',\n  [Site.AVALON]: 'www.spectacles.com',\n  [Site.CAREERS]: 'careers.snap.com',\n  [Site.CHEERIOS]: 'www.pixy.com',\n  [Site.CITIZEN]: 'citizen.snap.com',\n  [Site.CREATORS]: 'creators.snapchat.com',\n  [Site.DIVERSITY]: 'belonging.snap.com',\n  [Site.EDUCATORS]: 'educators.snapchat.com',\n  [Site.ENG_BLOG]: 'eng.snap.com',\n  [Site.EXPERIENCE]: 'experience.snap.com',\n  [Site.FOR_BUSINESS]: 'forbusiness.snapchat.com',\n  [Site.NEWSROOM]: 'newsroom.snap.com',\n  [Site.PARENTS]: 'parents.snapchat.com',\n  [Site.SANDBOX]: 'sandbox-production-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.SNAP]: 'www.snap.com',\n  [Site.TRUST]: 'values.snap.com',\n  [Site.STINSON]: 'www.specs.com',\n};\n", "import { Brand } from './brands';\nimport { Site } from './sites';\n\nexport const SitesToBrands: Record<Site, Brand | undefined> = {\n  [Site.A523]: Brand.SNAPCHAT,\n  [Site.AR]: Brand.SNAPCHAT,\n  [Site.CAREERS]: Brand.SNAPCHAT,\n  [Site.CITIZEN]: Brand.SNAPCHAT,\n  [Site.CREATORS]: Brand.SNAPCHAT,\n  [Site.DIVERSITY]: Brand.SNAPCHAT,\n  [Site.EDUCATORS]: Brand.SNAPCHAT,\n  [Site.ENG_BLOG]: Brand.SNAPCHAT,\n  [Site.EXPERIENCE]: Brand.SNAPCHAT,\n  [Site.FOR_BUSINESS]: Brand.SNAPCHAT,\n  [Site.NEWSROOM]: Brand.SNAPCHAT,\n  [Site.PARENTS]: Brand.SNAPCHAT,\n  [Site.SANDBOX]: Brand.SNAPCHAT,\n  [Site.TRUST]: Brand.SNAPCHAT,\n  [Site.AVALON]: Brand.SPECTACLES,\n  [Site.SNAP]: Brand.SNAP,\n  [Site.ARCADIA]: undefined,\n  [Site.CHEERIOS]: undefined,\n  [Site.STINSON]: undefined,\n};\n", "import { Site } from './sites';\n\nexport const stagingDomains: Record<Site, string> = {\n  [Site.A523]: 'https://snap-523-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.ARCADIA]: 'https://arcadia-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.AR]: 'https://snap-ar-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.CAREERS]: 'https://careers-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.CHEERIOS]: 'https://cheerios-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.CITIZEN]: 'https://citizen-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.CREATORS]: 'https://creators-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.DIVERSITY]: 'https://diversity-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.ENG_BLOG]: 'https://eng-blog-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.EXPERIENCE]: 'https://experience-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.FOR_BUSINESS]: 'https://for-business-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.NEWSROOM]: 'https://newsroom-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.PARENTS]: 'https://parents-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.SANDBOX]: 'https://sandbox-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.TRUST]: 'https://trust-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.AVALON]: 'https://avalon-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.EDUCATORS]: 'https://educators-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.SNAP]: 'https://snap-staging-dot-entapps-web-dev.gae.sc-corp.net',\n  [Site.STINSON]: 'https://stinson-staging-dot-entapps-web-dev.gae.sc-corp.net',\n};\n", "import type { GeoLocation } from './geoHeaderTypes';\n\n/** See 'unknown' country code here: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 */\nexport const defaultCountryCode = 'ZZ';\n\n/** By convention using this value. */\nexport const defaultStateCode = 'na';\n\nexport const defaultGeo: GeoLocation = {\n  country: defaultCountryCode,\n  region: defaultStateCode,\n  regionSubdivision: `${defaultCountryCode}${defaultStateCode}`.toUpperCase(),\n};\n\n/** Parses the Google Cloud Load Balancer Geo headers into {@link GeoLocation} format. */\nexport function parseGclbGeoHeaders(regionHeader: string, subdivisionHeader: string): GeoLocation {\n  const country = regionHeader; // Upper-cased like US or CA\n  const regionSubdivision = subdivisionHeader; // Upper-cased like USCA or CAQC\n  const region = regionSubdivision.replace(country, '').toLocaleLowerCase();\n  return {\n    country,\n    region,\n    regionSubdivision,\n  };\n}\n\n/** Convert header names to lower-case (in case not done already), and discard duplicate headers. */\nexport function cleanGeoHeaders(\n  rawHeaders: Record<string, string | string[] | undefined>\n): Record<string, string | undefined> {\n  return Object.fromEntries(\n    Object.entries(rawHeaders).map(([header, value]) => [\n      header.toLocaleLowerCase(),\n      Array.isArray(value) ? value[value.length - 1] : value,\n    ])\n  );\n}\n\n/**\n * Returns the parsed geo location from the provided headers.\n *\n * Parses in this order:\n *\n * - Snap Geo headers\n * - Forwarded Load Balancer headers\n * - Load Balancer headers\n * - AppEngine headers\n *\n * Note that 'snapGeoHeaderParser' is an argument because the current implementation uses JSPB which\n * is very heavy and uses eval (not appropriate for common code).\n *\n * If no geo headers exist, returns undefined.\n *\n * TODO: Rewrite the parsing from the value using raw wire format. See wire format:\n * https://developers.google.com/protocol-buffers/docs/encoding See proto def:\n * https://github.sc-corp.net/Snapchat/geo-header-api/blob/master/api/v1/geo_header.proto\n */\nexport function parseGeoHeaders(\n  rawHeaders: Record<string, string | string[] | undefined>,\n  snapGeoHeaderParser?: (snapGeoHeader: string) => GeoLocation | undefined\n): GeoLocation | undefined {\n  const headers = cleanGeoHeaders(rawHeaders);\n\n  // 1. First, try to see if we've been forwarded GCLB headers from API Gateway.\n  if (headers['x-gcp-client-region'] && headers['x-gcp-client-subdivision']) {\n    return parseGclbGeoHeaders(headers['x-gcp-client-region'], headers['x-gcp-client-subdivision']);\n  }\n\n  // 2. Second parse snapchat headers. See https://wiki.sc-corp.net/x/HNWDBQ\n  // These are set by service mesh if our page are being proxied through that.\n  if (headers['x-snap-geo'] && snapGeoHeaderParser) {\n    const snapGeo = snapGeoHeaderParser(headers['x-snap-geo']);\n\n    if (snapGeo) {\n      return snapGeo;\n    }\n  }\n\n  // 3. Then try parse forwarded geo headers from MWP/Snapchat.\n  // These are set when forwarding requests from MWP to cookie service.\n  if (\n    headers['x-sc-forwarded-client-region'] &&\n    headers['x-sc-forwarded-client-region-subdivision']\n  ) {\n    return parseGclbGeoHeaders(\n      headers['x-sc-forwarded-client-region'],\n      headers['x-sc-forwarded-client-region-subdivision']\n    );\n  }\n\n  // 4. Check MWP load balancer headers.\n  // These are set by MWP load balancer. See https://cloud.google.com/load-balancing/docs/https/custom-headers\n  if (headers['x-lb-client-region-subdivision'] && headers['x-lb-client-region']) {\n    return parseGclbGeoHeaders(\n      headers['x-lb-client-region'],\n      headers['x-lb-client-region-subdivision']\n    );\n  }\n\n  // 5. Check AppEngine headers.\n  // These are set by AppEngine.\n  if (headers['x-appengine-country'] && headers['x-appengine-region']) {\n    // Upper-case. But can be '?' when not certain.\n    const country =\n      headers['x-appengine-country'] === '?' ? defaultCountryCode : headers['x-appengine-country'];\n    // lower-case like 'ca' or 'tx'. Can be '?' when not certain.\n    const region =\n      headers['x-appengine-region'] === '?' ? defaultStateCode : headers['x-appengine-region'];\n    const regionSubdivision = `${country}${region}`.toUpperCase();\n    return {\n      country,\n      region,\n      regionSubdivision,\n    };\n  }\n\n  // 5. Return undefined if no headers exist\n  return undefined;\n}\n", "const getTokens = (baseUrl: string, url: string) => {\n  // check if url is a valid asset url\n  if (!url.startsWith(baseUrl)) return {};\n\n  // remove \"base\" from url\n  const withoutBase = url.replace(baseUrl, '');\n\n  // remove trailing file extension\n  const withoutExtension = withoutBase.match(/(.*)\\.[^.]+$/)?.[1];\n\n  // extract tokens\n  const [spaceId, assetId, assetHash, fileName] = withoutExtension?.split('/') ?? [];\n\n  return {\n    spaceId,\n    assetId,\n    assetHash,\n    fileName,\n  };\n};\n\n/**\n * Extracts the space ID, asset ID, asset hash, and file name from an asset URL formatted as follow:\n *\n * https://videos.ctfassets.net/space-id/asset-id/asset-hash/file-name.file-extension\n */\nexport const getTokensFromAssetUrl = (assetUrl: string) =>\n  getTokens('https://videos.ctfassets.net/', assetUrl);\n\n/**\n * Extracts the asset hash from a VOD URL formatted as follow:\n *\n * https://web-platform.snap.com/vod/space-id/asset-id/asset-hash/file-name.m3u8\n */\nexport const getTokensFromVodUrl = (vodUrl: string) =>\n  getTokens('https://web-platform.snap.com/vod/', vodUrl);\n", "import type { Locale } from 'contentful';\nimport { noop } from 'radashi';\nimport type { RefObject } from 'react';\nimport { createContext } from 'react';\n\nimport type { ExperimentBucketData } from './components/Experiment';\nimport type { Personas } from './types/personas';\nimport type { CookieManager } from './utils/cookies/CookieManager';\nimport type { PersonaResponse } from './utils/persona/personaTypes';\nimport type { CreateUuidV4 } from './utils/uuid/uuidFactory';\n\nexport interface UserLocation {\n  country: string;\n  // NOTE: We do not include region here because the location is computed on\n  // the server and is cached in CDN, and adding region here would destroy\n  // the CDN cache hit rate.\n  // If you need to get the region of the user, do it on the client-side only\n  // by fetching https://web-platform.snap.com/cookies/user_location\n}\n\n/**\n * Specific meta about the user that we only compute on the client-side because it's based on things\n * that we aren't able to compute on the server-side because it would destroy the CDN cache hit\n * rate.\n */\nexport interface UserInfo {\n  experimentBucket: ExperimentBucketData;\n}\n\nexport type RedirectOptions = {\n  isPermanent?: boolean;\n  newTab?: boolean;\n};\n\n/**\n * Properties of the AppContext that are passed-in from outside of the App, and are typically\n * different between client and server.\n */\nexport interface PassThroughAppProviderProps {\n  /** Locale in which the app should render in. */\n  currentLocale: string;\n  /** All supported locales that the app can be rendered in. */\n  supportedLocales: Record<string, Locale>;\n  /** The location of the user. */\n  userLocation: UserLocation;\n  getCurrentUrl: () => string;\n  onRedirect?: (location: string, options?: RedirectOptions) => void;\n  cookieManager: CookieManager;\n  createUuidV4: CreateUuidV4;\n  getUserInfo: () => Promise<UserInfo>;\n  getPersona: () => Promise<PersonaResponse>;\n  /** To be used on the server side to tell the client that it has detected an hls video during SSR */\n  onHlsVideo: () => void;\n\n  /**\n   * Custom site data. Used for passing server-rendered info into the app.\n   *\n   * TODO: Deprecate this after SPS 2023.\n   */\n  siteData?: Record<string, unknown>;\n}\n\n/** App Props that can be grabbed from the AppContext. */\nexport interface AppProviderProps extends PassThroughAppProviderProps {\n  isRTL: boolean;\n  /**\n   * Setter for custom site data.\n   *\n   * DO NOT USE. This forces a page re-render. Instead copy this context into another local context\n   * and change the value there.\n   *\n   * TODO: Deprecate this after SPS 2023.\n   */\n  setSiteData: (siteData: Record<string, unknown>) => void;\n  /** Reference for the header portal. */\n  headerPortalRef?: RefObject<HTMLElement>;\n  /** Reference for the sticky portal at the bottom of the <Page />. */\n  pageBottomStickyPortalRef?: RefObject<HTMLElement>;\n  /** Reference for the fixed portal on the <Page />. */\n  pageFixedPortalRef?: RefObject<HTMLElement>;\n  /** Reference for the root level portal right above the footer */\n  appPortalRef?: RefObject<HTMLElement>;\n  /**\n   * Reference to the updated personas. Only needed on client side to set cookies in case personas\n   * are updated after the initial render.\n   */\n  personasRef?: RefObject<Personas | undefined>;\n  /**\n   * Function to update the personas. Only needed on server side to set the APP_STATE value for\n   * personas\n   */\n  updatePersonas?: (personas: Personas) => void;\n}\n\nexport const defaultContext: AppProviderProps = {\n  currentLocale: 'en-US',\n  supportedLocales: {\n    'en-US': {\n      code: 'en-US',\n      name: 'English (United States)',\n      default: true,\n      fallbackCode: null,\n      sys: {\n        id: '[Redacted]',\n        type: 'Locale',\n        version: 1,\n      },\n    },\n  },\n  userLocation: {\n    country: 'US',\n  },\n  isRTL: false,\n  getCurrentUrl: () => 'https://marketing-web-platform.appspot.com/',\n  setSiteData: () => undefined,\n  getUserInfo: () => Promise.resolve({ experimentBucket: { id: '' } }),\n  getPersona: () => Promise.resolve({}),\n  cookieManager: {\n    getCookie: _ => undefined,\n    getCookieJson: _ => undefined,\n    setCookie: noop,\n    setCookieJson: noop,\n    deleteCookie: noop,\n  },\n  createUuidV4: () => '00000000-0000-0000-0000-000000000000',\n  onHlsVideo: noop,\n};\n\nexport const AppContext = createContext<AppProviderProps>(defaultContext);\n", "import type { AdjustedChartData, AdjustedSeries, ChartDataRow, ChartSeries } from './types';\n\n/**\n * Given the corresponding \"Series\", merge a single \"Data\" row with a \"Localized Data\" row TODO:\n * Remove once V2 visualization migration is complete\n */\nconst mergeRowWithLocalized = (\n  series: ChartSeries,\n  row: ChartDataRow,\n  localizedRow: ChartDataRow\n) => {\n  const mergedRow: ChartDataRow = {};\n  const keys = Object.keys(series.schema.items.properties!);\n\n  for (const key of keys) {\n    // Use \"Localizable Properties\" to determine if we should pull\n    // from localized partition or regular partition.\n    // If we have to, fallback on whatever partition has data for given key.\n    if (series.localizableProperties?.includes(key)) {\n      mergedRow[key] = localizedRow[key] ?? row[key]!;\n    } else {\n      mergedRow[key] = row[key] ?? localizedRow[key]!;\n    }\n  }\n\n  return mergedRow;\n};\n\n/**\n * Given the corresponding series, merges the \"Data\" rows with the \"Localized Data\" rows from a\n * \"Chart Data\" TODO: Remove once V2 visualization migration is complete\n */\nexport function mergeDataWithLocalized(\n  series: ChartSeries,\n  rows?: ChartDataRow[],\n  localizedRows?: ChartDataRow[]\n): ChartDataRow[] {\n  // Data really should never be null or undefined, but if it gets into a bad state\n  // then we'll act as if the data is an empty list to prevent MWP from crashing.\n  if (!rows) {\n    return [];\n  }\n\n  // Localized data was not provided, assume all data is non-localizable\n  if (!localizedRows) {\n    return rows;\n  }\n\n  // Localizable data entries should exactly match the number of regular date entries\n  if (rows.length !== localizedRows.length) {\n    //@ts-ignore allow console.warn for this case https://jira.sc-corp.net/browse/WEBP-10119 to update to log\n    console?.warn('Data size mismatch between localized and non-localized data.');\n  }\n\n  return rows.map((row, i) => mergeRowWithLocalized(series, row, localizedRows[i] as ChartDataRow));\n}\n\n/** Given a Chart Data, returns the full underlying raw data as a list of rows */\nexport function getRawData(data: AdjustedChartData): ChartDataRow[] {\n  const localizedRows = data.localizedData ?? [];\n  const nonLocalizedRows = data.data ?? [];\n\n  // Localized data was not provided, assume all data is non-localizable\n  if (!localizedRows) {\n    return nonLocalizedRows;\n  }\n\n  // Localizable data entries should exactly match the number of regular data entries\n  if (nonLocalizedRows.length !== localizedRows.length) {\n    //@ts-ignore allow console.warn for this case https://jira.sc-corp.net/browse/WEBP-10119 to update to log\n    console?.warn('Data size mismatch between localized and non-localized data.');\n  }\n\n  return nonLocalizedRows.map((row, i) =>\n    mergeLocalizedAndNonLocalizedRows(row, localizedRows[i] as ChartDataRow, data.seriesName!)\n  );\n}\n\nconst mergeLocalizedAndNonLocalizedRows = (\n  nonLocalizedRow: ChartDataRow,\n  localizedRow: ChartDataRow,\n  series: AdjustedSeries\n) => {\n  const mergedRow: ChartDataRow = {};\n  const keys = Object.keys(series.schema.items.properties!);\n\n  for (const key of keys) {\n    // Use \"Localizable Properties\" to determine if we should pull\n    // from localized partition or regular partition.\n    // If we have to, fallback on whatever partition has data for given key.\n    if (series.localizableProperties?.includes(key)) {\n      mergedRow[key] = localizedRow[key] ?? nonLocalizedRow[key] ?? '';\n    } else {\n      mergedRow[key] = nonLocalizedRow[key] ?? localizedRow[key] ?? '';\n    }\n  }\n\n  return mergedRow;\n};\n", "import { Site } from '@snapchat/mw-common';\n\n/** These tokens have published content read permission from the /production/ alias. */\nexport const productionContentTokens: Record<Site, string> = {\n  [Site.A523]: 'TEeowd5MSMxWWV4qRGfuSzP6jDyCw7bGPBnSc7FgeCA',\n  [Site.ARCADIA]: 'ZylclnWJF6xeq5chuHTvEpmhNm0LD6Ea0oWEQcNJXxs',\n  [Site.AR]: 'iAOsVMXtR32scQ6d0zbJ_-sYO9nYKG07W_ABFJDUn88',\n  [Site.CAREERS]: 'ry27SzE0GBgWgQTTHH6g7WVu3w6vGTRej-vWTRxBtRE',\n  [Site.CHEERIOS]: '1bn1NIbQCGGTxkSdVtqXidIaQmeiTuWG64URI3Y2K84',\n  [Site.CITIZEN]: 'UIeH-b7nqyTFwt2V3q9j4RiOwHZUI-6-2XVYX3O372A',\n  [Site.CREATORS]: 'vQAHEP8QOjgzxHNAEPOm1uwmb6IblHEsgj7k4oGpJ-E',\n  [Site.DIVERSITY]: 'AYCNZfq0m4oXfzlA29mV7TWnZ-hpJJ1AtaWJ6lVlG4k',\n  [Site.ENG_BLOG]: 'z_FW9MI2WUz8WVdgsv8RNE7VqR2_lWnb1J7zWUTWc8U',\n  [Site.EXPERIENCE]: '-8HQWmpfZSv3H0o_nVdED5WyMgNGQ3cwY-UGJRjpBCc',\n  [Site.FOR_BUSINESS]: 'KdZZ9fEF015H8Vt4QKYMLEer6WRF8Cp7qYhSXtUn1V4',\n  [Site.NEWSROOM]: '5hC-nHrt38Uq1VpDdMnuYHD8aPSdX2yFaIHItIsz9AA',\n  [Site.PARENTS]: 'xz7uwXl9fWX24J9thrLu9QutVk9fJjKetAZPSkFELJc',\n  [Site.SANDBOX]: 'cj8SMzzCy4jmm1NZknJo1pYFmi0a_7OXvI_Jix-ScaM',\n  [Site.TRUST]: 'ur-lfHTOBaqzBf0I_8-ooUzS3KbsIyIEc9HGiMfV0HE',\n  [Site.AVALON]: 'Z0Ld8g2AgpMqOpLIV4JU5ymaPUlqGpUTsDvGw5VEih8',\n  [Site.EDUCATORS]: 'PBrC1AS3d_KhPlR7UdEwebaW0B4nyvYhu5oY3N4hJxk',\n  [Site.SNAP]: 's9X24xBFL18NQDxQmQXjdz542eu17QiYDX2OSs80e0A',\n  [Site.STINSON]: 'nl2ohHj_ucAbN2BmGvhJXGgR25srNPBefHwt8JtiBGs',\n};\n", "import { documentToPlainTextString } from '@contentful/rich-text-plain-text-renderer';\nimport type { Document } from '@contentful/rich-text-types';\n\n/** Helper function, renders the passed data to a plain text string. */\nexport const getPlainText = (data: Document | string | undefined): string => {\n  if (typeof data === 'string') {\n    return data;\n  }\n\n  if (!data || !data?.content) {\n    return '';\n  }\n\n  return documentToPlainTextString(data);\n};\n", "import type { Document } from '@contentful/rich-text-types';\nimport { BLOCKS } from '@contentful/rich-text-types';\nimport merge from 'lodash/merge.js';\n\n/** Merges the text in 2 rich text documents into a single document. */\n// eslint-disable-next-line import/no-unused-modules\nexport function mergeRichText(\n  doc1: Document | undefined,\n  doc2: Document | undefined\n): Document | undefined {\n  if (!doc1) return doc2;\n  if (!doc2) return doc1;\n\n  return {\n    data: merge(doc1.data, doc2.data),\n    content: [...doc1.content, ...doc2.content],\n    nodeType: BLOCKS.DOCUMENT,\n  };\n}\n", "/** Display text for corresponding values for snap personas. */\nexport const snapPersonasDisplayTextMap: Record<string, string> = {\n  // This value is set whenever a user signs in to ads manager/business manager/profile manager.\n  s1: 'Signed Up User',\n} as const;\n", "import baseFor from './_baseFor.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n  return object && baseFor(object, iteratee, keys);\n}\n\nexport default baseForOwn;\n", "import baseForOwn from './_baseForOwn.js';\n\n/**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\nfunction baseInverter(object, setter, iteratee, accumulator) {\n  baseForOwn(object, function(value, key, object) {\n    setter(accumulator, iteratee(value), key, object);\n  });\n  return accumulator;\n}\n\nexport default baseInverter;\n", "import baseInverter from './_baseInverter.js';\n\n/**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\nfunction createInverter(setter, toIteratee) {\n  return function(object, iteratee) {\n    return baseInverter(object, setter, toIteratee(iteratee), {});\n  };\n}\n\nexport default createInverter;\n", "import constant from './constant.js';\nimport createInverter from './_createInverter.js';\nimport identity from './identity.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\nvar invert = createInverter(function(result, value, key) {\n  if (value != null &&\n      typeof value.toString != 'function') {\n    value = nativeObjectToString.call(value);\n  }\n\n  result[value] = key;\n}, constant(identity));\n\nexport default invert;\n", "import { Site } from '@snapchat/mw-common';\nimport invert from 'lodash/invert.js';\n\n/** Space IDs for all of the contentful spaces under MWP. */\nexport const contentfulSpaceIds: Record<Site, string> = {\n  [Site.A523]: '6f4y0nzsmtwg',\n  [Site.ARCADIA]: '8tv80wwv755s',\n  [Site.AR]: 'ub38vssza5h3',\n  [Site.CAREERS]: 'jwenq9l5fmib',\n  [Site.CHEERIOS]: 'svn43w404u4n',\n  [Site.CITIZEN]: 'ngit5gcrb661',\n  [Site.CREATORS]: 'ji04otasc2ol',\n  [Site.DIVERSITY]: 'kql3ubzzanzk',\n  [Site.EDUCATORS]: 'ou2g43s52fjc',\n  [Site.ENG_BLOG]: '7w2tf600vbko',\n  [Site.EXPERIENCE]: 'zu0g3q4so0yf',\n  [Site.FOR_BUSINESS]: 'inb32lme5009',\n  [Site.NEWSROOM]: 'o1znirz7lzo4',\n  [Site.PARENTS]: 'e6fbkkb3ka3b',\n  [Site.SANDBOX]: 'akh6d57cjeed',\n  [Site.TRUST]: 'kw9k15zxztrs',\n  [Site.AVALON]: 'cbjigzuhgs28',\n  [Site.SNAP]: 'dwtpq5hdcqjg',\n  [Site.STINSON]: 'fdtlyqzgdb9e',\n};\n\nexport const siteBySpaceId = invert(contentfulSpaceIds);\n", "import { Site } from '@snapchat/mw-common';\n\n/** Keys for the dev tokens in contentful by site */\nexport const contentfulDevTokenKeys: Record<Site, string> = {\n  [Site.A523]: 'SNAP_523_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.ARCADIA]: 'ARCADIA_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.AR]: 'AR_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.AVALON]: 'AVALON_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.CAREERS]: 'CAREERS_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.CHEERIOS]: 'CHEERIOS_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.CITIZEN]: 'CITIZEN_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.CREATORS]: 'CREATORS_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.DIVERSITY]: 'DIVERSITY_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.EDUCATORS]: 'EDUCATORS_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.ENG_BLOG]: 'ENG_BLOG_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.EXPERIENCE]: 'EXPERIENCE_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.FOR_BUSINESS]: 'FOR_BUSINESS_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.NEWSROOM]: 'NEWSROOM_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.PARENTS]: 'PARENTS_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.SANDBOX]: 'SANDBOX_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.TRUST]: 'TRUST_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.SNAP]: 'SNAP_CONTENTFUL_DEV_ACCESS_TOKEN',\n  [Site.STINSON]: 'STINSON_CONTENTFUL_DEV_ACCESS_TOKEN',\n};\n\n/** Keys for the preview tokens in contentful by site */\nexport const contentfulPreviewTokenKeys: Record<Site, string> = {\n  [Site.A523]: 'SNAP_523_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.ARCADIA]: 'ARCADIA_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.AR]: 'AR_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.AVALON]: 'AVALON_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.CAREERS]: 'CAREERS_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.CHEERIOS]: 'CHEERIOS_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.CITIZEN]: 'CITIZEN_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.CREATORS]: 'CREATORS_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.DIVERSITY]: 'DIVERSITY_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.EDUCATORS]: 'EDUCATORS_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.ENG_BLOG]: 'ENG_BLOG_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.EXPERIENCE]: 'EXPERIENCE_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.FOR_BUSINESS]: 'FOR_BUSINESS_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.NEWSROOM]: 'NEWSROOM_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.PARENTS]: 'PARENTS_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.SANDBOX]: 'SANDBOX_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.TRUST]: 'TRUST_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.SNAP]: 'SNAP_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n  [Site.STINSON]: 'STINSON_CONTENTFUL_PREVIEW_ACCESS_TOKEN',\n};\n\n/**\n * Keys for the production tokens in contentful by site.\n *\n * NOTE: this should be for the `All Access Keys` API tokens, NOT the Production API tokens. The\n * intended use case for these is to fetch the published version of a given entry since the\n * Contentful Management API does not support this functioanlity.\n */\nexport const contentfulPublishedVersionTokenKeys: Record<Site, string> = {\n  [Site.A523]: 'SNAP_523_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.ARCADIA]: 'ARCADIA_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.AR]: 'AR_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.AVALON]: 'AVALON_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.CAREERS]: 'CAREERS_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.CHEERIOS]: 'CHEERIOS_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.CITIZEN]: 'CITIZEN_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.CREATORS]: 'CREATORS_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.DIVERSITY]: 'DIVERSITY_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.EDUCATORS]: 'EDUCATORS_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.ENG_BLOG]: 'ENG_BLOG_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.EXPERIENCE]: 'EXPERIENCE_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.FOR_BUSINESS]: 'FOR_BUSINESS_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.NEWSROOM]: 'NEWSROOM_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.PARENTS]: 'PARENTS_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.SANDBOX]: 'SANDBOX_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.TRUST]: 'TRUST_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.SNAP]: 'SNAP_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n  [Site.STINSON]: 'STINSON_CONTENTFUL_PUBLISHED_VERSION_ACCESS_TOKEN',\n};\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n  extendStatics = Object.setPrototypeOf ||\n      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n  return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n  if (typeof b !== \"function\" && b !== null)\n      throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n  extendStatics(d, b);\n  function __() { this.constructor = d; }\n  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n  __assign = Object.assign || function __assign(t) {\n      for (var s, i = 1, n = arguments.length; i < n; i++) {\n          s = arguments[i];\n          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n      }\n      return t;\n  }\n  return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n  var t = {};\n  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n      t[p] = s[p];\n  if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n              t[p[i]] = s[p[i]];\n      }\n  return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n  if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n  return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n  return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n  function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n  var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n  var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n  var _, done = false;\n  for (var i = decorators.length - 1; i >= 0; i--) {\n      var context = {};\n      for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n      for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n      context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n      var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n      if (kind === \"accessor\") {\n          if (result === void 0) continue;\n          if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n          if (_ = accept(result.get)) descriptor.get = _;\n          if (_ = accept(result.set)) descriptor.set = _;\n          if (_ = accept(result.init)) initializers.unshift(_);\n      }\n      else if (_ = accept(result)) {\n          if (kind === \"field\") initializers.unshift(_);\n          else descriptor[key] = _;\n      }\n  }\n  if (target) Object.defineProperty(target, contextIn.name, descriptor);\n  done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n  var useValue = arguments.length > 2;\n  for (var i = 0; i < initializers.length; i++) {\n      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n  }\n  return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n  return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n  if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n  return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n  if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n  return new (P || (P = Promise))(function (resolve, reject) {\n      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n      function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n      step((generator = generator.apply(thisArg, _arguments || [])).next());\n  });\n}\n\nexport function __generator(thisArg, body) {\n  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n  return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n  function verb(n) { return function (v) { return step([n, v]); }; }\n  function step(op) {\n      if (f) throw new TypeError(\"Generator is already executing.\");\n      while (g && (g = 0, op[0] && (_ = 0)), _) try {\n          if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n          if (y = 0, t) op = [op[0] & 2, t.value];\n          switch (op[0]) {\n              case 0: case 1: t = op; break;\n              case 4: _.label++; return { value: op[1], done: false };\n              case 5: _.label++; y = op[1]; op = [0]; continue;\n              case 7: op = _.ops.pop(); _.trys.pop(); continue;\n              default:\n                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                  if (t[2]) _.ops.pop();\n                  _.trys.pop(); continue;\n          }\n          op = body.call(thisArg, _);\n      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n  }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  var desc = Object.getOwnPropertyDescriptor(m, k);\n  if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n  }\n  Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n  for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n  var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n  if (m) return m.call(o);\n  if (o && typeof o.length === \"number\") return {\n      next: function () {\n          if (o && i >= o.length) o = void 0;\n          return { value: o && o[i++], done: !o };\n      }\n  };\n  throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n  var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n  if (!m) return o;\n  var i = m.call(o), r, ar = [], e;\n  try {\n      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n  }\n  catch (error) { e = { error: error }; }\n  finally {\n      try {\n          if (r && !r.done && (m = i[\"return\"])) m.call(i);\n      }\n      finally { if (e) throw e.error; }\n  }\n  return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n  for (var ar = [], i = 0; i < arguments.length; i++)\n      ar = ar.concat(__read(arguments[i]));\n  return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n  for (var r = Array(s), k = 0, i = 0; i < il; i++)\n      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n          r[k] = a[j];\n  return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n      if (ar || !(i in from)) {\n          if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n          ar[i] = from[i];\n      }\n  }\n  return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n  return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var g = generator.apply(thisArg, _arguments || []), i, q = [];\n  return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n  function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n  function fulfill(value) { resume(\"next\", value); }\n  function reject(value) { resume(\"throw\", value); }\n  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n  var i, p;\n  return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var m = o[Symbol.asyncIterator], i;\n  return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n  if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n  return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n  Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n  o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n  if (mod && mod.__esModule) return mod;\n  var result = {};\n  if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n  __setModuleDefault(result, mod);\n  return result;\n}\n\nexport function __importDefault(mod) {\n  return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n  return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n  if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n  return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n  if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n  return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n  if (value !== null && value !== void 0) {\n    if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n    var dispose;\n    if (async) {\n        if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n        dispose = value[Symbol.asyncDispose];\n    }\n    if (dispose === void 0) {\n        if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n        dispose = value[Symbol.dispose];\n    }\n    if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n    env.stack.push({ value: value, dispose: dispose, async: async });\n  }\n  else if (async) {\n    env.stack.push({ async: true });\n  }\n  return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n  var e = new Error(message);\n  return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n  function fail(e) {\n    env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n    env.hasError = true;\n  }\n  function next() {\n    while (env.stack.length) {\n      var rec = env.stack.pop();\n      try {\n        var result = rec.dispose && rec.dispose.call(rec.value);\n        if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n      }\n      catch (e) {\n          fail(e);\n      }\n    }\n    if (env.hasError) throw env.error;\n  }\n  return next();\n}\n\nexport default {\n  __extends,\n  __assign,\n  __rest,\n  __decorate,\n  __param,\n  __metadata,\n  __awaiter,\n  __generator,\n  __createBinding,\n  __exportStar,\n  __values,\n  __read,\n  __spread,\n  __spreadArrays,\n  __spreadArray,\n  __await,\n  __asyncGenerator,\n  __asyncDelegator,\n  __asyncValues,\n  __makeTemplateObject,\n  __importStar,\n  __importDefault,\n  __classPrivateFieldGet,\n  __classPrivateFieldSet,\n  __classPrivateFieldIn,\n  __addDisposableResource,\n  __disposeResources,\n};\n", "const genericMessage = \"Invariant Violation\";\nconst {\n  setPrototypeOf = function (obj: any, proto: any) {\n    obj.__proto__ = proto;\n    return obj;\n  },\n} = Object as any;\n\nexport class InvariantError extends Error {\n  framesToPop = 1;\n  name = genericMessage;\n  constructor(message: string | number = genericMessage) {\n    super(\n      typeof message === \"number\"\n        ? `${genericMessage}: ${message} (see https://github.com/apollographql/invariant-packages)`\n        : message\n    );\n    setPrototypeOf(this, InvariantError.prototype);\n  }\n}\n\nexport function invariant(\n  condition: any,\n  message?: string | number,\n): asserts condition {\n  if (!condition) {\n    throw new InvariantError(message);\n  }\n}\n\nconst verbosityLevels = [\"debug\", \"log\", \"warn\", \"error\", \"silent\"] as const;\nexport type VerbosityLevel = (typeof verbosityLevels)[number];\nexport type ConsoleMethodName = Exclude<VerbosityLevel, \"silent\">;\nlet verbosityLevel = verbosityLevels.indexOf(\"log\");\n\nfunction wrapConsoleMethod<M extends ConsoleMethodName>(name: M) {\n  return function () {\n    if (verbosityLevels.indexOf(name) >= verbosityLevel) {\n      // Default to console.log if this host environment happens not to provide\n      // all the console.* methods we need.\n      const method = console[name] || console.log;\n      return method.apply(console, arguments as any);\n    }\n  } as (typeof console)[M];\n}\n\nexport namespace invariant {\n  export const debug = wrapConsoleMethod(\"debug\");\n  export const log = wrapConsoleMethod(\"log\");\n  export const warn = wrapConsoleMethod(\"warn\");\n  export const error = wrapConsoleMethod(\"error\");\n}\n\nexport function setVerbosity(level: VerbosityLevel): VerbosityLevel {\n  const old = verbosityLevels[verbosityLevel];\n  verbosityLevel = Math.max(0, verbosityLevels.indexOf(level));\n  return old;\n}\n\nexport default invariant;\n", "export const version = \"local\";\n", "export function maybe<T>(thunk: () => T): T | undefined {\n  try {\n    return thunk();\n  } catch {}\n}\n", "import { maybe } from \"./maybe.js\";\n\ndeclare global {\n  const __DEV__: boolean; // will be removed in `dist` by the `postprocessDist` script\n  interface Window {\n    __DEV__?: boolean;\n  }\n}\n\nexport default (maybe(() => globalThis) ||\n  maybe(() => window) ||\n  maybe(() => self) ||\n  maybe(() => global) ||\n  // We don't expect the Function constructor ever to be invoked at runtime, as\n  // long as at least one of globalThis, window, self, or global is defined, so\n  // we are under no obligation to make it easy for static analysis tools to\n  // detect syntactic usage of the Function constructor. If you think you can\n  // improve your static analysis to detect this obfuscation, think again. This\n  // is an arms race you cannot win, at least not in JavaScript.\n  maybe(function () {\n    return maybe.constructor(\"return this\")();\n  })) as typeof globalThis & Window;\n", "const prefixCounts = new Map<string, number>();\n\n// These IDs won't be globally unique, but they will be unique within this\n// process, thanks to the counter, and unguessable thanks to the random suffix.\nexport function makeUniqueId(prefix: string) {\n  const count = prefixCounts.get(prefix) || 1;\n  prefixCounts.set(prefix, count + 1);\n  return `${prefix}:${count}:${Math.random().toString(36).slice(2)}`;\n}\n", "import { makeUniqueId } from \"./makeUniqueId.js\";\n\nexport function stringifyForDisplay(value: any, space = 0): string {\n  const undefId = makeUniqueId(\"stringifyForDisplay\");\n  return JSON.stringify(\n    value,\n    (key, value) => {\n      return value === void 0 ? undefId : value;\n    },\n    space\n  )\n    .split(JSON.stringify(undefId))\n    .join(\"<undefined>\");\n}\n", "import { invariant as originalInvariant, InvariantError } from \"ts-invariant\";\nimport { version } from \"../../version.js\";\nimport global from \"./global.js\";\nimport type { ErrorCodes } from \"../../invariantErrorCodes.js\";\nimport { stringifyForDisplay } from \"../common/stringifyForDisplay.js\";\n\nfunction wrap(fn: (msg?: string, ...args: any[]) => void) {\n  return function (message?: string | number, ...args: any[]) {\n    if (typeof message === \"number\") {\n      const arg0 = message;\n      message = getHandledErrorMsg(arg0);\n      if (!message) {\n        message = getFallbackErrorMsg(arg0, args);\n        args = [];\n      }\n    }\n    fn(...[message].concat(args));\n  };\n}\n\ntype LogFunction = {\n  /**\n   * Logs a `$level` message if the user used `ts-invariant`'s `setVerbosity` to set\n   * a verbosity level of `$level` or lower. (defaults to `\"log\"`).\n   *\n   * The user will either be presented with a link to the documentation for the message,\n   * or they can use the `loadDevMessages` to add the message strings to the bundle.\n   * The documentation will display the message without argument substitution.\n   * Instead, the arguments will be printed on the console after the link.\n   *\n   * `message` can only be a string, a concatenation of strings, or a ternary statement\n   * that results in a string. This will be enforced on build, where the message will\n   * be replaced with a message number.\n   *\n   * String substitutions like %s, %o, %d or %f are supported.\n   */\n  (message?: any, ...optionalParams: unknown[]): void;\n};\n\ntype WrappedInvariant = {\n  /**\n   * Throws and InvariantError with the given message if the condition is false.\n   *\n   * `message` can only be a string, a concatenation of strings, or a ternary statement\n   * that results in a string. This will be enforced on build, where the message will\n   * be replaced with a message number.\n   *\n   * The user will either be presented with a link to the documentation for the message,\n   * or they can use the `loadErrorMessages` to add the message strings to the bundle.\n   * The documentation will display the message with the arguments substituted.\n   *\n   * String substitutions with %s are supported and will also return\n   * pretty-stringified objects.\n   * Excess `optionalParams` will be swallowed.\n   */\n  (\n    condition: any,\n    message?: string | number,\n    ...optionalParams: unknown[]\n  ): asserts condition;\n\n  debug: LogFunction;\n  log: LogFunction;\n  warn: LogFunction;\n  error: LogFunction;\n};\nconst invariant: WrappedInvariant = Object.assign(\n  function invariant(\n    condition: any,\n    message?: string | number,\n    ...args: unknown[]\n  ): asserts condition {\n    if (!condition) {\n      originalInvariant(\n        condition,\n        getHandledErrorMsg(message, args) || getFallbackErrorMsg(message, args)\n      );\n    }\n  },\n  {\n    debug: wrap(originalInvariant.debug),\n    log: wrap(originalInvariant.log),\n    warn: wrap(originalInvariant.warn),\n    error: wrap(originalInvariant.error),\n  }\n);\n\n/**\n * Returns an InvariantError.\n *\n * `message` can only be a string, a concatenation of strings, or a ternary statement\n * that results in a string. This will be enforced on build, where the message will\n * be replaced with a message number.\n * String substitutions with %s are supported and will also return\n * pretty-stringified objects.\n * Excess `optionalParams` will be swallowed.\n */\nfunction newInvariantError(\n  message?: string | number,\n  ...optionalParams: unknown[]\n) {\n  return new InvariantError(\n    getHandledErrorMsg(message, optionalParams) ||\n      getFallbackErrorMsg(message, optionalParams)\n  );\n}\n\nconst ApolloErrorMessageHandler = Symbol.for(\n  \"ApolloErrorMessageHandler_\" + version\n);\ndeclare global {\n  interface Window {\n    [ApolloErrorMessageHandler]?: {\n      (message: string | number, args: string[]): string | undefined;\n    } & ErrorCodes;\n  }\n}\n\nfunction stringify(arg: any) {\n  return typeof arg == \"string\" ? arg : (\n      stringifyForDisplay(arg, 2).slice(0, 1000)\n    );\n}\n\nfunction getHandledErrorMsg(\n  message?: string | number,\n  messageArgs: unknown[] = []\n) {\n  if (!message) return;\n  return (\n    global[ApolloErrorMessageHandler] &&\n    global[ApolloErrorMessageHandler](message, messageArgs.map(stringify))\n  );\n}\n\nfunction getFallbackErrorMsg(\n  message?: string | number,\n  messageArgs: unknown[] = []\n) {\n  if (!message) return;\n  return `An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#${encodeURIComponent(\n    JSON.stringify({\n      version,\n      message,\n      args: messageArgs.map(stringify),\n    })\n  )}`;\n}\n\nexport {\n  invariant,\n  InvariantError,\n  newInvariantError,\n  ApolloErrorMessageHandler,\n};\n", "import {\n  invariant,\n  newInvariantError,\n  InvariantError,\n} from \"./invariantWrappers.js\";\n\nexport { maybe } from \"./maybe.js\";\nexport { default as global } from \"./global.js\";\nexport { invariant, newInvariantError, InvariantError };\n\n/**\n * @deprecated we do not use this internally anymore,\n * it is just exported for backwards compatibility\n */\n// this file is extempt from automatic `__DEV__` replacement\n// so we have to write it out here\n// @ts-ignore\nexport const DEV = globalThis.__DEV__ !== false;\nexport { DEV as __DEV__ };\n", "function _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/**\n * Return true if `value` is object-like. A value is object-like if it's not\n * `null` and has a `typeof` result of \"object\".\n */\nexport default function isObjectLike(value) {\n  return _typeof(value) == 'object' && value !== null;\n}\n", "// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator\n// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\nexport var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator != null ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator\n// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\n\nexport var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator != null ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\n\nexport var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag';\n", "/**\n * Represents a location in a Source.\n */\n\n/**\n * Takes a Source and a UTF-8 character offset, and returns the corresponding\n * line and column as a SourceLocation.\n */\nexport function getLocation(source, position) {\n  var lineRegexp = /\\r\\n|[\\n\\r]/g;\n  var line = 1;\n  var column = position + 1;\n  var match;\n\n  while ((match = lineRegexp.exec(source.body)) && match.index < position) {\n    line += 1;\n    column = position + 1 - (match.index + match[0].length);\n  }\n\n  return {\n    line: line,\n    column: column\n  };\n}\n", "import { getLocation } from \"./location.mjs\";\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\n\nexport function printLocation(location) {\n  return printSourceLocation(location.source, getLocation(location.source, location.start));\n}\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\n\nexport function printSourceLocation(source, sourceLocation) {\n  var firstLineColumnOffset = source.locationOffset.column - 1;\n  var body = whitespace(firstLineColumnOffset) + source.body;\n  var lineIndex = sourceLocation.line - 1;\n  var lineOffset = source.locationOffset.line - 1;\n  var lineNum = sourceLocation.line + lineOffset;\n  var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;\n  var columnNum = sourceLocation.column + columnOffset;\n  var locationStr = \"\".concat(source.name, \":\").concat(lineNum, \":\").concat(columnNum, \"\\n\");\n  var lines = body.split(/\\r\\n|[\\n\\r]/g);\n  var locationLine = lines[lineIndex]; // Special case for minified documents\n\n  if (locationLine.length > 120) {\n    var subLineIndex = Math.floor(columnNum / 80);\n    var subLineColumnNum = columnNum % 80;\n    var subLines = [];\n\n    for (var i = 0; i < locationLine.length; i += 80) {\n      subLines.push(locationLine.slice(i, i + 80));\n    }\n\n    return locationStr + printPrefixedLines([[\"\".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {\n      return ['', subLine];\n    }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));\n  }\n\n  return locationStr + printPrefixedLines([// Lines specified like this: [\"prefix\", \"string\"],\n  [\"\".concat(lineNum - 1), lines[lineIndex - 1]], [\"\".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], [\"\".concat(lineNum + 1), lines[lineIndex + 1]]]);\n}\n\nfunction printPrefixedLines(lines) {\n  var existingLines = lines.filter(function (_ref) {\n    var _ = _ref[0],\n        line = _ref[1];\n    return line !== undefined;\n  });\n  var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {\n    var prefix = _ref2[0];\n    return prefix.length;\n  }));\n  return existingLines.map(function (_ref3) {\n    var prefix = _ref3[0],\n        line = _ref3[1];\n    return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');\n  }).join('\\n');\n}\n\nfunction whitespace(len) {\n  return Array(len + 1).join(' ');\n}\n\nfunction leftPad(len, str) {\n  return whitespace(len - str.length) + str;\n}\n", "function _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\n\nfunction _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nimport isObjectLike from \"../jsutils/isObjectLike.mjs\";\nimport { SYMBOL_TO_STRING_TAG } from \"../polyfills/symbols.mjs\";\nimport { getLocation } from \"../language/location.mjs\";\nimport { printLocation, printSourceLocation } from \"../language/printLocation.mjs\";\n/**\n * A GraphQLError describes an Error found during the parse, validate, or\n * execute phases of performing a GraphQL operation. In addition to a message\n * and stack trace, it also includes information about the locations in a\n * GraphQL document and/or execution result that correspond to the Error.\n */\n\nexport var GraphQLError = /*#__PURE__*/function (_Error) {\n  _inherits(GraphQLError, _Error);\n\n  var _super = _createSuper(GraphQLError);\n\n  /**\n   * An array of { line, column } locations within the source GraphQL document\n   * which correspond to this error.\n   *\n   * Errors during validation often contain multiple locations, for example to\n   * point out two things with the same name. Errors during execution include a\n   * single location, the field which produced the error.\n   *\n   * Enumerable, and appears in the result of JSON.stringify().\n   */\n\n  /**\n   * An array describing the JSON-path into the execution response which\n   * corresponds to this error. Only included for errors during execution.\n   *\n   * Enumerable, and appears in the result of JSON.stringify().\n   */\n\n  /**\n   * An array of GraphQL AST Nodes corresponding to this error.\n   */\n\n  /**\n   * The source GraphQL document for the first location of this error.\n   *\n   * Note that if this Error represents more than one node, the source may not\n   * represent nodes after the first node.\n   */\n\n  /**\n   * An array of character offsets within the source GraphQL document\n   * which correspond to this error.\n   */\n\n  /**\n   * The original error thrown from a field resolver during execution.\n   */\n\n  /**\n   * Extension fields to add to the formatted error.\n   */\n  function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {\n    var _nodeLocations, _nodeLocations2, _nodeLocations3;\n\n    var _this;\n\n    _classCallCheck(this, GraphQLError);\n\n    _this = _super.call(this, message);\n    _this.name = 'GraphQLError';\n    _this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes.\n\n    _this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined);\n    var nodeLocations = [];\n\n    for (var _i2 = 0, _ref3 = (_this$nodes = _this.nodes) !== null && _this$nodes !== void 0 ? _this$nodes : []; _i2 < _ref3.length; _i2++) {\n      var _this$nodes;\n\n      var _ref4 = _ref3[_i2];\n      var loc = _ref4.loc;\n\n      if (loc != null) {\n        nodeLocations.push(loc);\n      }\n    }\n\n    nodeLocations = undefinedIfEmpty(nodeLocations); // Compute locations in the source for the given nodes/positions.\n\n    _this.source = source !== null && source !== void 0 ? source : (_nodeLocations = nodeLocations) === null || _nodeLocations === void 0 ? void 0 : _nodeLocations[0].source;\n    _this.positions = positions !== null && positions !== void 0 ? positions : (_nodeLocations2 = nodeLocations) === null || _nodeLocations2 === void 0 ? void 0 : _nodeLocations2.map(function (loc) {\n      return loc.start;\n    });\n    _this.locations = positions && source ? positions.map(function (pos) {\n      return getLocation(source, pos);\n    }) : (_nodeLocations3 = nodeLocations) === null || _nodeLocations3 === void 0 ? void 0 : _nodeLocations3.map(function (loc) {\n      return getLocation(loc.source, loc.start);\n    });\n    _this.path = path !== null && path !== void 0 ? path : undefined;\n    var originalExtensions = originalError === null || originalError === void 0 ? void 0 : originalError.extensions;\n\n    if (extensions == null && isObjectLike(originalExtensions)) {\n      _this.extensions = _objectSpread({}, originalExtensions);\n    } else {\n      _this.extensions = extensions !== null && extensions !== void 0 ? extensions : {};\n    } // By being enumerable, JSON.stringify will include bellow properties in the resulting output.\n    // This ensures that the simplest possible GraphQL service adheres to the spec.\n\n\n    Object.defineProperties(_assertThisInitialized(_this), {\n      message: {\n        enumerable: true\n      },\n      locations: {\n        enumerable: _this.locations != null\n      },\n      path: {\n        enumerable: _this.path != null\n      },\n      extensions: {\n        enumerable: _this.extensions != null && Object.keys(_this.extensions).length > 0\n      },\n      name: {\n        enumerable: false\n      },\n      nodes: {\n        enumerable: false\n      },\n      source: {\n        enumerable: false\n      },\n      positions: {\n        enumerable: false\n      },\n      originalError: {\n        enumerable: false\n      }\n    }); // Include (non-enumerable) stack trace.\n\n    if (originalError !== null && originalError !== void 0 && originalError.stack) {\n      Object.defineProperty(_assertThisInitialized(_this), 'stack', {\n        value: originalError.stack,\n        writable: true,\n        configurable: true\n      });\n      return _possibleConstructorReturn(_this);\n    } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\n\n\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);\n    } else {\n      Object.defineProperty(_assertThisInitialized(_this), 'stack', {\n        value: Error().stack,\n        writable: true,\n        configurable: true\n      });\n    }\n\n    return _this;\n  }\n\n  _createClass(GraphQLError, [{\n    key: \"toString\",\n    value: function toString() {\n      return printError(this);\n    } // FIXME: workaround to not break chai comparisons, should be remove in v16\n    // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet\n\n  }, {\n    key: SYMBOL_TO_STRING_TAG,\n    get: function get() {\n      return 'Object';\n    }\n  }]);\n\n  return GraphQLError;\n}( /*#__PURE__*/_wrapNativeSuper(Error));\n\nfunction undefinedIfEmpty(array) {\n  return array === undefined || array.length === 0 ? undefined : array;\n}\n/**\n * Prints a GraphQLError to a string, representing useful location information\n * about the error's position in the source.\n */\n\n\nexport function printError(error) {\n  var output = error.message;\n\n  if (error.nodes) {\n    for (var _i4 = 0, _error$nodes2 = error.nodes; _i4 < _error$nodes2.length; _i4++) {\n      var node = _error$nodes2[_i4];\n\n      if (node.loc) {\n        output += '\\n\\n' + printLocation(node.loc);\n      }\n    }\n  } else if (error.source && error.locations) {\n    for (var _i6 = 0, _error$locations2 = error.locations; _i6 < _error$locations2.length; _i6++) {\n      var location = _error$locations2[_i6];\n      output += '\\n\\n' + printSourceLocation(error.source, location);\n    }\n  }\n\n  return output;\n}\n", "import { GraphQLError } from \"./GraphQLError.mjs\";\n/**\n * Produces a GraphQLError representing a syntax error, containing useful\n * descriptive information about the syntax error's position in the source.\n */\n\nexport function syntaxError(source, position, description) {\n  return new GraphQLError(\"Syntax Error: \".concat(description), undefined, source, [position]);\n}\n", "/**\n * The set of allowed kind values for AST nodes.\n */\nexport var Kind = Object.freeze({\n  // Name\n  NAME: 'Name',\n  // Document\n  DOCUMENT: 'Document',\n  OPERATION_DEFINITION: 'OperationDefinition',\n  VARIABLE_DEFINITION: 'VariableDefinition',\n  SELECTION_SET: 'SelectionSet',\n  FIELD: 'Field',\n  ARGUMENT: 'Argument',\n  // Fragments\n  FRAGMENT_SPREAD: 'FragmentSpread',\n  INLINE_FRAGMENT: 'InlineFragment',\n  FRAGMENT_DEFINITION: 'FragmentDefinition',\n  // Values\n  VARIABLE: 'Variable',\n  INT: 'IntValue',\n  FLOAT: 'FloatValue',\n  STRING: 'StringValue',\n  BOOLEAN: 'BooleanValue',\n  NULL: 'NullValue',\n  ENUM: 'EnumValue',\n  LIST: 'ListValue',\n  OBJECT: 'ObjectValue',\n  OBJECT_FIELD: 'ObjectField',\n  // Directives\n  DIRECTIVE: 'Directive',\n  // Types\n  NAMED_TYPE: 'NamedType',\n  LIST_TYPE: 'ListType',\n  NON_NULL_TYPE: 'NonNullType',\n  // Type System Definitions\n  SCHEMA_DEFINITION: 'SchemaDefinition',\n  OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',\n  // Type Definitions\n  SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',\n  OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',\n  FIELD_DEFINITION: 'FieldDefinition',\n  INPUT_VALUE_DEFINITION: 'InputValueDefinition',\n  INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',\n  UNION_TYPE_DEFINITION: 'UnionTypeDefinition',\n  ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',\n  ENUM_VALUE_DEFINITION: 'EnumValueDefinition',\n  INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',\n  // Directive Definitions\n  DIRECTIVE_DEFINITION: 'DirectiveDefinition',\n  // Type System Extensions\n  SCHEMA_EXTENSION: 'SchemaExtension',\n  // Type Extensions\n  SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',\n  OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',\n  INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',\n  UNION_TYPE_EXTENSION: 'UnionTypeExtension',\n  ENUM_TYPE_EXTENSION: 'EnumTypeExtension',\n  INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'\n});\n/**\n * The enum type representing the possible kind values of AST nodes.\n */\n", "export default function invariant(condition, message) {\n  var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')\n\n  if (!booleanCondition) {\n    throw new Error(message != null ? message : 'Unexpected invariant triggered.');\n  }\n}\n", "// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\nvar nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;\nexport default nodejsCustomInspectSymbol;\n", "import invariant from \"./invariant.mjs\";\nimport nodejsCustomInspectSymbol from \"./nodejsCustomInspectSymbol.mjs\";\n/**\n * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`\n */\n\nexport default function defineInspect(classObject) {\n  var fn = classObject.prototype.toJSON;\n  typeof fn === 'function' || invariant(0);\n  classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317')\n\n  if (nodejsCustomInspectSymbol) {\n    classObject.prototype[nodejsCustomInspectSymbol] = fn;\n  }\n}\n", "import defineInspect from \"../jsutils/defineInspect.mjs\";\n\n/**\n * Contains a range of UTF-8 character offsets and token references that\n * identify the region of the source from which the AST derived.\n */\nexport var Location = /*#__PURE__*/function () {\n  /**\n   * The character offset at which this Node begins.\n   */\n\n  /**\n   * The character offset at which this Node ends.\n   */\n\n  /**\n   * The Token at which this Node begins.\n   */\n\n  /**\n   * The Token at which this Node ends.\n   */\n\n  /**\n   * The Source document the AST represents.\n   */\n  function Location(startToken, endToken, source) {\n    this.start = startToken.start;\n    this.end = endToken.end;\n    this.startToken = startToken;\n    this.endToken = endToken;\n    this.source = source;\n  }\n\n  var _proto = Location.prototype;\n\n  _proto.toJSON = function toJSON() {\n    return {\n      start: this.start,\n      end: this.end\n    };\n  };\n\n  return Location;\n}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.\n\ndefineInspect(Location);\n/**\n * Represents a range of characters represented by a lexical token\n * within a Source.\n */\n\nexport var Token = /*#__PURE__*/function () {\n  /**\n   * The kind of Token.\n   */\n\n  /**\n   * The character offset at which this Node begins.\n   */\n\n  /**\n   * The character offset at which this Node ends.\n   */\n\n  /**\n   * The 1-indexed line number on which this Token appears.\n   */\n\n  /**\n   * The 1-indexed column number at which this Token begins.\n   */\n\n  /**\n   * For non-punctuation tokens, represents the interpreted value of the token.\n   */\n\n  /**\n   * Tokens exist as nodes in a double-linked-list amongst all tokens\n   * including ignored tokens. <SOF> is always the first node and <EOF>\n   * the last.\n   */\n  function Token(kind, start, end, line, column, prev, value) {\n    this.kind = kind;\n    this.start = start;\n    this.end = end;\n    this.line = line;\n    this.column = column;\n    this.value = value;\n    this.prev = prev;\n    this.next = null;\n  }\n\n  var _proto2 = Token.prototype;\n\n  _proto2.toJSON = function toJSON() {\n    return {\n      kind: this.kind,\n      value: this.value,\n      line: this.line,\n      column: this.column\n    };\n  };\n\n  return Token;\n}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.\n\ndefineInspect(Token);\n/**\n * @internal\n */\n\nexport function isNode(maybeNode) {\n  return maybeNode != null && typeof maybeNode.kind === 'string';\n}\n/**\n * The list of all possible AST node types.\n */\n", "/**\n * An exported enum describing the different kinds of tokens that the\n * lexer emits.\n */\nexport var TokenKind = Object.freeze({\n  SOF: '<SOF>',\n  EOF: '<EOF>',\n  BANG: '!',\n  DOLLAR: '$',\n  AMP: '&',\n  PAREN_L: '(',\n  PAREN_R: ')',\n  SPREAD: '...',\n  COLON: ':',\n  EQUALS: '=',\n  AT: '@',\n  BRACKET_L: '[',\n  BRACKET_R: ']',\n  BRACE_L: '{',\n  PIPE: '|',\n  BRACE_R: '}',\n  NAME: 'Name',\n  INT: 'Int',\n  FLOAT: 'Float',\n  STRING: 'String',\n  BLOCK_STRING: 'BlockString',\n  COMMENT: 'Comment'\n});\n/**\n * The enum type representing the token kinds values.\n */\n", "function _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-disable flowtype/no-weak-types */\nimport nodejsCustomInspectSymbol from \"./nodejsCustomInspectSymbol.mjs\";\nvar MAX_ARRAY_LENGTH = 10;\nvar MAX_RECURSIVE_DEPTH = 2;\n/**\n * Used to print values in error messages.\n */\n\nexport default function inspect(value) {\n  return formatValue(value, []);\n}\n\nfunction formatValue(value, seenValues) {\n  switch (_typeof(value)) {\n    case 'string':\n      return JSON.stringify(value);\n\n    case 'function':\n      return value.name ? \"[function \".concat(value.name, \"]\") : '[function]';\n\n    case 'object':\n      if (value === null) {\n        return 'null';\n      }\n\n      return formatObjectValue(value, seenValues);\n\n    default:\n      return String(value);\n  }\n}\n\nfunction formatObjectValue(value, previouslySeenValues) {\n  if (previouslySeenValues.indexOf(value) !== -1) {\n    return '[Circular]';\n  }\n\n  var seenValues = [].concat(previouslySeenValues, [value]);\n  var customInspectFn = getCustomFn(value);\n\n  if (customInspectFn !== undefined) {\n    var customValue = customInspectFn.call(value); // check for infinite recursion\n\n    if (customValue !== value) {\n      return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);\n    }\n  } else if (Array.isArray(value)) {\n    return formatArray(value, seenValues);\n  }\n\n  return formatObject(value, seenValues);\n}\n\nfunction formatObject(object, seenValues) {\n  var keys = Object.keys(object);\n\n  if (keys.length === 0) {\n    return '{}';\n  }\n\n  if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n    return '[' + getObjectTag(object) + ']';\n  }\n\n  var properties = keys.map(function (key) {\n    var value = formatValue(object[key], seenValues);\n    return key + ': ' + value;\n  });\n  return '{ ' + properties.join(', ') + ' }';\n}\n\nfunction formatArray(array, seenValues) {\n  if (array.length === 0) {\n    return '[]';\n  }\n\n  if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n    return '[Array]';\n  }\n\n  var len = Math.min(MAX_ARRAY_LENGTH, array.length);\n  var remaining = array.length - len;\n  var items = [];\n\n  for (var i = 0; i < len; ++i) {\n    items.push(formatValue(array[i], seenValues));\n  }\n\n  if (remaining === 1) {\n    items.push('... 1 more item');\n  } else if (remaining > 1) {\n    items.push(\"... \".concat(remaining, \" more items\"));\n  }\n\n  return '[' + items.join(', ') + ']';\n}\n\nfunction getCustomFn(object) {\n  var customInspectFn = object[String(nodejsCustomInspectSymbol)];\n\n  if (typeof customInspectFn === 'function') {\n    return customInspectFn;\n  }\n\n  if (typeof object.inspect === 'function') {\n    return object.inspect;\n  }\n}\n\nfunction getObjectTag(object) {\n  var tag = Object.prototype.toString.call(object).replace(/^\\[object /, '').replace(/]$/, '');\n\n  if (tag === 'Object' && typeof object.constructor === 'function') {\n    var name = object.constructor.name;\n\n    if (typeof name === 'string' && name !== '') {\n      return name;\n    }\n  }\n\n  return tag;\n}\n", "export default function devAssert(condition, message) {\n  var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')\n\n  if (!booleanCondition) {\n    throw new Error(message);\n  }\n}\n", "function _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nimport inspect from \"./inspect.mjs\";\n/**\n * A replacement for instanceof which includes an error warning when multi-realm\n * constructors are detected.\n */\n\n// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production\n// See: https://webpack.js.org/guides/production/\nexport default process.env.NODE_ENV === 'production' ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\n// eslint-disable-next-line no-shadow\nfunction instanceOf(value, constructor) {\n  return value instanceof constructor;\n} : // eslint-disable-next-line no-shadow\nfunction instanceOf(value, constructor) {\n  if (value instanceof constructor) {\n    return true;\n  }\n\n  if (_typeof(value) === 'object' && value !== null) {\n    var _value$constructor;\n\n    var className = constructor.prototype[Symbol.toStringTag];\n    var valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library.\n    Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name;\n\n    if (className === valueClassName) {\n      var stringifiedValue = inspect(value);\n      throw new Error(\"Cannot use \".concat(className, \" \\\"\").concat(stringifiedValue, \"\\\" from another module or realm.\\n\\nEnsure that there is only one instance of \\\"graphql\\\" in the node_modules\\ndirectory. If different versions of \\\"graphql\\\" are the dependencies of other\\nrelied on modules, use \\\"resolutions\\\" to ensure only one version is installed.\\n\\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\\n\\nDuplicate \\\"graphql\\\" modules cannot be used at the same time since different\\nversions may have different capabilities and behavior. The data from one\\nversion used in the function from another could produce confusing and\\nspurious results.\"));\n    }\n  }\n\n  return false;\n};\n", "function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nimport { SYMBOL_TO_STRING_TAG } from \"../polyfills/symbols.mjs\";\nimport inspect from \"../jsutils/inspect.mjs\";\nimport devAssert from \"../jsutils/devAssert.mjs\";\nimport instanceOf from \"../jsutils/instanceOf.mjs\";\n\n/**\n * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are\n * optional, but they are useful for clients who store GraphQL documents in source files.\n * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might\n * be useful for `name` to be `\"Foo.graphql\"` and location to be `{ line: 40, column: 1 }`.\n * The `line` and `column` properties in `locationOffset` are 1-indexed.\n */\nexport var Source = /*#__PURE__*/function () {\n  function Source(body) {\n    var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request';\n    var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n      line: 1,\n      column: 1\n    };\n    typeof body === 'string' || devAssert(0, \"Body must be a string. Received: \".concat(inspect(body), \".\"));\n    this.body = body;\n    this.name = name;\n    this.locationOffset = locationOffset;\n    this.locationOffset.line > 0 || devAssert(0, 'line in locationOffset is 1-indexed and must be positive.');\n    this.locationOffset.column > 0 || devAssert(0, 'column in locationOffset is 1-indexed and must be positive.');\n  } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet\n\n\n  _createClass(Source, [{\n    key: SYMBOL_TO_STRING_TAG,\n    get: function get() {\n      return 'Source';\n    }\n  }]);\n\n  return Source;\n}();\n/**\n * Test if the given value is a Source object.\n *\n * @internal\n */\n\n// eslint-disable-next-line no-redeclare\nexport function isSource(source) {\n  return instanceOf(source, Source);\n}\n", "/**\n * The set of allowed directive location values.\n */\nexport var DirectiveLocation = Object.freeze({\n  // Request Definitions\n  QUERY: 'QUERY',\n  MUTATION: 'MUTATION',\n  SUBSCRIPTION: 'SUBSCRIPTION',\n  FIELD: 'FIELD',\n  FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',\n  FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',\n  INLINE_FRAGMENT: 'INLINE_FRAGMENT',\n  VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',\n  // Type System Definitions\n  SCHEMA: 'SCHEMA',\n  SCALAR: 'SCALAR',\n  OBJECT: 'OBJECT',\n  FIELD_DEFINITION: 'FIELD_DEFINITION',\n  ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',\n  INTERFACE: 'INTERFACE',\n  UNION: 'UNION',\n  ENUM: 'ENUM',\n  ENUM_VALUE: 'ENUM_VALUE',\n  INPUT_OBJECT: 'INPUT_OBJECT',\n  INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'\n});\n/**\n * The enum type representing the directive location values.\n */\n", "/**\n * Produces the value of a block string from its parsed raw value, similar to\n * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.\n *\n * This implements the GraphQL spec's BlockStringValue() static algorithm.\n *\n * @internal\n */\nexport function dedentBlockStringValue(rawString) {\n  // Expand a block string's raw value into independent lines.\n  var lines = rawString.split(/\\r\\n|[\\n\\r]/g); // Remove common indentation from all lines but first.\n\n  var commonIndent = getBlockStringIndentation(rawString);\n\n  if (commonIndent !== 0) {\n    for (var i = 1; i < lines.length; i++) {\n      lines[i] = lines[i].slice(commonIndent);\n    }\n  } // Remove leading and trailing blank lines.\n\n\n  var startLine = 0;\n\n  while (startLine < lines.length && isBlank(lines[startLine])) {\n    ++startLine;\n  }\n\n  var endLine = lines.length;\n\n  while (endLine > startLine && isBlank(lines[endLine - 1])) {\n    --endLine;\n  } // Return a string of the lines joined with U+000A.\n\n\n  return lines.slice(startLine, endLine).join('\\n');\n}\n\nfunction isBlank(str) {\n  for (var i = 0; i < str.length; ++i) {\n    if (str[i] !== ' ' && str[i] !== '\\t') {\n      return false;\n    }\n  }\n\n  return true;\n}\n/**\n * @internal\n */\n\n\nexport function getBlockStringIndentation(value) {\n  var _commonIndent;\n\n  var isFirstLine = true;\n  var isEmptyLine = true;\n  var indent = 0;\n  var commonIndent = null;\n\n  for (var i = 0; i < value.length; ++i) {\n    switch (value.charCodeAt(i)) {\n      case 13:\n        //  \\r\n        if (value.charCodeAt(i + 1) === 10) {\n          ++i; // skip \\r\\n as one symbol\n        }\n\n      // falls through\n\n      case 10:\n        //  \\n\n        isFirstLine = false;\n        isEmptyLine = true;\n        indent = 0;\n        break;\n\n      case 9: //   \\t\n\n      case 32:\n        //  <space>\n        ++indent;\n        break;\n\n      default:\n        if (isEmptyLine && !isFirstLine && (commonIndent === null || indent < commonIndent)) {\n          commonIndent = indent;\n        }\n\n        isEmptyLine = false;\n    }\n  }\n\n  return (_commonIndent = commonIndent) !== null && _commonIndent !== void 0 ? _commonIndent : 0;\n}\n/**\n * Print a block string in the indented block form by adding a leading and\n * trailing blank line. However, if a block string starts with whitespace and is\n * a single-line, adding a leading blank line would strip that whitespace.\n *\n * @internal\n */\n\nexport function printBlockString(value) {\n  var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n  var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n  var isSingleLine = value.indexOf('\\n') === -1;\n  var hasLeadingSpace = value[0] === ' ' || value[0] === '\\t';\n  var hasTrailingQuote = value[value.length - 1] === '\"';\n  var hasTrailingSlash = value[value.length - 1] === '\\\\';\n  var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines;\n  var result = ''; // Format a multi-line block quote to account for leading space.\n\n  if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {\n    result += '\\n' + indentation;\n  }\n\n  result += indentation ? value.replace(/\\n/g, '\\n' + indentation) : value;\n\n  if (printAsMultipleLines) {\n    result += '\\n';\n  }\n\n  return '\"\"\"' + result.replace(/\"\"\"/g, '\\\\\"\"\"') + '\"\"\"';\n}\n", "import { syntaxError } from \"../error/syntaxError.mjs\";\nimport { Token } from \"./ast.mjs\";\nimport { TokenKind } from \"./tokenKind.mjs\";\nimport { dedentBlockStringValue } from \"./blockString.mjs\";\n/**\n * Given a Source object, creates a Lexer for that source.\n * A Lexer is a stateful stream generator in that every time\n * it is advanced, it returns the next token in the Source. Assuming the\n * source lexes, the final Token emitted by the lexer will be of kind\n * EOF, after which the lexer will repeatedly return the same EOF token\n * whenever called.\n */\n\nexport var Lexer = /*#__PURE__*/function () {\n  /**\n   * The previously focused non-ignored token.\n   */\n\n  /**\n   * The currently focused non-ignored token.\n   */\n\n  /**\n   * The (1-indexed) line containing the current token.\n   */\n\n  /**\n   * The character offset at which the current line begins.\n   */\n  function Lexer(source) {\n    var startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null);\n    this.source = source;\n    this.lastToken = startOfFileToken;\n    this.token = startOfFileToken;\n    this.line = 1;\n    this.lineStart = 0;\n  }\n  /**\n   * Advances the token stream to the next non-ignored token.\n   */\n\n\n  var _proto = Lexer.prototype;\n\n  _proto.advance = function advance() {\n    this.lastToken = this.token;\n    var token = this.token = this.lookahead();\n    return token;\n  }\n  /**\n   * Looks ahead and returns the next non-ignored token, but does not change\n   * the state of Lexer.\n   */\n  ;\n\n  _proto.lookahead = function lookahead() {\n    var token = this.token;\n\n    if (token.kind !== TokenKind.EOF) {\n      do {\n        var _token$next;\n\n        // Note: next is only mutable during parsing, so we cast to allow this.\n        token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token);\n      } while (token.kind === TokenKind.COMMENT);\n    }\n\n    return token;\n  };\n\n  return Lexer;\n}();\n/**\n * @internal\n */\n\nexport function isPunctuatorTokenKind(kind) {\n  return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;\n}\n\nfunction printCharCode(code) {\n  return (// NaN/undefined represents access beyond the end of the file.\n    isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.\n    code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.\n    \"\\\"\\\\u\".concat(('00' + code.toString(16).toUpperCase()).slice(-4), \"\\\"\")\n  );\n}\n/**\n * Gets the next token from the source starting at the given position.\n *\n * This skips over whitespace until it finds the next lexable token, then lexes\n * punctuators immediately or calls the appropriate helper function for more\n * complicated tokens.\n */\n\n\nfunction readToken(lexer, prev) {\n  var source = lexer.source;\n  var body = source.body;\n  var bodyLength = body.length;\n  var pos = prev.end;\n\n  while (pos < bodyLength) {\n    var code = body.charCodeAt(pos);\n    var _line = lexer.line;\n\n    var _col = 1 + pos - lexer.lineStart; // SourceCharacter\n\n\n    switch (code) {\n      case 0xfeff: // <BOM>\n\n      case 9: //   \\t\n\n      case 32: //  <space>\n\n      case 44:\n        //  ,\n        ++pos;\n        continue;\n\n      case 10:\n        //  \\n\n        ++pos;\n        ++lexer.line;\n        lexer.lineStart = pos;\n        continue;\n\n      case 13:\n        //  \\r\n        if (body.charCodeAt(pos + 1) === 10) {\n          pos += 2;\n        } else {\n          ++pos;\n        }\n\n        ++lexer.line;\n        lexer.lineStart = pos;\n        continue;\n\n      case 33:\n        //  !\n        return new Token(TokenKind.BANG, pos, pos + 1, _line, _col, prev);\n\n      case 35:\n        //  #\n        return readComment(source, pos, _line, _col, prev);\n\n      case 36:\n        //  $\n        return new Token(TokenKind.DOLLAR, pos, pos + 1, _line, _col, prev);\n\n      case 38:\n        //  &\n        return new Token(TokenKind.AMP, pos, pos + 1, _line, _col, prev);\n\n      case 40:\n        //  (\n        return new Token(TokenKind.PAREN_L, pos, pos + 1, _line, _col, prev);\n\n      case 41:\n        //  )\n        return new Token(TokenKind.PAREN_R, pos, pos + 1, _line, _col, prev);\n\n      case 46:\n        //  .\n        if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) {\n          return new Token(TokenKind.SPREAD, pos, pos + 3, _line, _col, prev);\n        }\n\n        break;\n\n      case 58:\n        //  :\n        return new Token(TokenKind.COLON, pos, pos + 1, _line, _col, prev);\n\n      case 61:\n        //  =\n        return new Token(TokenKind.EQUALS, pos, pos + 1, _line, _col, prev);\n\n      case 64:\n        //  @\n        return new Token(TokenKind.AT, pos, pos + 1, _line, _col, prev);\n\n      case 91:\n        //  [\n        return new Token(TokenKind.BRACKET_L, pos, pos + 1, _line, _col, prev);\n\n      case 93:\n        //  ]\n        return new Token(TokenKind.BRACKET_R, pos, pos + 1, _line, _col, prev);\n\n      case 123:\n        // {\n        return new Token(TokenKind.BRACE_L, pos, pos + 1, _line, _col, prev);\n\n      case 124:\n        // |\n        return new Token(TokenKind.PIPE, pos, pos + 1, _line, _col, prev);\n\n      case 125:\n        // }\n        return new Token(TokenKind.BRACE_R, pos, pos + 1, _line, _col, prev);\n\n      case 34:\n        //  \"\n        if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) {\n          return readBlockString(source, pos, _line, _col, prev, lexer);\n        }\n\n        return readString(source, pos, _line, _col, prev);\n\n      case 45: //  -\n\n      case 48: //  0\n\n      case 49: //  1\n\n      case 50: //  2\n\n      case 51: //  3\n\n      case 52: //  4\n\n      case 53: //  5\n\n      case 54: //  6\n\n      case 55: //  7\n\n      case 56: //  8\n\n      case 57:\n        //  9\n        return readNumber(source, pos, code, _line, _col, prev);\n\n      case 65: //  A\n\n      case 66: //  B\n\n      case 67: //  C\n\n      case 68: //  D\n\n      case 69: //  E\n\n      case 70: //  F\n\n      case 71: //  G\n\n      case 72: //  H\n\n      case 73: //  I\n\n      case 74: //  J\n\n      case 75: //  K\n\n      case 76: //  L\n\n      case 77: //  M\n\n      case 78: //  N\n\n      case 79: //  O\n\n      case 80: //  P\n\n      case 81: //  Q\n\n      case 82: //  R\n\n      case 83: //  S\n\n      case 84: //  T\n\n      case 85: //  U\n\n      case 86: //  V\n\n      case 87: //  W\n\n      case 88: //  X\n\n      case 89: //  Y\n\n      case 90: //  Z\n\n      case 95: //  _\n\n      case 97: //  a\n\n      case 98: //  b\n\n      case 99: //  c\n\n      case 100: // d\n\n      case 101: // e\n\n      case 102: // f\n\n      case 103: // g\n\n      case 104: // h\n\n      case 105: // i\n\n      case 106: // j\n\n      case 107: // k\n\n      case 108: // l\n\n      case 109: // m\n\n      case 110: // n\n\n      case 111: // o\n\n      case 112: // p\n\n      case 113: // q\n\n      case 114: // r\n\n      case 115: // s\n\n      case 116: // t\n\n      case 117: // u\n\n      case 118: // v\n\n      case 119: // w\n\n      case 120: // x\n\n      case 121: // y\n\n      case 122:\n        // z\n        return readName(source, pos, _line, _col, prev);\n    }\n\n    throw syntaxError(source, pos, unexpectedCharacterMessage(code));\n  }\n\n  var line = lexer.line;\n  var col = 1 + pos - lexer.lineStart;\n  return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);\n}\n/**\n * Report a message that an unexpected character was encountered.\n */\n\n\nfunction unexpectedCharacterMessage(code) {\n  if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {\n    return \"Cannot contain the invalid character \".concat(printCharCode(code), \".\");\n  }\n\n  if (code === 39) {\n    // '\n    return 'Unexpected single quote character (\\'), did you mean to use a double quote (\")?';\n  }\n\n  return \"Cannot parse the unexpected character \".concat(printCharCode(code), \".\");\n}\n/**\n * Reads a comment token from the source file.\n *\n * #[\\u0009\\u0020-\\uFFFF]*\n */\n\n\nfunction readComment(source, start, line, col, prev) {\n  var body = source.body;\n  var code;\n  var position = start;\n\n  do {\n    code = body.charCodeAt(++position);\n  } while (!isNaN(code) && ( // SourceCharacter but not LineTerminator\n  code > 0x001f || code === 0x0009));\n\n  return new Token(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position));\n}\n/**\n * Reads a number token from the source file, either a float\n * or an int depending on whether a decimal point appears.\n *\n * Int:   -?(0|[1-9][0-9]*)\n * Float: -?(0|[1-9][0-9]*)(\\.[0-9]+)?((E|e)(+|-)?[0-9]+)?\n */\n\n\nfunction readNumber(source, start, firstCode, line, col, prev) {\n  var body = source.body;\n  var code = firstCode;\n  var position = start;\n  var isFloat = false;\n\n  if (code === 45) {\n    // -\n    code = body.charCodeAt(++position);\n  }\n\n  if (code === 48) {\n    // 0\n    code = body.charCodeAt(++position);\n\n    if (code >= 48 && code <= 57) {\n      throw syntaxError(source, position, \"Invalid number, unexpected digit after 0: \".concat(printCharCode(code), \".\"));\n    }\n  } else {\n    position = readDigits(source, position, code);\n    code = body.charCodeAt(position);\n  }\n\n  if (code === 46) {\n    // .\n    isFloat = true;\n    code = body.charCodeAt(++position);\n    position = readDigits(source, position, code);\n    code = body.charCodeAt(position);\n  }\n\n  if (code === 69 || code === 101) {\n    // E e\n    isFloat = true;\n    code = body.charCodeAt(++position);\n\n    if (code === 43 || code === 45) {\n      // + -\n      code = body.charCodeAt(++position);\n    }\n\n    position = readDigits(source, position, code);\n    code = body.charCodeAt(position);\n  } // Numbers cannot be followed by . or NameStart\n\n\n  if (code === 46 || isNameStart(code)) {\n    throw syntaxError(source, position, \"Invalid number, expected digit but got: \".concat(printCharCode(code), \".\"));\n  }\n\n  return new Token(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position));\n}\n/**\n * Returns the new position in the source after reading digits.\n */\n\n\nfunction readDigits(source, start, firstCode) {\n  var body = source.body;\n  var position = start;\n  var code = firstCode;\n\n  if (code >= 48 && code <= 57) {\n    // 0 - 9\n    do {\n      code = body.charCodeAt(++position);\n    } while (code >= 48 && code <= 57); // 0 - 9\n\n\n    return position;\n  }\n\n  throw syntaxError(source, position, \"Invalid number, expected digit but got: \".concat(printCharCode(code), \".\"));\n}\n/**\n * Reads a string token from the source file.\n *\n * \"([^\"\\\\\\u000A\\u000D]|(\\\\(u[0-9a-fA-F]{4}|[\"\\\\/bfnrt])))*\"\n */\n\n\nfunction readString(source, start, line, col, prev) {\n  var body = source.body;\n  var position = start + 1;\n  var chunkStart = position;\n  var code = 0;\n  var value = '';\n\n  while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator\n  code !== 0x000a && code !== 0x000d) {\n    // Closing Quote (\")\n    if (code === 34) {\n      value += body.slice(chunkStart, position);\n      return new Token(TokenKind.STRING, start, position + 1, line, col, prev, value);\n    } // SourceCharacter\n\n\n    if (code < 0x0020 && code !== 0x0009) {\n      throw syntaxError(source, position, \"Invalid character within String: \".concat(printCharCode(code), \".\"));\n    }\n\n    ++position;\n\n    if (code === 92) {\n      // \\\n      value += body.slice(chunkStart, position - 1);\n      code = body.charCodeAt(position);\n\n      switch (code) {\n        case 34:\n          value += '\"';\n          break;\n\n        case 47:\n          value += '/';\n          break;\n\n        case 92:\n          value += '\\\\';\n          break;\n\n        case 98:\n          value += '\\b';\n          break;\n\n        case 102:\n          value += '\\f';\n          break;\n\n        case 110:\n          value += '\\n';\n          break;\n\n        case 114:\n          value += '\\r';\n          break;\n\n        case 116:\n          value += '\\t';\n          break;\n\n        case 117:\n          {\n            // uXXXX\n            var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4));\n\n            if (charCode < 0) {\n              var invalidSequence = body.slice(position + 1, position + 5);\n              throw syntaxError(source, position, \"Invalid character escape sequence: \\\\u\".concat(invalidSequence, \".\"));\n            }\n\n            value += String.fromCharCode(charCode);\n            position += 4;\n            break;\n          }\n\n        default:\n          throw syntaxError(source, position, \"Invalid character escape sequence: \\\\\".concat(String.fromCharCode(code), \".\"));\n      }\n\n      ++position;\n      chunkStart = position;\n    }\n  }\n\n  throw syntaxError(source, position, 'Unterminated string.');\n}\n/**\n * Reads a block string token from the source file.\n *\n * \"\"\"(\"?\"?(\\\\\"\"\"|\\\\(?!=\"\"\")|[^\"\\\\]))*\"\"\"\n */\n\n\nfunction readBlockString(source, start, line, col, prev, lexer) {\n  var body = source.body;\n  var position = start + 3;\n  var chunkStart = position;\n  var code = 0;\n  var rawValue = '';\n\n  while (position < body.length && !isNaN(code = body.charCodeAt(position))) {\n    // Closing Triple-Quote (\"\"\")\n    if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {\n      rawValue += body.slice(chunkStart, position);\n      return new Token(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedentBlockStringValue(rawValue));\n    } // SourceCharacter\n\n\n    if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {\n      throw syntaxError(source, position, \"Invalid character within String: \".concat(printCharCode(code), \".\"));\n    }\n\n    if (code === 10) {\n      // new line\n      ++position;\n      ++lexer.line;\n      lexer.lineStart = position;\n    } else if (code === 13) {\n      // carriage return\n      if (body.charCodeAt(position + 1) === 10) {\n        position += 2;\n      } else {\n        ++position;\n      }\n\n      ++lexer.line;\n      lexer.lineStart = position;\n    } else if ( // Escape Triple-Quote (\\\"\"\")\n    code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {\n      rawValue += body.slice(chunkStart, position) + '\"\"\"';\n      position += 4;\n      chunkStart = position;\n    } else {\n      ++position;\n    }\n  }\n\n  throw syntaxError(source, position, 'Unterminated string.');\n}\n/**\n * Converts four hexadecimal chars to the integer that the\n * string represents. For example, uniCharCode('0','0','0','f')\n * will return 15, and uniCharCode('0','0','f','f') returns 255.\n *\n * Returns a negative number on error, if a char was invalid.\n *\n * This is implemented by noting that char2hex() returns -1 on error,\n * which means the result of ORing the char2hex() will also be negative.\n */\n\n\nfunction uniCharCode(a, b, c, d) {\n  return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);\n}\n/**\n * Converts a hex character to its integer value.\n * '0' becomes 0, '9' becomes 9\n * 'A' becomes 10, 'F' becomes 15\n * 'a' becomes 10, 'f' becomes 15\n *\n * Returns -1 on error.\n */\n\n\nfunction char2hex(a) {\n  return a >= 48 && a <= 57 ? a - 48 // 0-9\n  : a >= 65 && a <= 70 ? a - 55 // A-F\n  : a >= 97 && a <= 102 ? a - 87 // a-f\n  : -1;\n}\n/**\n * Reads an alphanumeric + underscore name from the source.\n *\n * [_A-Za-z][_0-9A-Za-z]*\n */\n\n\nfunction readName(source, start, line, col, prev) {\n  var body = source.body;\n  var bodyLength = body.length;\n  var position = start + 1;\n  var code = 0;\n\n  while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _\n  code >= 48 && code <= 57 || // 0-9\n  code >= 65 && code <= 90 || // A-Z\n  code >= 97 && code <= 122) // a-z\n  ) {\n    ++position;\n  }\n\n  return new Token(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position));\n} // _ A-Z a-z\n\n\nfunction isNameStart(code) {\n  return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122;\n}\n", "import { syntaxError } from \"../error/syntaxError.mjs\";\nimport { Kind } from \"./kinds.mjs\";\nimport { Location } from \"./ast.mjs\";\nimport { TokenKind } from \"./tokenKind.mjs\";\nimport { Source, isSource } from \"./source.mjs\";\nimport { DirectiveLocation } from \"./directiveLocation.mjs\";\nimport { Lexer, isPunctuatorTokenKind } from \"./lexer.mjs\";\n/**\n * Configuration options to control parser behavior\n */\n\n/**\n * Given a GraphQL source, parses it into a Document.\n * Throws GraphQLError if a syntax error is encountered.\n */\nexport function parse(source, options) {\n  var parser = new Parser(source, options);\n  return parser.parseDocument();\n}\n/**\n * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for\n * that value.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Values directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: valueFromAST().\n */\n\nexport function parseValue(source, options) {\n  var parser = new Parser(source, options);\n  parser.expectToken(TokenKind.SOF);\n  var value = parser.parseValueLiteral(false);\n  parser.expectToken(TokenKind.EOF);\n  return value;\n}\n/**\n * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for\n * that type.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Types directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: typeFromAST().\n */\n\nexport function parseType(source, options) {\n  var parser = new Parser(source, options);\n  parser.expectToken(TokenKind.SOF);\n  var type = parser.parseTypeReference();\n  parser.expectToken(TokenKind.EOF);\n  return type;\n}\n/**\n * This class is exported only to assist people in implementing their own parsers\n * without duplicating too much code and should be used only as last resort for cases\n * such as experimental syntax or if certain features could not be contributed upstream.\n *\n * It is still part of the internal API and is versioned, so any changes to it are never\n * considered breaking changes. If you still need to support multiple versions of the\n * library, please use the `versionInfo` variable for version detection.\n *\n * @internal\n */\n\nexport var Parser = /*#__PURE__*/function () {\n  function Parser(source, options) {\n    var sourceObj = isSource(source) ? source : new Source(source);\n    this._lexer = new Lexer(sourceObj);\n    this._options = options;\n  }\n  /**\n   * Converts a name lex token into a name parse node.\n   */\n\n\n  var _proto = Parser.prototype;\n\n  _proto.parseName = function parseName() {\n    var token = this.expectToken(TokenKind.NAME);\n    return {\n      kind: Kind.NAME,\n      value: token.value,\n      loc: this.loc(token)\n    };\n  } // Implements the parsing rules in the Document section.\n\n  /**\n   * Document : Definition+\n   */\n  ;\n\n  _proto.parseDocument = function parseDocument() {\n    var start = this._lexer.token;\n    return {\n      kind: Kind.DOCUMENT,\n      definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * Definition :\n   *   - ExecutableDefinition\n   *   - TypeSystemDefinition\n   *   - TypeSystemExtension\n   *\n   * ExecutableDefinition :\n   *   - OperationDefinition\n   *   - FragmentDefinition\n   */\n  ;\n\n  _proto.parseDefinition = function parseDefinition() {\n    if (this.peek(TokenKind.NAME)) {\n      switch (this._lexer.token.value) {\n        case 'query':\n        case 'mutation':\n        case 'subscription':\n          return this.parseOperationDefinition();\n\n        case 'fragment':\n          return this.parseFragmentDefinition();\n\n        case 'schema':\n        case 'scalar':\n        case 'type':\n        case 'interface':\n        case 'union':\n        case 'enum':\n        case 'input':\n        case 'directive':\n          return this.parseTypeSystemDefinition();\n\n        case 'extend':\n          return this.parseTypeSystemExtension();\n      }\n    } else if (this.peek(TokenKind.BRACE_L)) {\n      return this.parseOperationDefinition();\n    } else if (this.peekDescription()) {\n      return this.parseTypeSystemDefinition();\n    }\n\n    throw this.unexpected();\n  } // Implements the parsing rules in the Operations section.\n\n  /**\n   * OperationDefinition :\n   *  - SelectionSet\n   *  - OperationType Name? VariableDefinitions? Directives? SelectionSet\n   */\n  ;\n\n  _proto.parseOperationDefinition = function parseOperationDefinition() {\n    var start = this._lexer.token;\n\n    if (this.peek(TokenKind.BRACE_L)) {\n      return {\n        kind: Kind.OPERATION_DEFINITION,\n        operation: 'query',\n        name: undefined,\n        variableDefinitions: [],\n        directives: [],\n        selectionSet: this.parseSelectionSet(),\n        loc: this.loc(start)\n      };\n    }\n\n    var operation = this.parseOperationType();\n    var name;\n\n    if (this.peek(TokenKind.NAME)) {\n      name = this.parseName();\n    }\n\n    return {\n      kind: Kind.OPERATION_DEFINITION,\n      operation: operation,\n      name: name,\n      variableDefinitions: this.parseVariableDefinitions(),\n      directives: this.parseDirectives(false),\n      selectionSet: this.parseSelectionSet(),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * OperationType : one of query mutation subscription\n   */\n  ;\n\n  _proto.parseOperationType = function parseOperationType() {\n    var operationToken = this.expectToken(TokenKind.NAME);\n\n    switch (operationToken.value) {\n      case 'query':\n        return 'query';\n\n      case 'mutation':\n        return 'mutation';\n\n      case 'subscription':\n        return 'subscription';\n    }\n\n    throw this.unexpected(operationToken);\n  }\n  /**\n   * VariableDefinitions : ( VariableDefinition+ )\n   */\n  ;\n\n  _proto.parseVariableDefinitions = function parseVariableDefinitions() {\n    return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R);\n  }\n  /**\n   * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?\n   */\n  ;\n\n  _proto.parseVariableDefinition = function parseVariableDefinition() {\n    var start = this._lexer.token;\n    return {\n      kind: Kind.VARIABLE_DEFINITION,\n      variable: this.parseVariable(),\n      type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),\n      defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined,\n      directives: this.parseDirectives(true),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * Variable : $ Name\n   */\n  ;\n\n  _proto.parseVariable = function parseVariable() {\n    var start = this._lexer.token;\n    this.expectToken(TokenKind.DOLLAR);\n    return {\n      kind: Kind.VARIABLE,\n      name: this.parseName(),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * SelectionSet : { Selection+ }\n   */\n  ;\n\n  _proto.parseSelectionSet = function parseSelectionSet() {\n    var start = this._lexer.token;\n    return {\n      kind: Kind.SELECTION_SET,\n      selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * Selection :\n   *   - Field\n   *   - FragmentSpread\n   *   - InlineFragment\n   */\n  ;\n\n  _proto.parseSelection = function parseSelection() {\n    return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();\n  }\n  /**\n   * Field : Alias? Name Arguments? Directives? SelectionSet?\n   *\n   * Alias : Name :\n   */\n  ;\n\n  _proto.parseField = function parseField() {\n    var start = this._lexer.token;\n    var nameOrAlias = this.parseName();\n    var alias;\n    var name;\n\n    if (this.expectOptionalToken(TokenKind.COLON)) {\n      alias = nameOrAlias;\n      name = this.parseName();\n    } else {\n      name = nameOrAlias;\n    }\n\n    return {\n      kind: Kind.FIELD,\n      alias: alias,\n      name: name,\n      arguments: this.parseArguments(false),\n      directives: this.parseDirectives(false),\n      selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * Arguments[Const] : ( Argument[?Const]+ )\n   */\n  ;\n\n  _proto.parseArguments = function parseArguments(isConst) {\n    var item = isConst ? this.parseConstArgument : this.parseArgument;\n    return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);\n  }\n  /**\n   * Argument[Const] : Name : Value[?Const]\n   */\n  ;\n\n  _proto.parseArgument = function parseArgument() {\n    var start = this._lexer.token;\n    var name = this.parseName();\n    this.expectToken(TokenKind.COLON);\n    return {\n      kind: Kind.ARGUMENT,\n      name: name,\n      value: this.parseValueLiteral(false),\n      loc: this.loc(start)\n    };\n  };\n\n  _proto.parseConstArgument = function parseConstArgument() {\n    var start = this._lexer.token;\n    return {\n      kind: Kind.ARGUMENT,\n      name: this.parseName(),\n      value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)),\n      loc: this.loc(start)\n    };\n  } // Implements the parsing rules in the Fragments section.\n\n  /**\n   * Corresponds to both FragmentSpread and InlineFragment in the spec.\n   *\n   * FragmentSpread : ... FragmentName Directives?\n   *\n   * InlineFragment : ... TypeCondition? Directives? SelectionSet\n   */\n  ;\n\n  _proto.parseFragment = function parseFragment() {\n    var start = this._lexer.token;\n    this.expectToken(TokenKind.SPREAD);\n    var hasTypeCondition = this.expectOptionalKeyword('on');\n\n    if (!hasTypeCondition && this.peek(TokenKind.NAME)) {\n      return {\n        kind: Kind.FRAGMENT_SPREAD,\n        name: this.parseFragmentName(),\n        directives: this.parseDirectives(false),\n        loc: this.loc(start)\n      };\n    }\n\n    return {\n      kind: Kind.INLINE_FRAGMENT,\n      typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,\n      directives: this.parseDirectives(false),\n      selectionSet: this.parseSelectionSet(),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * FragmentDefinition :\n   *   - fragment FragmentName on TypeCondition Directives? SelectionSet\n   *\n   * TypeCondition : NamedType\n   */\n  ;\n\n  _proto.parseFragmentDefinition = function parseFragmentDefinition() {\n    var _this$_options;\n\n    var start = this._lexer.token;\n    this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes\n    // the grammar of FragmentDefinition:\n    //   - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet\n\n    if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) {\n      return {\n        kind: Kind.FRAGMENT_DEFINITION,\n        name: this.parseFragmentName(),\n        variableDefinitions: this.parseVariableDefinitions(),\n        typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n        directives: this.parseDirectives(false),\n        selectionSet: this.parseSelectionSet(),\n        loc: this.loc(start)\n      };\n    }\n\n    return {\n      kind: Kind.FRAGMENT_DEFINITION,\n      name: this.parseFragmentName(),\n      typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n      directives: this.parseDirectives(false),\n      selectionSet: this.parseSelectionSet(),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * FragmentName : Name but not `on`\n   */\n  ;\n\n  _proto.parseFragmentName = function parseFragmentName() {\n    if (this._lexer.token.value === 'on') {\n      throw this.unexpected();\n    }\n\n    return this.parseName();\n  } // Implements the parsing rules in the Values section.\n\n  /**\n   * Value[Const] :\n   *   - [~Const] Variable\n   *   - IntValue\n   *   - FloatValue\n   *   - StringValue\n   *   - BooleanValue\n   *   - NullValue\n   *   - EnumValue\n   *   - ListValue[?Const]\n   *   - ObjectValue[?Const]\n   *\n   * BooleanValue : one of `true` `false`\n   *\n   * NullValue : `null`\n   *\n   * EnumValue : Name but not `true`, `false` or `null`\n   */\n  ;\n\n  _proto.parseValueLiteral = function parseValueLiteral(isConst) {\n    var token = this._lexer.token;\n\n    switch (token.kind) {\n      case TokenKind.BRACKET_L:\n        return this.parseList(isConst);\n\n      case TokenKind.BRACE_L:\n        return this.parseObject(isConst);\n\n      case TokenKind.INT:\n        this._lexer.advance();\n\n        return {\n          kind: Kind.INT,\n          value: token.value,\n          loc: this.loc(token)\n        };\n\n      case TokenKind.FLOAT:\n        this._lexer.advance();\n\n        return {\n          kind: Kind.FLOAT,\n          value: token.value,\n          loc: this.loc(token)\n        };\n\n      case TokenKind.STRING:\n      case TokenKind.BLOCK_STRING:\n        return this.parseStringLiteral();\n\n      case TokenKind.NAME:\n        this._lexer.advance();\n\n        switch (token.value) {\n          case 'true':\n            return {\n              kind: Kind.BOOLEAN,\n              value: true,\n              loc: this.loc(token)\n            };\n\n          case 'false':\n            return {\n              kind: Kind.BOOLEAN,\n              value: false,\n              loc: this.loc(token)\n            };\n\n          case 'null':\n            return {\n              kind: Kind.NULL,\n              loc: this.loc(token)\n            };\n\n          default:\n            return {\n              kind: Kind.ENUM,\n              value: token.value,\n              loc: this.loc(token)\n            };\n        }\n\n      case TokenKind.DOLLAR:\n        if (!isConst) {\n          return this.parseVariable();\n        }\n\n        break;\n    }\n\n    throw this.unexpected();\n  };\n\n  _proto.parseStringLiteral = function parseStringLiteral() {\n    var token = this._lexer.token;\n\n    this._lexer.advance();\n\n    return {\n      kind: Kind.STRING,\n      value: token.value,\n      block: token.kind === TokenKind.BLOCK_STRING,\n      loc: this.loc(token)\n    };\n  }\n  /**\n   * ListValue[Const] :\n   *   - [ ]\n   *   - [ Value[?Const]+ ]\n   */\n  ;\n\n  _proto.parseList = function parseList(isConst) {\n    var _this = this;\n\n    var start = this._lexer.token;\n\n    var item = function item() {\n      return _this.parseValueLiteral(isConst);\n    };\n\n    return {\n      kind: Kind.LIST,\n      values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ObjectValue[Const] :\n   *   - { }\n   *   - { ObjectField[?Const]+ }\n   */\n  ;\n\n  _proto.parseObject = function parseObject(isConst) {\n    var _this2 = this;\n\n    var start = this._lexer.token;\n\n    var item = function item() {\n      return _this2.parseObjectField(isConst);\n    };\n\n    return {\n      kind: Kind.OBJECT,\n      fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ObjectField[Const] : Name : Value[?Const]\n   */\n  ;\n\n  _proto.parseObjectField = function parseObjectField(isConst) {\n    var start = this._lexer.token;\n    var name = this.parseName();\n    this.expectToken(TokenKind.COLON);\n    return {\n      kind: Kind.OBJECT_FIELD,\n      name: name,\n      value: this.parseValueLiteral(isConst),\n      loc: this.loc(start)\n    };\n  } // Implements the parsing rules in the Directives section.\n\n  /**\n   * Directives[Const] : Directive[?Const]+\n   */\n  ;\n\n  _proto.parseDirectives = function parseDirectives(isConst) {\n    var directives = [];\n\n    while (this.peek(TokenKind.AT)) {\n      directives.push(this.parseDirective(isConst));\n    }\n\n    return directives;\n  }\n  /**\n   * Directive[Const] : @ Name Arguments[?Const]?\n   */\n  ;\n\n  _proto.parseDirective = function parseDirective(isConst) {\n    var start = this._lexer.token;\n    this.expectToken(TokenKind.AT);\n    return {\n      kind: Kind.DIRECTIVE,\n      name: this.parseName(),\n      arguments: this.parseArguments(isConst),\n      loc: this.loc(start)\n    };\n  } // Implements the parsing rules in the Types section.\n\n  /**\n   * Type :\n   *   - NamedType\n   *   - ListType\n   *   - NonNullType\n   */\n  ;\n\n  _proto.parseTypeReference = function parseTypeReference() {\n    var start = this._lexer.token;\n    var type;\n\n    if (this.expectOptionalToken(TokenKind.BRACKET_L)) {\n      type = this.parseTypeReference();\n      this.expectToken(TokenKind.BRACKET_R);\n      type = {\n        kind: Kind.LIST_TYPE,\n        type: type,\n        loc: this.loc(start)\n      };\n    } else {\n      type = this.parseNamedType();\n    }\n\n    if (this.expectOptionalToken(TokenKind.BANG)) {\n      return {\n        kind: Kind.NON_NULL_TYPE,\n        type: type,\n        loc: this.loc(start)\n      };\n    }\n\n    return type;\n  }\n  /**\n   * NamedType : Name\n   */\n  ;\n\n  _proto.parseNamedType = function parseNamedType() {\n    var start = this._lexer.token;\n    return {\n      kind: Kind.NAMED_TYPE,\n      name: this.parseName(),\n      loc: this.loc(start)\n    };\n  } // Implements the parsing rules in the Type Definition section.\n\n  /**\n   * TypeSystemDefinition :\n   *   - SchemaDefinition\n   *   - TypeDefinition\n   *   - DirectiveDefinition\n   *\n   * TypeDefinition :\n   *   - ScalarTypeDefinition\n   *   - ObjectTypeDefinition\n   *   - InterfaceTypeDefinition\n   *   - UnionTypeDefinition\n   *   - EnumTypeDefinition\n   *   - InputObjectTypeDefinition\n   */\n  ;\n\n  _proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() {\n    // Many definitions begin with a description and require a lookahead.\n    var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token;\n\n    if (keywordToken.kind === TokenKind.NAME) {\n      switch (keywordToken.value) {\n        case 'schema':\n          return this.parseSchemaDefinition();\n\n        case 'scalar':\n          return this.parseScalarTypeDefinition();\n\n        case 'type':\n          return this.parseObjectTypeDefinition();\n\n        case 'interface':\n          return this.parseInterfaceTypeDefinition();\n\n        case 'union':\n          return this.parseUnionTypeDefinition();\n\n        case 'enum':\n          return this.parseEnumTypeDefinition();\n\n        case 'input':\n          return this.parseInputObjectTypeDefinition();\n\n        case 'directive':\n          return this.parseDirectiveDefinition();\n      }\n    }\n\n    throw this.unexpected(keywordToken);\n  };\n\n  _proto.peekDescription = function peekDescription() {\n    return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);\n  }\n  /**\n   * Description : StringValue\n   */\n  ;\n\n  _proto.parseDescription = function parseDescription() {\n    if (this.peekDescription()) {\n      return this.parseStringLiteral();\n    }\n  }\n  /**\n   * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }\n   */\n  ;\n\n  _proto.parseSchemaDefinition = function parseSchemaDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('schema');\n    var directives = this.parseDirectives(true);\n    var operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);\n    return {\n      kind: Kind.SCHEMA_DEFINITION,\n      description: description,\n      directives: directives,\n      operationTypes: operationTypes,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * OperationTypeDefinition : OperationType : NamedType\n   */\n  ;\n\n  _proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() {\n    var start = this._lexer.token;\n    var operation = this.parseOperationType();\n    this.expectToken(TokenKind.COLON);\n    var type = this.parseNamedType();\n    return {\n      kind: Kind.OPERATION_TYPE_DEFINITION,\n      operation: operation,\n      type: type,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ScalarTypeDefinition : Description? scalar Name Directives[Const]?\n   */\n  ;\n\n  _proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('scalar');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    return {\n      kind: Kind.SCALAR_TYPE_DEFINITION,\n      description: description,\n      name: name,\n      directives: directives,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ObjectTypeDefinition :\n   *   Description?\n   *   type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?\n   */\n  ;\n\n  _proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('type');\n    var name = this.parseName();\n    var interfaces = this.parseImplementsInterfaces();\n    var directives = this.parseDirectives(true);\n    var fields = this.parseFieldsDefinition();\n    return {\n      kind: Kind.OBJECT_TYPE_DEFINITION,\n      description: description,\n      name: name,\n      interfaces: interfaces,\n      directives: directives,\n      fields: fields,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ImplementsInterfaces :\n   *   - implements `&`? NamedType\n   *   - ImplementsInterfaces & NamedType\n   */\n  ;\n\n  _proto.parseImplementsInterfaces = function parseImplementsInterfaces() {\n    var _this$_options2;\n\n    if (!this.expectOptionalKeyword('implements')) {\n      return [];\n    }\n\n    if (((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true) {\n      var types = []; // Optional leading ampersand\n\n      this.expectOptionalToken(TokenKind.AMP);\n\n      do {\n        types.push(this.parseNamedType());\n      } while (this.expectOptionalToken(TokenKind.AMP) || this.peek(TokenKind.NAME));\n\n      return types;\n    }\n\n    return this.delimitedMany(TokenKind.AMP, this.parseNamedType);\n  }\n  /**\n   * FieldsDefinition : { FieldDefinition+ }\n   */\n  ;\n\n  _proto.parseFieldsDefinition = function parseFieldsDefinition() {\n    var _this$_options3;\n\n    // Legacy support for the SDL?\n    if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) {\n      this._lexer.advance();\n\n      this._lexer.advance();\n\n      return [];\n    }\n\n    return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R);\n  }\n  /**\n   * FieldDefinition :\n   *   - Description? Name ArgumentsDefinition? : Type Directives[Const]?\n   */\n  ;\n\n  _proto.parseFieldDefinition = function parseFieldDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    var name = this.parseName();\n    var args = this.parseArgumentDefs();\n    this.expectToken(TokenKind.COLON);\n    var type = this.parseTypeReference();\n    var directives = this.parseDirectives(true);\n    return {\n      kind: Kind.FIELD_DEFINITION,\n      description: description,\n      name: name,\n      arguments: args,\n      type: type,\n      directives: directives,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ArgumentsDefinition : ( InputValueDefinition+ )\n   */\n  ;\n\n  _proto.parseArgumentDefs = function parseArgumentDefs() {\n    return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R);\n  }\n  /**\n   * InputValueDefinition :\n   *   - Description? Name : Type DefaultValue? Directives[Const]?\n   */\n  ;\n\n  _proto.parseInputValueDef = function parseInputValueDef() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    var name = this.parseName();\n    this.expectToken(TokenKind.COLON);\n    var type = this.parseTypeReference();\n    var defaultValue;\n\n    if (this.expectOptionalToken(TokenKind.EQUALS)) {\n      defaultValue = this.parseValueLiteral(true);\n    }\n\n    var directives = this.parseDirectives(true);\n    return {\n      kind: Kind.INPUT_VALUE_DEFINITION,\n      description: description,\n      name: name,\n      type: type,\n      defaultValue: defaultValue,\n      directives: directives,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * InterfaceTypeDefinition :\n   *   - Description? interface Name Directives[Const]? FieldsDefinition?\n   */\n  ;\n\n  _proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('interface');\n    var name = this.parseName();\n    var interfaces = this.parseImplementsInterfaces();\n    var directives = this.parseDirectives(true);\n    var fields = this.parseFieldsDefinition();\n    return {\n      kind: Kind.INTERFACE_TYPE_DEFINITION,\n      description: description,\n      name: name,\n      interfaces: interfaces,\n      directives: directives,\n      fields: fields,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * UnionTypeDefinition :\n   *   - Description? union Name Directives[Const]? UnionMemberTypes?\n   */\n  ;\n\n  _proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('union');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    var types = this.parseUnionMemberTypes();\n    return {\n      kind: Kind.UNION_TYPE_DEFINITION,\n      description: description,\n      name: name,\n      directives: directives,\n      types: types,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * UnionMemberTypes :\n   *   - = `|`? NamedType\n   *   - UnionMemberTypes | NamedType\n   */\n  ;\n\n  _proto.parseUnionMemberTypes = function parseUnionMemberTypes() {\n    return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : [];\n  }\n  /**\n   * EnumTypeDefinition :\n   *   - Description? enum Name Directives[Const]? EnumValuesDefinition?\n   */\n  ;\n\n  _proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('enum');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    var values = this.parseEnumValuesDefinition();\n    return {\n      kind: Kind.ENUM_TYPE_DEFINITION,\n      description: description,\n      name: name,\n      directives: directives,\n      values: values,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * EnumValuesDefinition : { EnumValueDefinition+ }\n   */\n  ;\n\n  _proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() {\n    return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R);\n  }\n  /**\n   * EnumValueDefinition : Description? EnumValue Directives[Const]?\n   *\n   * EnumValue : Name\n   */\n  ;\n\n  _proto.parseEnumValueDefinition = function parseEnumValueDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    return {\n      kind: Kind.ENUM_VALUE_DEFINITION,\n      description: description,\n      name: name,\n      directives: directives,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * InputObjectTypeDefinition :\n   *   - Description? input Name Directives[Const]? InputFieldsDefinition?\n   */\n  ;\n\n  _proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('input');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    var fields = this.parseInputFieldsDefinition();\n    return {\n      kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,\n      description: description,\n      name: name,\n      directives: directives,\n      fields: fields,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * InputFieldsDefinition : { InputValueDefinition+ }\n   */\n  ;\n\n  _proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() {\n    return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R);\n  }\n  /**\n   * TypeSystemExtension :\n   *   - SchemaExtension\n   *   - TypeExtension\n   *\n   * TypeExtension :\n   *   - ScalarTypeExtension\n   *   - ObjectTypeExtension\n   *   - InterfaceTypeExtension\n   *   - UnionTypeExtension\n   *   - EnumTypeExtension\n   *   - InputObjectTypeDefinition\n   */\n  ;\n\n  _proto.parseTypeSystemExtension = function parseTypeSystemExtension() {\n    var keywordToken = this._lexer.lookahead();\n\n    if (keywordToken.kind === TokenKind.NAME) {\n      switch (keywordToken.value) {\n        case 'schema':\n          return this.parseSchemaExtension();\n\n        case 'scalar':\n          return this.parseScalarTypeExtension();\n\n        case 'type':\n          return this.parseObjectTypeExtension();\n\n        case 'interface':\n          return this.parseInterfaceTypeExtension();\n\n        case 'union':\n          return this.parseUnionTypeExtension();\n\n        case 'enum':\n          return this.parseEnumTypeExtension();\n\n        case 'input':\n          return this.parseInputObjectTypeExtension();\n      }\n    }\n\n    throw this.unexpected(keywordToken);\n  }\n  /**\n   * SchemaExtension :\n   *  - extend schema Directives[Const]? { OperationTypeDefinition+ }\n   *  - extend schema Directives[Const]\n   */\n  ;\n\n  _proto.parseSchemaExtension = function parseSchemaExtension() {\n    var start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('schema');\n    var directives = this.parseDirectives(true);\n    var operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);\n\n    if (directives.length === 0 && operationTypes.length === 0) {\n      throw this.unexpected();\n    }\n\n    return {\n      kind: Kind.SCHEMA_EXTENSION,\n      directives: directives,\n      operationTypes: operationTypes,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ScalarTypeExtension :\n   *   - extend scalar Name Directives[Const]\n   */\n  ;\n\n  _proto.parseScalarTypeExtension = function parseScalarTypeExtension() {\n    var start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('scalar');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n\n    if (directives.length === 0) {\n      throw this.unexpected();\n    }\n\n    return {\n      kind: Kind.SCALAR_TYPE_EXTENSION,\n      name: name,\n      directives: directives,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * ObjectTypeExtension :\n   *  - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n   *  - extend type Name ImplementsInterfaces? Directives[Const]\n   *  - extend type Name ImplementsInterfaces\n   */\n  ;\n\n  _proto.parseObjectTypeExtension = function parseObjectTypeExtension() {\n    var start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('type');\n    var name = this.parseName();\n    var interfaces = this.parseImplementsInterfaces();\n    var directives = this.parseDirectives(true);\n    var fields = this.parseFieldsDefinition();\n\n    if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n      throw this.unexpected();\n    }\n\n    return {\n      kind: Kind.OBJECT_TYPE_EXTENSION,\n      name: name,\n      interfaces: interfaces,\n      directives: directives,\n      fields: fields,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * InterfaceTypeExtension :\n   *  - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n   *  - extend interface Name ImplementsInterfaces? Directives[Const]\n   *  - extend interface Name ImplementsInterfaces\n   */\n  ;\n\n  _proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() {\n    var start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('interface');\n    var name = this.parseName();\n    var interfaces = this.parseImplementsInterfaces();\n    var directives = this.parseDirectives(true);\n    var fields = this.parseFieldsDefinition();\n\n    if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n      throw this.unexpected();\n    }\n\n    return {\n      kind: Kind.INTERFACE_TYPE_EXTENSION,\n      name: name,\n      interfaces: interfaces,\n      directives: directives,\n      fields: fields,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * UnionTypeExtension :\n   *   - extend union Name Directives[Const]? UnionMemberTypes\n   *   - extend union Name Directives[Const]\n   */\n  ;\n\n  _proto.parseUnionTypeExtension = function parseUnionTypeExtension() {\n    var start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('union');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    var types = this.parseUnionMemberTypes();\n\n    if (directives.length === 0 && types.length === 0) {\n      throw this.unexpected();\n    }\n\n    return {\n      kind: Kind.UNION_TYPE_EXTENSION,\n      name: name,\n      directives: directives,\n      types: types,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * EnumTypeExtension :\n   *   - extend enum Name Directives[Const]? EnumValuesDefinition\n   *   - extend enum Name Directives[Const]\n   */\n  ;\n\n  _proto.parseEnumTypeExtension = function parseEnumTypeExtension() {\n    var start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('enum');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    var values = this.parseEnumValuesDefinition();\n\n    if (directives.length === 0 && values.length === 0) {\n      throw this.unexpected();\n    }\n\n    return {\n      kind: Kind.ENUM_TYPE_EXTENSION,\n      name: name,\n      directives: directives,\n      values: values,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * InputObjectTypeExtension :\n   *   - extend input Name Directives[Const]? InputFieldsDefinition\n   *   - extend input Name Directives[Const]\n   */\n  ;\n\n  _proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() {\n    var start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('input');\n    var name = this.parseName();\n    var directives = this.parseDirectives(true);\n    var fields = this.parseInputFieldsDefinition();\n\n    if (directives.length === 0 && fields.length === 0) {\n      throw this.unexpected();\n    }\n\n    return {\n      kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n      name: name,\n      directives: directives,\n      fields: fields,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * DirectiveDefinition :\n   *   - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations\n   */\n  ;\n\n  _proto.parseDirectiveDefinition = function parseDirectiveDefinition() {\n    var start = this._lexer.token;\n    var description = this.parseDescription();\n    this.expectKeyword('directive');\n    this.expectToken(TokenKind.AT);\n    var name = this.parseName();\n    var args = this.parseArgumentDefs();\n    var repeatable = this.expectOptionalKeyword('repeatable');\n    this.expectKeyword('on');\n    var locations = this.parseDirectiveLocations();\n    return {\n      kind: Kind.DIRECTIVE_DEFINITION,\n      description: description,\n      name: name,\n      arguments: args,\n      repeatable: repeatable,\n      locations: locations,\n      loc: this.loc(start)\n    };\n  }\n  /**\n   * DirectiveLocations :\n   *   - `|`? DirectiveLocation\n   *   - DirectiveLocations | DirectiveLocation\n   */\n  ;\n\n  _proto.parseDirectiveLocations = function parseDirectiveLocations() {\n    return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);\n  }\n  /*\n   * DirectiveLocation :\n   *   - ExecutableDirectiveLocation\n   *   - TypeSystemDirectiveLocation\n   *\n   * ExecutableDirectiveLocation : one of\n   *   `QUERY`\n   *   `MUTATION`\n   *   `SUBSCRIPTION`\n   *   `FIELD`\n   *   `FRAGMENT_DEFINITION`\n   *   `FRAGMENT_SPREAD`\n   *   `INLINE_FRAGMENT`\n   *\n   * TypeSystemDirectiveLocation : one of\n   *   `SCHEMA`\n   *   `SCALAR`\n   *   `OBJECT`\n   *   `FIELD_DEFINITION`\n   *   `ARGUMENT_DEFINITION`\n   *   `INTERFACE`\n   *   `UNION`\n   *   `ENUM`\n   *   `ENUM_VALUE`\n   *   `INPUT_OBJECT`\n   *   `INPUT_FIELD_DEFINITION`\n   */\n  ;\n\n  _proto.parseDirectiveLocation = function parseDirectiveLocation() {\n    var start = this._lexer.token;\n    var name = this.parseName();\n\n    if (DirectiveLocation[name.value] !== undefined) {\n      return name;\n    }\n\n    throw this.unexpected(start);\n  } // Core parsing utility functions\n\n  /**\n   * Returns a location object, used to identify the place in the source that created a given parsed object.\n   */\n  ;\n\n  _proto.loc = function loc(startToken) {\n    var _this$_options4;\n\n    if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) {\n      return new Location(startToken, this._lexer.lastToken, this._lexer.source);\n    }\n  }\n  /**\n   * Determines if the next token is of a given kind\n   */\n  ;\n\n  _proto.peek = function peek(kind) {\n    return this._lexer.token.kind === kind;\n  }\n  /**\n   * If the next token is of the given kind, return that token after advancing the lexer.\n   * Otherwise, do not change the parser state and throw an error.\n   */\n  ;\n\n  _proto.expectToken = function expectToken(kind) {\n    var token = this._lexer.token;\n\n    if (token.kind === kind) {\n      this._lexer.advance();\n\n      return token;\n    }\n\n    throw syntaxError(this._lexer.source, token.start, \"Expected \".concat(getTokenKindDesc(kind), \", found \").concat(getTokenDesc(token), \".\"));\n  }\n  /**\n   * If the next token is of the given kind, return that token after advancing the lexer.\n   * Otherwise, do not change the parser state and return undefined.\n   */\n  ;\n\n  _proto.expectOptionalToken = function expectOptionalToken(kind) {\n    var token = this._lexer.token;\n\n    if (token.kind === kind) {\n      this._lexer.advance();\n\n      return token;\n    }\n\n    return undefined;\n  }\n  /**\n   * If the next token is a given keyword, advance the lexer.\n   * Otherwise, do not change the parser state and throw an error.\n   */\n  ;\n\n  _proto.expectKeyword = function expectKeyword(value) {\n    var token = this._lexer.token;\n\n    if (token.kind === TokenKind.NAME && token.value === value) {\n      this._lexer.advance();\n    } else {\n      throw syntaxError(this._lexer.source, token.start, \"Expected \\\"\".concat(value, \"\\\", found \").concat(getTokenDesc(token), \".\"));\n    }\n  }\n  /**\n   * If the next token is a given keyword, return \"true\" after advancing the lexer.\n   * Otherwise, do not change the parser state and return \"false\".\n   */\n  ;\n\n  _proto.expectOptionalKeyword = function expectOptionalKeyword(value) {\n    var token = this._lexer.token;\n\n    if (token.kind === TokenKind.NAME && token.value === value) {\n      this._lexer.advance();\n\n      return true;\n    }\n\n    return false;\n  }\n  /**\n   * Helper function for creating an error when an unexpected lexed token is encountered.\n   */\n  ;\n\n  _proto.unexpected = function unexpected(atToken) {\n    var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;\n    return syntaxError(this._lexer.source, token.start, \"Unexpected \".concat(getTokenDesc(token), \".\"));\n  }\n  /**\n   * Returns a possibly empty list of parse nodes, determined by the parseFn.\n   * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n   * Advances the parser to the next lex token after the closing token.\n   */\n  ;\n\n  _proto.any = function any(openKind, parseFn, closeKind) {\n    this.expectToken(openKind);\n    var nodes = [];\n\n    while (!this.expectOptionalToken(closeKind)) {\n      nodes.push(parseFn.call(this));\n    }\n\n    return nodes;\n  }\n  /**\n   * Returns a list of parse nodes, determined by the parseFn.\n   * It can be empty only if open token is missing otherwise it will always return non-empty list\n   * that begins with a lex token of openKind and ends with a lex token of closeKind.\n   * Advances the parser to the next lex token after the closing token.\n   */\n  ;\n\n  _proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) {\n    if (this.expectOptionalToken(openKind)) {\n      var nodes = [];\n\n      do {\n        nodes.push(parseFn.call(this));\n      } while (!this.expectOptionalToken(closeKind));\n\n      return nodes;\n    }\n\n    return [];\n  }\n  /**\n   * Returns a non-empty list of parse nodes, determined by the parseFn.\n   * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n   * Advances the parser to the next lex token after the closing token.\n   */\n  ;\n\n  _proto.many = function many(openKind, parseFn, closeKind) {\n    this.expectToken(openKind);\n    var nodes = [];\n\n    do {\n      nodes.push(parseFn.call(this));\n    } while (!this.expectOptionalToken(closeKind));\n\n    return nodes;\n  }\n  /**\n   * Returns a non-empty list of parse nodes, determined by the parseFn.\n   * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.\n   * Advances the parser to the next lex token after last item in the list.\n   */\n  ;\n\n  _proto.delimitedMany = function delimitedMany(delimiterKind, parseFn) {\n    this.expectOptionalToken(delimiterKind);\n    var nodes = [];\n\n    do {\n      nodes.push(parseFn.call(this));\n    } while (this.expectOptionalToken(delimiterKind));\n\n    return nodes;\n  };\n\n  return Parser;\n}();\n/**\n * A helper function to describe a token as a string for debugging.\n */\n\nfunction getTokenDesc(token) {\n  var value = token.value;\n  return getTokenKindDesc(token.kind) + (value != null ? \" \\\"\".concat(value, \"\\\"\") : '');\n}\n/**\n * A helper function to describe a token kind as a string for debugging.\n */\n\n\nfunction getTokenKindDesc(kind) {\n  return isPunctuatorTokenKind(kind) ? \"\\\"\".concat(kind, \"\\\"\") : kind;\n}\n", "import inspect from \"../jsutils/inspect.mjs\";\nimport { isNode } from \"./ast.mjs\";\n/**\n * A visitor is provided to visit, it contains the collection of\n * relevant functions to be called during the visitor's traversal.\n */\n\nexport var QueryDocumentKeys = {\n  Name: [],\n  Document: ['definitions'],\n  OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],\n  VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],\n  Variable: ['name'],\n  SelectionSet: ['selections'],\n  Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],\n  Argument: ['name', 'value'],\n  FragmentSpread: ['name', 'directives'],\n  InlineFragment: ['typeCondition', 'directives', 'selectionSet'],\n  FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed\n  // or removed in the future.\n  'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],\n  IntValue: [],\n  FloatValue: [],\n  StringValue: [],\n  BooleanValue: [],\n  NullValue: [],\n  EnumValue: [],\n  ListValue: ['values'],\n  ObjectValue: ['fields'],\n  ObjectField: ['name', 'value'],\n  Directive: ['name', 'arguments'],\n  NamedType: ['name'],\n  ListType: ['type'],\n  NonNullType: ['type'],\n  SchemaDefinition: ['description', 'directives', 'operationTypes'],\n  OperationTypeDefinition: ['type'],\n  ScalarTypeDefinition: ['description', 'name', 'directives'],\n  ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],\n  FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],\n  InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],\n  InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],\n  UnionTypeDefinition: ['description', 'name', 'directives', 'types'],\n  EnumTypeDefinition: ['description', 'name', 'directives', 'values'],\n  EnumValueDefinition: ['description', 'name', 'directives'],\n  InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],\n  DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],\n  SchemaExtension: ['directives', 'operationTypes'],\n  ScalarTypeExtension: ['name', 'directives'],\n  ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n  InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n  UnionTypeExtension: ['name', 'directives', 'types'],\n  EnumTypeExtension: ['name', 'directives', 'values'],\n  InputObjectTypeExtension: ['name', 'directives', 'fields']\n};\nexport var BREAK = Object.freeze({});\n/**\n * visit() will walk through an AST using a depth-first traversal, calling\n * the visitor's enter function at each node in the traversal, and calling the\n * leave function after visiting that node and all of its child nodes.\n *\n * By returning different values from the enter and leave functions, the\n * behavior of the visitor can be altered, including skipping over a sub-tree of\n * the AST (by returning false), editing the AST by returning a value or null\n * to remove the value, or to stop the whole traversal by returning BREAK.\n *\n * When using visit() to edit an AST, the original AST will not be modified, and\n * a new version of the AST with the changes applied will be returned from the\n * visit function.\n *\n *     const editedAST = visit(ast, {\n *       enter(node, key, parent, path, ancestors) {\n *         // @return\n *         //   undefined: no action\n *         //   false: skip visiting this node\n *         //   visitor.BREAK: stop visiting altogether\n *         //   null: delete this node\n *         //   any value: replace this node with the returned value\n *       },\n *       leave(node, key, parent, path, ancestors) {\n *         // @return\n *         //   undefined: no action\n *         //   false: no action\n *         //   visitor.BREAK: stop visiting altogether\n *         //   null: delete this node\n *         //   any value: replace this node with the returned value\n *       }\n *     });\n *\n * Alternatively to providing enter() and leave() functions, a visitor can\n * instead provide functions named the same as the kinds of AST nodes, or\n * enter/leave visitors at a named key, leading to four permutations of the\n * visitor API:\n *\n * 1) Named visitors triggered when entering a node of a specific kind.\n *\n *     visit(ast, {\n *       Kind(node) {\n *         // enter the \"Kind\" node\n *       }\n *     })\n *\n * 2) Named visitors that trigger upon entering and leaving a node of\n *    a specific kind.\n *\n *     visit(ast, {\n *       Kind: {\n *         enter(node) {\n *           // enter the \"Kind\" node\n *         }\n *         leave(node) {\n *           // leave the \"Kind\" node\n *         }\n *       }\n *     })\n *\n * 3) Generic visitors that trigger upon entering and leaving any node.\n *\n *     visit(ast, {\n *       enter(node) {\n *         // enter any node\n *       },\n *       leave(node) {\n *         // leave any node\n *       }\n *     })\n *\n * 4) Parallel visitors for entering and leaving nodes of a specific kind.\n *\n *     visit(ast, {\n *       enter: {\n *         Kind(node) {\n *           // enter the \"Kind\" node\n *         }\n *       },\n *       leave: {\n *         Kind(node) {\n *           // leave the \"Kind\" node\n *         }\n *       }\n *     })\n */\n\nexport function visit(root, visitor) {\n  var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;\n\n  /* eslint-disable no-undef-init */\n  var stack = undefined;\n  var inArray = Array.isArray(root);\n  var keys = [root];\n  var index = -1;\n  var edits = [];\n  var node = undefined;\n  var key = undefined;\n  var parent = undefined;\n  var path = [];\n  var ancestors = [];\n  var newRoot = root;\n  /* eslint-enable no-undef-init */\n\n  do {\n    index++;\n    var isLeaving = index === keys.length;\n    var isEdited = isLeaving && edits.length !== 0;\n\n    if (isLeaving) {\n      key = ancestors.length === 0 ? undefined : path[path.length - 1];\n      node = parent;\n      parent = ancestors.pop();\n\n      if (isEdited) {\n        if (inArray) {\n          node = node.slice();\n        } else {\n          var clone = {};\n\n          for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {\n            var k = _Object$keys2[_i2];\n            clone[k] = node[k];\n          }\n\n          node = clone;\n        }\n\n        var editOffset = 0;\n\n        for (var ii = 0; ii < edits.length; ii++) {\n          var editKey = edits[ii][0];\n          var editValue = edits[ii][1];\n\n          if (inArray) {\n            editKey -= editOffset;\n          }\n\n          if (inArray && editValue === null) {\n            node.splice(editKey, 1);\n            editOffset++;\n          } else {\n            node[editKey] = editValue;\n          }\n        }\n      }\n\n      index = stack.index;\n      keys = stack.keys;\n      edits = stack.edits;\n      inArray = stack.inArray;\n      stack = stack.prev;\n    } else {\n      key = parent ? inArray ? index : keys[index] : undefined;\n      node = parent ? parent[key] : newRoot;\n\n      if (node === null || node === undefined) {\n        continue;\n      }\n\n      if (parent) {\n        path.push(key);\n      }\n    }\n\n    var result = void 0;\n\n    if (!Array.isArray(node)) {\n      if (!isNode(node)) {\n        throw new Error(\"Invalid AST Node: \".concat(inspect(node), \".\"));\n      }\n\n      var visitFn = getVisitFn(visitor, node.kind, isLeaving);\n\n      if (visitFn) {\n        result = visitFn.call(visitor, node, key, parent, path, ancestors);\n\n        if (result === BREAK) {\n          break;\n        }\n\n        if (result === false) {\n          if (!isLeaving) {\n            path.pop();\n            continue;\n          }\n        } else if (result !== undefined) {\n          edits.push([key, result]);\n\n          if (!isLeaving) {\n            if (isNode(result)) {\n              node = result;\n            } else {\n              path.pop();\n              continue;\n            }\n          }\n        }\n      }\n    }\n\n    if (result === undefined && isEdited) {\n      edits.push([key, node]);\n    }\n\n    if (isLeaving) {\n      path.pop();\n    } else {\n      var _visitorKeys$node$kin;\n\n      stack = {\n        inArray: inArray,\n        index: index,\n        keys: keys,\n        edits: edits,\n        prev: stack\n      };\n      inArray = Array.isArray(node);\n      keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : [];\n      index = -1;\n      edits = [];\n\n      if (parent) {\n        ancestors.push(parent);\n      }\n\n      parent = node;\n    }\n  } while (stack !== undefined);\n\n  if (edits.length !== 0) {\n    newRoot = edits[edits.length - 1][1];\n  }\n\n  return newRoot;\n}\n/**\n * Creates a new visitor instance which delegates to many visitors to run in\n * parallel. Each visitor will be visited for each node before moving on.\n *\n * If a prior visitor edits a node, no following visitors will see that node.\n */\n\nexport function visitInParallel(visitors) {\n  var skipping = new Array(visitors.length);\n  return {\n    enter: function enter(node) {\n      for (var i = 0; i < visitors.length; i++) {\n        if (skipping[i] == null) {\n          var fn = getVisitFn(visitors[i], node.kind,\n          /* isLeaving */\n          false);\n\n          if (fn) {\n            var result = fn.apply(visitors[i], arguments);\n\n            if (result === false) {\n              skipping[i] = node;\n            } else if (result === BREAK) {\n              skipping[i] = BREAK;\n            } else if (result !== undefined) {\n              return result;\n            }\n          }\n        }\n      }\n    },\n    leave: function leave(node) {\n      for (var i = 0; i < visitors.length; i++) {\n        if (skipping[i] == null) {\n          var fn = getVisitFn(visitors[i], node.kind,\n          /* isLeaving */\n          true);\n\n          if (fn) {\n            var result = fn.apply(visitors[i], arguments);\n\n            if (result === BREAK) {\n              skipping[i] = BREAK;\n            } else if (result !== undefined && result !== false) {\n              return result;\n            }\n          }\n        } else if (skipping[i] === node) {\n          skipping[i] = null;\n        }\n      }\n    }\n  };\n}\n/**\n * Given a visitor instance, if it is leaving or not, and a node kind, return\n * the function the visitor runtime should call.\n */\n\nexport function getVisitFn(visitor, kind, isLeaving) {\n  var kindVisitor = visitor[kind];\n\n  if (kindVisitor) {\n    if (!isLeaving && typeof kindVisitor === 'function') {\n      // { Kind() {} }\n      return kindVisitor;\n    }\n\n    var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;\n\n    if (typeof kindSpecificVisitor === 'function') {\n      // { Kind: { enter() {}, leave() {} } }\n      return kindSpecificVisitor;\n    }\n  } else {\n    var specificVisitor = isLeaving ? visitor.leave : visitor.enter;\n\n    if (specificVisitor) {\n      if (typeof specificVisitor === 'function') {\n        // { enter() {}, leave() {} }\n        return specificVisitor;\n      }\n\n      var specificKindVisitor = specificVisitor[kind];\n\n      if (typeof specificKindVisitor === 'function') {\n        // { enter: { Kind() {} }, leave: { Kind() {} } }\n        return specificKindVisitor;\n      }\n    }\n  }\n}\n", "import { visit } from \"./visitor.mjs\";\nimport { printBlockString } from \"./blockString.mjs\";\n/**\n * Converts an AST into a string, using one set of reasonable\n * formatting rules.\n */\n\nexport function print(ast) {\n  return visit(ast, {\n    leave: printDocASTReducer\n  });\n}\nvar MAX_LINE_LENGTH = 80; // TODO: provide better type coverage in future\n\nvar printDocASTReducer = {\n  Name: function Name(node) {\n    return node.value;\n  },\n  Variable: function Variable(node) {\n    return '$' + node.name;\n  },\n  // Document\n  Document: function Document(node) {\n    return join(node.definitions, '\\n\\n') + '\\n';\n  },\n  OperationDefinition: function OperationDefinition(node) {\n    var op = node.operation;\n    var name = node.name;\n    var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');\n    var directives = join(node.directives, ' ');\n    var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use\n    // the query short form.\n\n    return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' ');\n  },\n  VariableDefinition: function VariableDefinition(_ref) {\n    var variable = _ref.variable,\n        type = _ref.type,\n        defaultValue = _ref.defaultValue,\n        directives = _ref.directives;\n    return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' '));\n  },\n  SelectionSet: function SelectionSet(_ref2) {\n    var selections = _ref2.selections;\n    return block(selections);\n  },\n  Field: function Field(_ref3) {\n    var alias = _ref3.alias,\n        name = _ref3.name,\n        args = _ref3.arguments,\n        directives = _ref3.directives,\n        selectionSet = _ref3.selectionSet;\n    var prefix = wrap('', alias, ': ') + name;\n    var argsLine = prefix + wrap('(', join(args, ', '), ')');\n\n    if (argsLine.length > MAX_LINE_LENGTH) {\n      argsLine = prefix + wrap('(\\n', indent(join(args, '\\n')), '\\n)');\n    }\n\n    return join([argsLine, join(directives, ' '), selectionSet], ' ');\n  },\n  Argument: function Argument(_ref4) {\n    var name = _ref4.name,\n        value = _ref4.value;\n    return name + ': ' + value;\n  },\n  // Fragments\n  FragmentSpread: function FragmentSpread(_ref5) {\n    var name = _ref5.name,\n        directives = _ref5.directives;\n    return '...' + name + wrap(' ', join(directives, ' '));\n  },\n  InlineFragment: function InlineFragment(_ref6) {\n    var typeCondition = _ref6.typeCondition,\n        directives = _ref6.directives,\n        selectionSet = _ref6.selectionSet;\n    return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');\n  },\n  FragmentDefinition: function FragmentDefinition(_ref7) {\n    var name = _ref7.name,\n        typeCondition = _ref7.typeCondition,\n        variableDefinitions = _ref7.variableDefinitions,\n        directives = _ref7.directives,\n        selectionSet = _ref7.selectionSet;\n    return (// Note: fragment variable definitions are experimental and may be changed\n      // or removed in the future.\n      \"fragment \".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), \" \") + \"on \".concat(typeCondition, \" \").concat(wrap('', join(directives, ' '), ' ')) + selectionSet\n    );\n  },\n  // Value\n  IntValue: function IntValue(_ref8) {\n    var value = _ref8.value;\n    return value;\n  },\n  FloatValue: function FloatValue(_ref9) {\n    var value = _ref9.value;\n    return value;\n  },\n  StringValue: function StringValue(_ref10, key) {\n    var value = _ref10.value,\n        isBlockString = _ref10.block;\n    return isBlockString ? printBlockString(value, key === 'description' ? '' : '  ') : JSON.stringify(value);\n  },\n  BooleanValue: function BooleanValue(_ref11) {\n    var value = _ref11.value;\n    return value ? 'true' : 'false';\n  },\n  NullValue: function NullValue() {\n    return 'null';\n  },\n  EnumValue: function EnumValue(_ref12) {\n    var value = _ref12.value;\n    return value;\n  },\n  ListValue: function ListValue(_ref13) {\n    var values = _ref13.values;\n    return '[' + join(values, ', ') + ']';\n  },\n  ObjectValue: function ObjectValue(_ref14) {\n    var fields = _ref14.fields;\n    return '{' + join(fields, ', ') + '}';\n  },\n  ObjectField: function ObjectField(_ref15) {\n    var name = _ref15.name,\n        value = _ref15.value;\n    return name + ': ' + value;\n  },\n  // Directive\n  Directive: function Directive(_ref16) {\n    var name = _ref16.name,\n        args = _ref16.arguments;\n    return '@' + name + wrap('(', join(args, ', '), ')');\n  },\n  // Type\n  NamedType: function NamedType(_ref17) {\n    var name = _ref17.name;\n    return name;\n  },\n  ListType: function ListType(_ref18) {\n    var type = _ref18.type;\n    return '[' + type + ']';\n  },\n  NonNullType: function NonNullType(_ref19) {\n    var type = _ref19.type;\n    return type + '!';\n  },\n  // Type System Definitions\n  SchemaDefinition: addDescription(function (_ref20) {\n    var directives = _ref20.directives,\n        operationTypes = _ref20.operationTypes;\n    return join(['schema', join(directives, ' '), block(operationTypes)], ' ');\n  }),\n  OperationTypeDefinition: function OperationTypeDefinition(_ref21) {\n    var operation = _ref21.operation,\n        type = _ref21.type;\n    return operation + ': ' + type;\n  },\n  ScalarTypeDefinition: addDescription(function (_ref22) {\n    var name = _ref22.name,\n        directives = _ref22.directives;\n    return join(['scalar', name, join(directives, ' ')], ' ');\n  }),\n  ObjectTypeDefinition: addDescription(function (_ref23) {\n    var name = _ref23.name,\n        interfaces = _ref23.interfaces,\n        directives = _ref23.directives,\n        fields = _ref23.fields;\n    return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');\n  }),\n  FieldDefinition: addDescription(function (_ref24) {\n    var name = _ref24.name,\n        args = _ref24.arguments,\n        type = _ref24.type,\n        directives = _ref24.directives;\n    return name + (hasMultilineItems(args) ? wrap('(\\n', indent(join(args, '\\n')), '\\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' '));\n  }),\n  InputValueDefinition: addDescription(function (_ref25) {\n    var name = _ref25.name,\n        type = _ref25.type,\n        defaultValue = _ref25.defaultValue,\n        directives = _ref25.directives;\n    return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ');\n  }),\n  InterfaceTypeDefinition: addDescription(function (_ref26) {\n    var name = _ref26.name,\n        interfaces = _ref26.interfaces,\n        directives = _ref26.directives,\n        fields = _ref26.fields;\n    return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');\n  }),\n  UnionTypeDefinition: addDescription(function (_ref27) {\n    var name = _ref27.name,\n        directives = _ref27.directives,\n        types = _ref27.types;\n    return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');\n  }),\n  EnumTypeDefinition: addDescription(function (_ref28) {\n    var name = _ref28.name,\n        directives = _ref28.directives,\n        values = _ref28.values;\n    return join(['enum', name, join(directives, ' '), block(values)], ' ');\n  }),\n  EnumValueDefinition: addDescription(function (_ref29) {\n    var name = _ref29.name,\n        directives = _ref29.directives;\n    return join([name, join(directives, ' ')], ' ');\n  }),\n  InputObjectTypeDefinition: addDescription(function (_ref30) {\n    var name = _ref30.name,\n        directives = _ref30.directives,\n        fields = _ref30.fields;\n    return join(['input', name, join(directives, ' '), block(fields)], ' ');\n  }),\n  DirectiveDefinition: addDescription(function (_ref31) {\n    var name = _ref31.name,\n        args = _ref31.arguments,\n        repeatable = _ref31.repeatable,\n        locations = _ref31.locations;\n    return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\\n', indent(join(args, '\\n')), '\\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ');\n  }),\n  SchemaExtension: function SchemaExtension(_ref32) {\n    var directives = _ref32.directives,\n        operationTypes = _ref32.operationTypes;\n    return join(['extend schema', join(directives, ' '), block(operationTypes)], ' ');\n  },\n  ScalarTypeExtension: function ScalarTypeExtension(_ref33) {\n    var name = _ref33.name,\n        directives = _ref33.directives;\n    return join(['extend scalar', name, join(directives, ' ')], ' ');\n  },\n  ObjectTypeExtension: function ObjectTypeExtension(_ref34) {\n    var name = _ref34.name,\n        interfaces = _ref34.interfaces,\n        directives = _ref34.directives,\n        fields = _ref34.fields;\n    return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');\n  },\n  InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) {\n    var name = _ref35.name,\n        interfaces = _ref35.interfaces,\n        directives = _ref35.directives,\n        fields = _ref35.fields;\n    return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');\n  },\n  UnionTypeExtension: function UnionTypeExtension(_ref36) {\n    var name = _ref36.name,\n        directives = _ref36.directives,\n        types = _ref36.types;\n    return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');\n  },\n  EnumTypeExtension: function EnumTypeExtension(_ref37) {\n    var name = _ref37.name,\n        directives = _ref37.directives,\n        values = _ref37.values;\n    return join(['extend enum', name, join(directives, ' '), block(values)], ' ');\n  },\n  InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) {\n    var name = _ref38.name,\n        directives = _ref38.directives,\n        fields = _ref38.fields;\n    return join(['extend input', name, join(directives, ' '), block(fields)], ' ');\n  }\n};\n\nfunction addDescription(cb) {\n  return function (node) {\n    return join([node.description, cb(node)], '\\n');\n  };\n}\n/**\n * Given maybeArray, print an empty string if it is null or empty, otherwise\n * print all items together separated by separator if provided\n */\n\n\nfunction join(maybeArray) {\n  var _maybeArray$filter$jo;\n\n  var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n  return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) {\n    return x;\n  }).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : '';\n}\n/**\n * Given array, print each item on its own line, wrapped in an\n * indented \"{ }\" block.\n */\n\n\nfunction block(array) {\n  return wrap('{\\n', indent(join(array, '\\n')), '\\n}');\n}\n/**\n * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.\n */\n\n\nfunction wrap(start, maybeString) {\n  var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';\n  return maybeString != null && maybeString !== '' ? start + maybeString + end : '';\n}\n\nfunction indent(str) {\n  return wrap('  ', str.replace(/\\n/g, '\\n  '));\n}\n\nfunction isMultiline(str) {\n  return str.indexOf('\\n') !== -1;\n}\n\nfunction hasMultilineItems(maybeArray) {\n  return maybeArray != null && maybeArray.some(isMultiline);\n}\n", "import { Kind } from \"./kinds.mjs\";\nexport function isDefinitionNode(node) {\n  return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);\n}\nexport function isExecutableDefinitionNode(node) {\n  return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION;\n}\nexport function isSelectionNode(node) {\n  return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT;\n}\nexport function isValueNode(node) {\n  return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT;\n}\nexport function isTypeNode(node) {\n  return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE;\n}\nexport function isTypeSystemDefinitionNode(node) {\n  return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION;\n}\nexport function isTypeDefinitionNode(node) {\n  return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION;\n}\nexport function isTypeSystemExtensionNode(node) {\n  return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);\n}\nexport function isTypeExtensionNode(node) {\n  return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION;\n}\n", "import { Source, isSource } from \"../language/source.mjs\";\nimport { TokenKind } from \"../language/tokenKind.mjs\";\nimport { Lexer, isPunctuatorTokenKind } from \"../language/lexer.mjs\";\nimport { dedentBlockStringValue, getBlockStringIndentation } from \"../language/blockString.mjs\";\n/**\n * Strips characters that are not significant to the validity or execution\n * of a GraphQL document:\n *   - UnicodeBOM\n *   - WhiteSpace\n *   - LineTerminator\n *   - Comment\n *   - Comma\n *   - BlockString indentation\n *\n * Note: It is required to have a delimiter character between neighboring\n * non-punctuator tokens and this function always uses single space as delimiter.\n *\n * It is guaranteed that both input and output documents if parsed would result\n * in the exact same AST except for nodes location.\n *\n * Warning: It is guaranteed that this function will always produce stable results.\n * However, it's not guaranteed that it will stay the same between different\n * releases due to bugfixes or changes in the GraphQL specification.\n *\n * Query example:\n *\n * query SomeQuery($foo: String!, $bar: String) {\n *   someField(foo: $foo, bar: $bar) {\n *     a\n *     b {\n *       c\n *       d\n *     }\n *   }\n * }\n *\n * Becomes:\n *\n * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}\n *\n * SDL example:\n *\n * \"\"\"\n * Type description\n * \"\"\"\n * type Foo {\n *   \"\"\"\n *   Field description\n *   \"\"\"\n *   bar: String\n * }\n *\n * Becomes:\n *\n * \"\"\"Type description\"\"\" type Foo{\"\"\"Field description\"\"\" bar:String}\n */\n\nexport function stripIgnoredCharacters(source) {\n  var sourceObj = isSource(source) ? source : new Source(source);\n  var body = sourceObj.body;\n  var lexer = new Lexer(sourceObj);\n  var strippedBody = '';\n  var wasLastAddedTokenNonPunctuator = false;\n\n  while (lexer.advance().kind !== TokenKind.EOF) {\n    var currentToken = lexer.token;\n    var tokenKind = currentToken.kind;\n    /**\n     * Every two non-punctuator tokens should have space between them.\n     * Also prevent case of non-punctuator token following by spread resulting\n     * in invalid token (e.g. `1...` is invalid Float token).\n     */\n\n    var isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);\n\n    if (wasLastAddedTokenNonPunctuator) {\n      if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {\n        strippedBody += ' ';\n      }\n    }\n\n    var tokenBody = body.slice(currentToken.start, currentToken.end);\n\n    if (tokenKind === TokenKind.BLOCK_STRING) {\n      strippedBody += dedentBlockString(tokenBody);\n    } else {\n      strippedBody += tokenBody;\n    }\n\n    wasLastAddedTokenNonPunctuator = isNonPunctuator;\n  }\n\n  return strippedBody;\n}\n\nfunction dedentBlockString(blockStr) {\n  // skip leading and trailing triple quotations\n  var rawStr = blockStr.slice(3, -3);\n  var body = dedentBlockStringValue(rawStr);\n\n  if (getBlockStringIndentation(body) > 0) {\n    body = '\\n' + body;\n  }\n\n  var lastChar = body[body.length - 1];\n  var hasTrailingQuote = lastChar === '\"' && body.slice(-4) !== '\\\\\"\"\"';\n\n  if (hasTrailingQuote || lastChar === '\\\\') {\n    body += '\\n';\n  }\n\n  return '\"\"\"' + body + '\"\"\"';\n}\n", "import { invariant } from \"../globals/index.js\";\n\n// Provides the methods that allow QueryManager to handle the `skip` and\n// `include` directives within GraphQL.\nimport type {\n  SelectionNode,\n  VariableNode,\n  BooleanValueNode,\n  DirectiveNode,\n  DocumentNode,\n  ArgumentNode,\n  ValueNode,\n  ASTNode,\n} from \"graphql\";\nimport { visit, BREAK } from \"graphql\";\n\nexport type DirectiveInfo = {\n  [fieldName: string]: { [argName: string]: any };\n};\n\nexport function shouldInclude(\n  { directives }: SelectionNode,\n  variables?: Record<string, any>\n): boolean {\n  if (!directives || !directives.length) {\n    return true;\n  }\n  return getInclusionDirectives(directives).every(\n    ({ directive, ifArgument }) => {\n      let evaledValue: boolean = false;\n      if (ifArgument.value.kind === \"Variable\") {\n        evaledValue =\n          variables && variables[(ifArgument.value as VariableNode).name.value];\n        invariant(\n          evaledValue !== void 0,\n          `Invalid variable referenced in @%s directive.`,\n          directive.name.value\n        );\n      } else {\n        evaledValue = (ifArgument.value as BooleanValueNode).value;\n      }\n      return directive.name.value === \"skip\" ? !evaledValue : evaledValue;\n    }\n  );\n}\n\nexport function getDirectiveNames(root: ASTNode) {\n  const names: string[] = [];\n\n  visit(root, {\n    Directive(node: DirectiveNode) {\n      names.push(node.name.value);\n    },\n  });\n\n  return names;\n}\n\nexport const hasAnyDirectives = (names: string[], root: ASTNode) =>\n  hasDirectives(names, root, false);\n\nexport const hasAllDirectives = (names: string[], root: ASTNode) =>\n  hasDirectives(names, root, true);\n\nexport function hasDirectives(names: string[], root: ASTNode, all?: boolean) {\n  const nameSet = new Set(names);\n  const uniqueCount = nameSet.size;\n\n  visit(root, {\n    Directive(node) {\n      if (nameSet.delete(node.name.value) && (!all || !nameSet.size)) {\n        return BREAK;\n      }\n    },\n  });\n\n  // If we found all the names, nameSet will be empty. If we only care about\n  // finding some of them, the < condition is sufficient.\n  return all ? !nameSet.size : nameSet.size < uniqueCount;\n}\n\nexport function hasClientExports(document: DocumentNode) {\n  return document && hasDirectives([\"client\", \"export\"], document, true);\n}\n\nexport type InclusionDirectives = Array<{\n  directive: DirectiveNode;\n  ifArgument: ArgumentNode;\n}>;\n\nfunction isInclusionDirective({ name: { value } }: DirectiveNode): boolean {\n  return value === \"skip\" || value === \"include\";\n}\n\nexport function getInclusionDirectives(\n  directives: ReadonlyArray<DirectiveNode>\n): InclusionDirectives {\n  const result: InclusionDirectives = [];\n\n  if (directives && directives.length) {\n    directives.forEach((directive) => {\n      if (!isInclusionDirective(directive)) return;\n\n      const directiveArguments = directive.arguments;\n      const directiveName = directive.name.value;\n\n      invariant(\n        directiveArguments && directiveArguments.length === 1,\n        `Incorrect number of arguments for the @%s directive.`,\n        directiveName\n      );\n\n      const ifArgument = directiveArguments![0];\n      invariant(\n        ifArgument.name && ifArgument.name.value === \"if\",\n        `Invalid argument for the @%s directive.`,\n        directiveName\n      );\n\n      const ifValue: ValueNode = ifArgument.value;\n\n      // means it has to be a variable value if this is a valid @skip or @include directive\n      invariant(\n        ifValue &&\n          (ifValue.kind === \"Variable\" || ifValue.kind === \"BooleanValue\"),\n        `Argument for the @%s directive must be a variable or a boolean value.`,\n        directiveName\n      );\n\n      result.push({ directive, ifArgument });\n    });\n  }\n\n  return result;\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<Data> {\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<any, Trie<Data>>;\n  private strong?: Map<any, Trie<Data>>;\n  private data?: Data;\n\n  constructor(\n    private weakness = true,\n    private makeData: (array: any[]) => Data = defaultMakeData,\n  ) {}\n\n  public lookup<T extends any[]>(...array: T): Data;\n  public lookup(): Data {\n    return this.lookupArray(arguments);\n  }\n\n  public lookupArray<T extends IArguments | any[]>(array: T): Data {\n    let node: Trie<Data> = 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<T extends any[]>(...array: T): Data | undefined;\n  public peek(): Data | undefined {\n    return this.peekArray(arguments);\n  }\n\n  public peekArray<T extends IArguments | any[]>(array: T): Data | undefined {\n    let node: Trie<Data> | 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<T extends IArguments | any[]>(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<Data>(this.weakness, this.makeData));\n    return child;\n  }\n\n  private mapFor(key: any, create: boolean): Trie<Data>[\"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", "import { maybe } from \"../globals/index.js\";\n\nexport const canUseWeakMap =\n  typeof WeakMap === \"function\" &&\n  !maybe(\n    () => navigator.product == \"ReactNative\" && !(global as any).HermesInternal\n  );\n\nexport const canUseWeakSet = typeof WeakSet === \"function\";\n\nexport const canUseSymbol =\n  typeof Symbol === \"function\" && typeof Symbol.for === \"function\";\n\nexport const canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;\n\nexport const canUseDOM =\n  typeof maybe(() => window.document.createElement) === \"function\";\n\nconst usingJSDOM: boolean =\n  // Following advice found in this comment from @domenic (maintainer of jsdom):\n  // https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327\n  //\n  // Since we control the version of Jest and jsdom used when running Apollo\n  // Client tests, and that version is recent enought to include \" jsdom/x.y.z\"\n  // at the end of the user agent string, I believe this case is all we need to\n  // check. Testing for \"Node.js\" was recommended for backwards compatibility\n  // with older version of jsdom, but we don't have that problem.\n  maybe(() => navigator.userAgent.indexOf(\"jsdom\") >= 0) || false;\n\n// Our tests should all continue to pass if we remove this !usingJSDOM\n// condition, thereby allowing useLayoutEffect when using jsdom. Unfortunately,\n// if we allow useLayoutEffect, then useSyncExternalStore generates many\n// warnings about useLayoutEffect doing nothing on the server. While these\n// warnings are harmless, this !usingJSDOM condition seems to be the best way to\n// prevent them (i.e. skipping useLayoutEffect when using jsdom).\nexport const canUseLayoutEffect = canUseDOM && !usingJSDOM;\n", "export function isNonNullObject(obj: any): obj is Record<string | number, any> {\n  return obj !== null && typeof obj === \"object\";\n}\n\nexport function isPlainObject(obj: any): obj is Record<string | number, any> {\n  return (\n    obj !== null &&\n    typeof obj === \"object\" &&\n    (Object.getPrototypeOf(obj) === Object.prototype ||\n      Object.getPrototypeOf(obj) === null)\n  );\n}\n", "import { invariant, newInvariantError } from \"../globals/index.js\";\n\nimport type {\n  DocumentNode,\n  FragmentDefinitionNode,\n  InlineFragmentNode,\n  SelectionNode,\n} from \"graphql\";\n\n// TODO(brian): A hack until this issue is resolved (https://github.com/graphql/graphql-js/issues/3356)\ntype Kind = any;\ntype OperationTypeNode = any;\n/**\n * Returns a query document which adds a single query operation that only\n * spreads the target fragment inside of it.\n *\n * So for example a document of:\n *\n * ```graphql\n * fragment foo on Foo { a b c }\n * ```\n *\n * Turns into:\n *\n * ```graphql\n * { ...foo }\n *\n * fragment foo on Foo { a b c }\n * ```\n *\n * The target fragment will either be the only fragment in the document, or a\n * fragment specified by the provided `fragmentName`. If there is more than one\n * fragment, but a `fragmentName` was not defined then an error will be thrown.\n */\nexport function getFragmentQueryDocument(\n  document: DocumentNode,\n  fragmentName?: string\n): DocumentNode {\n  let actualFragmentName = fragmentName;\n\n  // Build an array of all our fragment definitions that will be used for\n  // validations. We also do some validations on the other definitions in the\n  // document while building this list.\n  const fragments: Array<FragmentDefinitionNode> = [];\n  document.definitions.forEach((definition) => {\n    // Throw an error if we encounter an operation definition because we will\n    // define our own operation definition later on.\n    if (definition.kind === \"OperationDefinition\") {\n      throw newInvariantError(\n        `Found a %s operation%s. ` +\n          \"No operations are allowed when using a fragment as a query. Only fragments are allowed.\",\n        definition.operation,\n        definition.name ? ` named '${definition.name.value}'` : \"\"\n      );\n    }\n    // Add our definition to the fragments array if it is a fragment\n    // definition.\n    if (definition.kind === \"FragmentDefinition\") {\n      fragments.push(definition);\n    }\n  });\n\n  // If the user did not give us a fragment name then let us try to get a\n  // name from a single fragment in the definition.\n  if (typeof actualFragmentName === \"undefined\") {\n    invariant(\n      fragments.length === 1,\n      `Found %s fragments. \\`fragmentName\\` must be provided when there is not exactly 1 fragment.`,\n      fragments.length\n    );\n    actualFragmentName = fragments[0].name.value;\n  }\n\n  // Generate a query document with an operation that simply spreads the\n  // fragment inside of it.\n  const query: DocumentNode = {\n    ...document,\n    definitions: [\n      {\n        kind: \"OperationDefinition\" as Kind,\n        // OperationTypeNode is an enum\n        operation: \"query\" as OperationTypeNode,\n        selectionSet: {\n          kind: \"SelectionSet\" as Kind,\n          selections: [\n            {\n              kind: \"FragmentSpread\" as Kind,\n              name: {\n                kind: \"Name\" as Kind,\n                value: actualFragmentName,\n              },\n            },\n          ],\n        },\n      },\n      ...document.definitions,\n    ],\n  };\n\n  return query;\n}\n\n/**\n * This is an interface that describes a map from fragment names to fragment definitions.\n */\nexport interface FragmentMap {\n  [fragmentName: string]: FragmentDefinitionNode;\n}\n\nexport type FragmentMapFunction = (\n  fragmentName: string\n) => FragmentDefinitionNode | null;\n\n// Utility function that takes a list of fragment definitions and makes a hash out of them\n// that maps the name of the fragment to the fragment definition.\nexport function createFragmentMap(\n  fragments: FragmentDefinitionNode[] = []\n): FragmentMap {\n  const symTable: FragmentMap = {};\n  fragments.forEach((fragment) => {\n    symTable[fragment.name.value] = fragment;\n  });\n  return symTable;\n}\n\nexport function getFragmentFromSelection(\n  selection: SelectionNode,\n  fragmentMap?: FragmentMap | FragmentMapFunction\n): InlineFragmentNode | FragmentDefinitionNode | null {\n  switch (selection.kind) {\n    case \"InlineFragment\":\n      return selection;\n    case \"FragmentSpread\": {\n      const fragmentName = selection.name.value;\n      if (typeof fragmentMap === \"function\") {\n        return fragmentMap(fragmentName);\n      }\n      const fragment = fragmentMap && fragmentMap[fragmentName];\n      invariant(fragment, `No fragment named %s`, fragmentName);\n      return fragment || null;\n    }\n    default:\n      return null;\n  }\n}\n", "import type { CommonCache } from \"./common\";\n\ninterface Node<K, V> {\n  key: K;\n  value: V;\n  newer: Node<K, V> | null;\n  older: Node<K, V> | null;\n}\n\nfunction defaultDispose() {}\n\nexport class StrongCache<K = any, V = any> implements CommonCache<K, V> {\n  private map = new Map<K, Node<K, V>>();\n  private newest: Node<K, V> | null = null;\n  private oldest: Node<K, V> | null = null;\n\n  constructor(\n    private max = Infinity,\n    public dispose: (value: V, key: K) => void = defaultDispose,\n  ) {}\n\n  public has(key: K): boolean {\n    return this.map.has(key);\n  }\n\n  public get(key: K): V | undefined {\n    const node = this.getNode(key);\n    return node && node.value;\n  }\n\n  public get size() {\n    return this.map.size;\n  }\n\n  private getNode(key: K): Node<K, V> | undefined {\n    const node = this.map.get(key);\n\n    if (node && node !== this.newest) {\n      const { older, newer } = node;\n\n      if (newer) {\n        newer.older = older;\n      }\n\n      if (older) {\n        older.newer = newer;\n      }\n\n      node.older = this.newest;\n      node.older!.newer = node;\n\n      node.newer = null;\n      this.newest = node;\n\n      if (node === this.oldest) {\n        this.oldest = newer;\n      }\n    }\n\n    return node;\n  }\n\n  public set(key: K, value: V): V {\n    let node = this.getNode(key);\n    if (node) {\n      return node.value = value;\n    }\n\n    node = {\n      key,\n      value,\n      newer: null,\n      older: this.newest\n    };\n\n    if (this.newest) {\n      this.newest.newer = node;\n    }\n\n    this.newest = node;\n    this.oldest = this.oldest || node;\n\n    this.map.set(key, node);\n\n    return node.value;\n  }\n\n  public clean() {\n    while (this.oldest && this.map.size > this.max) {\n      this.delete(this.oldest.key);\n    }\n  }\n\n  public delete(key: K): boolean {\n    const node = this.map.get(key);\n    if (node) {\n      if (node === this.newest) {\n        this.newest = node.older;\n      }\n\n      if (node === this.oldest) {\n        this.oldest = node.newer;\n      }\n\n      if (node.newer) {\n        node.newer.older = node.older;\n      }\n\n      if (node.older) {\n        node.older.newer = node.newer;\n      }\n\n      this.map.delete(key);\n      this.dispose(node.value, key);\n\n      return true;\n    }\n\n    return false;\n  }\n}\n", "import type { CommonCache } from \"./common\";\n\ninterface PartialNode<K extends object, V> {\n  value: V;\n  newer: Node<K, V> | null;\n  older: Node<K, V> | null;\n}\n\ninterface UnfinalizedNode<K extends object, V> extends PartialNode<K, V> {\n  keyRef?: undefined;\n  key: K;\n}\n\ninterface FullNode<K extends object, V> extends PartialNode<K, V> {\n  keyRef: WeakRef<K>;\n  key?: undefined;\n}\n\ntype Node<K extends object, V> = FullNode<K, V> | UnfinalizedNode<K, V>;\n\nfunction noop() {}\nconst defaultDispose = noop;\n\nconst _WeakRef =\n  typeof WeakRef !== \"undefined\"\n    ? WeakRef\n    : (function <T>(value: T) {\n        return { deref: () => value } satisfies Omit<\n          WeakRef<any>,\n          typeof Symbol.toStringTag\n        >;\n      } as any as typeof WeakRef);\nconst _WeakMap = typeof WeakMap !== \"undefined\" ? WeakMap : Map;\nconst _FinalizationRegistry =\n  typeof FinalizationRegistry !== \"undefined\"\n    ? FinalizationRegistry\n    : (function <T>() {\n        return {\n          register: noop,\n          unregister: noop,\n        } satisfies Omit<FinalizationRegistry<T>, typeof Symbol.toStringTag>;\n      } as any as typeof FinalizationRegistry);\n\nconst finalizationBatchSize = 10024;\n\nexport class WeakCache<K extends object = any, V = any>\n  implements CommonCache<K, V>\n{\n  private map = new _WeakMap<K, Node<K, V>>();\n  private registry: FinalizationRegistry<Node<K, V>>;\n  private newest: Node<K, V> | null = null;\n  private oldest: Node<K, V> | null = null;\n  private unfinalizedNodes: Set<UnfinalizedNode<K, V>> = new Set();\n  private finalizationScheduled = false;\n  public size = 0;\n\n  constructor(\n    private max = Infinity,\n    public dispose: (value: V, key?: K) => void = defaultDispose\n  ) {\n    this.registry = new _FinalizationRegistry<Node<K, V>>(\n      this.deleteNode.bind(this)\n    );\n  }\n\n  public has(key: K): boolean {\n    return this.map.has(key);\n  }\n\n  public get(key: K): V | undefined {\n    const node = this.getNode(key);\n    return node && node.value;\n  }\n\n  private getNode(key: K): Node<K, V> | undefined {\n    const node = this.map.get(key);\n\n    if (node && node !== this.newest) {\n      const { older, newer } = node;\n\n      if (newer) {\n        newer.older = older;\n      }\n\n      if (older) {\n        older.newer = newer;\n      }\n\n      node.older = this.newest;\n      node.older!.newer = node;\n\n      node.newer = null;\n      this.newest = node;\n\n      if (node === this.oldest) {\n        this.oldest = newer;\n      }\n    }\n\n    return node;\n  }\n\n  public set(key: K, value: V): V {\n    let node = this.getNode(key);\n    if (node) {\n      return (node.value = value);\n    }\n\n    node = {\n      key,\n      value,\n      newer: null,\n      older: this.newest,\n    };\n\n    if (this.newest) {\n      this.newest.newer = node;\n    }\n\n    this.newest = node;\n    this.oldest = this.oldest || node;\n\n    this.scheduleFinalization(node);\n    this.map.set(key, node);\n    this.size++;\n\n    return node.value;\n  }\n\n  public clean() {\n    while (this.oldest && this.size > this.max) {\n      this.deleteNode(this.oldest);\n    }\n  }\n\n  private deleteNode(node: Node<K, V>) {\n    if (node === this.newest) {\n      this.newest = node.older;\n    }\n\n    if (node === this.oldest) {\n      this.oldest = node.newer;\n    }\n\n    if (node.newer) {\n      node.newer.older = node.older;\n    }\n\n    if (node.older) {\n      node.older.newer = node.newer;\n    }\n\n    this.size--;\n    const key = node.key || (node.keyRef && node.keyRef.deref());\n    this.dispose(node.value, key);\n    if (!node.keyRef) {\n      this.unfinalizedNodes.delete(node);\n    } else {\n      this.registry.unregister(node);\n    }\n    if (key) this.map.delete(key);\n  }\n\n  public delete(key: K): boolean {\n    const node = this.map.get(key);\n    if (node) {\n      this.deleteNode(node);\n\n      return true;\n    }\n\n    return false;\n  }\n\n  private scheduleFinalization(node: UnfinalizedNode<K, V>) {\n    this.unfinalizedNodes.add(node);\n    if (!this.finalizationScheduled) {\n      this.finalizationScheduled = true;\n      queueMicrotask(this.finalize);\n    }\n  }\n\n  private finalize = () => {\n    const iterator = this.unfinalizedNodes.values();\n    for (let i = 0; i < finalizationBatchSize; i++) {\n      const node = iterator.next().value;\n      if (!node) break;\n      this.unfinalizedNodes.delete(node);\n      const key = node.key;\n      delete (node as unknown as FullNode<K, V>).key;\n      (node as unknown as FullNode<K, V>).keyRef = new _WeakRef(key);\n      this.registry.register(key, node, node);\n    }\n    if (this.unfinalizedNodes.size > 0) {\n      queueMicrotask(this.finalize);\n    } else {\n      this.finalizationScheduled = false;\n    }\n  };\n}\n", "import { WeakCache, StrongCache } from \"@wry/caches\";\n\ninterface CleanableCache {\n  size: number;\n  max?: number;\n  clean: () => void;\n}\nconst scheduledCleanup = new WeakSet<CleanableCache>();\nfunction schedule(cache: CleanableCache) {\n  if (cache.size <= (cache.max || -1)) {\n    return;\n  }\n  if (!scheduledCleanup.has(cache)) {\n    scheduledCleanup.add(cache);\n    setTimeout(() => {\n      cache.clean();\n      scheduledCleanup.delete(cache);\n    }, 100);\n  }\n}\n/**\n * @internal\n * A version of WeakCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of WeakCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `WeakCache`.\n */\nexport const AutoCleanedWeakCache = function (\n  max?: number | undefined,\n  dispose?: ((value: any, key: any) => void) | undefined\n) {\n  /*\n  Some builds of `WeakCache` are function prototypes, some are classes.\n  This library still builds with an ES5 target, so we can't extend the\n  real classes.\n  Instead, we have to use this workaround until we switch to a newer build\n  target.\n  */\n  const cache = new WeakCache(max, dispose);\n  cache.set = function (key: any, value: any) {\n    const ret = WeakCache.prototype.set.call(this, key, value);\n    schedule(this as any as CleanableCache);\n    return ret;\n  };\n  return cache;\n} as any as typeof WeakCache;\n/**\n * @internal\n */\nexport type AutoCleanedWeakCache<K extends object, V> = WeakCache<K, V>;\n\n/**\n * @internal\n * A version of StrongCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of StrongCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `StrongCache`.\n */\nexport const AutoCleanedStrongCache = function (\n  max?: number | undefined,\n  dispose?: ((value: any, key: any) => void) | undefined\n) {\n  /*\n  Some builds of `StrongCache` are function prototypes, some are classes.\n  This library still builds with an ES5 target, so we can't extend the\n  real classes.\n  Instead, we have to use this workaround until we switch to a newer build\n  target.\n  */\n  const cache = new StrongCache(max, dispose);\n  cache.set = function (key: any, value: any) {\n    const ret = StrongCache.prototype.set.call(this, key, value);\n    schedule(this as any as CleanableCache);\n    return ret;\n  };\n  return cache;\n} as any as typeof StrongCache;\n/**\n * @internal\n */\nexport type AutoCleanedStrongCache<K, V> = StrongCache<K, V>;\n", "import { global } from \"../globals/index.js\";\n\ndeclare global {\n  interface Window {\n    [cacheSizeSymbol]?: Partial<CacheSizes>;\n  }\n}\n\n/**\n * The cache sizes used by various Apollo Client caches.\n *\n * @remarks\n * All configurable caches hold memoized values. If an item is\n * cache-collected, it incurs only a small performance impact and\n * doesn't cause data loss. A smaller cache size might save you memory.\n *\n * You should choose cache sizes appropriate for storing a reasonable\n * number of values rather than every value. To prevent too much recalculation,\n * choose cache sizes that are at least large enough to hold memoized values for\n * all hooks/queries on the screen at any given time.\n */\n/*\n * We assume a \"base value\" of 1000 here, which is already very generous.\n * In most applications, it will be very unlikely that 1000 different queries\n * are on screen at the same time.\n */\nexport interface CacheSizes {\n  /**\n   * Cache size for the [`print`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/print.ts) function.\n   *\n   * It is called with transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @remarks\n   * This method is called to transform a GraphQL query AST parsed by `gql`\n   * back into a GraphQL string.\n   *\n   * @privateRemarks\n   * This method is called from the `QueryManager` and various `ApolloLink`s,\n   * always with the \"serverQuery\", so the server-facing part of a transformed\n   * `DocumentNode`.\n   */\n  print: number;\n  /**\n   * Cache size for the [`parser`](https://github.com/apollographql/apollo-client/blob/main/src/react/parser/index.ts) function.\n   *\n   * It is called with user-provided `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `1000`.\n   *\n   * @remarks\n   * This method is called by HOCs and hooks.\n   *\n   * @privateRemarks\n   * This function is used directly in HOCs, and nowadays mainly accessed by\n   * calling `verifyDocumentType` from various hooks.\n   * It is called with a user-provided DocumentNode.\n   */\n  parser: number;\n  /**\n   * Cache size for the cache of [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts)\n   * instances with the `cache` option set to `true`.\n   *\n   * Can be called with user-defined or already-transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @remarks\n   * The cache size here should be chosen with other `DocumentTransform`s in mind.\n   * For example, if there was a `DocumentTransform` that would take `x` `DocumentNode`s,\n   * and returned a differently-transformed `DocumentNode` depending if the app is\n   * online or offline, then we assume that the cache returns `2*x` documents.\n   * If that were concatenated with another `DocumentTransform` that would\n   * also duplicate the cache size, you'd need to account for `4*x` documents\n   * returned by the second transform.\n   *\n   * Due to an implementation detail of Apollo Client, if you use custom document\n   * transforms you should always add `n` (the \"base\" number of user-provided\n   * Documents) to the resulting cache size.\n   *\n   * If we assume that the user-provided transforms receive `n` documents and\n   * return `n` documents, the cache size should be `2*n`.\n   *\n   * If we assume that the chain of user-provided transforms receive `n` documents and\n   * return `4*n` documents, the cache size should be `5*n`.\n   *\n   * This size should also then be used in every other cache that mentions that\n   * it operates on a \"transformed\" `DocumentNode`.\n   *\n   * @privateRemarks\n   * Cache size for the `performWork` method of each [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts).\n   *\n   * No user-provided DocumentNode will actually be \"the last one\", as we run the\n   * `defaultDocumentTransform` before *and* after the user-provided transforms.\n   * For that reason, we need the extra `n` here - `n` for \"before transformation\"\n   * plus the actual maximum cache size of the user-provided transform chain.\n   *\n   * This method is called from `transformDocument`, which is called from\n   * `QueryManager` with a user-provided DocumentNode.\n   * It is also called with already-transformed DocumentNodes, assuming the\n   * user provided additional transforms.\n   *\n   */\n  \"documentTransform.cache\": number;\n  /**\n   * A cache inside of [`QueryManager`](https://github.com/apollographql/apollo-client/blob/main/src/core/QueryManager.ts).\n   *\n   * It is called with transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @privateRemarks\n   * Cache size for the `transformCache` used in the `getDocumentInfo` method of `QueryManager`.\n   * Called throughout the `QueryManager` with transformed DocumentNodes.\n   */\n  \"queryManager.getDocumentInfo\": number;\n  /**\n   * A cache inside of [`PersistedQueryLink`](https://github.com/apollographql/apollo-client/blob/main/src/link/persisted-queries/index.ts).\n   *\n   * It is called with transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @remarks\n   * This cache is used to cache the hashes of persisted queries.\n   *\n   * @privateRemarks\n   * Cache size for the `hashesByQuery` cache in the `PersistedQueryLink`.\n   */\n  \"PersistedQueryLink.persistedQueryHashes\": number;\n  /**\n   * Cache used by [`canonicalStringify`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/common/canonicalStringify.ts).\n   *\n   * @defaultValue\n   * Defaults to `1000`.\n   *\n   * @remarks\n   * This cache contains the sorted keys of objects that are stringified by\n   * `canonicalStringify`.\n   * It uses the stringified unsorted keys of objects as keys.\n   * The cache will not grow beyond the size of different object **shapes**\n   * encountered in an application, no matter how much actual data gets stringified.\n   *\n   * @privateRemarks\n   * Cache size for the `sortingMap` in `canonicalStringify`.\n   */\n  canonicalStringify: number;\n  /**\n   * A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n   *\n   * Can be called with user-defined or already-transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @privateRemarks\n   *\n   * Cache size for the `transform` method of FragmentRegistry.\n   * This function is called as part of the `defaultDocumentTransform` which will be called with\n   * user-provided and already-transformed DocumentNodes.\n   *\n   */\n  \"fragmentRegistry.transform\": number;\n  /**\n   * A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n   *\n   * This function is called with fragment names in the form of a string.\n   *\n   * @defaultValue\n   * Defaults to `1000`.\n   *\n   * @remarks\n   * The size of this case should be chosen with the number of fragments in\n   * your application in mind.\n   *\n   * Note:\n   * This function is a dependency of `fragmentRegistry.transform`, so having too small of a cache size here\n   * might involuntarily invalidate values in the `transform` cache.\n   *\n   * @privateRemarks\n   * Cache size for the `lookup` method of FragmentRegistry.\n   */\n  \"fragmentRegistry.lookup\": number;\n  /**\n   * Cache size for the `findFragmentSpreads` method of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n   *\n   * This function is called with transformed `DocumentNode`s, as well as recursively\n   * with every fragment spread referenced within that, or a fragment referenced by a\n   * fragment spread.\n   *\n   * @defaultValue\n   * Defaults to `4000`.\n   *\n   * @remarks\n   *\n   * Note: This function is a dependency of `fragmentRegistry.transform`, so having too small of cache size here\n   * might involuntarily invalidate values in the `transform` cache.\n   */\n  \"fragmentRegistry.findFragmentSpreads\": number;\n  /**\n   * Cache size for the `getFragmentDoc` method of [`ApolloCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/core/cache.ts).\n   *\n   * This function is called with user-provided fragment definitions.\n   *\n   * @defaultValue\n   * Defaults to `1000`.\n   *\n   * @remarks\n   * This function is called from `readFragment` with user-provided fragment definitions.\n   */\n  \"cache.fragmentQueryDocuments\": number;\n  /**\n   * Cache used in [`removeTypenameFromVariables`](https://github.com/apollographql/apollo-client/blob/main/src/link/remove-typename/removeTypenameFromVariables.ts).\n   *\n   * This function is called transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @privateRemarks\n   * Cache size for the `getVariableDefinitions` function of `removeTypenameFromVariables`.\n   */\n  \"removeTypenameFromVariables.getVariableDefinitions\": number;\n  /**\n   * Cache size for the `maybeBroadcastWatch` method on [`InMemoryCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/inMemoryCache.ts).\n   *\n   * Note: `maybeBroadcastWatch` will be set to the `resultCacheMaxSize` option and\n   * will fall back to this configuration value if the option is not set.\n   *\n   * @defaultValue\n   * Defaults to `5000`.\n   *\n   * @remarks\n   * This method is used for dependency tracking in the `InMemoryCache` and\n   * prevents from unnecessary re-renders.\n   * It is recommended to keep this value significantly higher than the number of\n   * possible subscribers you will have active at the same time in your application\n   * at any time.\n   */\n  \"inMemoryCache.maybeBroadcastWatch\": number;\n  /**\n   * Cache size for the `executeSelectionSet` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).\n   *\n   * Note:\n   * `executeSelectionSet` will be set to the `resultCacheMaxSize` option and\n   * will fall back to this configuration value if the option is not set.\n   *\n   * @defaultValue\n   * Defaults to `10000`.\n   *\n   * @remarks\n   * Every object that is read from the cache will be cached here, so it is\n   * recommended to set this to a high value.\n   */\n  \"inMemoryCache.executeSelectionSet\": number;\n  /**\n   * Cache size for the `executeSubSelectedArray` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).\n   *\n   * Note:\n   * `executeSubSelectedArray` will be set to the `resultCacheMaxSize` option and\n   * will fall back to this configuration value if the option is not set.\n   *\n   * @defaultValue\n   * Defaults to `5000`.\n   *\n   * @remarks\n   * Every array that is read from the cache will be cached here, so it is\n   * recommended to set this to a high value.\n   */\n  \"inMemoryCache.executeSubSelectedArray\": number;\n}\n\nconst cacheSizeSymbol = Symbol.for(\"apollo.cacheSize\");\n/**\n *\n * The global cache size configuration for Apollo Client.\n *\n * @remarks\n *\n * You can directly modify this object, but any modification will\n * only have an effect on caches that are created after the modification.\n *\n * So for global caches, such as `parser`, `canonicalStringify` and `print`,\n * you might need to call `.reset` on them, which will essentially re-create them.\n *\n * Alternatively, you can set `globalThis[Symbol.for(\"apollo.cacheSize\")]` before\n * you load the Apollo Client package:\n *\n * @example\n * ```ts\n * globalThis[Symbol.for(\"apollo.cacheSize\")] = {\n *   parser: 100\n * } satisfies Partial<CacheSizes> // the `satisfies` is optional if using TypeScript\n * ```\n */\nexport const cacheSizes: Partial<CacheSizes> = { ...global[cacheSizeSymbol] };\n\nexport const enum defaultCacheSizes {\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\" = 50000,\n  \"inMemoryCache.executeSubSelectedArray\" = 10000,\n}\n", "import type { OptimisticWrapperFunction } from \"optimism\";\nimport type {\n  InMemoryCache,\n  DocumentTransform,\n  ApolloLink,\n  ApolloCache,\n} from \"../../core/index.js\";\nimport type { ApolloClient } from \"../../core/index.js\";\nimport type { CacheSizes } from \"./sizes.js\";\nimport { cacheSizes, defaultCacheSizes } from \"./sizes.js\";\n\nconst globalCaches: {\n  print?: () => number;\n  parser?: () => number;\n  canonicalStringify?: () => number;\n} = {};\n\nexport function registerGlobalCache(\n  name: keyof typeof globalCaches,\n  getSize: () => number\n) {\n  globalCaches[name] = getSize;\n}\n\n/**\n * Transformative helper type to turn a function of the form\n * ```ts\n * (this: any) => R\n * ```\n * into a function of the form\n * ```ts\n * () => R\n * ```\n * preserving the return type, but removing the `this` parameter.\n *\n * @remarks\n *\n * Further down in the definitions of `_getApolloClientMemoryInternals`,\n * `_getApolloCacheMemoryInternals` and `_getInMemoryCacheMemoryInternals`,\n * having the `this` parameter annotation is extremely useful for type checking\n * inside the function.\n *\n * If this is preserved in the exported types, though, it leads to a situation\n * where `ApolloCache.getMemoryInternals` is a function that requires a `this`\n * of the type `ApolloCache`, while the extending class `InMemoryCache` has a\n * `getMemoryInternals` function that requires a `this` of the type\n * `InMemoryCache`.\n * This is not compatible with TypeScript's inheritence system (although it is\n * perfectly correct), and so TypeScript will complain loudly.\n *\n * We still want to define our functions with the `this` annotation, though,\n * and have the return type inferred.\n * (This requirement for return type inference here makes it impossible to use\n * a function overload that is more explicit on the inner overload than it is\n * on the external overload.)\n *\n * So in the end, we use this helper to remove the `this` annotation from the\n * exported function types, while keeping it in the internal implementation.\n *\n */\ntype RemoveThis<T> = T extends (this: any) => infer R ? () => R : never;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getApolloClientMemoryInternals =\n  __DEV__ ?\n    (_getApolloClientMemoryInternals as RemoveThis<\n      typeof _getApolloClientMemoryInternals\n    >)\n  : undefined;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getInMemoryCacheMemoryInternals =\n  __DEV__ ?\n    (_getInMemoryCacheMemoryInternals as RemoveThis<\n      typeof _getInMemoryCacheMemoryInternals\n    >)\n  : undefined;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getApolloCacheMemoryInternals =\n  __DEV__ ?\n    (_getApolloCacheMemoryInternals as RemoveThis<\n      typeof _getApolloCacheMemoryInternals\n    >)\n  : undefined;\n\nfunction getCurrentCacheSizes() {\n  // `defaultCacheSizes` is a `const enum` that will be inlined during build, so we have to reconstruct it's shape here\n  const defaults: Record<keyof CacheSizes, number> = {\n    parser: defaultCacheSizes[\"parser\"],\n    canonicalStringify: defaultCacheSizes[\"canonicalStringify\"],\n    print: defaultCacheSizes[\"print\"],\n    \"documentTransform.cache\": defaultCacheSizes[\"documentTransform.cache\"],\n    \"queryManager.getDocumentInfo\":\n      defaultCacheSizes[\"queryManager.getDocumentInfo\"],\n    \"PersistedQueryLink.persistedQueryHashes\":\n      defaultCacheSizes[\"PersistedQueryLink.persistedQueryHashes\"],\n    \"fragmentRegistry.transform\":\n      defaultCacheSizes[\"fragmentRegistry.transform\"],\n    \"fragmentRegistry.lookup\": defaultCacheSizes[\"fragmentRegistry.lookup\"],\n    \"fragmentRegistry.findFragmentSpreads\":\n      defaultCacheSizes[\"fragmentRegistry.findFragmentSpreads\"],\n    \"cache.fragmentQueryDocuments\":\n      defaultCacheSizes[\"cache.fragmentQueryDocuments\"],\n    \"removeTypenameFromVariables.getVariableDefinitions\":\n      defaultCacheSizes[\"removeTypenameFromVariables.getVariableDefinitions\"],\n    \"inMemoryCache.maybeBroadcastWatch\":\n      defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"],\n    \"inMemoryCache.executeSelectionSet\":\n      defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"],\n    \"inMemoryCache.executeSubSelectedArray\":\n      defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"],\n  };\n  return Object.fromEntries(\n    Object.entries(defaults).map(([k, v]) => [\n      k,\n      cacheSizes[k as keyof CacheSizes] || v,\n    ])\n  );\n}\n\nfunction _getApolloClientMemoryInternals(this: ApolloClient<any>) {\n  if (!__DEV__) throw new Error(\"only supported in development mode\");\n\n  return {\n    limits: getCurrentCacheSizes(),\n    sizes: {\n      print: globalCaches.print?.(),\n      parser: globalCaches.parser?.(),\n      canonicalStringify: globalCaches.canonicalStringify?.(),\n      links: linkInfo(this.link),\n      queryManager: {\n        getDocumentInfo: this[\"queryManager\"][\"transformCache\"].size,\n        documentTransforms: transformInfo(\n          this[\"queryManager\"].documentTransform\n        ),\n      },\n      ...(this.cache.getMemoryInternals?.() as Partial<\n        ReturnType<typeof _getApolloCacheMemoryInternals>\n      > &\n        Partial<ReturnType<typeof _getInMemoryCacheMemoryInternals>>),\n    },\n  };\n}\n\nfunction _getApolloCacheMemoryInternals(this: ApolloCache<any>) {\n  return {\n    cache: {\n      fragmentQueryDocuments: getWrapperInformation(this[\"getFragmentDoc\"]),\n    },\n  };\n}\n\nfunction _getInMemoryCacheMemoryInternals(this: InMemoryCache) {\n  const fragments = this.config.fragments as\n    | undefined\n    | {\n        findFragmentSpreads?: Function;\n        transform?: Function;\n        lookup?: Function;\n      };\n\n  return {\n    ..._getApolloCacheMemoryInternals.apply(this as any),\n    addTypenameDocumentTransform: transformInfo(this[\"addTypenameTransform\"]),\n    inMemoryCache: {\n      executeSelectionSet: getWrapperInformation(\n        this[\"storeReader\"][\"executeSelectionSet\"]\n      ),\n      executeSubSelectedArray: getWrapperInformation(\n        this[\"storeReader\"][\"executeSubSelectedArray\"]\n      ),\n      maybeBroadcastWatch: getWrapperInformation(this[\"maybeBroadcastWatch\"]),\n    },\n    fragmentRegistry: {\n      findFragmentSpreads: getWrapperInformation(\n        fragments?.findFragmentSpreads\n      ),\n      lookup: getWrapperInformation(fragments?.lookup),\n      transform: getWrapperInformation(fragments?.transform),\n    },\n  };\n}\n\nfunction isWrapper(f?: Function): f is OptimisticWrapperFunction<any, any> {\n  return !!f && \"dirtyKey\" in f;\n}\n\nfunction getWrapperInformation(f?: Function) {\n  return isWrapper(f) ? f.size : undefined;\n}\n\nfunction isDefined<T>(value: T | undefined | null): value is T {\n  return value != null;\n}\n\nfunction transformInfo(transform?: DocumentTransform) {\n  return recurseTransformInfo(transform).map((cache) => ({ cache }));\n}\n\nfunction recurseTransformInfo(transform?: DocumentTransform): number[] {\n  return transform ?\n      [\n        getWrapperInformation(transform?.[\"performWork\"]),\n        ...recurseTransformInfo(transform?.[\"left\"]),\n        ...recurseTransformInfo(transform?.[\"right\"]),\n      ].filter(isDefined)\n    : [];\n}\n\nfunction linkInfo(link?: ApolloLink): unknown[] {\n  return link ?\n      [\n        link?.getMemoryInternals?.(),\n        ...linkInfo(link?.left),\n        ...linkInfo(link?.right),\n      ].filter(isDefined)\n    : [];\n}\n", "import {\n  AutoCleanedStrongCache,\n  cacheSizes,\n  defaultCacheSizes,\n} from \"../../utilities/caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\n\n/**\n * Like JSON.stringify, but with object keys always sorted in the same order.\n *\n * To achieve performant sorting, this function uses a Map from JSON-serialized\n * arrays of keys (in any order) to sorted arrays of the same keys, with a\n * single sorted array reference shared by all permutations of the keys.\n *\n * As a drawback, this function will add a little bit more memory for every\n * object encountered that has different (more, less, a different order of) keys\n * than in the past.\n *\n * In a typical application, this extra memory usage should not play a\n * significant role, as `canonicalStringify` will be called for only a limited\n * number of object shapes, and the cache will not grow beyond a certain point.\n * But in some edge cases, this could be a problem, so we provide\n * canonicalStringify.reset() as a way of clearing the cache.\n * */\nexport const canonicalStringify = Object.assign(\n  function canonicalStringify(value: any): string {\n    return JSON.stringify(value, stableObjectReplacer);\n  },\n  {\n    reset() {\n      // Clearing the sortingMap will reclaim all cached memory, without\n      // affecting the logical results of canonicalStringify, but potentially\n      // sacrificing performance until the cache is refilled.\n      sortingMap = new AutoCleanedStrongCache<string, readonly string[]>(\n        cacheSizes.canonicalStringify || defaultCacheSizes.canonicalStringify\n      );\n    },\n  }\n);\n\nif (__DEV__) {\n  registerGlobalCache(\"canonicalStringify\", () => sortingMap.size);\n}\n\n// Values are JSON-serialized arrays of object keys (in any order), and values\n// are sorted arrays of the same keys.\nlet sortingMap!: AutoCleanedStrongCache<string, readonly string[]>;\ncanonicalStringify.reset();\n\n// The JSON.stringify function takes an optional second argument called a\n// replacer function. This function is called for each key-value pair in the\n// object being stringified, and its return value is used instead of the\n// original value. If the replacer function returns a new value, that value is\n// stringified as JSON instead of the original value of the property.\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter\nfunction stableObjectReplacer(key: string, value: any) {\n  if (value && typeof value === \"object\") {\n    const proto = Object.getPrototypeOf(value);\n    // We don't want to mess with objects that are not \"plain\" objects, which\n    // means their prototype is either Object.prototype or null. This check also\n    // prevents needlessly rearranging the indices of arrays.\n    if (proto === Object.prototype || proto === null) {\n      const keys = Object.keys(value);\n      // If keys is already sorted, let JSON.stringify serialize the original\n      // value instead of creating a new object with keys in the same order.\n      if (keys.every(everyKeyInOrder)) return value;\n      const unsortedKey = JSON.stringify(keys);\n      let sortedKeys = sortingMap.get(unsortedKey);\n      if (!sortedKeys) {\n        keys.sort();\n        const sortedKey = JSON.stringify(keys);\n        // Checking for sortedKey in the sortingMap allows us to share the same\n        // sorted array reference for all permutations of the same set of keys.\n        sortedKeys = sortingMap.get(sortedKey) || keys;\n        sortingMap.set(unsortedKey, sortedKeys);\n        sortingMap.set(sortedKey, sortedKeys);\n      }\n      const sortedObject = Object.create(proto);\n      // Reassigning the keys in sorted order will cause JSON.stringify to\n      // serialize them in sorted order.\n      sortedKeys.forEach((key) => {\n        sortedObject[key] = value[key];\n      });\n      return sortedObject;\n    }\n  }\n  return value;\n}\n\n// Since everything that happens in stableObjectReplacer benefits from being as\n// efficient as possible, we use a static function as the callback for\n// keys.every in order to test if the provided keys are already sorted without\n// allocating extra memory for a callback.\nfunction everyKeyInOrder(\n  key: string,\n  i: number,\n  keys: readonly string[]\n): boolean {\n  return i === 0 || keys[i - 1] <= key;\n}\n", "import { newInvariantError } from \"../globals/index.js\";\n\nimport type {\n  DirectiveNode,\n  FieldNode,\n  IntValueNode,\n  FloatValueNode,\n  StringValueNode,\n  BooleanValueNode,\n  ObjectValueNode,\n  ListValueNode,\n  EnumValueNode,\n  NullValueNode,\n  VariableNode,\n  InlineFragmentNode,\n  ValueNode,\n  SelectionNode,\n  NameNode,\n  SelectionSetNode,\n  DocumentNode,\n  FragmentSpreadNode,\n} from \"graphql\";\n\nimport { isNonNullObject } from \"../common/objects.js\";\nimport type { FragmentMap } from \"./fragments.js\";\nimport { getFragmentFromSelection } from \"./fragments.js\";\nimport { canonicalStringify } from \"../common/canonicalStringify.js\";\n\nexport interface Reference {\n  readonly __ref: string;\n}\n\nexport function makeReference(id: string): Reference {\n  return { __ref: String(id) };\n}\n\nexport function isReference(obj: any): obj is Reference {\n  return Boolean(\n    obj && typeof obj === \"object\" && typeof obj.__ref === \"string\"\n  );\n}\n\nexport type StoreValue =\n  | number\n  | string\n  | string[]\n  | Reference\n  | Reference[]\n  | null\n  | undefined\n  | void\n  | Object;\n\nexport interface StoreObject {\n  __typename?: string;\n  [storeFieldName: string]: StoreValue;\n}\n\n/**\n * Workaround for a TypeScript quirk:\n * types per default have an implicit index signature that makes them\n * assignable to `StoreObject`.\n * interfaces do not have that implicit index signature, so they cannot\n * be assigned to `StoreObject`.\n * This type just maps over a type or interface that is passed in,\n * implicitly adding the index signature.\n * That way, the result can be assigned to `StoreObject`.\n *\n * This is important if some user-defined interface is used e.g.\n * in cache.modify, where the `toReference` method expects a\n * `StoreObject` as input.\n */\nexport type AsStoreObject<T extends { __typename?: string }> = {\n  [K in keyof T]: T[K];\n};\n\nexport function isDocumentNode(value: any): value is DocumentNode {\n  return (\n    isNonNullObject(value) &&\n    (value as DocumentNode).kind === \"Document\" &&\n    Array.isArray((value as DocumentNode).definitions)\n  );\n}\n\nfunction isStringValue(value: ValueNode): value is StringValueNode {\n  return value.kind === \"StringValue\";\n}\n\nfunction isBooleanValue(value: ValueNode): value is BooleanValueNode {\n  return value.kind === \"BooleanValue\";\n}\n\nfunction isIntValue(value: ValueNode): value is IntValueNode {\n  return value.kind === \"IntValue\";\n}\n\nfunction isFloatValue(value: ValueNode): value is FloatValueNode {\n  return value.kind === \"FloatValue\";\n}\n\nfunction isVariable(value: ValueNode): value is VariableNode {\n  return value.kind === \"Variable\";\n}\n\nfunction isObjectValue(value: ValueNode): value is ObjectValueNode {\n  return value.kind === \"ObjectValue\";\n}\n\nfunction isListValue(value: ValueNode): value is ListValueNode {\n  return value.kind === \"ListValue\";\n}\n\nfunction isEnumValue(value: ValueNode): value is EnumValueNode {\n  return value.kind === \"EnumValue\";\n}\n\nfunction isNullValue(value: ValueNode): value is NullValueNode {\n  return value.kind === \"NullValue\";\n}\n\nexport function valueToObjectRepresentation(\n  argObj: any,\n  name: NameNode,\n  value: ValueNode,\n  variables?: Object\n) {\n  if (isIntValue(value) || isFloatValue(value)) {\n    argObj[name.value] = Number(value.value);\n  } else if (isBooleanValue(value) || isStringValue(value)) {\n    argObj[name.value] = value.value;\n  } else if (isObjectValue(value)) {\n    const nestedArgObj = {};\n    value.fields.map((obj) =>\n      valueToObjectRepresentation(nestedArgObj, obj.name, obj.value, variables)\n    );\n    argObj[name.value] = nestedArgObj;\n  } else if (isVariable(value)) {\n    const variableValue = (variables || ({} as any))[value.name.value];\n    argObj[name.value] = variableValue;\n  } else if (isListValue(value)) {\n    argObj[name.value] = value.values.map((listValue) => {\n      const nestedArgArrayObj = {};\n      valueToObjectRepresentation(\n        nestedArgArrayObj,\n        name,\n        listValue,\n        variables\n      );\n      return (nestedArgArrayObj as any)[name.value];\n    });\n  } else if (isEnumValue(value)) {\n    argObj[name.value] = (value as EnumValueNode).value;\n  } else if (isNullValue(value)) {\n    argObj[name.value] = null;\n  } else {\n    throw newInvariantError(\n      `The inline argument \"%s\" of kind \"%s\"` +\n        \"is not supported. Use variables instead of inline arguments to \" +\n        \"overcome this limitation.\",\n      name.value,\n      (value as any).kind\n    );\n  }\n}\n\nexport function storeKeyNameFromField(\n  field: FieldNode,\n  variables?: Object\n): string {\n  let directivesObj: any = null;\n  if (field.directives) {\n    directivesObj = {};\n    field.directives.forEach((directive) => {\n      directivesObj[directive.name.value] = {};\n\n      if (directive.arguments) {\n        directive.arguments.forEach(({ name, value }) =>\n          valueToObjectRepresentation(\n            directivesObj[directive.name.value],\n            name,\n            value,\n            variables\n          )\n        );\n      }\n    });\n  }\n\n  let argObj: any = null;\n  if (field.arguments && field.arguments.length) {\n    argObj = {};\n    field.arguments.forEach(({ name, value }) =>\n      valueToObjectRepresentation(argObj, name, value, variables)\n    );\n  }\n\n  return getStoreKeyName(field.name.value, argObj, directivesObj);\n}\n\nexport type Directives = {\n  [directiveName: string]: {\n    [argName: string]: any;\n  };\n};\n\nconst KNOWN_DIRECTIVES: string[] = [\n  \"connection\",\n  \"include\",\n  \"skip\",\n  \"client\",\n  \"rest\",\n  \"export\",\n  \"nonreactive\",\n];\n\n// Default stable JSON.stringify implementation used by getStoreKeyName. Can be\n// updated/replaced with something better by calling\n// getStoreKeyName.setStringify(newStringifyFunction).\nlet storeKeyNameStringify: (value: any) => string = canonicalStringify;\n\nexport const getStoreKeyName = Object.assign(\n  function (\n    fieldName: string,\n    args?: Record<string, any> | null,\n    directives?: Directives\n  ): string {\n    if (\n      args &&\n      directives &&\n      directives[\"connection\"] &&\n      directives[\"connection\"][\"key\"]\n    ) {\n      if (\n        directives[\"connection\"][\"filter\"] &&\n        (directives[\"connection\"][\"filter\"] as string[]).length > 0\n      ) {\n        const filterKeys =\n          directives[\"connection\"][\"filter\"] ?\n            (directives[\"connection\"][\"filter\"] as string[])\n          : [];\n        filterKeys.sort();\n\n        const filteredArgs = {} as { [key: string]: any };\n        filterKeys.forEach((key) => {\n          filteredArgs[key] = args[key];\n        });\n\n        return `${directives[\"connection\"][\"key\"]}(${storeKeyNameStringify(\n          filteredArgs\n        )})`;\n      } else {\n        return directives[\"connection\"][\"key\"];\n      }\n    }\n\n    let completeFieldName: string = fieldName;\n\n    if (args) {\n      // We can't use `JSON.stringify` here since it's non-deterministic,\n      // and can lead to different store key names being created even though\n      // the `args` object used during creation has the same properties/values.\n      const stringifiedArgs: string = storeKeyNameStringify(args);\n      completeFieldName += `(${stringifiedArgs})`;\n    }\n\n    if (directives) {\n      Object.keys(directives).forEach((key) => {\n        if (KNOWN_DIRECTIVES.indexOf(key) !== -1) return;\n        if (directives[key] && Object.keys(directives[key]).length) {\n          completeFieldName += `@${key}(${storeKeyNameStringify(\n            directives[key]\n          )})`;\n        } else {\n          completeFieldName += `@${key}`;\n        }\n      });\n    }\n\n    return completeFieldName;\n  },\n  {\n    setStringify(s: typeof storeKeyNameStringify) {\n      const previous = storeKeyNameStringify;\n      storeKeyNameStringify = s;\n      return previous;\n    },\n  }\n);\n\nexport function argumentsObjectFromField(\n  field: FieldNode | DirectiveNode,\n  variables?: Record<string, any>\n): Object | null {\n  if (field.arguments && field.arguments.length) {\n    const argObj: Object = {};\n    field.arguments.forEach(({ name, value }) =>\n      valueToObjectRepresentation(argObj, name, value, variables)\n    );\n    return argObj;\n  }\n  return null;\n}\n\nexport function resultKeyNameFromField(field: FieldNode): string {\n  return field.alias ? field.alias.value : field.name.value;\n}\n\nexport function getTypenameFromResult(\n  result: Record<string, any>,\n  selectionSet: SelectionSetNode,\n  fragmentMap?: FragmentMap\n): string | undefined {\n  let fragments: undefined | Array<InlineFragmentNode | FragmentSpreadNode>;\n  for (const selection of selectionSet.selections) {\n    if (isField(selection)) {\n      if (selection.name.value === \"__typename\") {\n        return result[resultKeyNameFromField(selection)];\n      }\n    } else if (fragments) {\n      fragments.push(selection);\n    } else {\n      fragments = [selection];\n    }\n  }\n  if (typeof result.__typename === \"string\") {\n    return result.__typename;\n  }\n  if (fragments) {\n    for (const selection of fragments) {\n      const typename = getTypenameFromResult(\n        result,\n        getFragmentFromSelection(selection, fragmentMap)!.selectionSet,\n        fragmentMap\n      );\n      if (typeof typename === \"string\") {\n        return typename;\n      }\n    }\n  }\n}\n\nexport function isField(selection: SelectionNode): selection is FieldNode {\n  return selection.kind === \"Field\";\n}\n\nexport function isInlineFragment(\n  selection: SelectionNode\n): selection is InlineFragmentNode {\n  return selection.kind === \"InlineFragment\";\n}\n\nexport type VariableValue = (node: VariableNode) => any;\n", "import { invariant, newInvariantError } from \"../globals/index.js\";\n\nimport type {\n  DocumentNode,\n  OperationDefinitionNode,\n  FragmentDefinitionNode,\n  ValueNode,\n} from \"graphql\";\n\nimport { valueToObjectRepresentation } from \"./storeUtils.js\";\n\ntype OperationDefinitionWithName = OperationDefinitionNode & {\n  name: NonNullable<OperationDefinitionNode[\"name\"]>;\n};\n\n// Checks the document for errors and throws an exception if there is an error.\nexport function checkDocument(doc: DocumentNode) {\n  invariant(\n    doc && doc.kind === \"Document\",\n    `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`\n  );\n\n  const operations = doc.definitions\n    .filter((d) => d.kind !== \"FragmentDefinition\")\n    .map((definition) => {\n      if (definition.kind !== \"OperationDefinition\") {\n        throw newInvariantError(\n          `Schema type definitions not allowed in queries. Found: \"%s\"`,\n          definition.kind\n        );\n      }\n      return definition;\n    });\n\n  invariant(\n    operations.length <= 1,\n    `Ambiguous GraphQL document: contains %s operations`,\n    operations.length\n  );\n\n  return doc;\n}\n\nexport function getOperationDefinition(\n  doc: DocumentNode\n): OperationDefinitionNode | undefined {\n  checkDocument(doc);\n  return doc.definitions.filter(\n    (definition): definition is OperationDefinitionNode =>\n      definition.kind === \"OperationDefinition\"\n  )[0];\n}\n\nexport function getOperationName(doc: DocumentNode): string | null {\n  return (\n    doc.definitions\n      .filter(\n        (definition): definition is OperationDefinitionWithName =>\n          definition.kind === \"OperationDefinition\" && !!definition.name\n      )\n      .map((x) => x.name.value)[0] || null\n  );\n}\n\n// Returns the FragmentDefinitions from a particular document as an array\nexport function getFragmentDefinitions(\n  doc: DocumentNode\n): FragmentDefinitionNode[] {\n  return doc.definitions.filter(\n    (definition): definition is FragmentDefinitionNode =>\n      definition.kind === \"FragmentDefinition\"\n  );\n}\n\nexport function getQueryDefinition(doc: DocumentNode): OperationDefinitionNode {\n  const queryDef = getOperationDefinition(doc)!;\n\n  invariant(\n    queryDef && queryDef.operation === \"query\",\n    \"Must contain a query definition.\"\n  );\n\n  return queryDef;\n}\n\nexport function getFragmentDefinition(\n  doc: DocumentNode\n): FragmentDefinitionNode {\n  invariant(\n    doc.kind === \"Document\",\n    `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`\n  );\n\n  invariant(\n    doc.definitions.length <= 1,\n    \"Fragment must have exactly one definition.\"\n  );\n\n  const fragmentDef = doc.definitions[0] as FragmentDefinitionNode;\n\n  invariant(\n    fragmentDef.kind === \"FragmentDefinition\",\n    \"Must be a fragment definition.\"\n  );\n\n  return fragmentDef as FragmentDefinitionNode;\n}\n\n/**\n * Returns the first operation definition found in this document.\n * If no operation definition is found, the first fragment definition will be returned.\n * If no definitions are found, an error will be thrown.\n */\nexport function getMainDefinition(\n  queryDoc: DocumentNode\n): OperationDefinitionNode | FragmentDefinitionNode {\n  checkDocument(queryDoc);\n\n  let fragmentDefinition;\n\n  for (let definition of queryDoc.definitions) {\n    if (definition.kind === \"OperationDefinition\") {\n      const operation = (definition as OperationDefinitionNode).operation;\n      if (\n        operation === \"query\" ||\n        operation === \"mutation\" ||\n        operation === \"subscription\"\n      ) {\n        return definition as OperationDefinitionNode;\n      }\n    }\n    if (definition.kind === \"FragmentDefinition\" && !fragmentDefinition) {\n      // we do this because we want to allow multiple fragment definitions\n      // to precede an operation definition.\n      fragmentDefinition = definition as FragmentDefinitionNode;\n    }\n  }\n\n  if (fragmentDefinition) {\n    return fragmentDefinition;\n  }\n\n  throw newInvariantError(\n    \"Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.\"\n  );\n}\n\nexport function getDefaultValues(\n  definition: OperationDefinitionNode | undefined\n): Record<string, any> {\n  const defaultValues = Object.create(null);\n  const defs = definition && definition.variableDefinitions;\n  if (defs && defs.length) {\n    defs.forEach((def) => {\n      if (def.defaultValue) {\n        valueToObjectRepresentation(\n          defaultValues,\n          def.variable.name,\n          def.defaultValue as ValueNode\n        );\n      }\n    });\n  }\n  return defaultValues;\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<TValue> {\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<TResult, TArgs extends any[], TThis = any>(\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<TArgs extends any[], TResult, TThis = any>(\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<TResult, TArgs extends any[], TThis = any>(\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<T>(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<typeof makeSlotClass> =\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<TYield, TReturn, TNext>\n) {\n  return function (this: any) {\n    const gen = genFn.apply(this, arguments as any);\n\n    type Method = (\n      this: Generator<TYield, TReturn, TNext>,\n      arg: any,\n    ) => IteratorResult<TYield, TReturn>;\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<any>;\n}\n\nfunction isPromiseLike(value: any): value is PromiseLike<any> {\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<F extends Function>(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<AnyEntry | undefined>();\n\nexport function nonReactive<R>(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][T extends any ? 0 : never];\n\nexport const {\n  hasOwnProperty,\n} = Object.prototype;\n\nexport const arrayFromSet: <T>(set: Set<T>) => 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<any>[] = [];\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<T> =\n  | []           // unknown\n  | [T]          // known value\n  | [void, any]; // known exception\n\nfunction valueIs(a: Value<any>, b: Value<any>) {\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<T>(value: Value<T>): 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<T>(value: Value<T>): Value<T> {\n  return value.slice(0) as Value<T>;\n}\n\nexport type AnyEntry = Entry<any, any>;\n\nexport class Entry<TArgs extends any[], TValue> {\n  public static count = 0;\n\n  public normalizeResult: OptimisticWrapOptions<TArgs, any, any, TValue>[\"normalizeResult\"];\n  public subscribe: OptimisticWrapOptions<TArgs>[\"subscribe\"];\n  public unsubscribe: Unsubscribable[\"unsubscribe\"];\n\n  public readonly parents = new Set<AnyEntry>();\n  public readonly childValues = new Map<AnyEntry, Value<any>>();\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<AnyEntry> | null = null;\n\n  public dirty = true;\n  public recomputing = false;\n  public readonly value: Value<TValue> = [];\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<Dep<any>> | null = null;\n\n  public dependOn(dep: Dep<any>) {\n    dep.add(this);\n    if (! this.deps) {\n      this.deps = emptySetPool.pop() || new Set<Set<AnyEntry>>();\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<any> | 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<TKey> =\n  ((key: TKey) => void) & {\n    dirty: (key: TKey, entryMethodName?: EntryMethodName) => void;\n  };\n\nexport type Dep<TKey> = Set<AnyEntry> & {\n  subscribe: OptimisticWrapOptions<[TKey]>[\"subscribe\"];\n} & Unsubscribable;\n\nexport function dep<TKey>(options?: {\n  subscribe: Dep<TKey>[\"subscribe\"];\n}) {\n  const depsByKey = new Map<TKey, Dep<TKey>>();\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<TKey>);\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<TKey>;\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<object> | 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<TArgs, TKeyArgs, TCacheKey>;\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<TCacheKey, TResult, TArgs extends any[]> extends Function {\n  new <K extends TCacheKey, V extends Entry<TArgs, TResult>>(max?: number, dispose?: (value: V, key?: K) => void): CommonCache<K,V>;\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<TKeyArgs>) => 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<NoInfer<TCacheKey>, Entry<NoInfer<TArgs>, NoInfer<TResult>>>\n    | CommonCacheConstructor<NoInfer<TCacheKey>, NoInfer<TResult>, NoInfer<TArgs>>;\n};\n\nexport interface OptionsWithCacheInstance<\n  TArgs extends any[],\n  TKeyArgs extends any[] = TArgs,\n  TCacheKey = any,\n  TResult = any,\n> extends OptimisticWrapOptions<TArgs, TKeyArgs, TCacheKey, TResult> {\n  cache: CommonCache<NoInfer<TCacheKey>, Entry<NoInfer<TArgs>, NoInfer<TResult>>>;\n};\n\nconst caches = new Set<CommonCache<any, AnyEntry>>();\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<TArgs, TKeyArgs, TCacheKey, TResult> = Object.create(null)) {\n  const cache: CommonCache<TCacheKey, Entry<TArgs, TResult>> =\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<TArgs, TResult, TKeyArgs, TCacheKey>;\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<unknown>;\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<DocumentNode>() : new Set<DocumentNode>();\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<WeakKey>(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<any, any>,\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 { 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<ASTNode, string>;\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<ASTNode, string>(\n        cacheSizes.print || defaultCacheSizes.print\n      );\n    },\n  }\n);\nprint.reset();\n\nif (__DEV__) {\n  registerGlobalCache(\"print\", () => (printCache ? printCache.size : 0));\n}\n", "// A version of Array.isArray that works better with readonly arrays.\nexport const isArray: (a: any) => a is any[] | readonly any[] = Array.isArray;\n\nexport function isNonEmptyArray<T>(value?: ArrayLike<T>): value is Array<T> {\n  return Array.isArray(value) && value.length > 0;\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<TVisitedNode extends ASTNode> {\n  readonly enter?: ASTVisitFn<TVisitedNode>;\n  readonly leave?: ASTVisitFn<TVisitedNode>;\n}\n\nexport type RemoveNodeConfig<N> = {\n  name?: string;\n  test?: (node: N) => boolean;\n  remove?: boolean;\n};\n\nexport type GetNodeConfig<N> = {\n  name?: string;\n  test?: (node: N) => boolean;\n};\n\nexport type RemoveDirectiveConfig = RemoveNodeConfig<DirectiveNode>;\nexport type GetDirectiveConfig = GetNodeConfig<DirectiveNode>;\nexport type RemoveArgumentsConfig = RemoveNodeConfig<ArgumentNode>;\nexport type GetFragmentSpreadConfig = GetNodeConfig<FragmentSpreadNode>;\nexport type RemoveFragmentSpreadConfig = RemoveNodeConfig<FragmentSpreadNode>;\nexport type RemoveFragmentDefinitionConfig =\n  RemoveNodeConfig<FragmentDefinitionNode>;\nexport type RemoveVariableDefinitionConfig =\n  RemoveNodeConfig<VariableDefinitionNode>;\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<string, RemoveDirectiveConfig | GetDirectiveConfig>();\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<string>;\n  fragmentSpreads: Set<string>;\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<string>;\n}\nfunction makeInUseGetterFunction<TKey>(defaultKey: TKey) {\n  const map = new Map<TKey, InternalInUseInfo>();\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<string>(\"\");\n  const getInUseByFragmentName = makeInUseGetterFunction<string>(\"\");\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<string, FragmentDefinitionNode>();\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<string>();\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 <TNode extends ASTNode>(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 = (<OperationDefinitionNode>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 { isNonNullObject } from \"./objects.js\";\n\nconst { hasOwnProperty } = Object.prototype;\n\n// These mergeDeep and mergeDeepArray utilities merge any number of objects\n// together, sharing as much memory as possible with the source objects, while\n// remaining careful to avoid modifying any source objects.\n\n// Logically, the return type of mergeDeep should be the intersection of\n// all the argument types. The binary call signature is by far the most\n// common, but we support 0- through 5-ary as well. After that, the\n// resulting type is just the inferred array element type. Note to nerds:\n// there is a more clever way of doing this that converts the tuple type\n// first to a union type (easy enough: T[number]) and then converts the\n// union to an intersection type using distributive conditional type\n// inference, but that approach has several fatal flaws (boolean becomes\n// true & false, and the inferred type ends up as unknown in many cases),\n// in addition to being nearly impossible to explain/understand.\nexport type TupleToIntersection<T extends any[]> =\n  T extends [infer A] ? A\n  : T extends [infer A, infer B] ? A & B\n  : T extends [infer A, infer B, infer C] ? A & B & C\n  : T extends [infer A, infer B, infer C, infer D] ? A & B & C & D\n  : T extends [infer A, infer B, infer C, infer D, infer E] ? A & B & C & D & E\n  : T extends (infer U)[] ? U\n  : any;\n\nexport function mergeDeep<T extends any[]>(\n  ...sources: T\n): TupleToIntersection<T> {\n  return mergeDeepArray(sources);\n}\n\n// In almost any situation where you could succeed in getting the\n// TypeScript compiler to infer a tuple type for the sources array, you\n// could just use mergeDeep instead of mergeDeepArray, so instead of\n// trying to convert T[] to an intersection type we just infer the array\n// element type, which works perfectly when the sources array has a\n// consistent element type.\nexport function mergeDeepArray<T>(sources: T[]): T {\n  let target = sources[0] || ({} as T);\n  const count = sources.length;\n  if (count > 1) {\n    const merger = new DeepMerger();\n    for (let i = 1; i < count; ++i) {\n      target = merger.merge(target, sources[i]);\n    }\n  }\n  return target;\n}\n\nexport type ReconcilerFunction<TContextArgs extends any[]> = (\n  this: DeepMerger<TContextArgs>,\n  target: Record<string | number, any>,\n  source: Record<string | number, any>,\n  property: string | number,\n  ...context: TContextArgs\n) => any;\n\nconst defaultReconciler: ReconcilerFunction<any[]> = function (\n  target,\n  source,\n  property\n) {\n  return this.merge(target[property], source[property]);\n};\n\nexport class DeepMerger<TContextArgs extends any[]> {\n  constructor(\n    private reconciler: ReconcilerFunction<TContextArgs> = defaultReconciler as any as ReconcilerFunction<TContextArgs>\n  ) {}\n\n  public merge(target: any, source: any, ...context: TContextArgs): any {\n    if (isNonNullObject(source) && isNonNullObject(target)) {\n      Object.keys(source).forEach((sourceKey) => {\n        if (hasOwnProperty.call(target, sourceKey)) {\n          const targetValue = target[sourceKey];\n          if (source[sourceKey] !== targetValue) {\n            const result = this.reconciler(\n              target,\n              source,\n              sourceKey,\n              ...context\n            );\n            // A well-implemented reconciler may return targetValue to indicate\n            // the merge changed nothing about the structure of the target.\n            if (result !== targetValue) {\n              target = this.shallowCopyForMerge(target);\n              target[sourceKey] = result;\n            }\n          }\n        } else {\n          // If there is no collision, the target can safely share memory with\n          // the source, and the recursion can terminate here.\n          target = this.shallowCopyForMerge(target);\n          target[sourceKey] = source[sourceKey];\n        }\n      });\n\n      return target;\n    }\n\n    // If source (or target) is not an object, let source replace target.\n    return source;\n  }\n\n  public isObject = isNonNullObject;\n\n  private pastCopies = new Set<any>();\n\n  public shallowCopyForMerge<T>(value: T): T {\n    if (isNonNullObject(value)) {\n      if (!this.pastCopies.has(value)) {\n        if (Array.isArray(value)) {\n          value = (value as any).slice(0);\n        } else {\n          value = {\n            __proto__: Object.getPrototypeOf(value),\n            ...value,\n          };\n        }\n        this.pastCopies.add(value);\n      }\n    }\n    return value;\n  }\n}\n", "function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n// === Symbol Support ===\nvar hasSymbols = function () {\n  return typeof Symbol === 'function';\n};\n\nvar hasSymbol = function (name) {\n  return hasSymbols() && Boolean(Symbol[name]);\n};\n\nvar getSymbol = function (name) {\n  return hasSymbol(name) ? Symbol[name] : '@@' + name;\n};\n\nif (hasSymbols() && !hasSymbol('observable')) {\n  Symbol.observable = Symbol('observable');\n}\n\nvar SymbolIterator = getSymbol('iterator');\nvar SymbolObservable = getSymbol('observable');\nvar SymbolSpecies = getSymbol('species'); // === Abstract Operations ===\n\nfunction getMethod(obj, key) {\n  var value = obj[key];\n  if (value == null) return undefined;\n  if (typeof value !== 'function') throw new TypeError(value + ' is not a function');\n  return value;\n}\n\nfunction getSpecies(obj) {\n  var ctor = obj.constructor;\n\n  if (ctor !== undefined) {\n    ctor = ctor[SymbolSpecies];\n\n    if (ctor === null) {\n      ctor = undefined;\n    }\n  }\n\n  return ctor !== undefined ? ctor : Observable;\n}\n\nfunction isObservable(x) {\n  return x instanceof Observable; // SPEC: Brand check\n}\n\nfunction hostReportError(e) {\n  if (hostReportError.log) {\n    hostReportError.log(e);\n  } else {\n    setTimeout(function () {\n      throw e;\n    });\n  }\n}\n\nfunction enqueue(fn) {\n  Promise.resolve().then(function () {\n    try {\n      fn();\n    } catch (e) {\n      hostReportError(e);\n    }\n  });\n}\n\nfunction cleanupSubscription(subscription) {\n  var cleanup = subscription._cleanup;\n  if (cleanup === undefined) return;\n  subscription._cleanup = undefined;\n\n  if (!cleanup) {\n    return;\n  }\n\n  try {\n    if (typeof cleanup === 'function') {\n      cleanup();\n    } else {\n      var unsubscribe = getMethod(cleanup, 'unsubscribe');\n\n      if (unsubscribe) {\n        unsubscribe.call(cleanup);\n      }\n    }\n  } catch (e) {\n    hostReportError(e);\n  }\n}\n\nfunction closeSubscription(subscription) {\n  subscription._observer = undefined;\n  subscription._queue = undefined;\n  subscription._state = 'closed';\n}\n\nfunction flushSubscription(subscription) {\n  var queue = subscription._queue;\n\n  if (!queue) {\n    return;\n  }\n\n  subscription._queue = undefined;\n  subscription._state = 'ready';\n\n  for (var i = 0; i < queue.length; ++i) {\n    notifySubscription(subscription, queue[i].type, queue[i].value);\n    if (subscription._state === 'closed') break;\n  }\n}\n\nfunction notifySubscription(subscription, type, value) {\n  subscription._state = 'running';\n  var observer = subscription._observer;\n\n  try {\n    var m = getMethod(observer, type);\n\n    switch (type) {\n      case 'next':\n        if (m) m.call(observer, value);\n        break;\n\n      case 'error':\n        closeSubscription(subscription);\n        if (m) m.call(observer, value);else throw value;\n        break;\n\n      case 'complete':\n        closeSubscription(subscription);\n        if (m) m.call(observer);\n        break;\n    }\n  } catch (e) {\n    hostReportError(e);\n  }\n\n  if (subscription._state === 'closed') cleanupSubscription(subscription);else if (subscription._state === 'running') subscription._state = 'ready';\n}\n\nfunction onNotify(subscription, type, value) {\n  if (subscription._state === 'closed') return;\n\n  if (subscription._state === 'buffering') {\n    subscription._queue.push({\n      type: type,\n      value: value\n    });\n\n    return;\n  }\n\n  if (subscription._state !== 'ready') {\n    subscription._state = 'buffering';\n    subscription._queue = [{\n      type: type,\n      value: value\n    }];\n    enqueue(function () {\n      return flushSubscription(subscription);\n    });\n    return;\n  }\n\n  notifySubscription(subscription, type, value);\n}\n\nvar Subscription = /*#__PURE__*/function () {\n  function Subscription(observer, subscriber) {\n    // ASSERT: observer is an object\n    // ASSERT: subscriber is callable\n    this._cleanup = undefined;\n    this._observer = observer;\n    this._queue = undefined;\n    this._state = 'initializing';\n    var subscriptionObserver = new SubscriptionObserver(this);\n\n    try {\n      this._cleanup = subscriber.call(undefined, subscriptionObserver);\n    } catch (e) {\n      subscriptionObserver.error(e);\n    }\n\n    if (this._state === 'initializing') this._state = 'ready';\n  }\n\n  var _proto = Subscription.prototype;\n\n  _proto.unsubscribe = function unsubscribe() {\n    if (this._state !== 'closed') {\n      closeSubscription(this);\n      cleanupSubscription(this);\n    }\n  };\n\n  _createClass(Subscription, [{\n    key: \"closed\",\n    get: function () {\n      return this._state === 'closed';\n    }\n  }]);\n\n  return Subscription;\n}();\n\nvar SubscriptionObserver = /*#__PURE__*/function () {\n  function SubscriptionObserver(subscription) {\n    this._subscription = subscription;\n  }\n\n  var _proto2 = SubscriptionObserver.prototype;\n\n  _proto2.next = function next(value) {\n    onNotify(this._subscription, 'next', value);\n  };\n\n  _proto2.error = function error(value) {\n    onNotify(this._subscription, 'error', value);\n  };\n\n  _proto2.complete = function complete() {\n    onNotify(this._subscription, 'complete');\n  };\n\n  _createClass(SubscriptionObserver, [{\n    key: \"closed\",\n    get: function () {\n      return this._subscription._state === 'closed';\n    }\n  }]);\n\n  return SubscriptionObserver;\n}();\n\nvar Observable = /*#__PURE__*/function () {\n  function Observable(subscriber) {\n    if (!(this instanceof Observable)) throw new TypeError('Observable cannot be called as a function');\n    if (typeof subscriber !== 'function') throw new TypeError('Observable initializer must be a function');\n    this._subscriber = subscriber;\n  }\n\n  var _proto3 = Observable.prototype;\n\n  _proto3.subscribe = function subscribe(observer) {\n    if (typeof observer !== 'object' || observer === null) {\n      observer = {\n        next: observer,\n        error: arguments[1],\n        complete: arguments[2]\n      };\n    }\n\n    return new Subscription(observer, this._subscriber);\n  };\n\n  _proto3.forEach = function forEach(fn) {\n    var _this = this;\n\n    return new Promise(function (resolve, reject) {\n      if (typeof fn !== 'function') {\n        reject(new TypeError(fn + ' is not a function'));\n        return;\n      }\n\n      function done() {\n        subscription.unsubscribe();\n        resolve();\n      }\n\n      var subscription = _this.subscribe({\n        next: function (value) {\n          try {\n            fn(value, done);\n          } catch (e) {\n            reject(e);\n            subscription.unsubscribe();\n          }\n        },\n        error: reject,\n        complete: resolve\n      });\n    });\n  };\n\n  _proto3.map = function map(fn) {\n    var _this2 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      return _this2.subscribe({\n        next: function (value) {\n          try {\n            value = fn(value);\n          } catch (e) {\n            return observer.error(e);\n          }\n\n          observer.next(value);\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          observer.complete();\n        }\n      });\n    });\n  };\n\n  _proto3.filter = function filter(fn) {\n    var _this3 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      return _this3.subscribe({\n        next: function (value) {\n          try {\n            if (!fn(value)) return;\n          } catch (e) {\n            return observer.error(e);\n          }\n\n          observer.next(value);\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          observer.complete();\n        }\n      });\n    });\n  };\n\n  _proto3.reduce = function reduce(fn) {\n    var _this4 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    var hasSeed = arguments.length > 1;\n    var hasValue = false;\n    var seed = arguments[1];\n    var acc = seed;\n    return new C(function (observer) {\n      return _this4.subscribe({\n        next: function (value) {\n          var first = !hasValue;\n          hasValue = true;\n\n          if (!first || hasSeed) {\n            try {\n              acc = fn(acc, value);\n            } catch (e) {\n              return observer.error(e);\n            }\n          } else {\n            acc = value;\n          }\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          if (!hasValue && !hasSeed) return observer.error(new TypeError('Cannot reduce an empty sequence'));\n          observer.next(acc);\n          observer.complete();\n        }\n      });\n    });\n  };\n\n  _proto3.concat = function concat() {\n    var _this5 = this;\n\n    for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {\n      sources[_key] = arguments[_key];\n    }\n\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      var subscription;\n      var index = 0;\n\n      function startNext(next) {\n        subscription = next.subscribe({\n          next: function (v) {\n            observer.next(v);\n          },\n          error: function (e) {\n            observer.error(e);\n          },\n          complete: function () {\n            if (index === sources.length) {\n              subscription = undefined;\n              observer.complete();\n            } else {\n              startNext(C.from(sources[index++]));\n            }\n          }\n        });\n      }\n\n      startNext(_this5);\n      return function () {\n        if (subscription) {\n          subscription.unsubscribe();\n          subscription = undefined;\n        }\n      };\n    });\n  };\n\n  _proto3.flatMap = function flatMap(fn) {\n    var _this6 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      var subscriptions = [];\n\n      var outer = _this6.subscribe({\n        next: function (value) {\n          if (fn) {\n            try {\n              value = fn(value);\n            } catch (e) {\n              return observer.error(e);\n            }\n          }\n\n          var inner = C.from(value).subscribe({\n            next: function (value) {\n              observer.next(value);\n            },\n            error: function (e) {\n              observer.error(e);\n            },\n            complete: function () {\n              var i = subscriptions.indexOf(inner);\n              if (i >= 0) subscriptions.splice(i, 1);\n              completeIfDone();\n            }\n          });\n          subscriptions.push(inner);\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          completeIfDone();\n        }\n      });\n\n      function completeIfDone() {\n        if (outer.closed && subscriptions.length === 0) observer.complete();\n      }\n\n      return function () {\n        subscriptions.forEach(function (s) {\n          return s.unsubscribe();\n        });\n        outer.unsubscribe();\n      };\n    });\n  };\n\n  _proto3[SymbolObservable] = function () {\n    return this;\n  };\n\n  Observable.from = function from(x) {\n    var C = typeof this === 'function' ? this : Observable;\n    if (x == null) throw new TypeError(x + ' is not an object');\n    var method = getMethod(x, SymbolObservable);\n\n    if (method) {\n      var observable = method.call(x);\n      if (Object(observable) !== observable) throw new TypeError(observable + ' is not an object');\n      if (isObservable(observable) && observable.constructor === C) return observable;\n      return new C(function (observer) {\n        return observable.subscribe(observer);\n      });\n    }\n\n    if (hasSymbol('iterator')) {\n      method = getMethod(x, SymbolIterator);\n\n      if (method) {\n        return new C(function (observer) {\n          enqueue(function () {\n            if (observer.closed) return;\n\n            for (var _iterator = _createForOfIteratorHelperLoose(method.call(x)), _step; !(_step = _iterator()).done;) {\n              var item = _step.value;\n              observer.next(item);\n              if (observer.closed) return;\n            }\n\n            observer.complete();\n          });\n        });\n      }\n    }\n\n    if (Array.isArray(x)) {\n      return new C(function (observer) {\n        enqueue(function () {\n          if (observer.closed) return;\n\n          for (var i = 0; i < x.length; ++i) {\n            observer.next(x[i]);\n            if (observer.closed) return;\n          }\n\n          observer.complete();\n        });\n      });\n    }\n\n    throw new TypeError(x + ' is not observable');\n  };\n\n  Observable.of = function of() {\n    for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n      items[_key2] = arguments[_key2];\n    }\n\n    var C = typeof this === 'function' ? this : Observable;\n    return new C(function (observer) {\n      enqueue(function () {\n        if (observer.closed) return;\n\n        for (var i = 0; i < items.length; ++i) {\n          observer.next(items[i]);\n          if (observer.closed) return;\n        }\n\n        observer.complete();\n      });\n    });\n  };\n\n  _createClass(Observable, null, [{\n    key: SymbolSpecies,\n    get: function () {\n      return this;\n    }\n  }]);\n\n  return Observable;\n}();\n\nif (hasSymbols()) {\n  Object.defineProperty(Observable, Symbol('extensions'), {\n    value: {\n      symbol: SymbolObservable,\n      hostReportError: hostReportError\n    },\n    configurable: true\n  });\n}\n\nexport { Observable };\n", "export default function symbolObservablePonyfill(root) {\n\tvar result;\n\tvar Symbol = root.Symbol;\n\n\tif (typeof Symbol === 'function') {\n\t\tif (Symbol.observable) {\n\t\t\tresult = Symbol.observable;\n\t\t} else {\n\n\t\t\tif (typeof Symbol.for === 'function') {\n\t\t\t\t// This just needs to be something that won't trample other user's Symbol.for use\n\t\t\t\t// It also will guide people to the source of their issues, if this is problematic.\n\t\t\t\t// META: It's a resource locator!\n\t\t\t\tresult = Symbol.for('https://github.com/benlesh/symbol-observable');\n\t\t\t} else {\n\t\t\t\t// Symbol.for didn't exist! The best we can do at this point is a totally \n\t\t\t\t// unique symbol. Note that the string argument here is a descriptor, not\n\t\t\t\t// an identifier. This symbol is unique.\n\t\t\t\tresult = Symbol('https://github.com/benlesh/symbol-observable');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tSymbol.observable = result;\n\t\t\t} catch (err) {\n\t\t\t\t// Do nothing. In some environments, users have frozen `Symbol` for security reasons,\n\t\t\t\t// if it is frozen assigning to it will throw. In this case, we don't care, because\n\t\t\t\t// they will need to use the returned value from the ponyfill.\n\t\t\t}\n\t\t}\n\t} else {\n\t\tresult = '@@observable';\n\t}\n\n\treturn result;\n};\n", "/* global window */\nimport ponyfill from './ponyfill.js';\n\nvar root;\n\nif (typeof self !== 'undefined') {\n  root = self;\n} else if (typeof window !== 'undefined') {\n  root = window;\n} else if (typeof global !== 'undefined') {\n  root = global;\n} else if (typeof module !== 'undefined') {\n  root = module;\n} else {\n  root = Function('return this')();\n}\n\nvar result = ponyfill(root);\nexport default result;\n", "import type {\n  Observer,\n  Subscription as ObservableSubscription,\n  Subscriber,\n} from \"zen-observable-ts\";\nimport { Observable } from \"zen-observable-ts\";\n\n// This simplified polyfill attempts to follow the ECMAScript Observable\n// proposal (https://github.com/zenparsing/es-observable)\nimport \"symbol-observable\";\n\nexport type { Observer, ObservableSubscription, Subscriber };\n\n// The zen-observable package defines Observable.prototype[Symbol.observable]\n// when Symbol is supported, but RxJS interop depends on also setting this fake\n// '@@observable' string as a polyfill for Symbol.observable.\nconst { prototype } = Observable;\nconst fakeObsSymbol = \"@@observable\" as keyof typeof prototype;\nif (!prototype[fakeObsSymbol]) {\n  // @ts-expect-error\n  prototype[fakeObsSymbol] = function () {\n    return this;\n  };\n}\n\nexport { Observable };\n", "const { toString } = Object.prototype;\n\n/**\n * Deeply clones a value to create a new instance.\n */\nexport function cloneDeep<T>(value: T): T {\n  return cloneDeepHelper(value);\n}\n\nfunction cloneDeepHelper<T>(val: T, seen?: Map<any, any>): 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<string, any>).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 { isNonNullObject } from \"./objects.js\";\n\nfunction deepFreeze(value: any) {\n  const workSet = new Set([value]);\n  workSet.forEach((obj) => {\n    if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {\n      Object.getOwnPropertyNames(obj).forEach((name) => {\n        if (isNonNullObject(obj[name])) workSet.add(obj[name]);\n      });\n    }\n  });\n  return value;\n}\n\nfunction shallowFreeze<T extends object>(obj: T): T | null {\n  if (__DEV__ && !Object.isFrozen(obj)) {\n    try {\n      Object.freeze(obj);\n    } catch (e) {\n      // Some types like Uint8Array and Node.js's Buffer cannot be frozen, but\n      // they all throw a TypeError when you try, so we re-throw any exceptions\n      // that are not TypeErrors, since that would be unexpected.\n      if (e instanceof TypeError) return null;\n      throw e;\n    }\n  }\n  return obj;\n}\n\nexport function maybeDeepFreeze<T>(obj: T): T {\n  if (__DEV__) {\n    deepFreeze(obj);\n  }\n  return obj;\n}\n", "import type { Observer } from \"./Observable.js\";\n\nexport function iterateObserversSafely<E, A>(\n  observers: Set<Observer<E>>,\n  method: keyof Observer<E>,\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<E>[] = [];\n  observers.forEach((obs) => obs[method] && observersWithMethod.push(obs));\n  observersWithMethod.forEach((obs) => (obs as any)[method](argument));\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<V, R>(\n  observable: Observable<V>,\n  mapFn: (value: V) => R | PromiseLike<R>,\n  catchFn?: (error: any) => R | PromiseLike<R>\n): Observable<R> {\n  return new Observable<R>((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<void>;\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<V> = {\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 { 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<any>,\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> = T | PromiseLike<T>;\n\nfunction isPromiseLike<T>(value: MaybeAsync<T>): value is PromiseLike<T> {\n  return value && typeof (value as any).then === \"function\";\n}\n\n// Any individual Source<T> can be an Observable<T> or a promise for one.\ntype Source<T> = MaybeAsync<Observable<T>>;\n\nexport type ConcastSourcesIterable<T> = Iterable<Source<T>>;\nexport type ConcastSourcesArray<T> = Array<Source<T>>;\n\n// A Concast<T> 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<T> is\n// similar to a BehaviorSubject<T>, because it is multicast and redelivers\n// the latest next/error message to new subscribers. Unlike Subject<T>,\n// Concast<T> does not expose an Observer<T> interface (this.handlers is\n// intentionally private), since Concast<T> 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<T> extends Observable<T> {\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<Observer<T>>();\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<ConcastSourcesIterable<T>> | Subscriber<T>) {\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<T>[] | undefined;\n\n  private start(sources: ConcastSourcesIterable<T>) {\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<T>) {\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<T>) {\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<T>) {\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<T>) => void;\n  private reject!: (reason: any) => void;\n  public readonly promise = new Promise<T | undefined>((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<NextResultListener>();\n\n  private notify(\n    method: Parameters<NextResultListener>[0],\n    arg?: Parameters<NextResultListener>[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", "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<T>(\n  value: FetchResult<T>\n): value is ExecutionPatchIncrementalResult {\n  return \"incremental\" in value;\n}\n\nexport function isExecutionPatchInitialResult<T>(\n  value: FetchResult<T>\n): value is ExecutionPatchInitialResult<T> {\n  return \"hasNext\" in value && \"data\" in value;\n}\n\nexport function isExecutionPatchResult<T>(\n  value: FetchResult<T>\n): value is ExecutionPatchResult<T> {\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<TData extends object>(\n  prevResult: TData,\n  result: ExecutionPatchResult<TData>\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<string | number, any> = 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 type { FetchResult } from \"../../link/core/index.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { isExecutionPatchIncrementalResult } from \"./incrementalResult.js\";\n\nexport function graphQLResultHasError<T>(result: FetchResult<T>): boolean {\n  const errors = getGraphQLErrorsFromResult(result);\n  return isNonEmptyArray(errors);\n}\n\nexport function getGraphQLErrorsFromResult<T>(result: FetchResult<T>) {\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 { TupleToIntersection } from \"./mergeDeep.js\";\n\n/**\n * Merges the provided objects shallowly and removes\n * all properties with an `undefined` value\n */\nexport function compact<TArgs extends any[]>(\n  ...objects: TArgs\n): TupleToIntersection<TArgs> {\n  const result = Object.create(null);\n\n  objects.forEach((obj) => {\n    if (!obj) return;\n    Object.keys(obj).forEach((key) => {\n      const value = (obj as any)[key];\n      if (value !== void 0) {\n        result[key] = value;\n      }\n    });\n  });\n\n  return result;\n}\n", "import type {\n  QueryOptions,\n  WatchQueryOptions,\n  MutationOptions,\n  OperationVariables,\n} from \"../../core/index.js\";\n\nimport { compact } from \"./compact.js\";\n\ntype OptionsUnion<TData, TVariables extends OperationVariables, TContext> =\n  | WatchQueryOptions<TVariables, TData>\n  | QueryOptions<TVariables, TData>\n  | MutationOptions<TData, TVariables, TContext, any>;\n\nexport function mergeOptions<\n  TDefaultOptions extends Partial<OptionsUnion<any, any, any>>,\n  TOptions extends TDefaultOptions,\n>(\n  defaults: TDefaultOptions | Partial<TDefaultOptions> | undefined,\n  options: TOptions | Partial<TOptions>\n): TOptions & TDefaultOptions {\n  return compact(\n    defaults,\n    options,\n    options.variables && {\n      variables: compact({\n        ...(defaults && defaults.variables),\n        ...options.variables,\n      }),\n    }\n  );\n}\n", "import { Observable } from \"../../utilities/index.js\";\n\nexport function fromError<T>(errorValue: any): Observable<T> {\n  return new Observable<T>((observer) => {\n    observer.error(errorValue);\n  });\n}\n", "export type ServerError = Error & {\n  response: Response;\n  result: Record<string, any> | 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 { newInvariantError } from \"../../utilities/globals/index.js\";\nimport type { GraphQLRequest } from \"../core/index.js\";\n\nexport function validateOperation(operation: GraphQLRequest): GraphQLRequest {\n  const OPERATION_FIELDS = [\n    \"query\",\n    \"operationName\",\n    \"variables\",\n    \"extensions\",\n    \"context\",\n  ];\n  for (let key of Object.keys(operation)) {\n    if (OPERATION_FIELDS.indexOf(key) < 0) {\n      throw newInvariantError(`illegal argument: %s`, key);\n    }\n  }\n\n  return operation;\n}\n", "import type { GraphQLRequest, Operation } from \"../core/index.js\";\n\nexport function createOperation(\n  starting: any,\n  operation: GraphQLRequest\n): Operation {\n  let context = { ...starting };\n  const setContext: Operation[\"setContext\"] = (next) => {\n    if (typeof next === \"function\") {\n      context = { ...context, ...next(context) };\n    } else {\n      context = { ...context, ...next };\n    }\n  };\n  const getContext: Operation[\"getContext\"] = () => ({ ...context });\n\n  Object.defineProperty(operation, \"setContext\", {\n    enumerable: false,\n    value: setContext,\n  });\n\n  Object.defineProperty(operation, \"getContext\", {\n    enumerable: false,\n    value: getContext,\n  });\n\n  return operation as Operation;\n}\n", "import type { GraphQLRequest, Operation } from \"../core/index.js\";\nimport { getOperationName } from \"../../utilities/index.js\";\n\nexport function transformOperation(operation: GraphQLRequest): GraphQLRequest {\n  const transformedOperation: GraphQLRequest = {\n    variables: operation.variables || {},\n    extensions: operation.extensions || {},\n    operationName: operation.operationName,\n    query: operation.query,\n  };\n\n  // Best guess at an operation name\n  if (!transformedOperation.operationName) {\n    transformedOperation.operationName =\n      typeof transformedOperation.query !== \"string\" ?\n        getOperationName(transformedOperation.query) || undefined\n      : \"\";\n  }\n\n  return transformedOperation as Operation;\n}\n", "import type { VariableDefinitionNode, DocumentNode } from \"graphql\";\nimport { visit } from \"graphql\";\n\nexport function filterOperationVariables(\n  variables: Record<string, any>,\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 { newInvariantError, invariant } from \"../../utilities/globals/index.js\";\n\nimport type { Observer } from \"../../utilities/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nimport type {\n  NextLink,\n  Operation,\n  RequestHandler,\n  FetchResult,\n  GraphQLRequest,\n} from \"./types.js\";\nimport {\n  validateOperation,\n  createOperation,\n  transformOperation,\n} from \"../utils/index.js\";\n\nfunction passthrough(op: Operation, forward: NextLink) {\n  return (forward ? forward(op) : Observable.of()) as Observable<FetchResult>;\n}\n\nfunction toLink(handler: RequestHandler | ApolloLink) {\n  return typeof handler === \"function\" ? new ApolloLink(handler) : handler;\n}\n\nfunction isTerminating(link: ApolloLink): boolean {\n  return link.request.length <= 1;\n}\n\nexport class ApolloLink {\n  public static empty(): ApolloLink {\n    return new ApolloLink(() => Observable.of());\n  }\n\n  public static from(links: (ApolloLink | RequestHandler)[]): ApolloLink {\n    if (links.length === 0) return ApolloLink.empty();\n    return links.map(toLink).reduce((x, y) => x.concat(y)) as ApolloLink;\n  }\n\n  public static split(\n    test: (op: Operation) => boolean,\n    left: ApolloLink | RequestHandler,\n    right?: ApolloLink | RequestHandler\n  ): ApolloLink {\n    const leftLink = toLink(left);\n    const rightLink = toLink(right || new ApolloLink(passthrough));\n\n    let ret: ApolloLink;\n    if (isTerminating(leftLink) && isTerminating(rightLink)) {\n      ret = new ApolloLink((operation) => {\n        return test(operation) ?\n            leftLink.request(operation) || Observable.of()\n          : rightLink.request(operation) || Observable.of();\n      });\n    } else {\n      ret = new ApolloLink((operation, forward) => {\n        return test(operation) ?\n            leftLink.request(operation, forward) || Observable.of()\n          : rightLink.request(operation, forward) || Observable.of();\n      });\n    }\n    return Object.assign(ret, { left: leftLink, right: rightLink });\n  }\n\n  public static execute(\n    link: ApolloLink,\n    operation: GraphQLRequest\n  ): Observable<FetchResult> {\n    return (\n      link.request(\n        createOperation(\n          operation.context,\n          transformOperation(validateOperation(operation))\n        )\n      ) || Observable.of()\n    );\n  }\n\n  public static concat(\n    first: ApolloLink | RequestHandler,\n    second: ApolloLink | RequestHandler\n  ) {\n    const firstLink = toLink(first);\n    if (isTerminating(firstLink)) {\n      invariant.warn(\n        `You are calling concat on a terminating link, which will have no effect %o`,\n        firstLink\n      );\n      return firstLink;\n    }\n    const nextLink = toLink(second);\n\n    let ret: ApolloLink;\n    if (isTerminating(nextLink)) {\n      ret = new ApolloLink(\n        (operation) =>\n          firstLink.request(\n            operation,\n            (op) => nextLink.request(op) || Observable.of()\n          ) || Observable.of()\n      );\n    } else {\n      ret = new ApolloLink((operation, forward) => {\n        return (\n          firstLink.request(operation, (op) => {\n            return nextLink.request(op, forward) || Observable.of();\n          }) || Observable.of()\n        );\n      });\n    }\n    return Object.assign(ret, { left: firstLink, right: nextLink });\n  }\n\n  constructor(request?: RequestHandler) {\n    if (request) this.request = request;\n  }\n\n  public split(\n    test: (op: Operation) => boolean,\n    left: ApolloLink | RequestHandler,\n    right?: ApolloLink | RequestHandler\n  ): ApolloLink {\n    return this.concat(\n      ApolloLink.split(test, left, right || new ApolloLink(passthrough))\n    );\n  }\n\n  public concat(next: ApolloLink | RequestHandler): ApolloLink {\n    return ApolloLink.concat(this, next);\n  }\n\n  public request(\n    operation: Operation,\n    forward?: NextLink\n  ): Observable<FetchResult> | null {\n    throw newInvariantError(\"request is not implemented\");\n  }\n\n  protected onError(\n    error: any,\n    observer?: Observer<FetchResult>\n  ): false | void {\n    if (observer && observer.error) {\n      observer.error(error);\n      // Returning false indicates that observer.error does not need to be\n      // called again, since it was already called (on the previous line).\n      // Calling observer.error again would not cause any real problems,\n      // since only the first call matters, but custom onError functions\n      // might have other reasons for wanting to prevent the default\n      // behavior by returning false.\n      return false;\n    }\n    // Throw errors will be passed to observer.error.\n    throw error;\n  }\n\n  public setOnError(fn: ApolloLink[\"onError\"]): this {\n    this.onError = fn;\n    return this;\n  }\n\n  /**\n   * @internal\n   * Used to iterate through all links that are concatenations or `split` links.\n   */\n  readonly left?: ApolloLink;\n  /**\n   * @internal\n   * Used to iterate through all links that are concatenations or `split` links.\n   */\n  readonly right?: ApolloLink;\n\n  /**\n   * @internal\n   * Can be provided by a link that has an internal cache to report it's memory details.\n   */\n  getMemoryInternals?: () => unknown;\n}\n", "import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const execute = ApolloLink.execute;\n", "/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts\n */\n\nexport default function asyncIterator<T>(\n  source: AsyncIterableIterator<T>\n): AsyncIterableIterator<T> {\n  const iterator = source[Symbol.asyncIterator]();\n  return {\n    next(): Promise<IteratorResult<T, boolean>> {\n      return iterator.next();\n    },\n    [Symbol.asyncIterator](): AsyncIterableIterator<T> {\n      return this;\n    },\n  };\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<T> {\n  next(): Promise<IteratorResult<T, boolean | undefined>>;\n  [Symbol.asyncIterator]?(): AsyncIterator<T>;\n}\n\nexport default function nodeStreamIterator<T>(\n  stream: NodeReadableStream\n): AsyncIterableIterator<T> {\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<T, boolean | undefined>\n        | PromiseLike<IteratorResult<T, boolean | undefined>>\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<IteratorResult<T, boolean | undefined>> {\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<T> = {\n    next(): Promise<IteratorResult<T, boolean | undefined>> {\n      return getNext();\n    },\n  };\n\n  if (canUseAsyncIteratorSymbol) {\n    iterator[Symbol.asyncIterator] = function (): AsyncIterator<T> {\n      return this;\n    };\n  }\n\n  return iterator as AsyncIterableIterator<T>;\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<T> {\n  next(): Promise<IteratorResult<T, ArrayBuffer | undefined>>;\n  [Symbol.asyncIterator]?(): AsyncIterator<T>;\n}\n\nexport default function promiseIterator<T = ArrayBuffer>(\n  promise: Promise<ArrayBuffer>\n): AsyncIterableIterator<T> {\n  let resolved = false;\n\n  const iterator: PromiseIterator<T> = {\n    next(): Promise<IteratorResult<T, ArrayBuffer | undefined>> {\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<T> {\n      return this;\n    };\n  }\n\n  return iterator as AsyncIterableIterator<T>;\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<T> {\n  next(): Promise<IteratorResult<T, T | undefined>>;\n  [Symbol.asyncIterator]?(): AsyncIterator<T>;\n}\n\nexport default function readerIterator<T>(\n  reader: ReadableStreamDefaultReader<T>\n): AsyncIterableIterator<T> {\n  const iterator: ReaderIterator<T> = {\n    next() {\n      return reader.read() as Promise<\n        | ReadableStreamReadValueResult<T>\n        // DoneResult has `value` optional, which doesn't comply with an\n        // `IteratorResult`, so we assert it to `T | undefined` instead\n        | Required<ReadableStreamReadDoneResult<T | undefined>>\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<T>;\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<any> {\n  return !!(value as ReadableStream<any>).getReader;\n}\n\nfunction isAsyncIterableIterator(\n  value: any\n): value is AsyncIterableIterator<any> {\n  return !!(\n    canUseAsyncIteratorSymbol &&\n    (value as AsyncIterableIterator<any>)[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<T>(\n  response: Response | NodeResponse\n): AsyncIterableIterator<T> {\n  let body: unknown = response;\n\n  if (isNodeResponse(response)) body = response.body;\n\n  if (isAsyncIterableIterator(body)) return asyncIterator<T>(body);\n\n  if (isReadableStream(body)) return readerIterator<T>(body.getReader());\n\n  // this errors without casting to ReadableStream<T>\n  // because Blob.stream() returns a NodeJS ReadableStream\n  if (isStreamableBlob(body)) {\n    return readerIterator<T>(\n      (body.stream() as unknown as ReadableStream<T>).getReader()\n    );\n  }\n\n  if (isBlob(body)) return promiseIterator<T>(body.arrayBuffer());\n\n  if (isNodeReadableStream(body)) return nodeStreamIterator<T>(body);\n\n  throw new Error(\n    \"Unknown body type for responseIterator. Please pass a streamable response.\"\n  );\n}\n", "import \"../utilities/globals/index.js\";\n\nimport type { GraphQLError, GraphQLErrorExtensions } from \"graphql\";\n\nimport { isNonNullObject } from \"../utilities/index.js\";\nimport type { ServerParseError } from \"../link/http/index.js\";\nimport type { ServerError } from \"../link/utils/index.js\";\nimport type { FetchResult } from \"../link/core/index.js\";\n\n// This Symbol allows us to pass transport-specific errors from the link chain\n// into QueryManager/client internals without risking a naming collision within\n// extensions (which implementers can use as they see fit).\nexport const PROTOCOL_ERRORS_SYMBOL: unique symbol = Symbol();\n\ntype FetchResultWithSymbolExtensions<T> = FetchResult<T> & {\n  extensions: Record<string | symbol, any>;\n};\n\nexport interface ApolloErrorOptions {\n  graphQLErrors?: ReadonlyArray<GraphQLError>;\n  protocolErrors?: ReadonlyArray<{\n    message: string;\n    extensions?: GraphQLErrorExtensions[];\n  }>;\n  clientErrors?: ReadonlyArray<Error>;\n  networkError?: Error | ServerParseError | ServerError | null;\n  errorMessage?: string;\n  extraInfo?: any;\n}\n\nexport function graphQLResultHasProtocolErrors<T>(\n  result: FetchResult<T>\n): result is FetchResultWithSymbolExtensions<T> {\n  if (result.extensions) {\n    return Array.isArray(\n      (result as FetchResultWithSymbolExtensions<T>).extensions[\n        PROTOCOL_ERRORS_SYMBOL\n      ]\n    );\n  }\n  return false;\n}\n\nexport function isApolloError(err: Error): err is ApolloError {\n  return err.hasOwnProperty(\"graphQLErrors\");\n}\n\n// Sets the error message on this error according to the\n// the GraphQL and network errors that are present.\n// If the error message has already been set through the\n// constructor or otherwise, this function is a nop.\nconst generateErrorMessage = (err: ApolloError) => {\n  const errors = [\n    ...err.graphQLErrors,\n    ...err.clientErrors,\n    ...err.protocolErrors,\n  ];\n  if (err.networkError) errors.push(err.networkError);\n  return (\n    errors\n      // The rest of the code sometimes unsafely types non-Error objects as GraphQLErrors\n      .map(\n        (err) =>\n          (isNonNullObject(err) && err.message) || \"Error message not found.\"\n      )\n      .join(\"\\n\")\n  );\n};\n\nexport type GraphQLErrors = ReadonlyArray<GraphQLError>;\n\nexport type NetworkError = Error | ServerParseError | ServerError | null;\n\nexport class ApolloError extends Error {\n  public name: string;\n  public message: string;\n  public graphQLErrors: GraphQLErrors;\n  public protocolErrors: ReadonlyArray<{\n    message: string;\n    extensions?: GraphQLErrorExtensions[];\n  }>;\n  public clientErrors: ReadonlyArray<Error>;\n  public networkError: Error | ServerParseError | ServerError | null;\n\n  // An object that can be used to provide some additional information\n  // about an error, e.g. specifying the type of error this is. Used\n  // internally within Apollo Client.\n  public extraInfo: any;\n\n  // Constructs an instance of ApolloError given a GraphQLError\n  // or a network error. Note that one of these has to be a valid\n  // value or the constructed error will be meaningless.\n  constructor({\n    graphQLErrors,\n    protocolErrors,\n    clientErrors,\n    networkError,\n    errorMessage,\n    extraInfo,\n  }: ApolloErrorOptions) {\n    super(errorMessage);\n    this.name = \"ApolloError\";\n    this.graphQLErrors = graphQLErrors || [];\n    this.protocolErrors = protocolErrors || [];\n    this.clientErrors = clientErrors || [];\n    this.networkError = networkError || null;\n    this.message = errorMessage || generateErrorMessage(this);\n    this.extraInfo = extraInfo;\n\n    // We're not using `Object.setPrototypeOf` here as it isn't fully\n    // supported on Android (see issue #3236).\n    (this as any).__proto__ = ApolloError.prototype;\n  }\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<string, unknown>,\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<T>(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<string, string> {\n  const headersInit: Record<string, string> = {};\n  headerText.split(\"\\n\").forEach((line) => {\n    const i = line.indexOf(\":\");\n    if (i > -1) {\n      // normalize headers to lowercase\n      const name = line.slice(0, i).trim().toLowerCase();\n      const value = line.slice(i + 1).trim();\n      headersInit[name] = value;\n    }\n  });\n  return headersInit;\n}\n\nexport function parseJsonBody<T>(response: Response, bodyText: string): T {\n  if (response.status >= 300) {\n    // Network error\n    const getResult = (): Record<string, unknown> | 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<any>) {\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\";\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 { 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<string, any>;\n  extensions?: Record<string, any>;\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<string, string>;\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<string, string>;\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<HttpConfig>\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<string, any>;\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<string, string>,\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 { 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 { 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", "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 { 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 { 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", "const { toString, hasOwnProperty } = Object.prototype;\nconst fnToStr = Function.prototype.toString;\nconst previousComparisons = new Map<object, Set<object>>();\n\n/**\n * Performs a deep equality check on two JavaScript values, tolerating cycles.\n */\nexport function equal(a: any, b: any): boolean {\n  try {\n    return check(a, b);\n  } finally {\n    previousComparisons.clear();\n  }\n}\n\n// Allow default imports as well.\nexport default equal;\n\nfunction check(a: any, b: any): boolean {\n  // If the two values are strictly equal, our job is easy.\n  if (a === b) {\n    return true;\n  }\n\n  // Object.prototype.toString returns a representation of the runtime type of\n  // the given value that is considerably more precise than typeof.\n  const aTag = toString.call(a);\n  const bTag = toString.call(b);\n\n  // If the runtime types of a and b are different, they could maybe be equal\n  // under some interpretation of equality, but for simplicity and performance\n  // we just return false instead.\n  if (aTag !== bTag) {\n    return false;\n  }\n\n  switch (aTag) {\n    case '[object Array]':\n      // Arrays are a lot like other objects, but we can cheaply compare their\n      // lengths as a short-cut before comparing their elements.\n      if (a.length !== b.length) return false;\n      // Fall through to object case...\n    case '[object Object]': {\n      if (previouslyCompared(a, b)) return true;\n\n      const aKeys = definedKeys(a);\n      const bKeys = definedKeys(b);\n\n      // If `a` and `b` have a different number of enumerable keys, they\n      // must be different.\n      const keyCount = aKeys.length;\n      if (keyCount !== bKeys.length) return false;\n\n      // Now make sure they have the same keys.\n      for (let k = 0; k < keyCount; ++k) {\n        if (!hasOwnProperty.call(b, aKeys[k])) {\n          return false;\n        }\n      }\n\n      // Finally, check deep equality of all child properties.\n      for (let k = 0; k < keyCount; ++k) {\n        const key = aKeys[k];\n        if (!check(a[key], b[key])) {\n          return false;\n        }\n      }\n\n      return true;\n    }\n\n    case '[object Error]':\n      return a.name === b.name && a.message === b.message;\n\n    case '[object Number]':\n      // Handle NaN, which is !== itself.\n      if (a !== a) return b !== b;\n      // Fall through to shared +a === +b case...\n    case '[object Boolean]':\n    case '[object Date]':\n      return +a === +b;\n\n    case '[object RegExp]':\n    case '[object String]':\n      return a == `${b}`;\n\n    case '[object Map]':\n    case '[object Set]': {\n      if (a.size !== b.size) return false;\n      if (previouslyCompared(a, b)) return true;\n\n      const aIterator = a.entries();\n      const isMap = aTag === '[object Map]';\n\n      while (true) {\n        const info = aIterator.next();\n        if (info.done) break;\n\n        // If a instanceof Set, aValue === aKey.\n        const [aKey, aValue] = info.value;\n\n        // So this works the same way for both Set and Map.\n        if (!b.has(aKey)) {\n          return false;\n        }\n\n        // However, we care about deep equality of values only when dealing\n        // with Map structures.\n        if (isMap && !check(aValue, b.get(aKey))) {\n          return false;\n        }\n      }\n\n      return true;\n    }\n\n    case '[object Uint16Array]':\n    case '[object Uint8Array]': // Buffer, in Node.js.\n    case '[object Uint32Array]':\n    case '[object Int32Array]':\n    case '[object Int8Array]':\n    case '[object Int16Array]':\n    case '[object ArrayBuffer]':\n      // DataView doesn't need these conversions, but the equality check is\n      // otherwise the same.\n      a = new Uint8Array(a);\n      b = new Uint8Array(b);\n      // Fall through...\n    case '[object DataView]': {\n      let len = a.byteLength;\n      if (len === b.byteLength) {\n        while (len-- && a[len] === b[len]) {\n          // Keep looping as long as the bytes are equal.\n        }\n      }\n      return len === -1;\n    }\n\n    case '[object AsyncFunction]':\n    case '[object GeneratorFunction]':\n    case '[object AsyncGeneratorFunction]':\n    case '[object Function]': {\n      const aCode = fnToStr.call(a);\n      if (aCode !== fnToStr.call(b)) {\n        return false;\n      }\n\n      // We consider non-native functions equal if they have the same code\n      // (native functions require === because their code is censored).\n      // Note that this behavior is not entirely sound, since !== function\n      // objects with the same code can behave differently depending on\n      // their closure scope. However, any function can behave differently\n      // depending on the values of its input arguments (including this)\n      // and its calling context (including its closure scope), even\n      // though the function object is === to itself; and it is entirely\n      // possible for functions that are not === to behave exactly the\n      // same under all conceivable circumstances. Because none of these\n      // factors are statically decidable in JavaScript, JS function\n      // equality is not well-defined. This ambiguity allows us to\n      // consider the best possible heuristic among various imperfect\n      // options, and equating non-native functions that have the same\n      // code has enormous practical benefits, such as when comparing\n      // functions that are repeatedly passed as fresh function\n      // expressions within objects that are otherwise deeply equal. Since\n      // any function created from the same syntactic expression (in the\n      // same code location) will always stringify to the same code\n      // according to fnToStr.call, we can reasonably expect these\n      // repeatedly passed function expressions to have the same code, and\n      // thus behave \"the same\" (with all the caveats mentioned above),\n      // even though the runtime function objects are !== to one another.\n      return !endsWith(aCode, nativeCodeSuffix);\n    }\n  }\n\n  // Otherwise the values are not equal.\n  return false;\n}\n\nfunction definedKeys<TObject extends object>(obj: TObject) {\n  // Remember that the second argument to Array.prototype.filter will be\n  // used as `this` within the callback function.\n  return Object.keys(obj).filter(isDefinedKey, obj);\n}\nfunction isDefinedKey<TObject extends object>(\n  this: TObject,\n  key: keyof TObject,\n) {\n  return this[key] !== void 0;\n}\n\nconst nativeCodeSuffix = \"{ [native code] }\";\n\nfunction endsWith(full: string, suffix: string) {\n  const fromIndex = full.length - suffix.length;\n  return fromIndex >= 0 &&\n    full.indexOf(suffix, fromIndex) === fromIndex;\n}\n\nfunction previouslyCompared(a: object, b: object): boolean {\n  // Though cyclic references can make an object graph appear infinite from the\n  // perspective of a depth-first traversal, the graph still contains a finite\n  // number of distinct object references. We use the previousComparisons cache\n  // to avoid comparing the same pair of object references more than once, which\n  // guarantees termination (even if we end up comparing every object in one\n  // graph to every object in the other graph, which is extremely unlikely),\n  // while still allowing weird isomorphic structures (like rings with different\n  // lengths) a chance to pass the equality test.\n  let bSet = previousComparisons.get(a);\n  if (bSet) {\n    // Return true here because we can be sure false will be returned somewhere\n    // else if the objects are not equivalent.\n    if (bSet.has(b)) return true;\n  } else {\n    previousComparisons.set(a, bSet = new Set);\n  }\n  bSet.add(b);\n  return false;\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 { equal } from \"@wry/equality\";\nimport type { MissingTree } from \"./types/common.js\";\n\nexport type Transaction<T> = (c: ApolloCache<T>) => void;\n\n/**\n * Watched fragment options.\n */\nexport interface WatchFragmentOptions<TData, TVars> {\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<TData, TVars>;\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<TData> =\n  | {\n      data: TData;\n      complete: true;\n      missing?: never;\n    }\n  | {\n      data: DeepPartial<TData>;\n      complete: false;\n      missing: MissingTree;\n    };\n\nexport abstract class ApolloCache<TSerialized> implements DataProxy {\n  public readonly assumeImmutableResults: boolean = false;\n\n  // required to implement\n  // core API\n  public abstract read<TData = any, TVariables = any>(\n    query: Cache.ReadOptions<TVariables, TData>\n  ): TData | null;\n  public abstract write<TData = any, TVariables = any>(\n    write: Cache.WriteOptions<TData, TVariables>\n  ): Reference | undefined;\n  public abstract diff<T>(query: Cache.DiffOptions): Cache.DiffResult<T>;\n  public abstract watch<TData = any, TVariables = any>(\n    watch: Cache.WatchOptions<TData, TVariables>\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<void>;\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<TSerialized>;\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<U>(options: Cache.BatchOptions<this, U>): 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<TSerialized>,\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<TSerialized>,\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<Entity extends Record<string, any> = Record<string, any>>(\n    options: Cache.ModifyOptions<Entity>\n  ): boolean {\n    return false;\n  }\n\n  // DataProxy API\n  public readQuery<QueryType, TVariables = any>(\n    options: Cache.ReadQueryOptions<QueryType, TVariables>,\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<TData = any, TVars = OperationVariables>(\n    options: WatchFragmentOptions<TData, TVars>\n  ): Observable<WatchFragmentResult<TData>> {\n    const { fragment, fragmentName, from, optimistic = true } = options;\n\n    const diffOptions: Cache.DiffOptions<TData, TVars> = {\n      returnPartialData: true,\n      id: typeof from === \"string\" ? from : this.identify(from),\n      query: this.getFragmentDoc(fragment, fragmentName),\n      optimistic,\n    };\n\n    let latestDiff: DataProxy.DiffResult<TData> | undefined;\n\n    return new Observable((observer) => {\n      return this.watch<TData, TVars>({\n        ...diffOptions,\n        immediate: true,\n        query: this.getFragmentDoc(fragment, fragmentName),\n        callback(diff) {\n          if (equal(diff, latestDiff)) {\n            return;\n          }\n\n          const result = {\n            data: diff.result as DeepPartial<TData>,\n            complete: !!diff.complete,\n          } as WatchFragmentResult<TData>;\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<FragmentType, TVariables = any>(\n    options: Cache.ReadFragmentOptions<FragmentType, TVariables>,\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<TData = any, TVariables = any>({\n    id,\n    data,\n    ...options\n  }: Cache.WriteQueryOptions<TData, TVariables>): 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<TData = any, TVariables = any>({\n    id,\n    data,\n    fragment,\n    fragmentName,\n    ...options\n  }: Cache.WriteFragmentOptions<TData, TVariables>): 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<TData = any, TVariables = any>(\n    options: Cache.UpdateQueryOptions<TData, TVariables>,\n    update: (data: TData | null) => TData | null | void\n  ): TData | null {\n    return this.batch({\n      update(cache) {\n        const value = cache.readQuery<TData, TVariables>(options);\n        const data = update(value);\n        if (data === void 0 || data === null) return value;\n        cache.writeQuery<TData, TVariables>({ ...options, data });\n        return data;\n      },\n    });\n  }\n\n  public updateFragment<TData = any, TVariables = any>(\n    options: Cache.UpdateFragmentOptions<TData, TVariables>,\n    update: (data: TData | null) => TData | null | void\n  ): TData | null {\n    return this.batch({\n      update(cache) {\n        const value = cache.readFragment<TData, TVariables>(options);\n        const data = update(value);\n        if (data === void 0 || data === null) return value;\n        cache.writeFragment<TData, TVariables>({ ...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<T> 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<string> collapses to just string, which makes string\n// assignable to SafeReadonly<any>, whereas string is not assignable to\n// Readonly<any>, somewhat surprisingly.\nexport type SafeReadonly<T> = T extends object ? Readonly<T> : 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<string | number>,\n    public readonly query: DocumentNode,\n    public readonly variables?: Record<string, any>\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<string, any>;\n  variables?: Record<string, any>;\n}\n\nexport interface ReadFieldOptions extends FieldSpecifier {\n  from?: StoreObject | Reference;\n}\n\nexport interface ReadFieldFunction {\n  <V = StoreValue>(options: ReadFieldOptions): SafeReadonly<V> | undefined;\n  <V = StoreValue>(\n    fieldName: string,\n    from?: StoreObject | Reference\n  ): SafeReadonly<V> | 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<T> = (\n  value: T,\n  details: ModifierDetails\n) => T | DeleteModifier | InvalidateModifier;\n\ntype StoreObjectValueMaybeReference<StoreVal> =\n  StoreVal extends Array<Record<string, any>> ?\n    StoreVal extends Array<infer Item> ?\n      Item extends Record<string, any> ?\n        ReadonlyArray<AsStoreObject<Item> | Reference>\n      : never\n    : never\n  : StoreVal extends Record<string, any> ? AsStoreObject<StoreVal> | Reference\n  : StoreVal;\n\nexport type AllFieldsModifier<Entity extends Record<string, any>> = Modifier<\n  Entity[keyof Entity] extends infer Value ?\n    StoreObjectValueMaybeReference<Exclude<Value, undefined>>\n  : never\n>;\n\nexport type Modifiers<T extends Record<string, any> = Record<string, unknown>> =\n  Partial<{\n    [FieldName in keyof T]: Modifier<\n      StoreObjectValueMaybeReference<Exclude<T[FieldName], undefined>>\n    >;\n  }>;\n", "import type {\n  DocumentNode,\n  FragmentDefinitionNode,\n  SelectionSetNode,\n} from \"graphql\";\n\nimport type { NormalizedCache, InMemoryCacheConfig } from \"./types.js\";\n\nimport type { KeyFieldsContext } from \"./policies.js\";\nimport type { FragmentRegistryAPI } from \"./fragmentRegistry.js\";\n\nimport type {\n  Reference,\n  StoreValue,\n  StoreObject,\n  FragmentMap,\n  FragmentMapFunction,\n} from \"../../utilities/index.js\";\nimport {\n  isReference,\n  isField,\n  DeepMerger,\n  resultKeyNameFromField,\n  shouldInclude,\n  isNonNullObject,\n  compact,\n  createFragmentMap,\n  getFragmentDefinitions,\n  isArray,\n} from \"../../utilities/index.js\";\n\nexport const { hasOwnProperty: hasOwn } = Object.prototype;\n\nexport function isNullish(value: any): value is null | undefined {\n  return value === null || value === void 0;\n}\n\nexport { isArray };\n\nexport function defaultDataIdFromObject(\n  { __typename, id, _id }: Readonly<StoreObject>,\n  context?: KeyFieldsContext\n): string | undefined {\n  if (typeof __typename === \"string\") {\n    if (context) {\n      context.keyObject =\n        !isNullish(id) ? { id }\n        : !isNullish(_id) ? { _id }\n        : void 0;\n    }\n\n    // If there is no object.id, fall back to object._id.\n    if (isNullish(id) && !isNullish(_id)) {\n      id = _id;\n    }\n\n    if (!isNullish(id)) {\n      return `${__typename}:${\n        typeof id === \"number\" || typeof id === \"string\" ?\n          id\n        : JSON.stringify(id)\n      }`;\n    }\n  }\n}\n\nconst defaultConfig = {\n  dataIdFromObject: defaultDataIdFromObject,\n  addTypename: true,\n  resultCaching: true,\n  // Thanks to the shouldCanonizeResults helper, this should be the only line\n  // you have to change to reenable canonization by default in the future.\n  canonizeResults: false,\n};\n\nexport function normalizeConfig(config: InMemoryCacheConfig) {\n  return compact(defaultConfig, config);\n}\n\nexport function shouldCanonizeResults(\n  config: Pick<InMemoryCacheConfig, \"canonizeResults\">\n): boolean {\n  const value = config.canonizeResults;\n  return value === void 0 ? defaultConfig.canonizeResults : value;\n}\n\nexport function getTypenameFromStoreObject(\n  store: NormalizedCache,\n  objectOrReference: StoreObject | Reference\n): string | undefined {\n  return isReference(objectOrReference) ?\n      (store.get(objectOrReference.__ref, \"__typename\") as string)\n    : objectOrReference && objectOrReference.__typename;\n}\n\nexport const TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;\n\nexport function fieldNameFromStoreName(storeFieldName: string): string {\n  const match = storeFieldName.match(TypeOrFieldNameRegExp);\n  return match ? match[0] : storeFieldName;\n}\n\nexport function selectionSetMatchesResult(\n  selectionSet: SelectionSetNode,\n  result: Record<string, any>,\n  variables?: Record<string, any>\n): boolean {\n  if (isNonNullObject(result)) {\n    return isArray(result) ?\n        result.every((item) =>\n          selectionSetMatchesResult(selectionSet, item, variables)\n        )\n      : selectionSet.selections.every((field) => {\n          if (isField(field) && shouldInclude(field, variables)) {\n            const key = resultKeyNameFromField(field);\n            return (\n              hasOwn.call(result, key) &&\n              (!field.selectionSet ||\n                selectionSetMatchesResult(\n                  field.selectionSet,\n                  result[key],\n                  variables\n                ))\n            );\n          }\n          // If the selection has been skipped with @skip(true) or\n          // @include(false), it should not count against the matching. If\n          // the selection is not a field, it must be a fragment (inline or\n          // named). We will determine if selectionSetMatchesResult for that\n          // fragment when we get to it, so for now we return true.\n          return true;\n        });\n  }\n  return false;\n}\n\nexport function storeValueIsStoreObject(\n  value: StoreValue\n): value is StoreObject {\n  return isNonNullObject(value) && !isReference(value) && !isArray(value);\n}\n\nexport function makeProcessedFieldsMerger() {\n  return new DeepMerger();\n}\n\nexport function extractFragmentContext(\n  document: DocumentNode,\n  fragments?: FragmentRegistryAPI\n): {\n  fragmentMap: FragmentMap;\n  lookupFragment: FragmentMapFunction;\n} {\n  // FragmentMap consisting only of fragments defined directly in document, not\n  // including other fragments registered in the FragmentRegistry.\n  const fragmentMap = createFragmentMap(getFragmentDefinitions(document));\n  return {\n    fragmentMap,\n    lookupFragment(name) {\n      let def: FragmentDefinitionNode | null = fragmentMap[name];\n      if (!def && fragments) {\n        def = fragments.lookup(name);\n      }\n      return def || null;\n    },\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<any> = () => 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<string, 1> = 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<any> | Modifiers<Record<string, any>>\n  ): boolean {\n    const storeObject = this.lookup(dataId);\n\n    if (storeObject) {\n      const changedFields: Record<string, any> = 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: <V = StoreValue>(\n          fieldNameOrOptions: string | ReadFieldOptions,\n          from?: StoreObject | Reference\n        ) =>\n          this.policies.readField<V>(\n            typeof fieldNameOrOptions === \"string\" ?\n              {\n                fieldName: fieldNameOrOptions,\n                from: from || makeReference(dataId),\n              }\n            : fieldNameOrOptions,\n            { store: this }\n          ),\n      } satisfies Partial<ModifierDetails>;\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<StoreValue> | 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<string, any>\n  ) {\n    const storeObject = this.lookup(dataId);\n    if (storeObject) {\n      const typename = this.getFieldValue<string>(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<string> 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<string>()) {\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: <dataId> } strings contained by this.data[dataId].\n  private refs: {\n    [dataId: string]: Record<string, true>;\n  } = Object.create(null);\n\n  public findChildRefIds(dataId: string): Record<string, true> {\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<Record<string | number, any>>([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<any>,\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 = <T = StoreValue>(\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<T>;\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<string> | null = null;\n\n  // Used by the EntityStore#makeCacheKey method to compute cache keys\n  // specific to this CacheGroup.\n  public keyMaker!: Trie<object>;\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<string>() : 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<StorageType>(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<string, true> {\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<T>(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)<object>();\n\n  // Efficient storage/lookup structure for canonical objects.\n  private pool = new Trie<{\n    array?: any[];\n    object?: Record<string, any>;\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<object, object>();\n  public pass<T>(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<T>(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<string, SortedKeysInfo>();\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<R = any> = {\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<any>,\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<string, any>,\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<T>({\n    store,\n    query,\n    rootId = \"ROOT_QUERY\",\n    variables,\n    returnPartialData = true,\n    canonizeResults = this.config.canonizeResults,\n  }: DiffQueryAgainstStoreOptions): Cache.DiffResult<T> {\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<string, any>,\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<string>(\n      objectOrReference,\n      \"__typename\"\n    );\n\n    const objectsToMerge: Record<string, any>[] = [];\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<T>(result: ExecResult<T>, 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: <truthy value>) or\n      // @include(if: <falsy value>).\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<MissingTree[]>();\n\n    function handleMissing<T>(childResult: ExecResult<T>, 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 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<T> {\n  (newValue?: T): T;\n  onNextChange(listener: ReactiveListener<T>): () => void;\n  attachCache(cache: ApolloCache<any>): this;\n  forgetCache(cache: ApolloCache<any>): boolean;\n}\n\nexport type ReactiveListener<T> = (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<ApolloCache<any>>();\n\nconst cacheInfoMap = new WeakMap<\n  ApolloCache<any>,\n  {\n    vars: Set<ReactiveVar<any>>;\n    dep: OptimisticDependencyFunction<ReactiveVar<any>>;\n  }\n>();\n\nfunction getCacheInfo(cache: ApolloCache<any>) {\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<any>) {\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<any>) {\n  getCacheInfo(cache).vars.forEach((rv) => rv.attachCache(cache));\n}\n\nexport function makeVar<T>(value: T): ReactiveVar<T> {\n  const caches = new Set<ApolloCache<any>>();\n  const listeners = new Set<ReactiveListener<T>>();\n\n  const rv: ReactiveVar<T> = 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<any> & {\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 {\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<string, any> {\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<TObj extends Record<string, any>, 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<string, any>,\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<T>(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<string | KeySpecifier>;\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<string, any>;\n};\n\nexport type KeyFieldsFunction = (\n  object: Readonly<StoreObject>,\n  context: KeyFieldsContext\n) => KeySpecifier | false | ReturnType<IdGetter>;\n\ntype KeyFieldsResult = Exclude<ReturnType<KeyFieldsFunction>, 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<any> | FieldReadFunction<any>;\n  };\n};\n\nexport type KeyArgsFunction = (\n  args: Record<string, any> | null,\n  context: {\n    typename: string;\n    fieldName: string;\n    field: FieldNode | null;\n    variables?: Record<string, any>;\n  }\n) => KeySpecifier | false | ReturnType<IdGetter>;\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<TExisting, TReadResult, TOptions>;\n  merge?: FieldMergeFunction<TExisting, TIncoming, TOptions> | boolean;\n};\n\nexport type StorageType = Record<string, any>;\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<string, any>,\n  TVars = Record<string, any>,\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 = <T extends StoreObject | Reference>(\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<TExisting> | 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<TExisting> | undefined,\n  // The incoming parameter needs to be positional as well, for the same\n  // reasons discussed in FieldReadFunction above.\n  incoming: SafeReadonly<TIncoming>,\n  options: TOptions\n) => SafeReadonly<TExisting>;\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<any> = (\n  existing,\n  incoming,\n  { mergeObjects }\n) => mergeObjects(existing, incoming);\nconst mergeFalseFn: FieldMergeFunction<any> = (_, 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<any>;\n      fields: {\n        [fieldName: string]: {\n          keyFn?: KeyArgsFunction;\n          read?: FieldReadFunction<any>;\n          merge?: FieldMergeFunction<any>;\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<string, Set<string>>();\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<string, RegExp>();\n\n  public readonly cache: InMemoryCache;\n\n  public readonly rootIdsByTypename: Record<string, string> =\n    Object.create(null);\n  public readonly rootTypenamesById: Record<string, string> =\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<KeyFieldsContext>\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<any>;\n        merge?: FieldMergeFunction<any>;\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<string> | undefined {\n    let supertypeSet = this.supertypeMap.get(subtype);\n    if (!supertypeSet && createIfMissing) {\n      this.supertypeMap.set(subtype, (supertypeSet = new Set<string>()));\n    }\n    return supertypeSet;\n  }\n\n  public fragmentMatches(\n    fragment: InlineFragmentNode | FragmentDefinitionNode,\n    typename: string | undefined,\n    result?: Record<string, any>,\n    variables?: Record<string, any>\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<ReturnType<KeyArgsFunction>, KeySpecifier>;\n\n    let keyFn = policy && policy.keyFn;\n    if (keyFn && typename) {\n      const context: Parameters<KeyArgsFunction>[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<V = StoreValue>(\n    options: ReadFieldOptions,\n    context: ReadMergeModifyContext\n  ): SafeReadonly<V> | 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<string>(\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<V>(\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<V>;\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<T>() {\n      return policies.readField<T>(\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<T>(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<FieldNode>;\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<string, FlavorableWriteContext>;\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<TContext extends FlavorableWriteContext>(\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<string, any>;\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<T>(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<string, true> =\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<FieldNode>();\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<string>(\"__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<string, any>,\n    context: TContext,\n    typename = getTypenameFromResult(result, selectionSet, context.fragmentMap)\n  ): Map<FieldNode, TContext> {\n    const fieldMap = new Map<FieldNode, TContext>();\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<T extends StoreValue>(\n    mergeTree: MergeTree,\n    existing: StoreValue,\n    incoming: T,\n    context: WriteContext,\n    getStorageArgs?: Parameters<EntityStore[\"getStorage\"]>\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<string | number, StoreValue> | 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<string>();\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<StoreObject>(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<string>(existingRef, \"__typename\") ||\n    store.getFieldValue<string>(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<InMemoryCache>,\n  \"optimistic\" | \"onWatchUpdated\"\n>;\n\nexport class InMemoryCache extends ApolloCache<NormalizedCacheObject> {\n  private data!: EntityStore;\n  private optimisticData!: EntityStore;\n\n  protected config: InMemoryCacheConfig;\n  private watches = new Set<Cache.WatchOptions>();\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<T>(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<T>({\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<Entity extends Record<string, any> = Record<string, any>>(\n    options: Cache.ModifyOptions<Entity>\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<TData, TVariables extends OperationVariables = any>(\n    options: Cache.DiffOptions<TData, TVariables>\n  ): Cache.DiffResult<TData> {\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<TData = any, TVariables = any>(\n    watch: Cache.WatchOptions<TData, TVariables>\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<void> {\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<TUpdateResult>(\n    options: Cache.BatchOptions<InMemoryCache, TUpdateResult>\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<Cache.WatchOptions>();\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<any>(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", "/**\n * The current status of a query’s execution in our system.\n */\nexport enum NetworkStatus {\n  /**\n   * The query has never been run before and the query is now currently running. A query will still\n   * have this network status even if a partial data result was returned from the cache, but a\n   * query was dispatched anyway.\n   */\n  loading = 1,\n\n  /**\n   * If `setVariables` was called and a query was fired because of that then the network status\n   * will be `setVariables` until the result of that query comes back.\n   */\n  setVariables = 2,\n\n  /**\n   * Indicates that `fetchMore` was called on this query and that the query created is currently in\n   * flight.\n   */\n  fetchMore = 3,\n\n  /**\n   * Similar to the `setVariables` network status. It means that `refetch` was called on a query\n   * and the refetch request is currently in flight.\n   */\n  refetch = 4,\n\n  /**\n   * Indicates that a polling query is currently in flight. So for example if you are polling a\n   * query every 10 seconds then the network status will switch to `poll` every 10 seconds whenever\n   * a poll request has been sent but not resolved.\n   */\n  poll = 6,\n\n  /**\n   * No request is in flight for this query, and no errors happened. Everything is OK.\n   */\n  ready = 7,\n\n  /**\n   * No request is in flight for this query, but one or more errors were detected.\n   */\n  error = 8,\n}\n\n/**\n * Returns true if there is currently a network request in flight according to a given network\n * status.\n */\nexport function isNetworkRequestInFlight(\n  networkStatus?: NetworkStatus\n): boolean {\n  return networkStatus ? networkStatus < 7 : false;\n}\n\n/**\n * Returns true if the network request is in ready or error state according to a given network\n * status.\n */\nexport function isNetworkRequestSettled(\n  networkStatus?: NetworkStatus\n): boolean {\n  return networkStatus === 7 || networkStatus === 8;\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<ApolloQueryResult<unknown>>,\n  { data: bData, ...bRest }: Partial<ApolloQueryResult<unknown>>,\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<TVariables> {\n  fragmentMap: FragmentMap;\n  variables: TVariables | undefined;\n}\n\nfunction equalBySelectionSet(\n  selectionSet: SelectionSetNode,\n  aResult: any,\n  bResult: any,\n  context: CompareContext<OperationVariables>\n): boolean {\n  if (aResult === bResult) {\n    return true;\n  }\n\n  const seenSelections = new Set<SelectionNode>();\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<TVariables> {\n  variables?: TVariables;\n}\n\ninterface Last<TData, TVariables> {\n  result: ApolloQueryResult<TData>;\n  variables?: TVariables;\n  error?: ApolloError;\n}\n\nexport class ObservableQuery<\n  TData = any,\n  TVariables extends OperationVariables = OperationVariables,\n> extends Observable<ApolloQueryResult<TData>> {\n  public readonly options: WatchQueryOptions<TVariables, TData>;\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<TData, TVariables> {\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<any>;\n  private observers = new Set<Observer<ApolloQueryResult<TData>>>();\n  private subscriptions = new Set<ObservableSubscription>();\n\n  private waitForOwnResult: boolean;\n  private last?: Last<TData, TVariables>;\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<ApolloQueryResult<TData>>;\n  private observer?: Observer<ApolloQueryResult<TData>>;\n\n  private pollingInfo?: {\n    interval: number;\n    timeout: ReturnType<typeof setTimeout>;\n  };\n\n  constructor({\n    queryManager,\n    queryInfo,\n    options,\n  }: {\n    queryManager: QueryManager<any>;\n    queryInfo: QueryInfo;\n    options: WatchQueryOptions<TVariables, TData>;\n  }) {\n    super((observer: Observer<ApolloQueryResult<TData>>) => {\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<ApolloQueryResult<TData>> {\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<ApolloQueryResult<TData>> = {\n        next: (result: ApolloQueryResult<TData>) => {\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<TData> {\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<TData>;\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<TData>,\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<K extends keyof Last<TData, TVariables>>(\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<TData> | 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<TVariables>\n  ): Promise<ApolloQueryResult<TData>> {\n    const reobserveOptions: Partial<WatchQueryOptions<TVariables, TData>> = {\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<TFetchVars, TFetchData> & {\n      updateQuery?: (\n        previousQueryResult: TData,\n        options: {\n          fetchMoreResult: TFetchData;\n          variables: TFetchVars;\n        }\n      ) => TData;\n    }\n  ): Promise<ApolloQueryResult<TFetchData>> {\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<TFetchVars, TFetchData>;\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<DocumentNode>();\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<TSubscriptionVariables>(\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<WatchQueryOptions<TVariables, TData>>\n  ): Promise<ApolloQueryResult<TData>> {\n    return this.reobserve(newOptions);\n  }\n\n  public silentSetOptions(\n    newOptions: Partial<WatchQueryOptions<TVariables, TData>>\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<ApolloQueryResult<TData> | 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<TVars extends OperationVariables = TVariables>(\n    mapFn: (\n      previousQueryResult: TData,\n      options: Pick<WatchQueryOptions<TVars, TData>, \"variables\">\n    ) => TData\n  ): void {\n    const { queryManager } = this;\n    const { result } = queryManager.cache.diff<TData>({\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<TData, TVariables>[\"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<TVariables, TData>\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<TVariables, TData>,\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) {\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<TData>,\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<WatchQueryOptions<TVariables, TData>>,\n    newNetworkStatus?: NetworkStatus\n  ): Concast<ApolloQueryResult<TData>> {\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<ApolloQueryResult<TData>> = {\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<WatchQueryOptions<TVariables, TData>>,\n    newNetworkStatus?: NetworkStatus\n  ): Promise<ApolloQueryResult<TData>> {\n    return this.reobserveAsConcast(newOptions, newNetworkStatus)\n      .promise as TODO;\n  }\n\n  public resubscribeAfterError(\n    onNext: (value: ApolloQueryResult<TData>) => void,\n    onError?: (error: any) => void,\n    onComplete?: () => void\n  ): ObservableSubscription;\n\n  public resubscribeAfterError(\n    observer: Observer<ApolloQueryResult<TData>>\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<TData>,\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<TData>;\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<TData, TVars extends OperationVariables>(\n  obsQuery: ObservableQuery<TData, TVars>\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<TVars, TData>,\n        currentFetchPolicy: WatchQueryFetchPolicy,\n        context: NextFetchPolicyContext<TData, TVars>\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 { 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<string, any>;\n  onlyRunForcedResolvers: boolean;\n  selectionsToResolve: Set<SelectionNode>;\n};\n\nexport type LocalStateOptions<TCacheShape> = {\n  cache: ApolloCache<TCacheShape>;\n  client?: ApolloClient<TCacheShape>;\n  resolvers?: Resolvers | Resolvers[];\n  fragmentMatcher?: FragmentMatcher;\n};\n\nexport class LocalState<TCacheShape> {\n  private cache: ApolloCache<TCacheShape>;\n  private client?: ApolloClient<TCacheShape>;\n  private resolvers?: Resolvers;\n  private fragmentMatcher?: FragmentMatcher;\n  private selectionsToResolveCache = new WeakMap<\n    ExecutableDefinitionNode,\n    Set<SelectionNode>\n  >();\n\n  constructor({\n    cache,\n    client,\n    resolvers,\n    fragmentMatcher,\n  }: LocalStateOptions<TCacheShape>) {\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<TData>({\n    document,\n    remoteResult,\n    context,\n    variables,\n    onlyRunForcedResolvers = false,\n  }: {\n    document: DocumentNode | null;\n    remoteResult: FetchResult<TData>;\n    context?: Record<string, any>;\n    variables?: Record<string, any>;\n    onlyRunForcedResolvers?: boolean;\n  }): Promise<FetchResult<TData>> {\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<string, any>) {\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<TVars extends OperationVariables>(\n    document: DocumentNode,\n    variables: TVars = {} as TVars,\n    context = {}\n  ): /* returns at least the variables that were passed in */ Promise<TVars> {\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<string, any>\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<TData>(\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<TData>(\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<void> => {\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<any> {\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<SelectionNode> {\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<SelectionNode> {\n      if (!selectionsToResolveCache.has(definitionNode)) {\n        const matches = new Set<SelectionNode>();\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<any>,\n  number\n>();\n\nfunction wrapDestructiveCacheMethod(\n  cache: ApolloCache<any>,\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<QueryListener>();\n  document: DocumentNode | null = null;\n  lastRequestId = 1;\n  variables?: Record<string, any>;\n  networkStatus?: NetworkStatus;\n  networkError?: Error | null;\n  graphQLErrors?: ReadonlyArray<GraphQLError>;\n  stopped = false;\n\n  private cache: ApolloCache<any>;\n\n  constructor(\n    queryManager: QueryManager<any>,\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<string, any> | 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<any, any>;\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<typeof setTimeout>;\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<any> {\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<any>;\n    options: Cache.DiffOptions;\n  };\n\n  private updateLastDiff(\n    diff: Cache.DiffResult<any> | 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<any> | null) {\n    const oldDiff = this.lastDiff && this.lastDiff.diff;\n\n    // If we do not tolerate partial results, skip this update to prevent it\n    // from being reported. This prevents a situtuation where a query that\n    // errors and another succeeds with overlapping data does not report the\n    // partial data result to the errored query.\n    //\n    // See https://github.com/apollographql/apollo-client/issues/11400 for more\n    // information on this issue.\n    if (\n      diff &&\n      !diff.complete &&\n      !this.observableQuery?.options.returnPartialData &&\n      // In the case of a cache eviction, the diff will become partial so we\n      // schedule a notification to send a network request (this.oqListener) to\n      // go and fetch the missing data.\n      !(oldDiff && oldDiff.complete)\n    ) {\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<any, any> | null = null;\n  private oqListener?: QueryListener;\n\n  setObservableQuery(oq: ObservableQuery<any, any> | 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<any>;\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<any>,\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<T>(\n    result: FetchResult<T>,\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<T>(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<T>(\n  result: FetchResult<T>,\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<string, any>;\n  loading: boolean;\n  error: Error | null;\n}\n\ntype UpdateQueries<TData> = MutationOptions<TData, any, any>[\"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<TStore> {\n  public cache: ApolloCache<TStore>;\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<DefaultContext>;\n\n  private queryDeduplication: boolean;\n  private clientAwareness: Record<string, string> = {};\n  private localState: LocalState<TStore>;\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<string, QueryInfo>();\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<string, (error: any) => 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<TStore>;\n    link: ApolloLink;\n    defaultOptions?: DefaultOptions;\n    documentTransform?: DocumentTransform;\n    queryDeduplication?: boolean;\n    onBroadcast?: () => void;\n    ssrMode?: boolean;\n    clientAwareness?: Record<string, string>;\n    localState?: LocalState<TStore>;\n    assumeImmutableResults?: boolean;\n    defaultContext?: Partial<DefaultContext>;\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<string, any>,\n    TCache extends ApolloCache<any>,\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<TData, TVariables, TContext>): Promise<\n    FetchResult<TData>\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<TData, TVariables, TContext, TCache>(\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<TData>) => {\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<TData, TVariables, TContext, TCache>({\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<any>,\n  >(\n    mutation: {\n      mutationId: string;\n      result: FetchResult<TData>;\n      document: DocumentNode;\n      variables?: TVariables;\n      fetchPolicy?: MutationFetchPolicy;\n      errorPolicy: ErrorPolicy;\n      context?: TContext;\n      updateQueries: UpdateQueries<TData>;\n      update?: MutationUpdaterFunction<TData, TVariables, TContext, TCache>;\n      awaitRefetchQueries?: boolean;\n      refetchQueries?: InternalRefetchQueriesInclude;\n      removeOptimistic?: string;\n      onQueryUpdated?: OnQueryUpdated<any>;\n      keepRootFields?: boolean;\n    },\n    cache = this.cache\n  ): Promise<FetchResult<TData>> {\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<TData>({\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<TData>({\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<TData>({\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<any>,\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<TData>;\n      update?: MutationUpdaterFunction<TData, TVariables, TContext, TCache>;\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<TData, TVariables, TContext, TCache>(\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<TData, TVars extends OperationVariables>(\n    queryId: string,\n    options: WatchQueryOptions<TVars, TData>,\n    networkStatus?: NetworkStatus\n  ): Promise<ApolloQueryResult<TData>> {\n    return this.fetchConcastWithInfo(queryId, options, networkStatus).concast\n      .promise as TODO;\n  }\n\n  public getQueryStore() {\n    const store: Record<string, QueryStoreValue> = 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<TVariables>(\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<TVariables, T>): ObservableQuery<T, TVariables> {\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<T, TVariables>({\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<TData, TVars extends OperationVariables = OperationVariables>(\n    options: QueryOptions<TVars, TData>,\n    queryId = this.generateQueryId()\n  ): Promise<ApolloQueryResult<TData>> {\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<TData, TVars>(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<void> {\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<string, ObservableQuery<any>>();\n    const queryNamesAndDocs = new Map<string | DocumentNode, boolean>();\n    const legacyQueryOptions = new Set<QueryOptions>();\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<ApolloQueryResult<any>[]> {\n    const observableQueryPromises: Promise<ApolloQueryResult<any>>[] = [];\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<any, any>) {\n    this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);\n  }\n\n  public startGraphQLSubscription<T = any>({\n    query,\n    fetchPolicy,\n    errorPolicy = \"none\",\n    variables,\n    context = {},\n  }: SubscriptionOptions): Observable<FetchResult<T>> {\n    query = this.transform(query);\n    variables = this.getVariables(query, variables);\n\n    const makeObservable = (variables: OperationVariables) =>\n      this.getObservableFromLink<T>(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<FetchResult<T>>((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<TStore> {\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<FetchResult<any>>;\n  }>(false);\n\n  private getObservableFromLink<T = any>(\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<FetchResult<T>> {\n    let observable: Observable<FetchResult<T>> | 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<FetchResult<T>>,\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<FetchResult<T>>,\n        ]);\n      }\n    } else {\n      observable = new Concast([Observable.of({ data: {} } as FetchResult<T>)]);\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<TData, TVars extends OperationVariables>(\n    queryInfo: QueryInfo,\n    cacheWriteBehavior: CacheWriteBehavior,\n    options: Pick<\n      WatchQueryOptions<TVars, TData>,\n      \"query\" | \"variables\" | \"context\" | \"fetchPolicy\" | \"errorPolicy\"\n    >\n  ): Observable<ApolloQueryResult<TData>> {\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<TData> = {\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<TData, TVars extends OperationVariables>(\n    queryId: string,\n    options: WatchQueryOptions<TVars, TData>,\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<TData> {\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<TData, TVars>(\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<ApolloQueryResult<TData>>,\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<TResult>({\n    updateCache,\n    include,\n    optimistic = false,\n    removeOptimistic = optimistic ? makeUniqueId(\"refetchQueries\") : void 0,\n    onQueryUpdated,\n  }: InternalRefetchQueriesOptions<\n    ApolloCache<TStore>,\n    TResult\n  >): InternalRefetchQueriesMap<TResult> {\n    const includedQueriesById = new Map<\n      string,\n      {\n        oq: ObservableQuery<any>;\n        lastDiff?: Cache.DiffResult<any>;\n        diff?: Cache.DiffResult<any>;\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<TResult> = 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<ApolloQueryResult<any>> =\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<TResult>\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<ApolloQueryResult<any>>\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<TResult>);\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<TData, TVars extends OperationVariables>(\n    queryInfo: QueryInfo,\n    {\n      query,\n      variables,\n      fetchPolicy,\n      refetchWritePolicy,\n      errorPolicy,\n      returnPartialData,\n      context,\n      notifyOnNetworkStatusChange,\n    }: WatchQueryOptions<TVars, TData>,\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<TData> {\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<TData>,\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<TData>);\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<TData, TVars>(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<TData> extends FetchConcastInfo {\n  sources: ConcastSourcesArray<ApolloQueryResult<TData>>;\n}\ninterface ConcastAndInfo<TData> extends FetchConcastInfo {\n  concast: Concast<ApolloQueryResult<TData>>;\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<WatchQueryOptions<any, any>>;\n  query?: Partial<QueryOptions<any, any>>;\n  mutate?: Partial<MutationOptions<any, any, any>>;\n}\n\nlet hasSuggestedDevtools = false;\n\nexport interface ApolloClientOptions<TCacheShape> {\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<string, string>;\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<TCacheShape>;\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<DefaultContext>;\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<TCacheShape> implements DataProxy {\n  public link: ApolloLink;\n  public cache: ApolloCache<TCacheShape>;\n  public disableNetworkFetches: boolean;\n  public version: string;\n  public queryDeduplication: boolean;\n  public defaultOptions: DefaultOptions;\n  public readonly typeDefs: ApolloClientOptions<TCacheShape>[\"typeDefs\"];\n\n  private queryManager: QueryManager<TCacheShape>;\n  private devToolsHookCb?: Function;\n  private resetStoreCallbacks: Array<() => Promise<any>> = [];\n  private clearStoreCallbacks: Array<() => Promise<any>> = [];\n  private localState: LocalState<TCacheShape>;\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<TCacheShape>) {\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<any>): void;\n      };\n      const windowWithDevTools = window as Window & {\n        [devtoolsSymbol]?: DevToolsConnector;\n        __APOLLO_CLIENT__?: ApolloClient<any>;\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        ) {\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<TVariables, T>): ObservableQuery<T, TVariables> {\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<T, TVariables>(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<TVariables, T>): Promise<ApolloQueryResult<T>> {\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<T, TVariables>(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<string, any> = DefaultContext,\n    TCache extends ApolloCache<any> = ApolloCache<any>,\n  >(\n    options: MutationOptions<TData, TVariables, TContext>\n  ): Promise<FetchResult<TData>> {\n    if (this.defaultOptions.mutate) {\n      options = mergeOptions(this.defaultOptions.mutate, options);\n    }\n    return this.queryManager.mutate<TData, TVariables, TContext, TCache>(\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<TVariables, T>): Observable<FetchResult<T>> {\n    return this.queryManager.startGraphQLSubscription<T>(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<T = any, TVariables = OperationVariables>(\n    options: DataProxy.Query<TVariables, T>,\n    optimistic: boolean = false\n  ): T | null {\n    return this.cache.readQuery<T, TVariables>(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<TFragmentData, TVariables>\n  ): Observable<WatchFragmentResult<TFragmentData>> {\n    return this.cache.watchFragment<TFragmentData, TVariables>(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<T = any, TVariables = OperationVariables>(\n    options: DataProxy.Fragment<TVariables, T>,\n    optimistic: boolean = false\n  ): T | null {\n    return this.cache.readFragment<T, TVariables>(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<TData = any, TVariables = OperationVariables>(\n    options: DataProxy.WriteQueryOptions<TData, TVariables>\n  ): Reference | undefined {\n    const ref = this.cache.writeQuery<TData, TVariables>(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<TData = any, TVariables = OperationVariables>(\n    options: DataProxy.WriteFragmentOptions<TData, TVariables>\n  ): Reference | undefined {\n    const ref = this.cache.writeFragment<TData, TVariables>(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<ExecutionResult> {\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<ApolloQueryResult<any>[] | 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<any[]> {\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<any>): () => 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<any>): () => 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<ApolloQueryResult<any>[]> {\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<any> = ApolloCache<TCacheShape>,\n    TResult = Promise<ApolloQueryResult<any>>,\n  >(\n    options: RefetchQueriesOptions<TCache, TResult>\n  ): RefetchQueriesResult<TResult> {\n    const map = this.queryManager.refetchQueries(\n      options as RefetchQueriesOptions<ApolloCache<TCacheShape>, TResult>\n    );\n    const queries: ObservableQuery<any>[] = [];\n    const results: InternalRefetchQueriesResult<TResult>[] = [];\n\n    map.forEach((result, obsQuery) => {\n      queries.push(obsQuery);\n      results.push(result);\n    });\n\n    const result = Promise.all<TResult>(\n      results as TResult[]\n    ) as RefetchQueriesResult<TResult>;\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<string, ObservableQuery<any>> {\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<TCacheShape> {\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 { 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<string, DocumentNode>();\n\n// A map fragmentName -> [normalized source]\nconst fragmentSourceMap = new Map<string, Set<string>>();\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<string>();\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<Record<string, any>>(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<string, any>;\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 * as React from \"rehackt\";\nimport type * as ReactTypes from \"react\";\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { canUseSymbol } from \"../../utilities/index.js\";\nimport type { RenderPromises } from \"../ssr/index.js\";\nimport { invariant } from \"../../utilities/globals/index.js\";\n\nexport interface ApolloContextValue {\n  client?: ApolloClient<object>;\n  renderPromises?: RenderPromises;\n}\n\n// To make sure Apollo Client doesn't create more than one React context\n// (which can lead to problems like having an Apollo Client instance added\n// in one context, then attempting to retrieve it from another different\n// context), a single Apollo context is created and tracked in global state.\nconst contextKey =\n  canUseSymbol ? Symbol.for(\"__APOLLO_CONTEXT__\") : \"__APOLLO_CONTEXT__\";\n\nexport function getApolloContext(): ReactTypes.Context<ApolloContextValue> {\n  invariant(\n    \"createContext\" in React,\n    \"Invoking `getApolloContext` in an environment where `React.createContext` is not available.\\n\" +\n      \"The Apollo Client functionality you are trying to use is only available in React Client Components.\\n\" +\n      'Please make sure to add \"use client\" at the top of your file.\\n' +\n      // TODO: change to React documentation once React documentation contains information about Client Components\n      \"For more information, see https://nextjs.org/docs/getting-started/react-essentials#client-components\"\n  );\n\n  let context = (React.createContext as any)[\n    contextKey\n  ] as React.Context<ApolloContextValue>;\n  if (!context) {\n    Object.defineProperty(React.createContext, contextKey, {\n      value: (context = React.createContext<ApolloContextValue>({})),\n      enumerable: false,\n      writable: false,\n      configurable: true,\n    });\n    context.displayName = \"ApolloContext\";\n  }\n  return context;\n}\n\n/**\n * @deprecated This function has no \"resetting\" effect since Apollo Client 3.4.12,\n * and will be removed in the next major version of Apollo Client.\n * If you want to get the Apollo Context, use `getApolloContext` instead.\n */\nexport const resetApolloContext = getApolloContext;\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<TCache> {\n  client: ApolloClient<TCache>;\n  children: ReactTypes.ReactNode | ReactTypes.ReactNode[] | null;\n}\n\nexport const ApolloProvider: ReactTypes.FC<ApolloProviderProps<any>> = ({\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    <ApolloContext.Provider value={context}>{children}</ApolloContext.Provider>\n  );\n};\n", "import { invariant } from \"../../utilities/globals/index.js\";\nimport * as React from \"rehackt\";\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { getApolloContext } from \"../context/index.js\";\n\n/**\n * @example\n * ```jsx\n * import { useApolloClient } from '@apollo/client';\n *\n * function SomeComponent() {\n *   const client = useApolloClient();\n *   // `client` is now set to the `ApolloClient` instance being used by the\n *   // application (that was configured using something like `ApolloProvider`)\n * }\n * ```\n *\n * @since 3.0.0\n * @returns The `ApolloClient` instance being used by the application.\n */\nexport function useApolloClient(\n  override?: ApolloClient<object>\n): ApolloClient<object> {\n  const context = React.useContext(getApolloContext());\n  const client = override || context.client;\n  invariant(\n    !!client,\n    'Could not find \"client\" in the context or passed in as an option. ' +\n      \"Wrap the root component in an <ApolloProvider>, or pass an ApolloClient \" +\n      \"instance in via options.\"\n  );\n\n  return client;\n}\n", "import { invariant } from \"../../utilities/globals/index.js\";\n\nimport * as React from \"rehackt\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport { equal } from \"@wry/equality\";\n\nimport type {\n  OperationVariables,\n  WatchQueryFetchPolicy,\n} from \"../../core/index.js\";\nimport { mergeOptions } from \"../../utilities/index.js\";\nimport type { ApolloContextValue } from \"../context/index.js\";\nimport { getApolloContext } from \"../context/index.js\";\nimport { ApolloError } from \"../../errors/index.js\";\nimport type {\n  ApolloClient,\n  ApolloQueryResult,\n  ObservableQuery,\n  DocumentNode,\n  TypedDocumentNode,\n  WatchQueryOptions,\n} from \"../../core/index.js\";\nimport { NetworkStatus } from \"../../core/index.js\";\nimport type {\n  QueryHookOptions,\n  QueryResult,\n  ObservableQueryFields,\n  NoInfer,\n} from \"../types/types.js\";\n\nimport { DocumentType, verifyDocumentType } from \"../parser/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport {\n  canUseWeakMap,\n  compact,\n  isNonEmptyArray,\n  maybeDeepFreeze,\n} from \"../../utilities/index.js\";\nimport { wrapHook } from \"./internal/index.js\";\n\nconst {\n  prototype: { hasOwnProperty },\n} = Object;\n\n/**\n * A hook for executing queries in an Apollo application.\n *\n * To run a query within a React component, call `useQuery` and pass it a GraphQL query document.\n *\n * When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, and `data` properties you can use to render your UI.\n *\n * > Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of `useQuery`.\n *\n * @example\n * ```jsx\n * import { gql, useQuery } 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 { loading, error, data } = useQuery(GET_GREETING, {\n *     variables: { language: 'english' },\n *   });\n *   if (loading) return <p>Loading ...</p>;\n *   return <h1>Hello {data.greeting.message}!</h1>;\n * }\n * ```\n * @since 3.0.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 Query result object\n */\nexport function useQuery<\n  TData = any,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: QueryHookOptions<\n    NoInfer<TData>,\n    NoInfer<TVariables>\n  > = Object.create(null)\n): QueryResult<TData, TVariables> {\n  return wrapHook(\n    \"useQuery\",\n    _useQuery,\n    useApolloClient(options && options.client)\n  )(query, options);\n}\n\nfunction _useQuery<\n  TData = any,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>\n) {\n  return useInternalState(useApolloClient(options.client), query).useQuery(\n    options\n  );\n}\n\nexport function useInternalState<TData, TVariables extends OperationVariables>(\n  client: ApolloClient<any>,\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>\n): InternalState<TData, TVariables> {\n  const stateRef = React.useRef<InternalState<TData, TVariables>>();\n  if (\n    !stateRef.current ||\n    client !== stateRef.current.client ||\n    query !== stateRef.current.query\n  ) {\n    stateRef.current = new InternalState(client, query, stateRef.current);\n  }\n  const state = stateRef.current;\n\n  // By default, InternalState.prototype.forceUpdate is an empty function, but\n  // we replace it here (before anyone has had a chance to see this state yet)\n  // with a function that unconditionally forces an update, using the latest\n  // setTick function. Updating this state by calling state.forceUpdate is the\n  // only way we trigger React component updates (no other useState calls within\n  // the InternalState class).\n  state.forceUpdateState = React.useReducer((tick) => tick + 1, 0)[1];\n\n  return state;\n}\n\nclass InternalState<TData, TVariables extends OperationVariables> {\n  constructor(\n    public readonly client: ReturnType<typeof useApolloClient>,\n    public readonly query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n    previous?: InternalState<TData, TVariables>\n  ) {\n    verifyDocumentType(query, DocumentType.Query);\n\n    // Reuse previousData from previous InternalState (if any) to provide\n    // continuity of previousData even if/when the query or client changes.\n    const previousResult = previous && previous.result;\n    const previousData = previousResult && previousResult.data;\n    if (previousData) {\n      this.previousData = previousData;\n    }\n  }\n\n  /**\n   * Forces an update using local component state.\n   * As this is not batched with `useSyncExternalStore` updates,\n   * this is only used as a fallback if the `useSyncExternalStore` \"force update\"\n   * method is not registered at the moment.\n   * See https://github.com/facebook/react/issues/25191\n   *  */\n  forceUpdateState() {\n    // Replaced (in useInternalState) with a method that triggers an update.\n    invariant.warn(\n      \"Calling default no-op implementation of InternalState#forceUpdate\"\n    );\n  }\n\n  /**\n   * Will be overwritten by the `useSyncExternalStore` \"force update\" method\n   * whenever it is available and reset to `forceUpdateState` when it isn't.\n   */\n  forceUpdate = () => this.forceUpdateState();\n\n  executeQuery(\n    options: QueryHookOptions<TData, TVariables> & {\n      query?: DocumentNode;\n    }\n  ) {\n    if (options.query) {\n      Object.assign(this, { query: options.query });\n    }\n\n    this.watchQueryOptions = this.createWatchQueryOptions(\n      (this.queryHookOptions = options)\n    );\n\n    const concast = this.observable.reobserveAsConcast(\n      this.getObsQueryOptions()\n    );\n\n    // Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,\n    // but save the current data as this.previousData, just like setResult\n    // usually does.\n    this.previousData = this.result?.data || this.previousData;\n    this.result = void 0;\n    this.forceUpdate();\n\n    return new Promise<QueryResult<TData, TVariables>>((resolve) => {\n      let result: ApolloQueryResult<TData>;\n\n      // Subscribe to the concast independently of the ObservableQuery in case\n      // the component gets unmounted before the promise resolves. This prevents\n      // the concast from terminating early and resolving with `undefined` when\n      // there are no more subscribers for the concast.\n      concast.subscribe({\n        next: (value) => {\n          result = value;\n        },\n        error: () => {\n          resolve(this.toQueryResult(this.observable.getCurrentResult()));\n        },\n        complete: () => {\n          resolve(this.toQueryResult(result));\n        },\n      });\n    });\n  }\n\n  // Methods beginning with use- should be called according to the standard\n  // rules of React hooks: only at the top level of the calling function, and\n  // without any dynamic conditional logic.\n  useQuery(options: QueryHookOptions<TData, TVariables>) {\n    // The renderPromises field gets initialized here in the useQuery method, at\n    // the beginning of everything (for a given component rendering, at least),\n    // so we can safely use this.renderPromises in other/later InternalState\n    // methods without worrying it might be uninitialized. Even after\n    // initialization, this.renderPromises is usually undefined (unless SSR is\n    // happening), but that's fine as long as it has been initialized that way,\n    // rather than left uninitialized.\n    this.renderPromises = React.useContext(getApolloContext()).renderPromises;\n\n    this.useOptions(options);\n\n    const obsQuery = this.useObservableQuery();\n\n    const result = useSyncExternalStore(\n      React.useCallback(\n        (handleStoreChange) => {\n          if (this.renderPromises) {\n            return () => {};\n          }\n\n          this.forceUpdate = handleStoreChange;\n\n          const onNext = () => {\n            const previousResult = this.result;\n            // We use `getCurrentResult()` instead of the onNext argument because\n            // the values differ slightly. Specifically, loading results will have\n            // an empty object for data instead of `undefined` for some reason.\n            const result = obsQuery.getCurrentResult();\n            // Make sure we're not attempting to re-render similar results\n            if (\n              previousResult &&\n              previousResult.loading === result.loading &&\n              previousResult.networkStatus === result.networkStatus &&\n              equal(previousResult.data, result.data)\n            ) {\n              return;\n            }\n\n            this.setResult(result);\n          };\n\n          const onError = (error: Error) => {\n            subscription.unsubscribe();\n            subscription = obsQuery.resubscribeAfterError(onNext, onError);\n\n            if (!hasOwnProperty.call(error, \"graphQLErrors\")) {\n              // The error is not a GraphQL error\n              throw error;\n            }\n\n            const previousResult = this.result;\n            if (\n              !previousResult ||\n              (previousResult && previousResult.loading) ||\n              !equal(error, previousResult.error)\n            ) {\n              this.setResult({\n                data: (previousResult && previousResult.data) as TData,\n                error: error as ApolloError,\n                loading: false,\n                networkStatus: NetworkStatus.error,\n              });\n            }\n          };\n\n          let subscription = obsQuery.subscribe(onNext, onError);\n\n          // Do the \"unsubscribe\" with a short delay.\n          // This way, an existing subscription can be reused without an additional\n          // request if \"unsubscribe\"  and \"resubscribe\" to the same ObservableQuery\n          // happen in very fast succession.\n          return () => {\n            setTimeout(() => subscription.unsubscribe());\n            this.forceUpdate = () => this.forceUpdateState();\n          };\n        },\n        [\n          // We memoize the subscribe function using useCallback and the following\n          // dependency keys, because the subscribe function reference is all that\n          // useSyncExternalStore uses internally as a dependency key for the\n          // useEffect ultimately responsible for the subscription, so we are\n          // effectively passing this dependency array to that useEffect buried\n          // inside useSyncExternalStore, as desired.\n          obsQuery,\n          this.renderPromises,\n          this.client.disableNetworkFetches,\n        ]\n      ),\n\n      () => this.getCurrentResult(),\n      () => this.getCurrentResult()\n    );\n\n    // TODO Remove this method when we remove support for options.partialRefetch.\n    this.unsafeHandlePartialRefetch(result);\n\n    return this.toQueryResult(result);\n  }\n\n  // These members (except for renderPromises) are all populated by the\n  // useOptions method, which is called unconditionally at the beginning of the\n  // useQuery method, so we can safely use these members in other/later methods\n  // without worrying they might be uninitialized.\n  private renderPromises: ApolloContextValue[\"renderPromises\"];\n  private queryHookOptions!: QueryHookOptions<TData, TVariables>;\n  private watchQueryOptions!: WatchQueryOptions<TVariables, TData>;\n\n  private useOptions(options: QueryHookOptions<TData, TVariables>) {\n    const watchQueryOptions = this.createWatchQueryOptions(\n      (this.queryHookOptions = options)\n    );\n\n    // Update this.watchQueryOptions, but only when they have changed, which\n    // allows us to depend on the referential stability of\n    // this.watchQueryOptions elsewhere.\n    const currentWatchQueryOptions = this.watchQueryOptions;\n\n    if (!equal(watchQueryOptions, currentWatchQueryOptions)) {\n      this.watchQueryOptions = watchQueryOptions;\n\n      if (currentWatchQueryOptions && this.observable) {\n        // Though it might be tempting to postpone this reobserve call to the\n        // useEffect block, we need getCurrentResult to return an appropriate\n        // loading:true result synchronously (later within the same call to\n        // useQuery). Since we already have this.observable here (not true for\n        // the very first call to useQuery), we are not initiating any new\n        // subscriptions, though it does feel less than ideal that reobserve\n        // (potentially) kicks off a network request (for example, when the\n        // variables have changed), which is technically a side-effect.\n        this.observable.reobserve(this.getObsQueryOptions());\n\n        // Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,\n        // but save the current data as this.previousData, just like setResult\n        // usually does.\n        this.previousData = this.result?.data || this.previousData;\n        this.result = void 0;\n      }\n    }\n\n    // Make sure state.onCompleted and state.onError always reflect the latest\n    // options.onCompleted and options.onError callbacks provided to useQuery,\n    // since those functions are often recreated every time useQuery is called.\n    // Like the forceUpdate method, the versions of these methods inherited from\n    // InternalState.prototype are empty no-ops, but we can override them on the\n    // base state object (without modifying the prototype).\n    this.onCompleted =\n      options.onCompleted || InternalState.prototype.onCompleted;\n    this.onError = options.onError || InternalState.prototype.onError;\n\n    if (\n      (this.renderPromises || this.client.disableNetworkFetches) &&\n      this.queryHookOptions.ssr === false &&\n      !this.queryHookOptions.skip\n    ) {\n      // If SSR has been explicitly disabled, and this function has been called\n      // on the server side, return the default loading state.\n      this.result = this.ssrDisabledResult;\n    } else if (\n      this.queryHookOptions.skip ||\n      this.watchQueryOptions.fetchPolicy === \"standby\"\n    ) {\n      // When skipping a query (ie. we're not querying for data but still want to\n      // render children), make sure the `data` is cleared out and `loading` is\n      // set to `false` (since we aren't loading anything).\n      //\n      // NOTE: We no longer think this is the correct behavior. Skipping should\n      // not automatically set `data` to `undefined`, but instead leave the\n      // previous data in place. In other words, skipping should not mandate that\n      // previously received data is all of a sudden removed. Unfortunately,\n      // changing this is breaking, so we'll have to wait until Apollo Client 4.0\n      // to address this.\n      this.result = this.skipStandbyResult;\n    } else if (\n      this.result === this.ssrDisabledResult ||\n      this.result === this.skipStandbyResult\n    ) {\n      this.result = void 0;\n    }\n  }\n\n  private getObsQueryOptions(): WatchQueryOptions<TVariables, TData> {\n    const toMerge: Array<Partial<WatchQueryOptions<TVariables, TData>>> = [];\n\n    const globalDefaults = this.client.defaultOptions.watchQuery;\n    if (globalDefaults) toMerge.push(globalDefaults);\n\n    if (this.queryHookOptions.defaultOptions) {\n      toMerge.push(this.queryHookOptions.defaultOptions);\n    }\n\n    // We use compact rather than mergeOptions for this part of the merge,\n    // because we want watchQueryOptions.variables (if defined) to replace\n    // this.observable.options.variables whole. This replacement allows\n    // removing variables by removing them from the variables input to\n    // useQuery. If the variables were always merged together (rather than\n    // replaced), there would be no way to remove existing variables.\n    // However, the variables from options.defaultOptions and globalDefaults\n    // (if provided) should be merged, to ensure individual defaulted\n    // variables always have values, if not otherwise defined in\n    // observable.options or watchQueryOptions.\n    toMerge.push(\n      compact(\n        this.observable && this.observable.options,\n        this.watchQueryOptions\n      )\n    );\n\n    return toMerge.reduce(mergeOptions) as WatchQueryOptions<TVariables, TData>;\n  }\n\n  private ssrDisabledResult = maybeDeepFreeze({\n    loading: true,\n    data: void 0 as unknown as TData,\n    error: void 0,\n    networkStatus: NetworkStatus.loading,\n  });\n\n  private skipStandbyResult = maybeDeepFreeze({\n    loading: false,\n    data: void 0 as unknown as TData,\n    error: void 0,\n    networkStatus: NetworkStatus.ready,\n  });\n\n  // A function to massage options before passing them to ObservableQuery.\n  private createWatchQueryOptions({\n    skip,\n    ssr,\n    onCompleted,\n    onError,\n    defaultOptions,\n    // The above options are useQuery-specific, so this ...otherOptions spread\n    // makes otherOptions almost a WatchQueryOptions object, except for the\n    // query property that we add below.\n    ...otherOptions\n  }: QueryHookOptions<TData, TVariables> = {}): WatchQueryOptions<\n    TVariables,\n    TData\n  > {\n    // This Object.assign is safe because otherOptions is a fresh ...rest object\n    // that did not exist until just now, so modifications are still allowed.\n    const watchQueryOptions: WatchQueryOptions<TVariables, TData> =\n      Object.assign(otherOptions, { query: this.query });\n\n    if (\n      this.renderPromises &&\n      (watchQueryOptions.fetchPolicy === \"network-only\" ||\n        watchQueryOptions.fetchPolicy === \"cache-and-network\")\n    ) {\n      // this behavior was added to react-apollo without explanation in this PR\n      // https://github.com/apollographql/react-apollo/pull/1579\n      watchQueryOptions.fetchPolicy = \"cache-first\";\n    }\n\n    if (!watchQueryOptions.variables) {\n      watchQueryOptions.variables = {} as TVariables;\n    }\n\n    if (skip) {\n      const {\n        fetchPolicy = this.getDefaultFetchPolicy(),\n        initialFetchPolicy = fetchPolicy,\n      } = watchQueryOptions;\n\n      // When skipping, we set watchQueryOptions.fetchPolicy initially to\n      // \"standby\", but we also need/want to preserve the initial non-standby\n      // fetchPolicy that would have been used if not skipping.\n      Object.assign(watchQueryOptions, {\n        initialFetchPolicy,\n        fetchPolicy: \"standby\",\n      });\n    } else if (!watchQueryOptions.fetchPolicy) {\n      watchQueryOptions.fetchPolicy =\n        this.observable?.options.initialFetchPolicy ||\n        this.getDefaultFetchPolicy();\n    }\n\n    return watchQueryOptions;\n  }\n\n  getDefaultFetchPolicy(): WatchQueryFetchPolicy {\n    return (\n      this.queryHookOptions.defaultOptions?.fetchPolicy ||\n      this.client.defaultOptions.watchQuery?.fetchPolicy ||\n      \"cache-first\"\n    );\n  }\n\n  // Defining these methods as no-ops on the prototype allows us to call\n  // state.onCompleted and/or state.onError without worrying about whether a\n  // callback was provided.\n  private onCompleted(data: TData) {}\n  private onError(error: ApolloError) {}\n\n  private observable!: ObservableQuery<TData, TVariables>;\n  private obsQueryFields!: Omit<\n    ObservableQueryFields<TData, TVariables>,\n    \"variables\"\n  >;\n\n  private useObservableQuery() {\n    // See if there is an existing observable that was used to fetch the same\n    // data and if so, use it instead since it will contain the proper queryId\n    // to fetch the result set. This is used during SSR.\n    const obsQuery = (this.observable =\n      (this.renderPromises &&\n        this.renderPromises.getSSRObservable(this.watchQueryOptions)) ||\n      this.observable || // Reuse this.observable if possible (and not SSR)\n      this.client.watchQuery(this.getObsQueryOptions()));\n\n    this.obsQueryFields = React.useMemo(\n      () => ({\n        refetch: obsQuery.refetch.bind(obsQuery),\n        reobserve: obsQuery.reobserve.bind(obsQuery),\n        fetchMore: obsQuery.fetchMore.bind(obsQuery),\n        updateQuery: obsQuery.updateQuery.bind(obsQuery),\n        startPolling: obsQuery.startPolling.bind(obsQuery),\n        stopPolling: obsQuery.stopPolling.bind(obsQuery),\n        subscribeToMore: obsQuery.subscribeToMore.bind(obsQuery),\n      }),\n      [obsQuery]\n    );\n\n    const ssrAllowed = !(\n      this.queryHookOptions.ssr === false || this.queryHookOptions.skip\n    );\n\n    if (this.renderPromises && ssrAllowed) {\n      this.renderPromises.registerSSRObservable(obsQuery);\n\n      if (obsQuery.getCurrentResult().loading) {\n        // TODO: This is a legacy API which could probably be cleaned up\n        this.renderPromises.addObservableQueryPromise(obsQuery);\n      }\n    }\n\n    return obsQuery;\n  }\n\n  // These members are populated by getCurrentResult and setResult, and it's\n  // okay/normal for them to be initially undefined.\n  private result: undefined | ApolloQueryResult<TData>;\n  private previousData: undefined | TData;\n\n  private setResult(nextResult: ApolloQueryResult<TData>) {\n    const previousResult = this.result;\n    if (previousResult && previousResult.data) {\n      this.previousData = previousResult.data;\n    }\n    this.result = nextResult;\n    // Calling state.setResult always triggers an update, though some call sites\n    // perform additional equality checks before committing to an update.\n    this.forceUpdate();\n    this.handleErrorOrCompleted(nextResult, previousResult);\n  }\n\n  private handleErrorOrCompleted(\n    result: ApolloQueryResult<TData>,\n    previousResult?: ApolloQueryResult<TData>\n  ) {\n    if (!result.loading) {\n      const error = this.toApolloError(result);\n\n      // wait a tick in case we are in the middle of rendering a component\n      Promise.resolve()\n        .then(() => {\n          if (error) {\n            this.onError(error);\n          } else if (\n            result.data &&\n            previousResult?.networkStatus !== result.networkStatus &&\n            result.networkStatus === NetworkStatus.ready\n          ) {\n            this.onCompleted(result.data);\n          }\n        })\n        .catch((error) => {\n          invariant.warn(error);\n        });\n    }\n  }\n\n  private toApolloError(\n    result: ApolloQueryResult<TData>\n  ): ApolloError | undefined {\n    return isNonEmptyArray(result.errors) ?\n        new ApolloError({ graphQLErrors: result.errors })\n      : result.error;\n  }\n\n  private getCurrentResult(): ApolloQueryResult<TData> {\n    // Using this.result as a cache ensures getCurrentResult continues returning\n    // the same (===) result object, unless state.setResult has been called, or\n    // we're doing server rendering and therefore override the result below.\n    if (!this.result) {\n      this.handleErrorOrCompleted(\n        (this.result = this.observable.getCurrentResult())\n      );\n    }\n    return this.result;\n  }\n\n  // This cache allows the referential stability of this.result (as returned by\n  // getCurrentResult) to translate into referential stability of the resulting\n  // QueryResult object returned by toQueryResult.\n  private toQueryResultCache = new (canUseWeakMap ? WeakMap : Map)<\n    ApolloQueryResult<TData>,\n    QueryResult<TData, TVariables>\n  >();\n\n  toQueryResult(\n    result: ApolloQueryResult<TData>\n  ): QueryResult<TData, TVariables> {\n    let queryResult = this.toQueryResultCache.get(result);\n    if (queryResult) return queryResult;\n\n    const { data, partial, ...resultWithoutPartial } = result;\n    this.toQueryResultCache.set(\n      result,\n      (queryResult = {\n        data, // Ensure always defined, even if result.data is missing.\n        ...resultWithoutPartial,\n        ...this.obsQueryFields,\n        client: this.client,\n        observable: this.observable,\n        variables: this.observable.variables,\n        called: !this.queryHookOptions.skip,\n        previousData: this.previousData,\n      })\n    );\n\n    if (!queryResult.error && isNonEmptyArray(result.errors)) {\n      // Until a set naming convention for networkError and graphQLErrors is\n      // decided upon, we map errors (graphQLErrors) to the error options.\n      // TODO: Is it possible for both result.error and result.errors to be\n      // defined here?\n      queryResult.error = new ApolloError({ graphQLErrors: result.errors });\n    }\n\n    return queryResult;\n  }\n\n  private unsafeHandlePartialRefetch(result: ApolloQueryResult<TData>) {\n    // WARNING: SIDE-EFFECTS IN THE RENDER FUNCTION\n    //\n    // TODO: This code should be removed when the partialRefetch option is\n    // removed. I was unable to get this hook to behave reasonably in certain\n    // edge cases when this block was put in an effect.\n    if (\n      result.partial &&\n      this.queryHookOptions.partialRefetch &&\n      !result.loading &&\n      (!result.data || Object.keys(result.data).length === 0) &&\n      this.observable.options.fetchPolicy !== \"cache-only\"\n    ) {\n      Object.assign(result, {\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n      });\n      this.observable.refetch();\n    }\n  }\n}\n", "import { invariant } from \"../../utilities/globals/index.js\";\nimport * as React from \"rehackt\";\n\nimport { canUseLayoutEffect } from \"../../utilities/index.js\";\n\nlet didWarnUncachedGetSnapshot = false;\n\ntype RealUseSESHookType =\n  // This import depends only on the @types/use-sync-external-store package, not\n  // the actual use-sync-external-store package, which is not installed. It\n  // might be nice to get this type from React 18, but it still needs to work\n  // when only React 17 or earlier is installed.\n  typeof import(\"use-sync-external-store\").useSyncExternalStore;\n\n// Prevent webpack from complaining about our feature detection of the\n// useSyncExternalStore property of the React namespace, which is expected not\n// to exist when using React 17 and earlier, and that's fine.\nconst uSESKey = \"useSyncExternalStore\" as keyof typeof React;\nconst realHook = React[uSESKey] as RealUseSESHookType | undefined;\n\n// Adapted from https://www.npmjs.com/package/use-sync-external-store, with\n// Apollo Client deviations called out by \"// DEVIATION ...\" comments.\n\n// When/if React.useSyncExternalStore is defined, delegate fully to it.\nexport const useSyncExternalStore: RealUseSESHookType =\n  realHook ||\n  ((subscribe, getSnapshot, getServerSnapshot) => {\n    // Read the current snapshot from the store on every render. Again, this\n    // breaks the rules of React, and only works here because of specific\n    // implementation details, most importantly that updates are\n    // always synchronous.\n    const value = getSnapshot();\n    if (\n      // DEVIATION: Using __DEV__\n      __DEV__ &&\n      !didWarnUncachedGetSnapshot &&\n      // DEVIATION: Not using Object.is because we know our snapshots will never\n      // be exotic primitive values like NaN, which is !== itself.\n      value !== getSnapshot()\n    ) {\n      didWarnUncachedGetSnapshot = true;\n      // DEVIATION: Using invariant.error instead of console.error directly.\n      invariant.error(\n        \"The result of getSnapshot should be cached to avoid an infinite loop\"\n      );\n    }\n\n    // Because updates are synchronous, we don't queue them. Instead we force a\n    // re-render whenever the subscribed state changes by updating an some\n    // arbitrary useState hook. Then, during render, we call getSnapshot to read\n    // the current value.\n    //\n    // Because we don't actually use the state returned by the useState hook, we\n    // can save a bit of memory by storing other stuff in that slot.\n    //\n    // To implement the early bailout, we need to track some things on a mutable\n    // object. Usually, we would put that in a useRef hook, but we can stash it in\n    // our useState hook instead.\n    //\n    // To force a re-render, we call forceUpdate({inst}). That works because the\n    // new object always fails an equality check.\n    const [{ inst }, forceUpdate] = React.useState({\n      inst: { value, getSnapshot },\n    });\n\n    // Track the latest getSnapshot function with a ref. This needs to be updated\n    // in the layout phase so we can access it during the tearing check that\n    // happens on subscribe.\n    if (canUseLayoutEffect) {\n      // DEVIATION: We avoid calling useLayoutEffect when !canUseLayoutEffect,\n      // which may seem like a conditional hook, but this code ends up behaving\n      // unconditionally (one way or the other) because canUseLayoutEffect is\n      // constant.\n      React.useLayoutEffect(() => {\n        Object.assign(inst, { value, getSnapshot });\n        // Whenever getSnapshot or subscribe changes, we need to check in the\n        // commit phase if there was an interleaved mutation. In concurrent mode\n        // this can happen all the time, but even in synchronous mode, an earlier\n        // effect may have mutated the store.\n        if (checkIfSnapshotChanged(inst)) {\n          // Force a re-render.\n          forceUpdate({ inst });\n        }\n      }, [subscribe, value, getSnapshot]);\n    } else {\n      Object.assign(inst, { value, getSnapshot });\n    }\n\n    React.useEffect(() => {\n      // Check for changes right before subscribing. Subsequent changes will be\n      // detected in the subscription handler.\n      if (checkIfSnapshotChanged(inst)) {\n        // Force a re-render.\n        forceUpdate({ inst });\n      }\n\n      // Subscribe to the store and return a clean-up function.\n      return subscribe(function handleStoreChange() {\n        // TODO: Because there is no cross-renderer API for batching updates, it's\n        // up to the consumer of this library to wrap their subscription event\n        // with unstable_batchedUpdates. Should we try to detect when this isn't\n        // the case and print a warning in development?\n\n        // The store changed. Check if the snapshot changed since the last time we\n        // read from the store.\n        if (checkIfSnapshotChanged(inst)) {\n          // Force a re-render.\n          forceUpdate({ inst });\n        }\n      });\n    }, [subscribe]);\n\n    return value;\n  });\n\nfunction checkIfSnapshotChanged<Snapshot>({\n  value,\n  getSnapshot,\n}: {\n  value: Snapshot;\n  getSnapshot: () => Snapshot;\n}): boolean {\n  try {\n    return value !== getSnapshot();\n  } catch {\n    return true;\n  }\n}\n", "import { invariant } from \"../../utilities/globals/index.js\";\n\nimport type {\n  DocumentNode,\n  DefinitionNode,\n  VariableDefinitionNode,\n  OperationDefinitionNode,\n} from \"graphql\";\nimport {\n  AutoCleanedWeakCache,\n  cacheSizes,\n  defaultCacheSizes,\n} from \"../../utilities/index.js\";\nimport { registerGlobalCache } from \"../../utilities/caching/getMemoryInternals.js\";\n\nexport enum DocumentType {\n  Query,\n  Mutation,\n  Subscription,\n}\n\nexport interface IDocumentDefinition {\n  type: DocumentType;\n  name: string;\n  variables: ReadonlyArray<VariableDefinitionNode>;\n}\n\nlet cache:\n  | undefined\n  | AutoCleanedWeakCache<\n      DocumentNode,\n      {\n        name: string;\n        type: DocumentType;\n        variables: readonly VariableDefinitionNode[];\n      }\n    >;\n\nexport function operationName(type: DocumentType) {\n  let name;\n  switch (type) {\n    case DocumentType.Query:\n      name = \"Query\";\n      break;\n    case DocumentType.Mutation:\n      name = \"Mutation\";\n      break;\n    case DocumentType.Subscription:\n      name = \"Subscription\";\n      break;\n  }\n  return name;\n}\n\n// This parser is mostly used to safety check incoming documents.\nexport function parser(document: DocumentNode): IDocumentDefinition {\n  if (!cache) {\n    cache = new AutoCleanedWeakCache(\n      cacheSizes.parser || defaultCacheSizes.parser\n    );\n  }\n  const cached = cache.get(document);\n  if (cached) return cached;\n\n  let variables, type, name;\n\n  invariant(\n    !!document && !!document.kind,\n    `Argument of %s passed to parser was not a valid GraphQL ` +\n      `DocumentNode. You may need to use 'graphql-tag' or another method ` +\n      `to convert your operation into a document`,\n    document\n  );\n\n  const fragments: DefinitionNode[] = [];\n  const queries: DefinitionNode[] = [];\n  const mutations: DefinitionNode[] = [];\n  const subscriptions: DefinitionNode[] = [];\n\n  for (const x of document.definitions) {\n    if (x.kind === \"FragmentDefinition\") {\n      fragments.push(x);\n      continue;\n    }\n\n    if (x.kind === \"OperationDefinition\") {\n      switch (x.operation) {\n        case \"query\":\n          queries.push(x);\n          break;\n        case \"mutation\":\n          mutations.push(x);\n          break;\n        case \"subscription\":\n          subscriptions.push(x);\n          break;\n      }\n    }\n  }\n\n  invariant(\n    !fragments.length ||\n      queries.length ||\n      mutations.length ||\n      subscriptions.length,\n    `Passing only a fragment to 'graphql' is not yet supported. ` +\n      `You must include a query, subscription or mutation as well`\n  );\n\n  invariant(\n    queries.length + mutations.length + subscriptions.length <= 1,\n    `react-apollo only supports a query, subscription, or a mutation per HOC. ` +\n      `%s had %s queries, %s ` +\n      `subscriptions and %s mutations. ` +\n      `You can use 'compose' to join multiple operation types to a component`,\n    document,\n    queries.length,\n    subscriptions.length,\n    mutations.length\n  );\n\n  type = queries.length ? DocumentType.Query : DocumentType.Mutation;\n  if (!queries.length && !mutations.length) type = DocumentType.Subscription;\n\n  const definitions =\n    queries.length ? queries\n    : mutations.length ? mutations\n    : subscriptions;\n\n  invariant(\n    definitions.length === 1,\n    `react-apollo only supports one definition per HOC. %s had ` +\n      `%s definitions. ` +\n      `You can use 'compose' to join multiple operation types to a component`,\n    document,\n    definitions.length\n  );\n\n  const definition = definitions[0] as OperationDefinitionNode;\n  variables = definition.variableDefinitions || [];\n\n  if (definition.name && definition.name.kind === \"Name\") {\n    name = definition.name.value;\n  } else {\n    name = \"data\"; // fallback to using data if no name\n  }\n\n  const payload = { name, type, variables };\n  cache.set(document, payload);\n  return payload;\n}\n\nparser.resetCache = () => {\n  cache = undefined;\n};\n\nif (__DEV__) {\n  registerGlobalCache(\"parser\", () => (cache ? cache.size : 0));\n}\n\nexport function verifyDocumentType(document: DocumentNode, type: DocumentType) {\n  const operation = parser(document);\n  const requiredOperationName = operationName(type);\n  const usedOperationName = operationName(operation.type);\n  invariant(\n    operation.type === type,\n    `Running a %s requires a graphql ` + `%s, but a %s was used instead.`,\n    requiredOperationName,\n    requiredOperationName,\n    usedOperationName\n  );\n}\n", "import type {\n  useQuery,\n  useSuspenseQuery,\n  useBackgroundQuery,\n  useReadQuery,\n  useFragment,\n  useQueryRefHandlers,\n} from \"../index.js\";\nimport type { QueryManager } from \"../../../core/QueryManager.js\";\nimport type { ApolloClient } from \"../../../core/ApolloClient.js\";\nimport type { ObservableQuery } from \"../../../core/ObservableQuery.js\";\n\nconst wrapperSymbol = Symbol.for(\"apollo.hook.wrappers\");\n\ninterface WrappableHooks {\n  useQuery: typeof useQuery;\n  useSuspenseQuery: typeof useSuspenseQuery;\n  useBackgroundQuery: typeof useBackgroundQuery;\n  useReadQuery: typeof useReadQuery;\n  useFragment: typeof useFragment;\n  useQueryRefHandlers: typeof useQueryRefHandlers;\n}\n\n/**\n * @internal\n * Can be used to correctly type the [Symbol.for(\"apollo.hook.wrappers\")] property of\n * `QueryManager`, to override/wrap hook functionality.\n */\nexport type HookWrappers = {\n  [K in keyof WrappableHooks]?: (\n    originalHook: WrappableHooks[K]\n  ) => WrappableHooks[K];\n};\n\ninterface QueryManagerWithWrappers<T> extends QueryManager<T> {\n  [wrapperSymbol]?: HookWrappers;\n}\n\n/**\n * @internal\n *\n * Makes an Apollo Client hook \"wrappable\".\n * That means that the Apollo Client instance can expose a \"wrapper\" that will be\n * used to wrap the original hook implementation with additional logic.\n * @example\n * ```tsx\n * // this is already done in `@apollo/client` for all wrappable hooks (see `WrappableHooks`)\n * // following this pattern\n * function useQuery() {\n *   return wrapHook('useQuery', _useQuery, options.client)(query, options);\n * }\n * function _useQuery(query, options) {\n *   // original implementation\n * }\n *\n * // this is what a library like `@apollo/client-react-streaming` would do\n * class ApolloClientWithStreaming extends ApolloClient {\n *   constructor(options) {\n *     super(options);\n *     this.queryManager[Symbol.for(\"apollo.hook.wrappers\")] = {\n *       useQuery: (original) => (query, options) => {\n *         console.log(\"useQuery was called with options\", options);\n *         return original(query, options);\n *       }\n *     }\n *   }\n * }\n *\n * // this will now log the options and then call the original `useQuery`\n * const client = new ApolloClientWithStreaming({ ... });\n * useQuery(query, { client });\n * ```\n */\nexport function wrapHook<Hook extends (...args: any[]) => any>(\n  hookName: keyof WrappableHooks,\n  useHook: Hook,\n  clientOrObsQuery: ObservableQuery<any> | ApolloClient<any>\n): Hook {\n  const queryManager = (\n    clientOrObsQuery as unknown as {\n      // both `ApolloClient` and `ObservableQuery` have a `queryManager` property\n      // but they're both `private`, so we have to cast around for a bit here.\n      queryManager: QueryManagerWithWrappers<any>;\n    }\n  )[\"queryManager\"];\n  const wrappers = queryManager && queryManager[wrapperSymbol];\n  const wrapper: undefined | ((wrap: Hook) => Hook) =\n    wrappers && (wrappers[hookName] as any);\n  return wrapper ? wrapper(useHook) : useHook;\n}\n", "import { createHttpLink } from '@apollo/client';\nimport { fetch } from 'cross-fetch';\n\nimport {\n  globalComponentsAccessToken,\n  globalComponentsEnvName,\n  globalComponentsSpaceId,\n} from './contentfulConstants';\n\n/**\n * Default Link for the global components apollo.\n *\n * Use this when you don't already have an apollo client installed.\n *\n * Usage:\n *\n * <ApolloProvider client={new ApolloClient({ link: globalComponentsApolloLink, cache: new\n * InMemoryCache() })}> ... </ApolloProvider>\n */\nexport const globalComponentsApolloLink = createHttpLink({\n  uri: `https://graphql.contentful.com/content/v1/spaces/${globalComponentsSpaceId}/environments/${globalComponentsEnvName}`,\n  credentials: 'same-origin',\n  headers: {\n    Authorization: `Bearer ${globalComponentsAccessToken}`,\n  },\n  fetch,\n});\n", "export const globalComponentsAccessToken = 'dpk-7L7rGYzkKk-jZwtIDnyhui6DgLq6VTapJNI7W44';\n\nexport const globalComponentsSpaceId = 'kp51zybwznx4';\n\nexport const globalComponentsEnvName = 'master';\n\nexport const globalComponentsClientName = 'global';\n", "import type {\n  DocumentNode,\n  OperationVariables,\n  QueryHookOptions,\n  QueryResult,\n  TypedDocumentNode,\n} from '@apollo/client';\nimport { useQuery } from '@apollo/client';\n\nimport { globalComponentsClientName } from '../contentful/contentfulConstants';\n\nexport interface ContentfulContext {\n  currentLocale: string;\n  isPreview: boolean;\n  isSSR: boolean;\n}\n\n/**\n * Wrapper around `useQuery` hook that adds variables from the GlobalComponentsContext and adds a\n * query context with `clientName` set to `global`.\n */\nexport function useGlobalComponentsContentfulQuery<\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  TData = any,\n  TVariables extends OperationVariables = OperationVariables\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  context: ContentfulContext,\n  options?: QueryHookOptions<TData, Omit<TVariables, 'locale' | 'preview'>>\n): QueryResult<TData, TVariables> {\n  const { currentLocale, isPreview, isSSR } = context;\n\n  const mergedOptions: QueryHookOptions<TData, TVariables> = {\n    ...options,\n    context: { clientName: globalComponentsClientName, ...options?.context },\n    // @ts-ignore: We assume that all queries require a 'locale' and 'preview' vars.\n    variables: {\n      locale: currentLocale,\n      preview: isPreview,\n      ...options?.variables,\n    },\n    ssr: isSSR ?? options?.ssr,\n  };\n\n  return useQuery(query, mergedOptions);\n}\n", "import type { ValueOf } from '../../types';\n\nexport const Template = {\n  None: 'None',\n  Straight: 'Straight',\n  Head: 'Head',\n  HeadFlipped: 'HeadFlipped',\n  Line: 'Line',\n  Skirt: 'Skirt',\n  Skirt2: 'Skirt2',\n  Skirt3: 'Skirt3',\n} as const;\n\nexport type Template = ValueOf<typeof Template>;\n\nexport enum BreakOverlayType {\n  BOTTOM = 'bottom',\n  BOTTOM_HALF = 'bottomHalf',\n  NONE = 'none',\n  TOP = 'top',\n  TOP_HALF = 'topHalf',\n  TOP_HALF_AND_BOTTOM_HALF = 'topAndBottomHalfs',\n}\n", "const escapedChars = /[\\u00A0-\\u9999<>&]/g;\n\n/**\n * Replaces weird UTF characters with HTML entitites. Useful for escaping user input. Based on:\n * https://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript\n */\nexport const htmlEscape = (value: string): string =>\n  value.replace(escapedChars, c => `&#${c.charCodeAt(0)};`);\n", "/**\n * Pattern to retrieve escaped Unicode values from the `htmlEscape` function. Includes a negative\n * lookahead to filter out character codes that we do not want to reverse: <>& Includes a capture\n * group (position 2) to extract the character code value Example: \u670B\u53CB => \u670B\u53CB\n */\nconst unicodePatternsToReverse = /&#(?!(38|60|62);)([\\d]{1,5});/g;\n\n/**\n * Pattern to retrieve escaped Unicode values from the `htmlEscape` function. Does NOT a filter for\n * dangerous character codes: `<>&`, instead includes a meaningless capture group so that it has the\n * same output structure as`unicodePatternsToReverse`. Includes a capture group (position 2) to\n * extract the character code value Example: \u670B\u53CB => \u670B\u53CB\n */\nconst unsafeUnicodePatternsToReverse = /(&#)([\\d]{1,5});/g;\n\n/**\n * Reverses output of htmlEscape function for most unicode characters, excluding known html related\n * characters. Used for specific cases where rendering the utf codes is insufficient, such as safely\n * rendering form input fields from query string parameters.\n *\n * @param value Value to process\n * @param undoDangerousCharacters Optional, enables reversal of dangerous characters: `<>&`\n */\nexport const htmlUnescape = (value: string, undoDangerousCharacters = false): string => {\n  const pattern = undoDangerousCharacters\n    ? unsafeUnicodePatternsToReverse\n    : unicodePatternsToReverse;\n\n  return value.replaceAll(pattern, (_1, _2, characterCode) => {\n    // uses capture group 2 to extract character code value\n    const code = Number.parseInt(characterCode);\n    return String.fromCharCode(code);\n  });\n};\n", "/**\n * A helper function that returns a string representation of an object.\n *\n * @param [detectCycles=false] If set to true will keep a reference to every object in the value and\n *   will not expand duplicates. Default is `false`\n */\nexport function jsonStringify(\n  value: unknown,\n  detectCycles = false,\n  space: number | undefined = 2\n): string {\n  if (!detectCycles) {\n    return JSON.stringify(value, null, space);\n  }\n\n  const visited = new Set<unknown>();\n\n  /** Skip circular dependencies. */\n  function replacer(_key: string, value: unknown) {\n    if (visited.has(value)) return null;\n    visited.add(value);\n    return value;\n  }\n\n  return JSON.stringify(value, replacer, space);\n}\n", "declare global {\n  interface Error {\n    /** Method that returns a plain object representing the error. */\n    toJSON(): object;\n  }\n}\n\n/**\n * An `Error` object that has a few convenience things.\n *\n * 1. It allows for setting fields like `stack` and `name` in the constructor.\n * 2. It overrides the toJSON field which makes this error serializable.\n * 3. It has a `.code` field which is pretty universally valuable.\n */\nexport class SnapError extends Error {\n  private static originalToJson = Error.prototype.toJSON;\n\n  /**\n   * Helper function to make all Errors write something out into a serialized object when passed\n   * through JSON.stringify.\n   *\n   * WARNING: This overrides the Error.prototype, so this has effect on ALL ERRORS in the system.\n   * Use with caution.\n   */\n  public static serializeErrors(): void {\n    Error.prototype.toJSON = SnapError.prototype.toJSON;\n  }\n\n  public static resetSerealizeErrors(): void {\n    Error.prototype.toJSON = SnapError.originalToJson;\n  }\n\n  public code: number | string | undefined;\n\n  constructor(\n    message: string,\n    options?: {\n      name?: string;\n      code?: number | string;\n      stack?: string;\n    }\n  ) {\n    super(message);\n    if (options?.name) {\n      this.name = options.name;\n    }\n    if (options?.code) {\n      this.code = options.code;\n    }\n    if (options?.stack) {\n      this.stack = options.stack;\n    } else {\n      // Sets this.stack to a stacktrace that excludes SnapError line.\n      Error.captureStackTrace(this, SnapError);\n    }\n  }\n\n  /** @override the behavior of `JSON.stringify(error)`. */\n  toJSON(): object {\n    return {\n      name: this.name,\n      message: this.message,\n      code: this.code,\n      stack: this.stack,\n    };\n  }\n}\n", "import { SnapError } from './SnapError';\n\n/** Parses an unknown error into an Error object. */\nexport function parseError(error: unknown): Error {\n  // Empty error.\n  if (!error) {\n    // biome-ignore lint/suspicious/useErrorMessage: Nothing useful we can do here.\n    return new Error();\n  }\n\n  // Already defined error.\n  if (error instanceof Error) {\n    return error;\n  }\n\n  // A string error.\n  if (typeof error === 'string') {\n    return new SnapError(error);\n  }\n\n  // An object of shape { message: ... }.\n  if (typeof error === 'object' && !Array.isArray(error)) {\n    const errorObject = error as Record<string, unknown>;\n    const snapError = new SnapError(\n      errorObject.message ? String(errorObject.message) : 'Unknown error',\n      {\n        code: errorObject.code ? String(errorObject.code) : undefined,\n        name: errorObject.name ? String(errorObject.name) : undefined,\n        stack: errorObject.stack ? String(errorObject.stack) : undefined,\n      }\n    );\n    return snapError;\n  }\n\n  // For other values, initialize a return value, handling arrays through JSON\n  // stringification to expand nested objects.\n  let errorString = Array.isArray(error) ? JSON.stringify(error) : String(error);\n\n  if (errorString.length > 100) {\n    errorString = `${errorString.substring(0, 100)}...`;\n  }\n\n  return new SnapError(errorString);\n}\n", "/**\n * Returns the union (combination) of all the iterables into one set. Useful for deduplicating\n * multiple collections.\n */\nexport const unionSet = <T>(...iterables: Iterable<T>[]): Set<T> => {\n  const set = new Set<T>();\n\n  for (const iterable of iterables) {\n    for (const value of iterable) {\n      set.add(value);\n    }\n  }\n\n  return set;\n};\n\n/**\n * Returns the difference of minuend set and subtrahend set.\n *\n * Note that duplicates are removed from the minuend even if they aren't in the subtrahend. E.g. [\n * 1, 2, 2, 3, 4 ] - [3, 4, 5] = { 1, 2 }\n */\nexport const differenceSet = <T>(minuend: Iterable<T>, subtrahend: Iterable<T>): Set<T> => {\n  const set = new Set<T>(minuend);\n\n  for (const value of subtrahend) {\n    set.delete(value);\n  }\n\n  return set;\n};\n", "/** Helper function to make Node/Browser wait for a period of time. */\nexport const sleep = (timeoutMs: number): Promise<void> =>\n  // NOTE: Node runner seems to be rounding so it's possible to wait timeoutMs - .5 which technically\n  // isn't sleeping at least timeoutMs.\n  new Promise(resolve => setTimeout(resolve, timeoutMs + 1));\n", "import { parseError } from '../errors/parseError';\nimport { sleep } from './sleep';\n\nexport interface WaitForOptions<T> {\n  /** Defaults to 5_000ms */\n  timeoutMs?: number;\n  /** Defaults to 100ms */\n  intervalMs?: number;\n  /* Clock. Use Date.now or performance.now for sub-ms precision. Defaults to Date.now */\n  clockMs?: () => number;\n  /** Sleeping function. Defaults to setTimeout. */\n  sleepMs?: (amount: number) => Promise<void>;\n  /**\n   * Test for the validity of a value. If this is provided and fails on a value, The waiter will\n   * retry.\n   */\n  valueTest?: (item: T) => boolean;\n  /** Callback if an error occurs when the value is read. Optional. */\n  onAttemptError?: (error: Error) => void;\n  /** Callback if the wait exceeds. Throws an error if this isn't specified. */\n  onTimeout?: (error?: Error) => void;\n}\n\n/**\n * Waits for an attempt to return without throwing an error and return a value that passes a value\n * check.\n *\n * Retries every intervalMs until timeoutMs at which point it throws an error or returns a null if\n * onTimeout callback is provided.\n */\nexport async function waitFor<T>(\n  attempt: () => Promise<T>,\n  options: WaitForOptions<T> = {}\n): Promise<T | null> {\n  const {\n    timeoutMs = 5e3,\n    intervalMs = 100,\n    clockMs = Date.now,\n    sleepMs = sleep,\n    valueTest,\n    onAttemptError: onEveryError,\n    onTimeout,\n  } = options;\n  const startMs = clockMs();\n\n  let lastError: Error | undefined;\n\n  while (clockMs() < startMs + timeoutMs) {\n    try {\n      const latest = await attempt();\n\n      if (!valueTest || valueTest(latest)) {\n        return latest;\n      }\n    } catch (error) {\n      lastError = parseError(error);\n      onEveryError?.(lastError);\n    }\n\n    // Wait until next attempt.\n    await sleepMs(intervalMs);\n  }\n\n  if (!onTimeout) {\n    if (!lastError) lastError = new Error(`Timeout of ${(timeoutMs / 1e3).toFixed(1)}s exceeded`);\n    throw lastError;\n  }\n  onTimeout(lastError);\n  return null;\n}\n", "/** Make a promise throw an error if it doesn't resolve before a timeout. */\nexport function timeoutWithError<T>(\n  promise: Promise<T>,\n  timeoutMs: number,\n  error: Error | (() => Error)\n): Promise<T> {\n  let timeoutPid: ReturnType<typeof setTimeout>;\n  const timeout = new Promise<T>((_, reject) => {\n    timeoutPid = setTimeout(() => reject(typeof error === 'function' ? error() : error), timeoutMs);\n  });\n  return Promise.race([promise, timeout]).finally(() => {\n    timeoutPid && clearTimeout(timeoutPid);\n  });\n}\n\n/** Make a promise return a default value if it doesn't resolve before a timeout. */\nexport function timeoutWithDefault<T>(\n  promise: Promise<T>,\n  timeoutMs: number,\n  defaultValue: T\n): Promise<T> {\n  let timeoutPid: ReturnType<typeof setTimeout>;\n  const timeout = new Promise<T>(resolve => {\n    timeoutPid = setTimeout(() => resolve(defaultValue), timeoutMs);\n  });\n  return Promise.race([promise, timeout]).finally(() => {\n    timeoutPid && clearTimeout(timeoutPid);\n  });\n}\n", "/**\n * Helper function to set a header on a request passed to a `fetch` function.\n *\n * The API is cumbersome to use, so this should simplify things.\n *\n * NOTE: This is ONLY NEEDED if you cannot modify the original object for some reason. For all other\n * purposes, you should do `request.headers = new Headers(request.headers)` and then set the new\n * header.\n */\nexport function setFetchHeader(request: RequestInit, header: string, value: string): RequestInit {\n  if (!request.headers) {\n    request.headers = { [header]: value };\n  } else if (request.headers instanceof Headers) {\n    request.headers.set(header, value);\n  } else if (Array.isArray(request.headers)) {\n    const existingHeaderIndex = request.headers.findIndex(([key]) => key === header);\n    if (existingHeaderIndex !== -1) {\n      request.headers[existingHeaderIndex] = [header, value];\n    } else {\n      request.headers.push([header, value]);\n    }\n  } else {\n    request.headers[header] = value;\n  }\n  return request;\n}\n\n/** Returns the value of a header in a header init. */\nexport function getFetchHeader(headers: HeadersInit | undefined, header: string): string | null {\n  if (!headers) return null;\n  if (headers instanceof Headers) {\n    return headers.get(header);\n  }\n  if (Array.isArray(headers)) {\n    const headerEntry = headers.find(([key]) => key === header);\n    return headerEntry ? headerEntry[1] : null;\n  }\n  return headers[header];\n}\n", "export type FetchWithTimeoutOptions = {\n  timeoutMs?: number;\n  fetchOverride?: typeof fetch;\n};\n\n/** Wraps fetch with a timeout. If no timeout is provided, the request will not be timed out. */\nexport async function fetchWithTimeout(\n  url: string | URL | Request,\n  requestInit: RequestInit,\n  options: FetchWithTimeoutOptions\n): Promise<Response> {\n  const fetchFn = options.fetchOverride ?? fetch;\n\n  if (!options.timeoutMs) {\n    return fetchFn(url, requestInit);\n  }\n\n  const controller = new AbortController();\n  const timeoutId = setTimeout(() => controller.abort(), options.timeoutMs);\n\n  try {\n    const response = await fetchFn(url, {\n      ...requestInit,\n      signal: requestInit.signal\n        ? AbortSignal.any([requestInit.signal, controller.signal])\n        : controller.signal,\n    });\n    return response;\n  } catch (error) {\n    if (typeof error === 'object' && error instanceof Error && error.name === 'AbortError') {\n      throw new Error(`Request timed out after ${options.timeoutMs}ms`);\n    }\n    throw error;\n  } finally {\n    clearTimeout(timeoutId);\n  }\n}\n", "import { parseError } from '../errors/parseError';\n\nimport { fetchWithTimeout, type FetchWithTimeoutOptions } from './fetchWithTimeout';\n\nexport type FetchWithRetriesOptions = FetchWithTimeoutOptions & {\n  retries?: 0 | 1 | 2 | 3 | 4 | 5;\n};\n\n/** Wraps fetchWithTimeout with retries. If no retries are provided, the request will not be retried. */\nexport async function fetchWithRetries(\n  url: string | URL | Request,\n  requestInit: RequestInit,\n  options: FetchWithRetriesOptions\n): Promise<Response> {\n  const maxRetries = options.retries ?? 0;\n  let lastError: Error | undefined;\n\n  for (let attempt = 0; attempt <= maxRetries; attempt++) {\n    try {\n      const response = await fetchWithTimeout(url, requestInit, {\n        timeoutMs: options.timeoutMs,\n        fetchOverride: options.fetchOverride,\n      });\n      return response;\n    } catch (error) {\n      lastError = parseError(error);\n      // Don't retry if we've exhausted all attempts\n      if (attempt === maxRetries) {\n        throw lastError;\n      }\n    }\n  }\n\n  throw lastError!;\n}\n", "/**\n * Environment variables used on the client.\n *\n * These do not have dynamic values on the client. They are exported during bundling. See\n * esbuild.client.ts\n *\n * The keys for this object need to match the key they are reading from in process.env otherwise the\n * values will be different between the client the build. The result of the build is stored into the\n * process.env of the client, so if the key is different, the value will be different because you\n * are always reading from the same key.\n *\n *     build:\n *       process.env = {\n *        b: 'value'\n *       };\n *       clientEnv = {\n *         a: process.env.b,\n *       }\n *\n *     client:\n *       // this process.env is set by the build using the values of clientEnv\n *       process.env = {\n *         a: 'value'\n *       };\n *       clientEnv = {\n *         a: process.env.b, // this ends up being undefined\n *       } *\n */\nexport const clientEnv = {\n  CI_COMMIT: process.env.CI_COMMIT,\n  CI_PIPELINE_ID: process.env.CI_PIPELINE_ID,\n  GOOGLE_CLOUD_PROJECT: process.env.GOOGLE_CLOUD_PROJECT!,\n  CONTENTFUL_PREVIEW_ACCESS_TOKEN: process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN!,\n  CONTENTFUL_DEV_ACCESS_TOKEN: process.env.CONTENTFUL_DEV_ACCESS_TOKEN!,\n  /** Override for the contentful environment name. Defaults to 'undefined' when not set. */\n  CONTENTFUL_ENVIRONMENT_NAME: process.env.CONTENTFUL_ENVIRONMENT_NAME!,\n  DEPLOYMENT_TYPE: process.env.DEPLOYMENT_TYPE!,\n  GLOBAL_COMPONENTS_CONTENTFUL_PREVIEW_ACCESS_TOKEN:\n    process.env.GLOBAL_COMPONENTS_CONTENTFUL_PREVIEW_ACCESS_TOKEN!,\n  /**\n   * This value is set in jenkins all the time, so we only forward the value if we are not in\n   * production and we set the value in devToolsEnv.ts\n   */\n  GLOBAL_COMPONENTS_CONTENTFUL_DEV_ACCESS_TOKEN:\n    process.env.GLOBAL_COMPONENTS_CONTENTFUL_DEV_ACCESS_TOKEN!,\n  NODE_ENV: process.env.NODE_ENV!,\n  PREVIEW: process.env.PREVIEW!,\n  SITE_CONFIG: process.env.SITE_CONFIG!,\n  SSR: process.env.SSR!,\n  JEST_WORKER_ID: process.env.JEST_WORKER_ID!,\n  // The ENV variables below are not resolved at compile time. They are dynamic.\n  GOOGLE_CLOUD_REGION: process.env.GOOGLE_CLOUD_REGION ?? 'unknown_region',\n  // Use npm script in elastic-etl package to:\n  //  1 - start docker with Elasticsearch container\n  //  2 - seed Elasticsearch with data (reindex script)\n  USE_LOCAL_ELASTIC: process.env.USE_LOCAL_ELASTIC,\n  ELASTIC_SERVERLESS_NODE: process.env.ELASTIC_SERVERLESS_NODE,\n  ELASTIC_SEARCH_READER_API_KEY: process.env.ELASTIC_SEARCH_READER_API_KEY,\n} as const;\n\n/** List of environment variables we don't want to hard-code into javascript. */\nexport const dynamicClientEnv: ReadonlyArray<keyof typeof clientEnv> = [\n  'GOOGLE_CLOUD_REGION',\n] as const;\n", "import { FontFamily } from '@snapchat/snap-design-system-marketing';\n\nimport type { FontSettings } from '../configTypes';\n\n/**\n * Default font settings for the site.\n *\n * This file defines the default font families and their associated stylesheets, and font files to\n * be preloaded. These settings are used as a baseline for typography across the site and can be\n * overridden by site-specific config files.\n */\nexport const defaultFontSettings: FontSettings = [\n  {\n    name: FontFamily.GHOST_SANS,\n    stylesheet: 'https://web-platform.snap.com/fonts/font.ghost-sans.css',\n    files: [\n      {\n        url: 'https://web-platform.snap.com/fonts/ghost-sans/GhostSans-Regular.woff2',\n        type: 'font/woff2',\n      },\n      {\n        url: 'https://web-platform.snap.com/fonts/ghost-sans/GhostSans-Medium.woff2',\n        type: 'font/woff2',\n      },\n      {\n        url: 'https://web-platform.snap.com/fonts/ghost-sans/GhostSans-SemiBold.woff2',\n        type: 'font/woff2',\n      },\n    ],\n  },\n  {\n    name: FontFamily.PROGRAM_OT,\n    stylesheet: 'https://web-platform.snap.com/fonts/font.program-ot.css',\n    files: [\n      {\n        url: 'https://web-platform.snap.com/fonts/program/Program-Regular.woff2',\n        type: 'font/woff2',\n      },\n      {\n        url: 'https://web-platform.snap.com/fonts/program/Program-Medium.woff2',\n        type: 'font/woff2',\n      },\n      {\n        url: 'https://web-platform.snap.com/fonts/program/Program-Bold.woff2',\n        type: 'font/woff2',\n      },\n      {\n        url: 'https://web-platform.snap.com/fonts/program/ProgramNarrow-Regular.woff2',\n        type: 'font/woff2',\n      },\n      {\n        url: 'https://web-platform.snap.com/fonts/program/ProgramNarrow-Medium.woff2',\n        type: 'font/woff2',\n      },\n      {\n        url: 'https://web-platform.snap.com/fonts/program/ProgramNarrow-Bold.woff2',\n        type: 'font/woff2',\n      },\n    ],\n  },\n];\n", "import { getTopLevelDomain } from '@snapchat/parse-domain';\n\nexport const cookieSettingsPath = '/cookie-settings';\n\nexport function getCookieDomain(domain: string, cookieDomain?: string | undefined): string {\n  // Use input value if specified\n  if (cookieDomain) return cookieDomain;\n\n  // Use top level domain (ar.snap.com => snap.com)\n  const topLevelDomain = getTopLevelDomain(domain);\n  // Return top level domain or empty string\n  return topLevelDomain;\n}\n\nexport const getCookieSettingsUrl = (domain: string, cookieDomain?: string | undefined): string => {\n  cookieDomain = getCookieDomain(domain, cookieDomain);\n\n  const isSameDomain = domain === cookieDomain;\n  return isSameDomain ? cookieSettingsPath : `https://${cookieDomain}${cookieSettingsPath}`;\n};\n", "export const isInWindow = (): boolean => typeof window !== 'undefined';\nexport const isInWorker = (): boolean => typeof WorkerGlobalScope !== 'undefined';\nexport const isInBrowser = (): boolean => isInWindow() || isInWorker();\n", "/**\n * Wrapper around `console.info` that can be turned on globally via:\n *\n *     logger.setDebugMode(true);\n */\nexport class Logger {\n  private debugMode = false;\n\n  setDebugMode(debugMode: boolean): void {\n    this.debugMode = debugMode;\n  }\n\n  /** Internal console log function */\n  log = (...message: unknown[]): void => {\n    if (this.debugMode) {\n      console.info('[Metrics SDK]', ...message);\n    }\n  };\n}\n\nexport const logger = new Logger();\n", "import { isInWindow } from './utils/isInBrowser';\nimport type { MetricCollector } from './collector/MetricCollector';\nimport { logger } from './logger';\nimport type { BaseNetworkHandler } from './network/BaseNetworkHandler';\nimport type { HistogramMetric, IncrementMetric, InitializeProps, TimerMetric } from './types';\nimport type { MetricsMap } from './collector/types';\n\n// TODO: This needs to have types to add types to the MetricCollector!\nexport abstract class BaseClient {\n  isInitialized = false;\n  timerId?: NodeJS.Timeout;\n  heartBeatId?: NodeJS.Timeout;\n  protected networkHandler?: BaseNetworkHandler;\n  protected metricCollector?: MetricCollector;\n  private onIncrement?: (param: IncrementMetric) => IncrementMetric[];\n  private onAddHistogram?: (param: HistogramMetric) => HistogramMetric[];\n  private onAddTimer?: (param: TimerMetric) => TimerMetric[];\n\n  abstract sendHeartBeatCounter(version: string): void;\n\n  // Initialize SDK instance\n  initialize(props: InitializeProps): void {\n    const {\n      debugMode = false,\n      logTimeInterval = 5 * 1000, // By default, flush all events every 5 secs\n      onIncrement = (v: IncrementMetric) => [v],\n      onAddHistogram = (v: HistogramMetric) => [v],\n      onAddTimer = (v: TimerMetric) => [v],\n    } = props;\n\n    logger.setDebugMode(debugMode);\n    this.networkHandler = props.networkHandler;\n    this.metricCollector = this.networkHandler?.config.collector;\n\n    this.onIncrement = onIncrement;\n    this.onAddHistogram = onAddHistogram;\n    this.onAddTimer = onAddTimer;\n\n    // Set a interval job to flush all events\n    this.timerId = setInterval(this.flush, logTimeInterval);\n\n    // Trying to flush all events before leaving the page\n    // Note that this is not guaranteed to completed before browser cancels the request\n    // because blocking users from leaving current page is not a proper design\n    // TODO: might consider using Web Worker\n    if (isInWindow()) {\n      window.addEventListener('beforeunload', this.flush);\n    }\n\n    this.isInitialized = true;\n    logger.log('initializing SDK with config', props);\n  }\n\n  // Cancel the interval timer and reset metrics\n  destroy(): void {\n    logger.log('destroying SDK.');\n    if (this.timerId) {\n      clearInterval(this.timerId);\n    }\n    if (this.heartBeatId) {\n      clearInterval(this.heartBeatId);\n    }\n    this.isInitialized = false;\n    this.metricCollector?.clearMetrics();\n    if (isInWindow()) {\n      window.removeEventListener('beforeunload', this.flush);\n    }\n  }\n\n  isReady(): boolean {\n    return this.isInitialized;\n  }\n\n  // Increment counter value\n  increment(metric: IncrementMetric): void {\n    if (!this.isInitialized || !this.metricCollector) {\n      return;\n    }\n    for (const mappedMetric of this.onIncrement?.(metric) ?? []) {\n      const { metricsName, dimensions, value = 1 } = mappedMetric;\n      if (!Number.isInteger(value)) {\n        throw new Error('value must be an integer in increment.');\n      }\n      this.metricCollector.increment({ metricsName, dimensions, value });\n      logger.log(\n        `increment counter ${metricsName} with dimension `,\n        dimensions,\n        ' with value ',\n        value\n      );\n    }\n  }\n\n  addHistogram(metric: HistogramMetric): void {\n    if (!this.isInitialized || !this.metricCollector) {\n      return;\n    }\n    for (const mappedMetric of this.onAddHistogram?.(metric) ?? []) {\n      const { metricsName, dimensions, value } = mappedMetric;\n      this.metricCollector.addHistogram({ metricsName, dimensions, value });\n      logger.log(\n        `addHistogram level ${metricsName} with dimension `,\n        dimensions,\n        ' with value ',\n        value\n      );\n    }\n  }\n\n  addTimer(metric: TimerMetric): void {\n    if (!this.isInitialized || !this.metricCollector) {\n      return;\n    }\n\n    for (const mappedMetric of this.onAddTimer?.(metric) ?? []) {\n      const { metricsName, dimensions, milliSec } = mappedMetric;\n      // From https://wiki.sc-corp.net/display/INF/Realtime+Metrics+At+Snap\n      // \"Must be non-negative integer with upper limit of 360 Million\"\n      // Round to be able to support adding floating point numbers. Useful example:\n      // Graphene.addTimer({metricsName, millSec: performance.now() - startTime});\n      const roundedMilliSec = Math.round(milliSec);\n\n      this.metricCollector.addTimer({ metricsName, dimensions, milliSec: roundedMilliSec });\n      logger.log(\n        `addTimer timer ${metricsName} with dimension `,\n        dimensions,\n        ' with milliSec ',\n        roundedMilliSec\n      );\n    }\n  }\n\n  /** Return all collected metrics */\n  getCollectedMetrics(): MetricsMap<unknown, unknown, unknown> | undefined {\n    return this.metricCollector?.metrics;\n  }\n\n  /** Whether SDK has any metrics. Return true, if there is no metrics to flush out. */\n  isMetricEmpty = (): boolean => !this.metricCollector || this.metricCollector.isEmpty();\n\n  /** Flush out and send all collected metrics */\n  flush = (): Promise<void> => {\n    if (!this.metricCollector || !this.networkHandler || this.metricCollector.isEmpty()) {\n      return Promise.resolve();\n    }\n    logger.log('flushing metrics', this.metricCollector.metrics);\n    const binaryPayload = this.metricCollector.getPayload();\n    this.metricCollector.clearMetrics();\n    return this.networkHandler.sendRequest(binaryPayload);\n  };\n}\n", "export const AuthType = {\n  Lca: 'lca',\n  WebAttestation: 'webAttestation',\n  None: 'none',\n} as const;\nexport type AuthType = (typeof AuthType)[keyof typeof AuthType];\n", "import type { HeaderMap } from '../types';\nimport type { AuthType } from './constants';\n\nexport abstract class Authenticator {\n  abstract authRequest(\n    authType: AuthType,\n    payload: Uint8Array,\n    headers: HeaderMap\n  ): Promise<HeaderMap>;\n}\n", "import type { BaseLogParam } from '../types';\nimport type { MetricsMap } from './types';\n\nexport abstract class MetricCollector<T1 = unknown, T2 = T1, T3 = T1> {\n  metrics: MetricsMap<T1, T2, T3>;\n\n  constructor() {\n    this.metrics = this.getFreshMetrics();\n  }\n\n  getFreshMetrics(): MetricsMap<T1, T2, T3> {\n    return {\n      counters: {},\n      timers: {},\n      levels: {},\n    };\n  }\n\n  isEmpty(): boolean {\n    return (\n      !Object.keys(this.metrics.counters).length &&\n      !Object.keys(this.metrics.timers).length &&\n      !Object.keys(this.metrics.levels).length\n    );\n  }\n\n  /** Clear out all stored metrics */\n  clearMetrics(): void {\n    this.metrics = this.getFreshMetrics();\n  }\n\n  abstract addHistogram({ metricsName, dimensions, value }: BaseLogParam & { value: number }): void;\n  abstract addTimer({\n    metricsName,\n    dimensions,\n    milliSec,\n  }: BaseLogParam & { milliSec: number }): void;\n  abstract getPayload(): Uint8Array;\n  abstract increment({ metricsName, dimensions, value }: BaseLogParam & { value: number }): void;\n}\n", "import type { Config } from '../config/types';\n\nexport abstract class BaseNetworkHandler {\n  readonly config: Config;\n\n  constructor(options: Config) {\n    this.config = options;\n  }\n\n  abstract sendRequest(payload: Uint8Array): Promise<void>;\n}\n", "import { logger } from '../logger';\nimport { BaseNetworkHandler } from './BaseNetworkHandler';\n\nexport class FetchError extends Error {\n  public status: number;\n  public statusText: string;\n  constructor(args: { status: number; statusText: string }) {\n    super(`Fetch error: ${args.status} - ${args.statusText}`);\n    this.status = args.status;\n    this.statusText = args.statusText;\n  }\n}\n\n/** A network handler that uses the fetch API. */\nexport class FetchNetworkHandler extends BaseNetworkHandler {\n  sendRequest(payload: Uint8Array): Promise<void> {\n    const { authType, authenticator, protocol, host, path, headers } = this.config;\n\n    return authenticator\n      .authRequest(authType, payload, headers)\n      .then(\n        authedHeaders =>\n          new Promise<void>((resolve, reject) => {\n            const url = `${protocol}//${host}${path}`;\n            return fetch(url, {\n              method: 'POST',\n              headers: authedHeaders,\n              body: payload,\n            })\n              .then(response => {\n                logger.log(\n                  'Received response from metrics server. Status code:',\n                  response.status,\n                  response.statusText\n                );\n                if (response.ok) {\n                  resolve();\n                } else {\n                  reject(\n                    new FetchError({\n                      status: response.status,\n                      statusText: response.statusText,\n                    })\n                  );\n                }\n              })\n              .catch((reason: DOMException | TypeError) => {\n                reject(\n                  new FetchError({\n                    status: -1,\n                    statusText: reason.message,\n                  })\n                );\n              });\n          })\n      )\n      .catch(e => {\n        logger.log('Got error when sending request:', e);\n      });\n  }\n}\n", "import type { BaseLogParam } from '../types';\n\n/**\n * Computes the metric key based on the provided parameters.\n *\n * @param metricsName - The name of the metric.\n * @param dimensions - The dimensions associated with the metric.\n * @param prefixes - Optional prefixes to be added to the metric key.\n * @returns The computed metric key.\n */\nexport const computeMetricKey = ({\n  metricsName,\n  dimensions,\n  prefixes = [],\n}: BaseLogParam & { prefixes?: string[] }): string => {\n  const metricNameFragments = [...prefixes];\n  metricNameFragments.push(metricsName);\n  if (dimensions) {\n    // sort the dimension keys to get stable key\n    Object.keys(dimensions)\n      .sort()\n      .forEach((key: string) => {\n        const value: string = dimensions[key];\n        metricNameFragments.push(key, value);\n      });\n  }\n  return metricNameFragments.join('.');\n};\n", "/**\n * Generate random number in a range (inclusive)\n *\n * @param min {number}: Min bound\n * @param max {number}: Max bound\n * @returns {number} A random integer in [min, max]\n */\nexport const getRandomIntFromRange = (min: number, max: number): number =>\n  Math.floor(Math.random() * (max - min + 1)) + min;\n", "import { getRandomIntFromRange } from './getRandomIntFromRange';\n\n/**\n * Use Reservoir Sampling to sample at most maxSize elements from given array\n *\n * @param array {T[]}: An array of elements to be sampled from\n * @param maxSize {number}: Max number of elements to be chosen\n * @returns {T[]} An array of element chosen randomly\n */\nexport const reservoirSample = <T>(array: T[], maxSize: number): T[] => {\n  if (array.length <= maxSize) {\n    return array;\n  }\n  const newValueList = array.slice(0, maxSize);\n  for (let i = maxSize; i < array.length; i++) {\n    const nextIndex = getRandomIntFromRange(0, i);\n    if (nextIndex < maxSize) {\n      newValueList[nextIndex] = array[i];\n    }\n  }\n  return newValueList;\n};\n", "/**\n * Encodes a string using base64 encoding.\n *\n * @param str - The string to be encoded.\n * @returns The base64 encoded string.\n */\nexport const inlineBtoa = (str: string): string => Buffer.from(str, 'binary').toString('base64');\n", "var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\nexport {\n  __name\n};\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map\n", "import type { Sha256 } from './hash.types';\n\n/**\n * Calculates the SHA-256 hash of the given data using the browser's built-in crypto API.\n *\n * @param data - The data to be hashed.\n * @returns A promise that resolves to the hexadecimal representation of the SHA-256 hash.\n */\nexport const sha256: Sha256 = async (data: Uint8Array): Promise<string> => {\n  const hash = await window.crypto.subtle.digest('SHA-256', data);\n  return bufferToHex(hash);\n};\n\n/**\n * Converts an ArrayBuffer to a hexadecimal string representation.\n *\n * @param buffer - The ArrayBuffer to convert.\n * @returns The hexadecimal string representation of the buffer.\n */\nfunction bufferToHex(buffer: ArrayBuffer): string {\n  return Array.from(new Uint8Array(buffer))\n    .map(b => b.toString(16).padStart(2, '0'))\n    .join('');\n}\n", "// TODO: Remove exports from @snapchat/metrics-utils so users who can import\n// directly from it.\nexport type {\n  MetricsMap,\n  Config,\n  BaseLogParam,\n  Dimensions,\n  HeaderMap,\n  HistogramMetric,\n  IncrementMetric,\n  InitializeProps,\n  TimerMetric,\n} from '@snapchat/metrics-utils';\nexport {\n  logger,\n  AuthType,\n  Authenticator,\n  MetricCollector,\n  FetchNetworkHandler,\n  BaseNetworkHandler,\n} from '@snapchat/metrics-utils';\n\nexport { Partition as PARTITION } from './partition'; // For backwards compatibility with 7.x.x\nexport { Partition, isValidPartitionName } from './partition';\nexport { graphene, Graphene } from './graphene';\nexport { WebMetricCollector, type WebMetricCollectorOptions } from './collector/WebMetricCollector';\nexport { getWebConfig } from './config/web';\n// NOTE: There's no export of the thin client because it's not meant for public consumption.\n", "/**\n * Define partition name here. Similar with\n * https://github.sc-corp.net/Snapchat/android/blob/master/snapchat/platform/analytics/graphene/api/src/main/java/com/snap/graphene/schema/Partition.java\n */\nexport enum Partition {\n  UNDEFINED = 'undefined',\n  ADS_LIBRARY = 'ads_library',\n  ADS_MANAGER = 'ads_manager',\n  BUSINESS_MANAGER = 'business_manager',\n  PROFILE_MANAGER = 'profile_manager',\n  REVIEW_TOOL = 'review_tool',\n  SNAP_MAPS = 'snap_maps',\n  FOR_BUSINESS = 'for_business',\n  ADFORMATS_WEB = 'adformats_web',\n  DISCOVER_CMS = 'discover_cms',\n  SNAP_WEB = 'snap_web',\n  NEWSROOM = 'newsroom',\n  YELLOW_LA = 'yellow_la',\n  CITIZEN_SNAP = 'citizen_snap',\n  SNAP_FOUNDATION = 'snap_foundation',\n  ENG_BLOG = 'eng_blog',\n  RESEARCH_SNAP = 'research_snap',\n  MY_LENSES = 'my_lenses',\n  PLAYCANVAS = 'playcanvas',\n  MEASUREMENT_PORTAL = 'measurement_portal',\n  TRUST = 'trust',\n  CHEERIOS = 'cheerios',\n  SPS = 'sps',\n  // added partitions by Bynd team\n  AR_SNAP = 'ar_snap',\n  DEVELOPER_SNAP = 'developer_snap',\n  DANDELION = 'dandelion',\n  CREATORS_SNAP = 'creators_snap',\n  DIVERSITY = 'diversity',\n  // to be used for snapchat on the web, including web sharing and story.snapchat.com\n  SNAPCHAT_WEB = 'snapchat_web',\n  EMBEDDED_WEBVIEW_ADS = 'embedded_webview_ads',\n  METRICS_MONITOR = 'metrics_monitor',\n  SNAPGRAPH = 'snapgraph',\n  MEASUREMENT_RESONANCE_SURVEY = 'measurement_resonance_survey',\n  MEASUREMENT_MR_SURVEY = 'measurement_mr_survey',\n  MEASUREMENT_COLLECTION_SURVEY = 'measurement_collection_survey',\n  // used for story studio lite (my.snapchat.com) - https://snapchat.quip.com/LRWmAVmV90zp\n  STORY_STUDIO_LITE = 'story_studio_lite',\n  // used for metrics within the web_self_serve_ads monorepo https://github.sc-corp.net/Snapchat/web-self-serve-ads\n  WEB_SELF_SERVE_ADS = 'web_self_serve_ads',\n  ARCADIA = 'arcadia',\n  SNAP_523 = 'snap_523',\n  ORIGINALS = 'originals',\n  // used for the law enforcement operations (LEO) internal web tool repo: https://github.sc-corp.net/Snapchat/leo-portal\n  LEO_WEB = 'leo_web',\n  // used for desktop web snapchat client\n  DWEB = 'dweb',\n  SCN_CONTENT_MANAGER = 'scn_content_manager',\n  ADVERTISER_360 = 'advertiser_360',\n  CAREERS = 'careers',\n  PRIVACY_INFRA = 'privacy_infra',\n  BLIZZARD = 'blizzard',\n  // used for the Snap cookie modal and related settings page used across website properties\n  COOKIE_MODAL_COMPONENTS = 'cookie_modal_components',\n  // used for content tools projects (storyteller, BIB) https://github.sc-corp.net/Snapchat/search/tree/master/ranking/snapgraph/web\n  CONTENT_TOOLS = 'content_tools',\n  WEB_ACCOUNTS = 'web_accounts',\n  // used for metrics within the marketing-web monorepo - https://github.sc-corp.net/Snapchat/marketing-web\n  MARKETING_WEB_PLATFORM = 'marketing_web_platform',\n  // added by AR Enterprise Shopping for off-platform web experiences through our SDK\n  ARES_SDK = 'ares_sdk',\n  // used for metrics on SnapOrca - https://github.sc-corp.net/Snapchat/snap-orca/\n  SNAP_ORCA = 'snap_orca',\n  // used for metrics on Safety Review Tool - https://github.sc-corp.net/Snapchat/safety-review-tool\n  SAFETY_REVIEW_TOOL = 'safety_review_tool',\n  // used for adding metrics to the Reporting-Service SDK\n  REPORTING_SERVICE = 'reporting_service',\n  // used for calling\n  SCN_ADDLIVE = 'scn_addlive',\n  // Used for Quality Org tooling\n  QUALITY = 'quality',\n  // used by parents.snapchat.com MWP microsite\n  PARENTS = 'parents',\n  // used by enterprise manager\n  ENTERPRISE_MANAGER = 'enterprise_manager',\n  // used by digital asset manager\n  DIGITAL_ASSET_MANAGER = 'digital_asset_manager',\n  // used by lens web builder - https://github.sc-corp.net/Snapchat/Lens-web-builder\n  LENS_WEB_BUILDER = 'lens_web_builder',\n  // used by Snapchat Camera for web (browser extension)\n  SNAPCHAT_CAMERA_BROWSER_EXTENSION = 'snapchat_camera_browser_extension',\n  // used by web ar player https://github.sc-corp.net/Snapchat/web-ar-player\n  WEB_AR_PLAYER = 'web_ar_player',\n  // Used by any web product that is using standard logging without a need for a special partition.\n  // https://wiki.sc-corp.net/pages/viewpage.action?pageId=292521031\n  /** @deprecated Do not use this any more. Its dimensions have been dropped. */\n  WEB_COMMON = 'web_common',\n  // used for metrics in hosted lenses - https://github.sc-corp.net/Snapchat/hosted-lenses-ui\n  HOSTED_LENSES = 'hosted_lenses',\n  AVALON = 'avalon',\n  // our in-house attestation solution - currently https://github.sc-corp.net/Snapchat/kameleon\n  ATTESTATION = 'attestation',\n  EXPERIENCE = 'experience',\n  // used by lens services team for work on the ar.snap.com/download page\n  AR_WEB = 'ar_web',\n  // used by LEO's Law Enforcement Operations Portal (LESS) - https://github.sc-corp.net/Snapchat/less\n  SNAP_LESS = 'snap-less',\n  // used by the data protection team\n  SNAP_IAM_WEB = 'snap_iam_web',\n  // My AI Enterprise\n  MY_AI_ENTERPRISE = 'my_ai_enterprise',\n  // Billboard self-serve - https://billboard.sc-corp.net\n  BILLBOARD_SELF_SERVE = 'billboard_self_serve',\n  LENS_STUDIO_WEB = 'lens_studio_web',\n  // Web Platform team partition\n  WEB_PLATFORM = 'web_platform',\n  // Service owned by Web Platform for web metrics\n  WEB_REPORTING = 'web_reporting',\n  // Used for https://educators.snapchat.com/\n  SNAP_EDUCATORS = 'snap_educators',\n  // Used for cloud console\n  CLOUD_CONSOLE = 'cloud_console',\n  // Used for SnapCI\n  SNAP_CI = 'snap_ci',\n  // Used for A/B console (go/ab)\n  AB_CONSOLE = 'ab_console',\n  // Used for Sherlock (go/sherlock)\n  SHERLOCK = 'sherlock',\n  // Used for Stinson/Specs\n  STINSON = 'stinson',\n}\n\n/**\n * Validates if a string is a valid partition name. Valid partition names should be in\n * lower_snake_case or kebab-case format.\n *\n * @param partitionName The partition name to validate\n * @returns True if the partition name is valid, false otherwise\n */\nexport function isValidPartitionName(partitionName: string): boolean {\n  if (!partitionName) return false;\n\n  // Check if it's a kvalid enum value\n  if (Object.values(Partition).includes(partitionName as Partition)) {\n    return true;\n  }\n\n  // Check if it's in lower_snake_case format or kebab-case format\n  return /^[a-z][a-z0-9]*(?:[_-][a-z0-9]+)*$/.test(partitionName);\n}\n", "import { isInWindow, BaseClient, type InitializeProps } from '@snapchat/metrics-utils';\nimport { ActivityDetector } from './ActivityDetector';\n\n// By default if user don't have any activity in 60 second, then it is inactive\nexport const defaultInactiveThreshold = 60;\n\nexport class Graphene extends BaseClient {\n  activityDetector?: ActivityDetector;\n\n  // Initialize graphene instance\n  initialize(props: InitializeProps): void {\n    if (this.isInitialized) {\n      throw new Error(\"this instance has been initialized. Can't re-initialize it.\");\n    }\n    super.initialize(props);\n\n    const { inactiveThresholdInSecond = defaultInactiveThreshold } = props;\n\n    if (isInWindow()) {\n      this.activityDetector = new ActivityDetector(inactiveThresholdInSecond);\n      // Trying to flush all events before leaving the page\n      // Note that this is not guaranteed to completed before browser cancels the request\n      // because blocking users from leaving current page is not a proper design\n      window.addEventListener('beforeunload', this.flush);\n    }\n  }\n\n  // send heart beat event\n  sendHeartBeatCounter = (version: string): void => {\n    if (!this.isInitialized) {\n      return;\n    }\n    const heartBeatDuration = 60000;\n    const sendHeartBeatEvent = () => {\n      const active = this.activityDetector?.getIsActive() ? 'active' : 'inactive';\n      this.increment({ metricsName: 'heart_beat', dimensions: { version, active } });\n    };\n    sendHeartBeatEvent();\n    this.heartBeatId = setInterval(sendHeartBeatEvent, heartBeatDuration);\n  };\n\n  // Cancel the interval timer and reset metrics\n  destroy(): void {\n    super.destroy();\n    if (isInWindow()) {\n      window.removeEventListener('beforeunload', this.flush);\n    }\n    if (this.activityDetector) {\n      this.activityDetector.destroy();\n    }\n  }\n}\n\n/** Default Graphene instance. If you need more clients, create them using `new Graphene()`. */\nexport const graphene = new Graphene();\n", "const activityEvents: string[] = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart'];\n\n/**\n * Represents an activity detector that tracks user activity and determines if the current browser\n * tab is inactive.\n */\nexport class ActivityDetector {\n  private lastActivityTimestamp: number;\n  private readonly inactiveThresholdInSecond: number;\n\n  /**\n   * Creates an instance of ActivityDetector.\n   *\n   * @param inactiveThresholdInSecond - The threshold in seconds to consider the browser tab as\n   *   inactive.\n   */\n  constructor(inactiveThresholdInSecond: number) {\n    this.lastActivityTimestamp = Date.now();\n    this.inactiveThresholdInSecond = inactiveThresholdInSecond;\n    this.registerListeners();\n  }\n\n  destroy = (): void => {\n    activityEvents.forEach((eventName): void => {\n      document.removeEventListener(eventName, this.onActivity, true);\n    });\n  };\n\n  /** Callback when user has any activity */\n  onActivity = (): void => {\n    // reset the timer\n    this.lastActivityTimestamp = Date.now();\n  };\n\n  /** Register all DOM events listeners tied to user activity */\n  registerListeners = (): void => {\n    activityEvents.forEach((eventName): void => {\n      document.addEventListener(eventName, this.onActivity, true);\n    });\n  };\n\n  /** Return seconds since last activity. */\n  getSecondsSinceLastActivity = (): number =>\n    Math.round((Date.now() - this.lastActivityTimestamp) / 1000);\n\n  /** Whether current browser tab is inactive. */\n  getIsActive = (): boolean => this.getSecondsSinceLastActivity() < this.inactiveThresholdInSecond;\n}\n", "import { type Partition, isValidPartitionName } from '../partition';\nimport {\n  MetricCollector,\n  type MetricsMap,\n  type BaseLogParam,\n  type Dimensions,\n  reservoirSample,\n  computeMetricKey,\n} from '@snapchat/metrics-utils';\n\n// TODO: See if we can use '@snapchat/ts-protos/graphene/metrics', but they\n// use `string` for uint64 encoding.\nimport {\n  MetricFrame,\n  Metric,\n  AppVersion,\n  type AppVersion_VersionNumber,\n  OsType,\n} from '../generated/graphene/metrics';\n\nexport interface WebMetricCollectorOptions {\n  /** Max size per metric */\n  maxSizePerMetric?: number;\n\n  /** Dimensions that'll be added to each metric. */\n  defaultDimensions?: Dimensions;\n\n  /**\n   * Build flavor, e.g., local, stage, prod.\n   *\n   * The heirarchy is graphene.web.${flavor}.${variant}.${version}.${partition}\n   */\n  flavor?: string;\n\n  /**\n   * For non-snapchat, this is name if your product.\n   *\n   * For snapchat on the web, this is the variant of the app, i.e. SNAPSHOT, OG, MUSHROOM see\n   * Blizzard Schema's AppVariantType https://snapchat.quip.com/UVHDA0J59IDz\n   *\n   * The heirarchy is graphene.web.${flavor}.${variant}.${version}.${partition}\n   */\n  variant?: string;\n\n  /**\n   * Sematic version of the snapchat app or version of your products.\n   *\n   * The heirarchy is graphene.web.${flavor}.${variant}.${version}.${partition}\n   */\n  versionNumber?: AppVersion_VersionNumber;\n\n  /**\n   * Use project name or team name.\n   *\n   * Service Name will be used if partitionName is not specified.\n   *\n   * The heirarchy is graphene.web.${flavor}.${variant}.${version}.${partition}\n   */\n  partitionName?: Partition;\n\n  /**\n   * Name of the service that is logging the metrics. Will be used over partitionName if\n   * partitionName is not specified.\n   */\n  serviceName?: string;\n}\n\ntype WebMetricsMap = MetricsMap<Metric>;\n\n/** Dedicated for frontend use case. Collect and process metrics. */\nexport class WebMetricCollector extends MetricCollector<Metric> {\n  partitionName: string;\n  private flavor?: string;\n  private variant?: string;\n  private versionNumber?: AppVersion_VersionNumber;\n  private maxSizePerMetric: number;\n  private defaultDimensions?: Dimensions;\n\n  constructor(options: WebMetricCollectorOptions) {\n    super();\n    if (!options.partitionName && !options.serviceName) {\n      throw new Error('Partition name or service name is required!');\n    }\n\n    const partitionName = options.partitionName ?? options.serviceName ?? '';\n\n    // Validate the partition name\n    if (!isValidPartitionName(partitionName)) {\n      throw new Error(\n        'Invalid partition name format! Partition name should be in lower_snake_case or kebab-case format.'\n      );\n    }\n    this.partitionName = partitionName;\n    this.flavor = options.flavor;\n    this.variant = options.variant;\n    this.versionNumber = options.versionNumber;\n    this.maxSizePerMetric = options.maxSizePerMetric || 50;\n    this.defaultDimensions = options.defaultDimensions;\n  }\n\n  increment({ metricsName, dimensions, value }: BaseLogParam & { value: number }): void {\n    const metricKey = computeMetricKey({ metricsName, dimensions });\n    const prevMetricObject = this.metrics.counters[metricKey];\n    this.metrics.counters[metricKey] = this.updateMetricObject({\n      prevMetricObject,\n      metricsName,\n      dimensions: this._decorateDimensions(dimensions),\n      value,\n      shouldAggregate: true,\n    });\n  }\n\n  addHistogram({ metricsName, dimensions, value }: BaseLogParam & { value: number }): void {\n    const metricKey = computeMetricKey({ metricsName, dimensions });\n    const prevMetricObject = this.metrics.levels[metricKey];\n    this.metrics.levels[metricKey] = this.updateMetricObject({\n      prevMetricObject,\n      metricsName,\n      dimensions: this._decorateDimensions(dimensions),\n      value,\n      shouldAggregate: false,\n    });\n  }\n\n  addTimer({ metricsName, dimensions, milliSec }: BaseLogParam & { milliSec: number }): void {\n    const metricKey = computeMetricKey({ metricsName, dimensions });\n    const prevMetricObject = this.metrics.timers[metricKey];\n    this.metrics.timers[metricKey] = this.updateMetricObject({\n      prevMetricObject,\n      metricsName,\n      dimensions: this._decorateDimensions(dimensions),\n      value: milliSec,\n      shouldAggregate: false,\n    });\n  }\n\n  getPayload(): Uint8Array {\n    const frame = this.convertToMetricFrame(this.metrics);\n    return MetricFrame.encode(frame).finish();\n  }\n\n  /**\n   * Truncates float values in int64 fields to ensure compatibility with ts-proto@2.x This preserves\n   * the behavior of ts-proto@1.181.2 where floats were silently truncated\n   */\n  private truncateInt64Values(frame: MetricFrame): void {\n    // Process counters\n    frame.counters.forEach(metric => {\n      metric.values = metric.values.map(value => Math.trunc(value));\n    });\n\n    // Process timers\n    frame.timers.forEach(metric => {\n      metric.values = metric.values.map(value => Math.trunc(value));\n    });\n\n    // Process levels\n    frame.levels.forEach(metric => {\n      metric.values = metric.values.map(value => Math.trunc(value));\n    });\n  }\n\n  updateMetricObject({\n    prevMetricObject,\n    metricsName,\n    dimensions = {},\n    value,\n    shouldAggregate = false,\n  }: BaseLogParam & {\n    prevMetricObject: Metric | undefined;\n    value: number;\n    shouldAggregate?: boolean;\n  }): Metric {\n    let metricObject = prevMetricObject;\n    // If there was no metric object, then create a new one\n    if (!metricObject) {\n      metricObject = Metric.fromPartial({\n        partitionName: this.partitionName,\n        metricName: metricsName,\n        customDimensions: dimensions,\n      });\n    }\n\n    // if aggregate, then sum up the value into single value\n    // otherwise, append new metric in the value list\n    if (shouldAggregate) {\n      const existingValueList = metricObject.values;\n      const newValue = value + (Number(existingValueList[0]) || 0);\n      metricObject.values = [newValue];\n    } else {\n      metricObject.values.push(value);\n    }\n    return metricObject;\n  }\n\n  // convert metrics into MetricFrame which is protobuf format\n  convertToMetricFrame(metricsToConvert: WebMetricsMap): MetricFrame {\n    const frame = MetricFrame.create();\n    frame.clientOsType = OsType.OS_WEB;\n\n    // If app version related values are set, then set app version\n    if (this.flavor || this.variant || this.versionNumber) {\n      const appVersion = AppVersion.create();\n      if (this.flavor) {\n        appVersion.flavor = this.flavor;\n      }\n      if (this.variant) {\n        appVersion.variant = this.variant;\n      }\n      if (this.versionNumber) {\n        appVersion.versionNumber = this.versionNumber;\n      }\n      frame.appVersion = appVersion;\n    }\n\n    Object.keys(metricsToConvert.counters).forEach(key => {\n      const metric = metricsToConvert.counters[key];\n      frame.counters.push(metric);\n    });\n    Object.keys(metricsToConvert.timers).forEach(key => {\n      const metric = this.sampleMetricValues(metricsToConvert.timers[key]);\n      frame.timers.push(metric);\n    });\n    Object.keys(metricsToConvert.levels).forEach(key => {\n      const metric = this.sampleMetricValues(metricsToConvert.levels[key]);\n      frame.levels.push(metric);\n    });\n    // Truncate all numeric values before encoding to maintain compatibility with ts-proto@1.181.2\n    this.truncateInt64Values(frame);\n    return frame;\n  }\n\n  // Reservoir Sampling on metric value list\n  sampleMetricValues(metricObject: Metric): Metric {\n    metricObject.values = reservoirSample(metricObject.values, this.maxSizePerMetric);\n    return metricObject;\n  }\n\n  _decorateDimensions(dimensions: Dimensions | undefined): Dimensions | undefined {\n    if (!this.defaultDimensions) {\n      return dimensions;\n    }\n    return {\n      ...this.defaultDimensions,\n      ...(dimensions ?? {}),\n    };\n  }\n}\n", "// Copyright 2008 Google Inc.  All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Code generated by the Protocol Buffer compiler is owned by the owner\n// of the input file used when generating it.  This code is not\n// standalone and requires a support library to be linked with it.  This\n// support library is itself covered by the above license.\n/* eslint-disable prefer-const,@typescript-eslint/restrict-plus-operands */\n/**\n * Read a 64 bit varint as two JS numbers.\n *\n * Returns tuple:\n * [0]: low bits\n * [1]: high bits\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175\n */\nexport function varint64read() {\n    let lowBits = 0;\n    let highBits = 0;\n    for (let shift = 0; shift < 28; shift += 7) {\n        let b = this.buf[this.pos++];\n        lowBits |= (b & 0x7f) << shift;\n        if ((b & 0x80) == 0) {\n            this.assertBounds();\n            return [lowBits, highBits];\n        }\n    }\n    let middleByte = this.buf[this.pos++];\n    // last four bits of the first 32 bit number\n    lowBits |= (middleByte & 0x0f) << 28;\n    // 3 upper bits are part of the next 32 bit number\n    highBits = (middleByte & 0x70) >> 4;\n    if ((middleByte & 0x80) == 0) {\n        this.assertBounds();\n        return [lowBits, highBits];\n    }\n    for (let shift = 3; shift <= 31; shift += 7) {\n        let b = this.buf[this.pos++];\n        highBits |= (b & 0x7f) << shift;\n        if ((b & 0x80) == 0) {\n            this.assertBounds();\n            return [lowBits, highBits];\n        }\n    }\n    throw new Error(\"invalid varint\");\n}\n/**\n * Write a 64 bit varint, given as two JS numbers, to the given bytes array.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344\n */\nexport function varint64write(lo, hi, bytes) {\n    for (let i = 0; i < 28; i = i + 7) {\n        const shift = lo >>> i;\n        const hasNext = !(shift >>> 7 == 0 && hi == 0);\n        const byte = (hasNext ? shift | 0x80 : shift) & 0xff;\n        bytes.push(byte);\n        if (!hasNext) {\n            return;\n        }\n    }\n    const splitBits = ((lo >>> 28) & 0x0f) | ((hi & 0x07) << 4);\n    const hasMoreBits = !(hi >> 3 == 0);\n    bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xff);\n    if (!hasMoreBits) {\n        return;\n    }\n    for (let i = 3; i < 31; i = i + 7) {\n        const shift = hi >>> i;\n        const hasNext = !(shift >>> 7 == 0);\n        const byte = (hasNext ? shift | 0x80 : shift) & 0xff;\n        bytes.push(byte);\n        if (!hasNext) {\n            return;\n        }\n    }\n    bytes.push((hi >>> 31) & 0x01);\n}\n// constants for binary math\nconst TWO_PWR_32_DBL = 0x100000000;\n/**\n * Parse decimal string of 64 bit integer value as two JS numbers.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function int64FromString(dec) {\n    // Check for minus sign.\n    const minus = dec[0] === \"-\";\n    if (minus) {\n        dec = dec.slice(1);\n    }\n    // Work 6 decimal digits at a time, acting like we're converting base 1e6\n    // digits to binary. This is safe to do with floating point math because\n    // Number.isSafeInteger(ALL_32_BITS * 1e6) == true.\n    const base = 1e6;\n    let lowBits = 0;\n    let highBits = 0;\n    function add1e6digit(begin, end) {\n        // Note: Number('') is 0.\n        const digit1e6 = Number(dec.slice(begin, end));\n        highBits *= base;\n        lowBits = lowBits * base + digit1e6;\n        // Carry bits from lowBits to\n        if (lowBits >= TWO_PWR_32_DBL) {\n            highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);\n            lowBits = lowBits % TWO_PWR_32_DBL;\n        }\n    }\n    add1e6digit(-24, -18);\n    add1e6digit(-18, -12);\n    add1e6digit(-12, -6);\n    add1e6digit(-6);\n    return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);\n}\n/**\n * Losslessly converts a 64-bit signed integer in 32:32 split representation\n * into a decimal string.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function int64ToString(lo, hi) {\n    let bits = newBits(lo, hi);\n    // If we're treating the input as a signed value and the high bit is set, do\n    // a manual two's complement conversion before the decimal conversion.\n    const negative = bits.hi & 0x80000000;\n    if (negative) {\n        bits = negate(bits.lo, bits.hi);\n    }\n    const result = uInt64ToString(bits.lo, bits.hi);\n    return negative ? \"-\" + result : result;\n}\n/**\n * Losslessly converts a 64-bit unsigned integer in 32:32 split representation\n * into a decimal string.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function uInt64ToString(lo, hi) {\n    ({ lo, hi } = toUnsigned(lo, hi));\n    // Skip the expensive conversion if the number is small enough to use the\n    // built-in conversions.\n    // Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with\n    // highBits <= 0x1FFFFF can be safely expressed with a double and retain\n    // integer precision.\n    // Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.\n    if (hi <= 0x1fffff) {\n        return String(TWO_PWR_32_DBL * hi + lo);\n    }\n    // What this code is doing is essentially converting the input number from\n    // base-2 to base-1e7, which allows us to represent the 64-bit range with\n    // only 3 (very large) digits. Those digits are then trivial to convert to\n    // a base-10 string.\n    // The magic numbers used here are -\n    // 2^24 = 16777216 = (1,6777216) in base-1e7.\n    // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.\n    // Split 32:32 representation into 16:24:24 representation so our\n    // intermediate digits don't overflow.\n    const low = lo & 0xffffff;\n    const mid = ((lo >>> 24) | (hi << 8)) & 0xffffff;\n    const high = (hi >> 16) & 0xffff;\n    // Assemble our three base-1e7 digits, ignoring carries. The maximum\n    // value in a digit at this step is representable as a 48-bit integer, which\n    // can be stored in a 64-bit floating point number.\n    let digitA = low + mid * 6777216 + high * 6710656;\n    let digitB = mid + high * 8147497;\n    let digitC = high * 2;\n    // Apply carries from A to B and from B to C.\n    const base = 10000000;\n    if (digitA >= base) {\n        digitB += Math.floor(digitA / base);\n        digitA %= base;\n    }\n    if (digitB >= base) {\n        digitC += Math.floor(digitB / base);\n        digitB %= base;\n    }\n    // If digitC is 0, then we should have returned in the trivial code path\n    // at the top for non-safe integers. Given this, we can assume both digitB\n    // and digitA need leading zeros.\n    return (digitC.toString() +\n        decimalFrom1e7WithLeadingZeros(digitB) +\n        decimalFrom1e7WithLeadingZeros(digitA));\n}\nfunction toUnsigned(lo, hi) {\n    return { lo: lo >>> 0, hi: hi >>> 0 };\n}\nfunction newBits(lo, hi) {\n    return { lo: lo | 0, hi: hi | 0 };\n}\n/**\n * Returns two's compliment negation of input.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers\n */\nfunction negate(lowBits, highBits) {\n    highBits = ~highBits;\n    if (lowBits) {\n        lowBits = ~lowBits + 1;\n    }\n    else {\n        // If lowBits is 0, then bitwise-not is 0xFFFFFFFF,\n        // adding 1 to that, results in 0x100000000, which leaves\n        // the low bits 0x0 and simply adds one to the high bits.\n        highBits += 1;\n    }\n    return newBits(lowBits, highBits);\n}\n/**\n * Returns decimal representation of digit1e7 with leading zeros.\n */\nconst decimalFrom1e7WithLeadingZeros = (digit1e7) => {\n    const partial = String(digit1e7);\n    return \"0000000\".slice(partial.length) + partial;\n};\n/**\n * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144\n */\nexport function varint32write(value, bytes) {\n    if (value >= 0) {\n        // write value as varint 32\n        while (value > 0x7f) {\n            bytes.push((value & 0x7f) | 0x80);\n            value = value >>> 7;\n        }\n        bytes.push(value);\n    }\n    else {\n        for (let i = 0; i < 9; i++) {\n            bytes.push((value & 127) | 128);\n            value = value >> 7;\n        }\n        bytes.push(1);\n    }\n}\n/**\n * Read an unsigned 32 bit varint.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220\n */\nexport function varint32read() {\n    let b = this.buf[this.pos++];\n    let result = b & 0x7f;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    b = this.buf[this.pos++];\n    result |= (b & 0x7f) << 7;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    b = this.buf[this.pos++];\n    result |= (b & 0x7f) << 14;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    b = this.buf[this.pos++];\n    result |= (b & 0x7f) << 21;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    // Extract only last 4 bits\n    b = this.buf[this.pos++];\n    result |= (b & 0x0f) << 28;\n    for (let readBytes = 5; (b & 0x80) !== 0 && readBytes < 10; readBytes++)\n        b = this.buf[this.pos++];\n    if ((b & 0x80) != 0)\n        throw new Error(\"invalid varint\");\n    this.assertBounds();\n    // Result can have 32 bits, convert it to unsigned\n    return result >>> 0;\n}\n", "// Copyright 2021-2024 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { int64FromString, int64ToString, uInt64ToString, } from \"./wire/varint.js\";\n/**\n * Int64Support for the current environment.\n */\nexport const protoInt64 = /*@__PURE__*/ makeInt64Support();\nfunction makeInt64Support() {\n    const dv = new DataView(new ArrayBuffer(8));\n    // note that Safari 14 implements BigInt, but not the DataView methods\n    const ok = typeof BigInt === \"function\" &&\n        typeof dv.getBigInt64 === \"function\" &&\n        typeof dv.getBigUint64 === \"function\" &&\n        typeof dv.setBigInt64 === \"function\" &&\n        typeof dv.setBigUint64 === \"function\" &&\n        (typeof process != \"object\" ||\n            typeof process.env != \"object\" ||\n            process.env.BUF_BIGINT_DISABLE !== \"1\");\n    if (ok) {\n        const MIN = BigInt(\"-9223372036854775808\"), MAX = BigInt(\"9223372036854775807\"), UMIN = BigInt(\"0\"), UMAX = BigInt(\"18446744073709551615\");\n        return {\n            zero: BigInt(0),\n            supported: true,\n            parse(value) {\n                const bi = typeof value == \"bigint\" ? value : BigInt(value);\n                if (bi > MAX || bi < MIN) {\n                    throw new Error(`invalid int64: ${value}`);\n                }\n                return bi;\n            },\n            uParse(value) {\n                const bi = typeof value == \"bigint\" ? value : BigInt(value);\n                if (bi > UMAX || bi < UMIN) {\n                    throw new Error(`invalid uint64: ${value}`);\n                }\n                return bi;\n            },\n            enc(value) {\n                dv.setBigInt64(0, this.parse(value), true);\n                return {\n                    lo: dv.getInt32(0, true),\n                    hi: dv.getInt32(4, true),\n                };\n            },\n            uEnc(value) {\n                dv.setBigInt64(0, this.uParse(value), true);\n                return {\n                    lo: dv.getInt32(0, true),\n                    hi: dv.getInt32(4, true),\n                };\n            },\n            dec(lo, hi) {\n                dv.setInt32(0, lo, true);\n                dv.setInt32(4, hi, true);\n                return dv.getBigInt64(0, true);\n            },\n            uDec(lo, hi) {\n                dv.setInt32(0, lo, true);\n                dv.setInt32(4, hi, true);\n                return dv.getBigUint64(0, true);\n            },\n        };\n    }\n    return {\n        zero: \"0\",\n        supported: false,\n        parse(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertInt64String(value);\n            return value;\n        },\n        uParse(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertUInt64String(value);\n            return value;\n        },\n        enc(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertInt64String(value);\n            return int64FromString(value);\n        },\n        uEnc(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertUInt64String(value);\n            return int64FromString(value);\n        },\n        dec(lo, hi) {\n            return int64ToString(lo, hi);\n        },\n        uDec(lo, hi) {\n            return uInt64ToString(lo, hi);\n        },\n    };\n}\nfunction assertInt64String(value) {\n    if (!/^-?[0-9]+$/.test(value)) {\n        throw new Error(\"invalid int64: \" + value);\n    }\n}\nfunction assertUInt64String(value) {\n    if (!/^[0-9]+$/.test(value)) {\n        throw new Error(\"invalid uint64: \" + value);\n    }\n}\n", "// Copyright 2021-2024 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst symbol = Symbol.for(\"@bufbuild/protobuf/text-encoding\");\n/**\n * Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to\n * binary. This WHATWG API is widely available, but it is not part of the\n * ECMAScript standard. On runtimes where it is not available, use this\n * function to provide your own implementation.\n *\n * Note that the Text Encoding API does not provide a way to validate UTF-8.\n * Our implementation falls back to use encodeURIComponent().\n */\nexport function configureTextEncoding(textEncoding) {\n    globalThis[symbol] = textEncoding;\n}\nexport function getTextEncoding() {\n    if (globalThis[symbol] == undefined) {\n        const te = new globalThis.TextEncoder();\n        const td = new globalThis.TextDecoder();\n        globalThis[symbol] = {\n            encodeUtf8(text) {\n                return te.encode(text);\n            },\n            decodeUtf8(bytes) {\n                return td.decode(bytes);\n            },\n            checkUtf8(text) {\n                try {\n                    encodeURIComponent(text);\n                    return true;\n                }\n                catch (e) {\n                    return false;\n                }\n            },\n        };\n    }\n    return globalThis[symbol];\n}\n", "// Copyright 2021-2024 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { varint32read, varint32write, varint64read, varint64write, } from \"./varint.js\";\nimport { protoInt64 } from \"../proto-int64.js\";\nimport { getTextEncoding } from \"./text-encoding.js\";\n/* eslint-disable prefer-const,no-case-declarations,@typescript-eslint/restrict-plus-operands */\n/**\n * Protobuf binary format wire types.\n *\n * A wire type provides just enough information to find the length of the\n * following value.\n *\n * See https://developers.google.com/protocol-buffers/docs/encoding#structure\n */\nexport var WireType;\n(function (WireType) {\n    /**\n     * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum\n     */\n    WireType[WireType[\"Varint\"] = 0] = \"Varint\";\n    /**\n     * Used for fixed64, sfixed64, double.\n     * Always 8 bytes with little-endian byte order.\n     */\n    WireType[WireType[\"Bit64\"] = 1] = \"Bit64\";\n    /**\n     * Used for string, bytes, embedded messages, packed repeated fields\n     *\n     * Only repeated numeric types (types which use the varint, 32-bit,\n     * or 64-bit wire types) can be packed. In proto3, such fields are\n     * packed by default.\n     */\n    WireType[WireType[\"LengthDelimited\"] = 2] = \"LengthDelimited\";\n    /**\n     * Start of a tag-delimited aggregate, such as a proto2 group, or a message\n     * in editions with message_encoding = DELIMITED.\n     */\n    WireType[WireType[\"StartGroup\"] = 3] = \"StartGroup\";\n    /**\n     * End of a tag-delimited aggregate.\n     */\n    WireType[WireType[\"EndGroup\"] = 4] = \"EndGroup\";\n    /**\n     * Used for fixed32, sfixed32, float.\n     * Always 4 bytes with little-endian byte order.\n     */\n    WireType[WireType[\"Bit32\"] = 5] = \"Bit32\";\n})(WireType || (WireType = {}));\n/**\n * Maximum value for a 32-bit floating point value (Protobuf FLOAT).\n */\nexport const FLOAT32_MAX = 3.4028234663852886e38;\n/**\n * Minimum value for a 32-bit floating point value (Protobuf FLOAT).\n */\nexport const FLOAT32_MIN = -3.4028234663852886e38;\n/**\n * Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).\n */\nexport const UINT32_MAX = 0xffffffff;\n/**\n * Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).\n */\nexport const INT32_MAX = 0x7fffffff;\n/**\n * Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).\n */\nexport const INT32_MIN = -0x80000000;\nexport class BinaryWriter {\n    constructor(encodeUtf8 = getTextEncoding().encodeUtf8) {\n        this.encodeUtf8 = encodeUtf8;\n        /**\n         * Previous fork states.\n         */\n        this.stack = [];\n        this.chunks = [];\n        this.buf = [];\n    }\n    /**\n     * Return all bytes written and reset this writer.\n     */\n    finish() {\n        if (this.buf.length) {\n            this.chunks.push(new Uint8Array(this.buf)); // flush the buffer\n            this.buf = [];\n        }\n        let len = 0;\n        for (let i = 0; i < this.chunks.length; i++)\n            len += this.chunks[i].length;\n        let bytes = new Uint8Array(len);\n        let offset = 0;\n        for (let i = 0; i < this.chunks.length; i++) {\n            bytes.set(this.chunks[i], offset);\n            offset += this.chunks[i].length;\n        }\n        this.chunks = [];\n        return bytes;\n    }\n    /**\n     * Start a new fork for length-delimited data like a message\n     * or a packed repeated field.\n     *\n     * Must be joined later with `join()`.\n     */\n    fork() {\n        this.stack.push({ chunks: this.chunks, buf: this.buf });\n        this.chunks = [];\n        this.buf = [];\n        return this;\n    }\n    /**\n     * Join the last fork. Write its length and bytes, then\n     * return to the previous state.\n     */\n    join() {\n        // get chunk of fork\n        let chunk = this.finish();\n        // restore previous state\n        let prev = this.stack.pop();\n        if (!prev)\n            throw new Error(\"invalid state, fork stack empty\");\n        this.chunks = prev.chunks;\n        this.buf = prev.buf;\n        // write length of chunk as varint\n        this.uint32(chunk.byteLength);\n        return this.raw(chunk);\n    }\n    /**\n     * Writes a tag (field number and wire type).\n     *\n     * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.\n     *\n     * Generated code should compute the tag ahead of time and call `uint32()`.\n     */\n    tag(fieldNo, type) {\n        return this.uint32(((fieldNo << 3) | type) >>> 0);\n    }\n    /**\n     * Write a chunk of raw bytes.\n     */\n    raw(chunk) {\n        if (this.buf.length) {\n            this.chunks.push(new Uint8Array(this.buf));\n            this.buf = [];\n        }\n        this.chunks.push(chunk);\n        return this;\n    }\n    /**\n     * Write a `uint32` value, an unsigned 32 bit varint.\n     */\n    uint32(value) {\n        assertUInt32(value);\n        // write value as varint 32, inlined for speed\n        while (value > 0x7f) {\n            this.buf.push((value & 0x7f) | 0x80);\n            value = value >>> 7;\n        }\n        this.buf.push(value);\n        return this;\n    }\n    /**\n     * Write a `int32` value, a signed 32 bit varint.\n     */\n    int32(value) {\n        assertInt32(value);\n        varint32write(value, this.buf);\n        return this;\n    }\n    /**\n     * Write a `bool` value, a variant.\n     */\n    bool(value) {\n        this.buf.push(value ? 1 : 0);\n        return this;\n    }\n    /**\n     * Write a `bytes` value, length-delimited arbitrary data.\n     */\n    bytes(value) {\n        this.uint32(value.byteLength); // write length of chunk as varint\n        return this.raw(value);\n    }\n    /**\n     * Write a `string` value, length-delimited data converted to UTF-8 text.\n     */\n    string(value) {\n        let chunk = this.encodeUtf8(value);\n        this.uint32(chunk.byteLength); // write length of chunk as varint\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `float` value, 32-bit floating point number.\n     */\n    float(value) {\n        assertFloat32(value);\n        let chunk = new Uint8Array(4);\n        new DataView(chunk.buffer).setFloat32(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `double` value, a 64-bit floating point number.\n     */\n    double(value) {\n        let chunk = new Uint8Array(8);\n        new DataView(chunk.buffer).setFloat64(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.\n     */\n    fixed32(value) {\n        assertUInt32(value);\n        let chunk = new Uint8Array(4);\n        new DataView(chunk.buffer).setUint32(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.\n     */\n    sfixed32(value) {\n        assertInt32(value);\n        let chunk = new Uint8Array(4);\n        new DataView(chunk.buffer).setInt32(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.\n     */\n    sint32(value) {\n        assertInt32(value);\n        // zigzag encode\n        value = ((value << 1) ^ (value >> 31)) >>> 0;\n        varint32write(value, this.buf);\n        return this;\n    }\n    /**\n     * Write a `fixed64` value, a signed, fixed-length 64-bit integer.\n     */\n    sfixed64(value) {\n        let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.enc(value);\n        view.setInt32(0, tc.lo, true);\n        view.setInt32(4, tc.hi, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.\n     */\n    fixed64(value) {\n        let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.uEnc(value);\n        view.setInt32(0, tc.lo, true);\n        view.setInt32(4, tc.hi, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `int64` value, a signed 64-bit varint.\n     */\n    int64(value) {\n        let tc = protoInt64.enc(value);\n        varint64write(tc.lo, tc.hi, this.buf);\n        return this;\n    }\n    /**\n     * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.\n     */\n    sint64(value) {\n        let tc = protoInt64.enc(value), \n        // zigzag encode\n        sign = tc.hi >> 31, lo = (tc.lo << 1) ^ sign, hi = ((tc.hi << 1) | (tc.lo >>> 31)) ^ sign;\n        varint64write(lo, hi, this.buf);\n        return this;\n    }\n    /**\n     * Write a `uint64` value, an unsigned 64-bit varint.\n     */\n    uint64(value) {\n        let tc = protoInt64.uEnc(value);\n        varint64write(tc.lo, tc.hi, this.buf);\n        return this;\n    }\n}\nexport class BinaryReader {\n    constructor(buf, decodeUtf8 = getTextEncoding().decodeUtf8) {\n        this.decodeUtf8 = decodeUtf8;\n        this.varint64 = varint64read; // dirty cast for `this`\n        /**\n         * Read a `uint32` field, an unsigned 32 bit varint.\n         */\n        this.uint32 = varint32read;\n        this.buf = buf;\n        this.len = buf.length;\n        this.pos = 0;\n        this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n    }\n    /**\n     * Reads a tag - field number and wire type.\n     */\n    tag() {\n        let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;\n        if (fieldNo <= 0 || wireType < 0 || wireType > 5)\n            throw new Error(\"illegal tag: field no \" + fieldNo + \" wire type \" + wireType);\n        return [fieldNo, wireType];\n    }\n    /**\n     * Skip one element and return the skipped data.\n     *\n     * When skipping StartGroup, provide the tags field number to check for\n     * matching field number in the EndGroup tag.\n     */\n    skip(wireType, fieldNo) {\n        let start = this.pos;\n        switch (wireType) {\n            case WireType.Varint:\n                while (this.buf[this.pos++] & 0x80) {\n                    // ignore\n                }\n                break;\n            // eslint-disable-next-line\n            // @ts-expect-error TS7029: Fallthrough case in switch\n            case WireType.Bit64:\n                this.pos += 4;\n            // eslint-disable-next-line no-fallthrough\n            case WireType.Bit32:\n                this.pos += 4;\n                break;\n            case WireType.LengthDelimited:\n                let len = this.uint32();\n                this.pos += len;\n                break;\n            case WireType.StartGroup:\n                for (;;) {\n                    const [fn, wt] = this.tag();\n                    if (wt === WireType.EndGroup) {\n                        if (fieldNo !== undefined && fn !== fieldNo) {\n                            throw new Error(\"invalid end group tag\");\n                        }\n                        break;\n                    }\n                    this.skip(wt, fn);\n                }\n                break;\n            default:\n                throw new Error(\"cant skip wire type \" + wireType);\n        }\n        this.assertBounds();\n        return this.buf.subarray(start, this.pos);\n    }\n    /**\n     * Throws error if position in byte array is out of range.\n     */\n    assertBounds() {\n        if (this.pos > this.len)\n            throw new RangeError(\"premature EOF\");\n    }\n    /**\n     * Read a `int32` field, a signed 32 bit varint.\n     */\n    int32() {\n        return this.uint32() | 0;\n    }\n    /**\n     * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.\n     */\n    sint32() {\n        let zze = this.uint32();\n        // decode zigzag\n        return (zze >>> 1) ^ -(zze & 1);\n    }\n    /**\n     * Read a `int64` field, a signed 64-bit varint.\n     */\n    int64() {\n        return protoInt64.dec(...this.varint64());\n    }\n    /**\n     * Read a `uint64` field, an unsigned 64-bit varint.\n     */\n    uint64() {\n        return protoInt64.uDec(...this.varint64());\n    }\n    /**\n     * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.\n     */\n    sint64() {\n        let [lo, hi] = this.varint64();\n        // decode zig zag\n        let s = -(lo & 1);\n        lo = ((lo >>> 1) | ((hi & 1) << 31)) ^ s;\n        hi = (hi >>> 1) ^ s;\n        return protoInt64.dec(lo, hi);\n    }\n    /**\n     * Read a `bool` field, a variant.\n     */\n    bool() {\n        let [lo, hi] = this.varint64();\n        return lo !== 0 || hi !== 0;\n    }\n    /**\n     * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.\n     */\n    fixed32() {\n        return this.view.getUint32((this.pos += 4) - 4, true);\n    }\n    /**\n     * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.\n     */\n    sfixed32() {\n        return this.view.getInt32((this.pos += 4) - 4, true);\n    }\n    /**\n     * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.\n     */\n    fixed64() {\n        return protoInt64.uDec(this.sfixed32(), this.sfixed32());\n    }\n    /**\n     * Read a `fixed64` field, a signed, fixed-length 64-bit integer.\n     */\n    sfixed64() {\n        return protoInt64.dec(this.sfixed32(), this.sfixed32());\n    }\n    /**\n     * Read a `float` field, 32-bit floating point number.\n     */\n    float() {\n        return this.view.getFloat32((this.pos += 4) - 4, true);\n    }\n    /**\n     * Read a `double` field, a 64-bit floating point number.\n     */\n    double() {\n        return this.view.getFloat64((this.pos += 8) - 8, true);\n    }\n    /**\n     * Read a `bytes` field, length-delimited arbitrary data.\n     */\n    bytes() {\n        let len = this.uint32(), start = this.pos;\n        this.pos += len;\n        this.assertBounds();\n        return this.buf.subarray(start, start + len);\n    }\n    /**\n     * Read a `string` field, length-delimited data converted to UTF-8 text.\n     */\n    string() {\n        return this.decodeUtf8(this.bytes());\n    }\n}\n/**\n * Assert a valid signed protobuf 32-bit integer as a number or string.\n */\nfunction assertInt32(arg) {\n    if (typeof arg == \"string\") {\n        arg = Number(arg);\n    }\n    else if (typeof arg != \"number\") {\n        throw new Error(\"invalid int32: \" + typeof arg);\n    }\n    if (!Number.isInteger(arg) ||\n        arg > INT32_MAX ||\n        arg < INT32_MIN)\n        throw new Error(\"invalid int32: \" + arg);\n}\n/**\n * Assert a valid unsigned protobuf 32-bit integer as a number or string.\n */\nfunction assertUInt32(arg) {\n    if (typeof arg == \"string\") {\n        arg = Number(arg);\n    }\n    else if (typeof arg != \"number\") {\n        throw new Error(\"invalid uint32: \" + typeof arg);\n    }\n    if (!Number.isInteger(arg) ||\n        arg > UINT32_MAX ||\n        arg < 0)\n        throw new Error(\"invalid uint32: \" + arg);\n}\n/**\n * Assert a valid protobuf float value as a number or string.\n */\nfunction assertFloat32(arg) {\n    if (typeof arg == \"string\") {\n        const o = arg;\n        arg = Number(arg);\n        if (isNaN(arg) && o !== \"NaN\") {\n            throw new Error(\"invalid float32: \" + o);\n        }\n    }\n    else if (typeof arg != \"number\") {\n        throw new Error(\"invalid float32: \" + typeof arg);\n    }\n    if (Number.isFinite(arg) &&\n        (arg > FLOAT32_MAX || arg < FLOAT32_MIN))\n        throw new Error(\"invalid float32: \" + arg);\n}\n", "// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n//   protoc-gen-ts_proto  v2.7.5\n//   protoc               v6.31.1\n// source: graphene/metrics.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\n\n/** Operating system type - prefixed with OS_ to avoid NDK definition conflict. */\nexport enum OsType {\n  UNKNOWN_OS_TYPE = 0,\n  OS_IOS = 1,\n  OS_ANDROID = 2,\n  OS_WEB = 3,\n  OS_SDK_IOS = 4,\n  OS_SDK_ANDROID = 5,\n  OS_SNAPOS = 6,\n  UNRECOGNIZED = -1,\n}\n\nexport function osTypeFromJSON(object: any): OsType {\n  switch (object) {\n    case 0:\n    case \"UNKNOWN_OS_TYPE\":\n      return OsType.UNKNOWN_OS_TYPE;\n    case 1:\n    case \"OS_IOS\":\n      return OsType.OS_IOS;\n    case 2:\n    case \"OS_ANDROID\":\n      return OsType.OS_ANDROID;\n    case 3:\n    case \"OS_WEB\":\n      return OsType.OS_WEB;\n    case 4:\n    case \"OS_SDK_IOS\":\n      return OsType.OS_SDK_IOS;\n    case 5:\n    case \"OS_SDK_ANDROID\":\n      return OsType.OS_SDK_ANDROID;\n    case 6:\n    case \"OS_SNAPOS\":\n      return OsType.OS_SNAPOS;\n    case -1:\n    case \"UNRECOGNIZED\":\n    default:\n      return OsType.UNRECOGNIZED;\n  }\n}\n\nexport function osTypeToJSON(object: OsType): string {\n  switch (object) {\n    case OsType.UNKNOWN_OS_TYPE:\n      return \"UNKNOWN_OS_TYPE\";\n    case OsType.OS_IOS:\n      return \"OS_IOS\";\n    case OsType.OS_ANDROID:\n      return \"OS_ANDROID\";\n    case OsType.OS_WEB:\n      return \"OS_WEB\";\n    case OsType.OS_SDK_IOS:\n      return \"OS_SDK_IOS\";\n    case OsType.OS_SDK_ANDROID:\n      return \"OS_SDK_ANDROID\";\n    case OsType.OS_SNAPOS:\n      return \"OS_SNAPOS\";\n    case OsType.UNRECOGNIZED:\n    default:\n      return \"UNRECOGNIZED\";\n  }\n}\n\nexport interface AppVersion {\n  versionNumber:\n    | AppVersion_VersionNumber\n    | undefined;\n  /** build flavor DEBUG, CANARY, ALPHA, MASTER */\n  flavor: string;\n  /** SNAPSHOT, OG, MUSHROOM see Blizzard Schema's AppVariantType https://snapchat.quip.com/UVHDA0J59IDz */\n  variant: string;\n}\n\n/** Deconstructed app version values (e.g 10.32.0.41512) */\nexport interface AppVersion_VersionNumber {\n  major: number;\n  minor: number;\n  patch: number;\n  build: number;\n}\n\n/** Used to represent multi-value collections - i.e buffers of timers/histograms (levels) */\nexport interface Metric {\n  /** key string (32 bytes max) */\n  partitionName: string;\n  /** value string (32 bytes max) */\n  metricName: string;\n  /** max 5 custom dimensions (32 bytes key to 100 byte mapping) */\n  customDimensions: { [key: string]: string };\n  /**\n   * Bound collection of values\n   * Units unspecified in transit - this depends on interpretation by the consumer/producer\n   * Scalar aggregate outputs i.e will have only 1 value (i.e summed up counter values)\n   */\n  values: number[];\n}\n\nexport interface Metric_CustomDimensionsEntry {\n  key: string;\n  value: string;\n}\n\n/** Frames may be flushed abitrarily on the client depending on client buffer size/timing */\nexport interface MetricFrame {\n  timers: Metric[];\n  counters: Metric[];\n  levels: Metric[];\n  /** protocol version of client measure - this is a compile time constant */\n  protocolVersion: number;\n  /**\n   * timestamp of first sampled metric in frame.\n   * milliseconds since epoch.\n   */\n  bufferStartTimestampMillis: number;\n  /**\n   * timestamp of last sampled metric in frame.\n   * milliseconds since epoch.\n   */\n  bufferEndTimestampMillis: number;\n  /** App Version encoded - this value will be the same on all requests from the same client binary */\n  appVersion:\n    | AppVersion\n    | undefined;\n  /** Client identifer - this value will be the same on all requests from the same client binary */\n  clientOsType: OsType;\n  /** User Name - Used for Graphene AB integration */\n  userName: string;\n  /** Sampling ID - Sampling basis data for RTAM */\n  samplingId: number;\n  /** User GUID - Used for Graphene AB integration */\n  userGuid: string;\n  /** AB C4 Token used to figure out what AB studies the user is part of, for Graphene AB joining. Should be small in size, around 100 bytes or so. */\n  abC4Token: Uint8Array;\n  /**\n   * Opaque data about the clients COF configuration which is used by RTAM to\n   * control server-side metrics generation such as AB experiments, rollout configuration metrics, etc.\n   * Clients should never try to inspect this data.\n   */\n  cofContext: Uint8Array;\n}\n\nfunction createBaseAppVersion(): AppVersion {\n  return { versionNumber: undefined, flavor: \"\", variant: \"\" };\n}\n\nexport const AppVersion: MessageFns<AppVersion> = {\n  encode(message: AppVersion, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n    if (message.versionNumber !== undefined) {\n      AppVersion_VersionNumber.encode(message.versionNumber, writer.uint32(10).fork()).join();\n    }\n    if (message.flavor !== \"\") {\n      writer.uint32(18).string(message.flavor);\n    }\n    if (message.variant !== \"\") {\n      writer.uint32(26).string(message.variant);\n    }\n    return writer;\n  },\n\n  decode(input: BinaryReader | Uint8Array, length?: number): AppVersion {\n    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n    const end = length === undefined ? reader.len : reader.pos + length;\n    const message = createBaseAppVersion();\n    while (reader.pos < end) {\n      const tag = reader.uint32();\n      switch (tag >>> 3) {\n        case 1: {\n          if (tag !== 10) {\n            break;\n          }\n\n          message.versionNumber = AppVersion_VersionNumber.decode(reader, reader.uint32());\n          continue;\n        }\n        case 2: {\n          if (tag !== 18) {\n            break;\n          }\n\n          message.flavor = reader.string();\n          continue;\n        }\n        case 3: {\n          if (tag !== 26) {\n            break;\n          }\n\n          message.variant = reader.string();\n          continue;\n        }\n      }\n      if ((tag & 7) === 4 || tag === 0) {\n        break;\n      }\n      reader.skip(tag & 7);\n    }\n    return message;\n  },\n\n  fromJSON(object: any): AppVersion {\n    return {\n      versionNumber: isSet(object.versionNumber) ? AppVersion_VersionNumber.fromJSON(object.versionNumber) : undefined,\n      flavor: isSet(object.flavor) ? globalThis.String(object.flavor) : \"\",\n      variant: isSet(object.variant) ? globalThis.String(object.variant) : \"\",\n    };\n  },\n\n  toJSON(message: AppVersion): unknown {\n    const obj: any = {};\n    if (message.versionNumber !== undefined) {\n      obj.versionNumber = AppVersion_VersionNumber.toJSON(message.versionNumber);\n    }\n    if (message.flavor !== \"\") {\n      obj.flavor = message.flavor;\n    }\n    if (message.variant !== \"\") {\n      obj.variant = message.variant;\n    }\n    return obj;\n  },\n\n  create<I extends Exact<DeepPartial<AppVersion>, I>>(base?: I): AppVersion {\n    return AppVersion.fromPartial(base ?? ({} as any));\n  },\n  fromPartial<I extends Exact<DeepPartial<AppVersion>, I>>(object: I): AppVersion {\n    const message = createBaseAppVersion();\n    message.versionNumber = (object.versionNumber !== undefined && object.versionNumber !== null)\n      ? AppVersion_VersionNumber.fromPartial(object.versionNumber)\n      : undefined;\n    message.flavor = object.flavor ?? \"\";\n    message.variant = object.variant ?? \"\";\n    return message;\n  },\n};\n\nfunction createBaseAppVersion_VersionNumber(): AppVersion_VersionNumber {\n  return { major: 0, minor: 0, patch: 0, build: 0 };\n}\n\nexport const AppVersion_VersionNumber: MessageFns<AppVersion_VersionNumber> = {\n  encode(message: AppVersion_VersionNumber, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n    if (message.major !== 0) {\n      writer.uint32(8).int32(message.major);\n    }\n    if (message.minor !== 0) {\n      writer.uint32(16).int32(message.minor);\n    }\n    if (message.patch !== 0) {\n      writer.uint32(24).int32(message.patch);\n    }\n    if (message.build !== 0) {\n      writer.uint32(32).int32(message.build);\n    }\n    return writer;\n  },\n\n  decode(input: BinaryReader | Uint8Array, length?: number): AppVersion_VersionNumber {\n    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n    const end = length === undefined ? reader.len : reader.pos + length;\n    const message = createBaseAppVersion_VersionNumber();\n    while (reader.pos < end) {\n      const tag = reader.uint32();\n      switch (tag >>> 3) {\n        case 1: {\n          if (tag !== 8) {\n            break;\n          }\n\n          message.major = reader.int32();\n          continue;\n        }\n        case 2: {\n          if (tag !== 16) {\n            break;\n          }\n\n          message.minor = reader.int32();\n          continue;\n        }\n        case 3: {\n          if (tag !== 24) {\n            break;\n          }\n\n          message.patch = reader.int32();\n          continue;\n        }\n        case 4: {\n          if (tag !== 32) {\n            break;\n          }\n\n          message.build = reader.int32();\n          continue;\n        }\n      }\n      if ((tag & 7) === 4 || tag === 0) {\n        break;\n      }\n      reader.skip(tag & 7);\n    }\n    return message;\n  },\n\n  fromJSON(object: any): AppVersion_VersionNumber {\n    return {\n      major: isSet(object.major) ? globalThis.Number(object.major) : 0,\n      minor: isSet(object.minor) ? globalThis.Number(object.minor) : 0,\n      patch: isSet(object.patch) ? globalThis.Number(object.patch) : 0,\n      build: isSet(object.build) ? globalThis.Number(object.build) : 0,\n    };\n  },\n\n  toJSON(message: AppVersion_VersionNumber): unknown {\n    const obj: any = {};\n    if (message.major !== 0) {\n      obj.major = Math.round(message.major);\n    }\n    if (message.minor !== 0) {\n      obj.minor = Math.round(message.minor);\n    }\n    if (message.patch !== 0) {\n      obj.patch = Math.round(message.patch);\n    }\n    if (message.build !== 0) {\n      obj.build = Math.round(message.build);\n    }\n    return obj;\n  },\n\n  create<I extends Exact<DeepPartial<AppVersion_VersionNumber>, I>>(base?: I): AppVersion_VersionNumber {\n    return AppVersion_VersionNumber.fromPartial(base ?? ({} as any));\n  },\n  fromPartial<I extends Exact<DeepPartial<AppVersion_VersionNumber>, I>>(object: I): AppVersion_VersionNumber {\n    const message = createBaseAppVersion_VersionNumber();\n    message.major = object.major ?? 0;\n    message.minor = object.minor ?? 0;\n    message.patch = object.patch ?? 0;\n    message.build = object.build ?? 0;\n    return message;\n  },\n};\n\nfunction createBaseMetric(): Metric {\n  return { partitionName: \"\", metricName: \"\", customDimensions: {}, values: [] };\n}\n\nexport const Metric: MessageFns<Metric> = {\n  encode(message: Metric, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n    if (message.partitionName !== \"\") {\n      writer.uint32(10).string(message.partitionName);\n    }\n    if (message.metricName !== \"\") {\n      writer.uint32(18).string(message.metricName);\n    }\n    Object.entries(message.customDimensions).forEach(([key, value]) => {\n      Metric_CustomDimensionsEntry.encode({ key: key as any, value }, writer.uint32(26).fork()).join();\n    });\n    writer.uint32(34).fork();\n    for (const v of message.values) {\n      writer.int64(v);\n    }\n    writer.join();\n    return writer;\n  },\n\n  decode(input: BinaryReader | Uint8Array, length?: number): Metric {\n    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n    const end = length === undefined ? reader.len : reader.pos + length;\n    const message = createBaseMetric();\n    while (reader.pos < end) {\n      const tag = reader.uint32();\n      switch (tag >>> 3) {\n        case 1: {\n          if (tag !== 10) {\n            break;\n          }\n\n          message.partitionName = reader.string();\n          continue;\n        }\n        case 2: {\n          if (tag !== 18) {\n            break;\n          }\n\n          message.metricName = reader.string();\n          continue;\n        }\n        case 3: {\n          if (tag !== 26) {\n            break;\n          }\n\n          const entry3 = Metric_CustomDimensionsEntry.decode(reader, reader.uint32());\n          if (entry3.value !== undefined) {\n            message.customDimensions[entry3.key] = entry3.value;\n          }\n          continue;\n        }\n        case 4: {\n          if (tag === 32) {\n            message.values.push(longToNumber(reader.int64()));\n\n            continue;\n          }\n\n          if (tag === 34) {\n            const end2 = reader.uint32() + reader.pos;\n            while (reader.pos < end2) {\n              message.values.push(longToNumber(reader.int64()));\n            }\n\n            continue;\n          }\n\n          break;\n        }\n      }\n      if ((tag & 7) === 4 || tag === 0) {\n        break;\n      }\n      reader.skip(tag & 7);\n    }\n    return message;\n  },\n\n  fromJSON(object: any): Metric {\n    return {\n      partitionName: isSet(object.partitionName) ? globalThis.String(object.partitionName) : \"\",\n      metricName: isSet(object.metricName) ? globalThis.String(object.metricName) : \"\",\n      customDimensions: isObject(object.customDimensions)\n        ? Object.entries(object.customDimensions).reduce<{ [key: string]: string }>((acc, [key, value]) => {\n          acc[key] = String(value);\n          return acc;\n        }, {})\n        : {},\n      values: globalThis.Array.isArray(object?.values) ? object.values.map((e: any) => globalThis.Number(e)) : [],\n    };\n  },\n\n  toJSON(message: Metric): unknown {\n    const obj: any = {};\n    if (message.partitionName !== \"\") {\n      obj.partitionName = message.partitionName;\n    }\n    if (message.metricName !== \"\") {\n      obj.metricName = message.metricName;\n    }\n    if (message.customDimensions) {\n      const entries = Object.entries(message.customDimensions);\n      if (entries.length > 0) {\n        obj.customDimensions = {};\n        entries.forEach(([k, v]) => {\n          obj.customDimensions[k] = v;\n        });\n      }\n    }\n    if (message.values?.length) {\n      obj.values = message.values.map((e) => Math.round(e));\n    }\n    return obj;\n  },\n\n  create<I extends Exact<DeepPartial<Metric>, I>>(base?: I): Metric {\n    return Metric.fromPartial(base ?? ({} as any));\n  },\n  fromPartial<I extends Exact<DeepPartial<Metric>, I>>(object: I): Metric {\n    const message = createBaseMetric();\n    message.partitionName = object.partitionName ?? \"\";\n    message.metricName = object.metricName ?? \"\";\n    message.customDimensions = Object.entries(object.customDimensions ?? {}).reduce<{ [key: string]: string }>(\n      (acc, [key, value]) => {\n        if (value !== undefined) {\n          acc[key] = globalThis.String(value);\n        }\n        return acc;\n      },\n      {},\n    );\n    message.values = object.values?.map((e) => e) || [];\n    return message;\n  },\n};\n\nfunction createBaseMetric_CustomDimensionsEntry(): Metric_CustomDimensionsEntry {\n  return { key: \"\", value: \"\" };\n}\n\nexport const Metric_CustomDimensionsEntry: MessageFns<Metric_CustomDimensionsEntry> = {\n  encode(message: Metric_CustomDimensionsEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n    if (message.key !== \"\") {\n      writer.uint32(10).string(message.key);\n    }\n    if (message.value !== \"\") {\n      writer.uint32(18).string(message.value);\n    }\n    return writer;\n  },\n\n  decode(input: BinaryReader | Uint8Array, length?: number): Metric_CustomDimensionsEntry {\n    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n    const end = length === undefined ? reader.len : reader.pos + length;\n    const message = createBaseMetric_CustomDimensionsEntry();\n    while (reader.pos < end) {\n      const tag = reader.uint32();\n      switch (tag >>> 3) {\n        case 1: {\n          if (tag !== 10) {\n            break;\n          }\n\n          message.key = reader.string();\n          continue;\n        }\n        case 2: {\n          if (tag !== 18) {\n            break;\n          }\n\n          message.value = reader.string();\n          continue;\n        }\n      }\n      if ((tag & 7) === 4 || tag === 0) {\n        break;\n      }\n      reader.skip(tag & 7);\n    }\n    return message;\n  },\n\n  fromJSON(object: any): Metric_CustomDimensionsEntry {\n    return {\n      key: isSet(object.key) ? globalThis.String(object.key) : \"\",\n      value: isSet(object.value) ? globalThis.String(object.value) : \"\",\n    };\n  },\n\n  toJSON(message: Metric_CustomDimensionsEntry): unknown {\n    const obj: any = {};\n    if (message.key !== \"\") {\n      obj.key = message.key;\n    }\n    if (message.value !== \"\") {\n      obj.value = message.value;\n    }\n    return obj;\n  },\n\n  create<I extends Exact<DeepPartial<Metric_CustomDimensionsEntry>, I>>(base?: I): Metric_CustomDimensionsEntry {\n    return Metric_CustomDimensionsEntry.fromPartial(base ?? ({} as any));\n  },\n  fromPartial<I extends Exact<DeepPartial<Metric_CustomDimensionsEntry>, I>>(object: I): Metric_CustomDimensionsEntry {\n    const message = createBaseMetric_CustomDimensionsEntry();\n    message.key = object.key ?? \"\";\n    message.value = object.value ?? \"\";\n    return message;\n  },\n};\n\nfunction createBaseMetricFrame(): MetricFrame {\n  return {\n    timers: [],\n    counters: [],\n    levels: [],\n    protocolVersion: 0,\n    bufferStartTimestampMillis: 0,\n    bufferEndTimestampMillis: 0,\n    appVersion: undefined,\n    clientOsType: 0,\n    userName: \"\",\n    samplingId: 0,\n    userGuid: \"\",\n    abC4Token: new Uint8Array(0),\n    cofContext: new Uint8Array(0),\n  };\n}\n\nexport const MetricFrame: MessageFns<MetricFrame> = {\n  encode(message: MetricFrame, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n    for (const v of message.timers) {\n      Metric.encode(v!, writer.uint32(10).fork()).join();\n    }\n    for (const v of message.counters) {\n      Metric.encode(v!, writer.uint32(18).fork()).join();\n    }\n    for (const v of message.levels) {\n      Metric.encode(v!, writer.uint32(26).fork()).join();\n    }\n    if (message.protocolVersion !== 0) {\n      writer.uint32(32).uint32(message.protocolVersion);\n    }\n    if (message.bufferStartTimestampMillis !== 0) {\n      writer.uint32(40).uint64(message.bufferStartTimestampMillis);\n    }\n    if (message.bufferEndTimestampMillis !== 0) {\n      writer.uint32(48).uint64(message.bufferEndTimestampMillis);\n    }\n    if (message.appVersion !== undefined) {\n      AppVersion.encode(message.appVersion, writer.uint32(58).fork()).join();\n    }\n    if (message.clientOsType !== 0) {\n      writer.uint32(64).int32(message.clientOsType);\n    }\n    if (message.userName !== \"\") {\n      writer.uint32(74).string(message.userName);\n    }\n    if (message.samplingId !== 0) {\n      writer.uint32(85).fixed32(message.samplingId);\n    }\n    if (message.userGuid !== \"\") {\n      writer.uint32(90).string(message.userGuid);\n    }\n    if (message.abC4Token.length !== 0) {\n      writer.uint32(98).bytes(message.abC4Token);\n    }\n    if (message.cofContext.length !== 0) {\n      writer.uint32(114).bytes(message.cofContext);\n    }\n    return writer;\n  },\n\n  decode(input: BinaryReader | Uint8Array, length?: number): MetricFrame {\n    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n    const end = length === undefined ? reader.len : reader.pos + length;\n    const message = createBaseMetricFrame();\n    while (reader.pos < end) {\n      const tag = reader.uint32();\n      switch (tag >>> 3) {\n        case 1: {\n          if (tag !== 10) {\n            break;\n          }\n\n          message.timers.push(Metric.decode(reader, reader.uint32()));\n          continue;\n        }\n        case 2: {\n          if (tag !== 18) {\n            break;\n          }\n\n          message.counters.push(Metric.decode(reader, reader.uint32()));\n          continue;\n        }\n        case 3: {\n          if (tag !== 26) {\n            break;\n          }\n\n          message.levels.push(Metric.decode(reader, reader.uint32()));\n          continue;\n        }\n        case 4: {\n          if (tag !== 32) {\n            break;\n          }\n\n          message.protocolVersion = reader.uint32();\n          continue;\n        }\n        case 5: {\n          if (tag !== 40) {\n            break;\n          }\n\n          message.bufferStartTimestampMillis = longToNumber(reader.uint64());\n          continue;\n        }\n        case 6: {\n          if (tag !== 48) {\n            break;\n          }\n\n          message.bufferEndTimestampMillis = longToNumber(reader.uint64());\n          continue;\n        }\n        case 7: {\n          if (tag !== 58) {\n            break;\n          }\n\n          message.appVersion = AppVersion.decode(reader, reader.uint32());\n          continue;\n        }\n        case 8: {\n          if (tag !== 64) {\n            break;\n          }\n\n          message.clientOsType = reader.int32() as any;\n          continue;\n        }\n        case 9: {\n          if (tag !== 74) {\n            break;\n          }\n\n          message.userName = reader.string();\n          continue;\n        }\n        case 10: {\n          if (tag !== 85) {\n            break;\n          }\n\n          message.samplingId = reader.fixed32();\n          continue;\n        }\n        case 11: {\n          if (tag !== 90) {\n            break;\n          }\n\n          message.userGuid = reader.string();\n          continue;\n        }\n        case 12: {\n          if (tag !== 98) {\n            break;\n          }\n\n          message.abC4Token = reader.bytes();\n          continue;\n        }\n        case 14: {\n          if (tag !== 114) {\n            break;\n          }\n\n          message.cofContext = reader.bytes();\n          continue;\n        }\n      }\n      if ((tag & 7) === 4 || tag === 0) {\n        break;\n      }\n      reader.skip(tag & 7);\n    }\n    return message;\n  },\n\n  fromJSON(object: any): MetricFrame {\n    return {\n      timers: globalThis.Array.isArray(object?.timers) ? object.timers.map((e: any) => Metric.fromJSON(e)) : [],\n      counters: globalThis.Array.isArray(object?.counters) ? object.counters.map((e: any) => Metric.fromJSON(e)) : [],\n      levels: globalThis.Array.isArray(object?.levels) ? object.levels.map((e: any) => Metric.fromJSON(e)) : [],\n      protocolVersion: isSet(object.protocolVersion) ? globalThis.Number(object.protocolVersion) : 0,\n      bufferStartTimestampMillis: isSet(object.bufferStartTimestampMillis)\n        ? globalThis.Number(object.bufferStartTimestampMillis)\n        : 0,\n      bufferEndTimestampMillis: isSet(object.bufferEndTimestampMillis)\n        ? globalThis.Number(object.bufferEndTimestampMillis)\n        : 0,\n      appVersion: isSet(object.appVersion) ? AppVersion.fromJSON(object.appVersion) : undefined,\n      clientOsType: isSet(object.clientOsType) ? osTypeFromJSON(object.clientOsType) : 0,\n      userName: isSet(object.userName) ? globalThis.String(object.userName) : \"\",\n      samplingId: isSet(object.samplingId) ? globalThis.Number(object.samplingId) : 0,\n      userGuid: isSet(object.userGuid) ? globalThis.String(object.userGuid) : \"\",\n      abC4Token: isSet(object.abC4Token) ? bytesFromBase64(object.abC4Token) : new Uint8Array(0),\n      cofContext: isSet(object.cofContext) ? bytesFromBase64(object.cofContext) : new Uint8Array(0),\n    };\n  },\n\n  toJSON(message: MetricFrame): unknown {\n    const obj: any = {};\n    if (message.timers?.length) {\n      obj.timers = message.timers.map((e) => Metric.toJSON(e));\n    }\n    if (message.counters?.length) {\n      obj.counters = message.counters.map((e) => Metric.toJSON(e));\n    }\n    if (message.levels?.length) {\n      obj.levels = message.levels.map((e) => Metric.toJSON(e));\n    }\n    if (message.protocolVersion !== 0) {\n      obj.protocolVersion = Math.round(message.protocolVersion);\n    }\n    if (message.bufferStartTimestampMillis !== 0) {\n      obj.bufferStartTimestampMillis = Math.round(message.bufferStartTimestampMillis);\n    }\n    if (message.bufferEndTimestampMillis !== 0) {\n      obj.bufferEndTimestampMillis = Math.round(message.bufferEndTimestampMillis);\n    }\n    if (message.appVersion !== undefined) {\n      obj.appVersion = AppVersion.toJSON(message.appVersion);\n    }\n    if (message.clientOsType !== 0) {\n      obj.clientOsType = osTypeToJSON(message.clientOsType);\n    }\n    if (message.userName !== \"\") {\n      obj.userName = message.userName;\n    }\n    if (message.samplingId !== 0) {\n      obj.samplingId = Math.round(message.samplingId);\n    }\n    if (message.userGuid !== \"\") {\n      obj.userGuid = message.userGuid;\n    }\n    if (message.abC4Token.length !== 0) {\n      obj.abC4Token = base64FromBytes(message.abC4Token);\n    }\n    if (message.cofContext.length !== 0) {\n      obj.cofContext = base64FromBytes(message.cofContext);\n    }\n    return obj;\n  },\n\n  create<I extends Exact<DeepPartial<MetricFrame>, I>>(base?: I): MetricFrame {\n    return MetricFrame.fromPartial(base ?? ({} as any));\n  },\n  fromPartial<I extends Exact<DeepPartial<MetricFrame>, I>>(object: I): MetricFrame {\n    const message = createBaseMetricFrame();\n    message.timers = object.timers?.map((e) => Metric.fromPartial(e)) || [];\n    message.counters = object.counters?.map((e) => Metric.fromPartial(e)) || [];\n    message.levels = object.levels?.map((e) => Metric.fromPartial(e)) || [];\n    message.protocolVersion = object.protocolVersion ?? 0;\n    message.bufferStartTimestampMillis = object.bufferStartTimestampMillis ?? 0;\n    message.bufferEndTimestampMillis = object.bufferEndTimestampMillis ?? 0;\n    message.appVersion = (object.appVersion !== undefined && object.appVersion !== null)\n      ? AppVersion.fromPartial(object.appVersion)\n      : undefined;\n    message.clientOsType = object.clientOsType ?? 0;\n    message.userName = object.userName ?? \"\";\n    message.samplingId = object.samplingId ?? 0;\n    message.userGuid = object.userGuid ?? \"\";\n    message.abC4Token = object.abC4Token ?? new Uint8Array(0);\n    message.cofContext = object.cofContext ?? new Uint8Array(0);\n    return message;\n  },\n};\n\nfunction bytesFromBase64(b64: string): Uint8Array {\n  if ((globalThis as any).Buffer) {\n    return Uint8Array.from(globalThis.Buffer.from(b64, \"base64\"));\n  } else {\n    const bin = globalThis.atob(b64);\n    const arr = new Uint8Array(bin.length);\n    for (let i = 0; i < bin.length; ++i) {\n      arr[i] = bin.charCodeAt(i);\n    }\n    return arr;\n  }\n}\n\nfunction base64FromBytes(arr: Uint8Array): string {\n  if ((globalThis as any).Buffer) {\n    return globalThis.Buffer.from(arr).toString(\"base64\");\n  } else {\n    const bin: string[] = [];\n    arr.forEach((byte) => {\n      bin.push(globalThis.String.fromCharCode(byte));\n    });\n    return globalThis.btoa(bin.join(\"\"));\n  }\n}\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n  : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n  : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n  : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n  : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n  : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n  const num = globalThis.Number(int64.toString());\n  if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n    throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n  }\n  if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n    throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n  }\n  return num;\n}\n\nfunction isObject(value: any): boolean {\n  return typeof value === \"object\" && value !== null;\n}\n\nfunction isSet(value: any): boolean {\n  return value !== null && value !== undefined;\n}\n\ninterface MessageFns<T> {\n  encode(message: T, writer?: BinaryWriter): BinaryWriter;\n  decode(input: BinaryReader | Uint8Array, length?: number): T;\n  fromJSON(object: any): T;\n  toJSON(message: T): unknown;\n  create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n  fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n", "import { AuthType, type Config } from '@snapchat/metrics-utils';\nimport { WebAuthenticator } from '../auth/WebAuthenticator';\nimport {\n  WebMetricCollector,\n  type WebMetricCollectorOptions,\n} from '../collector/WebMetricCollector';\n\n/** Network config for RTAM server (for web metrics) */\nexport const getWebConfig = (collectorOptions: WebMetricCollectorOptions): Config => ({\n  protocol: 'https:',\n  host: 'gcp.api.snapchat.com',\n  path: '/web/metrics',\n  headers: {\n    'Content-Type': 'application/x-protobuf',\n  },\n  authType: AuthType.WebAttestation,\n  authenticator: new WebAuthenticator(),\n  collector: new WebMetricCollector(collectorOptions),\n});\n", "import { Authenticator, AuthType, type HeaderMap } from '@snapchat/metrics-utils';\nimport { computeWebAttestation } from './computeWebAttestation';\n\nexport const webAttestationHeader = 'X-Snapchat-Web-Client-Auth';\n\nexport class WebAuthenticator extends Authenticator {\n  async authRequest(\n    authType: AuthType,\n    payload: Uint8Array,\n    headers: HeaderMap\n  ): Promise<HeaderMap> {\n    switch (authType) {\n      case AuthType.None: {\n        return headers;\n      }\n      case AuthType.WebAttestation: {\n        const webAttestationHeaderBase64 = await computeWebAttestation(payload);\n        return {\n          ...headers,\n          [webAttestationHeader]: webAttestationHeaderBase64,\n        };\n      }\n      default: {\n        throw new Error(`Unsupported auth type: ${authType}`);\n      }\n    }\n  }\n}\n", "import { isInBrowser, inlineBtoa } from '@snapchat/metrics-utils';\nimport { sha256 } from '@snapchat/hash';\n\n/**\n * Convert unsigned byte array into SHA-256 hashed string\n *\n * @param binaryPayload: Uint8Array unsigned byte array\n * @returns String. Base64 encoded SHA-256 Hash based on the byte array + `:<current_timestamp>`.\n */\nexport const computeWebAttestation = async (binaryPayload: Uint8Array): Promise<string> => {\n  const hashString = await sha256(binaryPayload);\n  const headerString = `${hashString}:${Date.now()}`;\n  return isInBrowser() ? btoa(headerString) : inlineBtoa(headerString);\n};\n", "import { css } from '@emotion/css';\nimport { m, mobileMediaQuery } from '@snapchat/snap-design-system-marketing';\n\nexport const customLocaleDropdownButtonCss = css`\n  align-items: center;\n  background-color: white;\n  border-radius: 25px;\n  border: 2px solid ${m('--fg-color')};\n  color: ${m('--fg-color')};\n  cursor: pointer;\n  display: flex;\n  /* Set font-family here or the var from the default motif is used */\n  font-family: ${m('--font-family')};\n  font-size: 14px;\n  font-weight: 500;\n  height: 42px;\n  justify-content: space-between;\n  min-width: 160px;\n  padding: ${m('--spacing-s')} ${m('--spacing-m')};\n\n  ${mobileMediaQuery} {\n    width: 100%;\n  }\n`;\n\nexport const dropdownButtonIconCss = css`\n  margin-left: ${m('--spacing-s')};\n  transition: transform 250ms;\n  transform: rotate(0deg); /* 'up' */\n  fill: ${m('--fg-color')};\n`;\n\nexport const dropdownButtonIconDownCss = css`\n  transform: rotate(180deg); /* 'down' */\n`;\n", "import { cx } from '@emotion/css';\nimport {\n  type DropdownMenuButtonProps,\n  Icon,\n  MotifScheme,\n} from '@snapchat/snap-design-system-marketing';\nimport type { FC } from 'react';\n\nimport {\n  customLocaleDropdownButtonCss,\n  dropdownButtonIconCss,\n  dropdownButtonIconDownCss,\n} from './CustomLocaleDropdown.styles';\n\n/**\n * Custom button for phase 1 of snap.com we can get most of the way there by actually updating\n * motif, but not doing that for phase 1.\n */\nexport const CustomLocaleDropdownButton: FC<DropdownMenuButtonProps> = ({\n  children,\n  onClick,\n  isExpanded,\n  ariaLabel,\n}) => (\n  <button\n    type=\"button\"\n    role=\"combobox\"\n    className={cx(MotifScheme.DEFAULT, customLocaleDropdownButtonCss)}\n    onClick={onClick}\n    aria-expanded={isExpanded}\n    aria-label={ariaLabel}\n  >\n    {children}\n    <Icon\n      size={20}\n      className={cx(dropdownButtonIconCss, { [dropdownButtonIconDownCss]: isExpanded })}\n      name=\"arrow\"\n    />\n  </button>\n);\n", "import {\n  FontFamily,\n  snapFooterCss,\n  snapHeaderCss,\n  Template,\n} from '@snapchat/snap-design-system-marketing';\n\nimport type { BrandPropOverrides, SiteConfiguration } from '../../configTypes';\nimport { CustomLocaleDropdownButton } from './CustomLocaleDropdownButton/CustomLocaleDropdownButton';\n\n/**\n * Shared theme configuration for Snap branded sites. This is used to maintain consistency across\n * all Snap branded sites.\n */\nexport const snapSiteConfigTheme: SiteConfiguration['theme'] = {\n  defaultCarouselOverflowDecoration: true,\n  footerPropsOverride: {\n    customLocaleDropdownButton: CustomLocaleDropdownButton,\n    className: snapFooterCss,\n  },\n  fontSettings: [\n    {\n      name: FontFamily.INTER,\n      stylesheet: 'https://web-platform.snap.com/fonts/font.inter.css',\n      files: [\n        {\n          url: 'https://web-platform.snap.com/fonts/inter/Inter.woff2',\n          type: 'font/woff2',\n        },\n      ],\n    },\n  ],\n  globalNavProps: {\n    defaultGroupKey: 'snap',\n    addBottomBorder: true,\n    lessMargins: true,\n    headerClassName: snapHeaderCss,\n  },\n  breakTemplates: [\n    Template.None,\n    Template.None,\n    Template.None,\n    Template.None,\n    Template.None,\n    Template.None,\n  ],\n  heroBreakTemplate: Template.None,\n};\n\n/**\n * This is a helper object that can be used in site configs to have alternate brand overrides. Used\n * in sandboxConfig to help preview in both configs.\n */\nexport const snapBrandConfigSharedSettings: BrandPropOverrides = {\n  carousel: {\n    defaultCarouselOverflowDecoration: snapSiteConfigTheme.defaultCarouselOverflowDecoration,\n  },\n  header: snapSiteConfigTheme.globalNavProps,\n  footer: snapSiteConfigTheme.footerPropsOverride,\n  page: {\n    breakTemplates: snapSiteConfigTheme.breakTemplates,\n    heroBreakTemplate: snapSiteConfigTheme.heroBreakTemplate,\n  },\n};\n", "import { useContext } from 'react';\n\nimport { AppContext } from '../../AppContext';\nimport { Config } from '../../config';\nimport { SitewideConfigurationContext } from '../../context/SitewideConfiguration/SitewideConfigurationContext';\nimport type { FeatureFlags } from './featureFlagTypes';\nimport { Feature } from './featureFlagTypes';\n\n/** Default values for the feature flags. */\nexport const defaultFeatureFlags: FeatureFlags = {\n  [Feature.TEST_FEATURE]: 'false',\n  [Feature.HOME_REDIRECT]: 'false',\n  [Feature.DISABLE_LAZY_LOAD_LOGGING]: 'false',\n  [Feature.SCROLL_TO_ANCHOR]: 'true',\n  [Feature.EXPERIENCE_ENABLE_ASL_STREAM]: 'true',\n  [Feature.EXPERIENCE_ENABLE_CAPTIONS]: 'true',\n  [Feature.SPS_SHOW_GO_TO_STREAM_BUTTON]: 'false',\n  [Feature.SPS_USE_EVENT_PLAYER]: 'false',\n  [Feature.ENABLE_PIXY_EUROPEAN_STORES]: 'false',\n  [Feature.COOKIE_BASED_BUCKETING]: 'false',\n  [Feature.ENABLE_DEVICE_SPECIFIC_MEDIA]: 'false',\n  [Feature.GLOBAL_NAV_ITEMS_POSITION]: 'right',\n  [Feature.USE_CHART_DROPDOWN_TOGGLE]: 'false',\n  [Feature.CAREERS_ENABLE_JOB_DETAIL_PAGE]: 'false',\n  [Feature.AVALON_ENABLE_CHAT_WIDGET]: 'false',\n  [Feature.ENABLE_SITE_SEARCH]: 'false',\n  [Feature.USE_CONTENT_ACCORDION_ITEMS]: 'true',\n  [Feature.ENABLE_HLS_PLAYBACK]: 'false',\n  [Feature.USE_SNAP_MOTIF]: 'false',\n  [Feature.USE_GHOST_MOTIF]: 'false',\n  [Feature.ENABLE_PERSISTENT_CTA_SCROLL_VISIBILITY]: 'false',\n} as const;\n\n/**\n * Returns the value of FeatureFlags for the current request.\n *\n * Takes into consideration site settings and contentful overrides.\n */\nexport function useFeatureFlags(): FeatureFlags {\n  // Reads URL overrides (non-prod only).\n  const { getCurrentUrl } = useContext(AppContext);\n  const searchParams = new URL(getCurrentUrl()).searchParams;\n  const { sitewideValues } = useContext(SitewideConfigurationContext);\n\n  const featureFlagsEntry = sitewideValues?.featureFlags;\n  const contentfulFeatureFlags = featureFlagsEntry?.featureFlags as FeatureFlags | undefined;\n\n  return combineFeatureFlags(contentfulFeatureFlags, getUrlFeatureFlags(searchParams));\n}\n\n/**\n * Function to combine all feature flags in proper overrided ordering.\n *\n * @param contentfulFeatureFlags Flags sourced from contentful\n * @param urlOverrides Flags sourced from the url parameters\n * @returns\n */\nexport function combineFeatureFlags(\n  contentfulFeatureFlags?: FeatureFlags,\n  urlOverrides?: Partial<FeatureFlags>\n): FeatureFlags {\n  return {\n    // First copy defaults.\n    ...defaultFeatureFlags,\n    // Then use site-specific settings.\n    ...Config.featureFlags,\n    // Thie use contentful overrides.\n    ...contentfulFeatureFlags,\n    // Lastly, apply URL overrides.\n    ...urlOverrides,\n  };\n}\n\n/** Get the feature flags stored in a urls search parameters */\nexport function getUrlFeatureFlags(searchParams: URLSearchParams): Partial<FeatureFlags> {\n  const urlOverrides: Partial<FeatureFlags> = {};\n\n  if (!Config.isDeploymentTypeProd) {\n    for (const feature of Object.keys(defaultFeatureFlags)) {\n      const override = searchParams.get(feature);\n      if (!override) continue;\n      urlOverrides[feature as Feature] = override;\n    }\n  }\n\n  return urlOverrides;\n}\n", "import type { SitewideValues } from '@snapchat/mw-contentful-schema';\nimport { createContext } from 'react';\n\nexport interface SitewideConfigurationContextProps {\n  sitewideValues?: SitewideValues;\n}\n\nexport const SitewideConfigurationContext = createContext<SitewideConfigurationContextProps>({});\n", "import { Partition } from '@snapchat/graphene';\n\nimport { snapSiteConfigTheme } from '../../brands/snap/snapBrandConfigSharedSettings';\nimport { Feature } from '../../components/FeatureFlags';\nimport type { SiteConfiguration } from '../../configTypes';\nimport { LoggingVendor } from '../../helpers/logging/eventListenerTypes';\n\nexport const config: SiteConfiguration = {\n  domainName: 'snap.com',\n\n  featureFlags: {\n    [Feature.USE_SNAP_MOTIF]: 'true',\n  },\n\n  theme: snapSiteConfigTheme,\n  trackingSettings: {\n    eventListeners: [\n      { vendor: LoggingVendor.BLIZZARD },\n      { vendor: LoggingVendor.CONSOLE },\n      { vendor: LoggingVendor.GOOGLE_CLOUD_LOGGING },\n      { vendor: LoggingVendor.GOOGLE_CLOUD_MONITORING },\n      { vendor: LoggingVendor.GOOGLE_CLOUD_ERROR_REPORTING },\n      { vendor: LoggingVendor.GRAPHENE, partitionName: Partition.SNAP_WEB },\n      {\n        vendor: LoggingVendor.GOOGLE_TAG_MANAGER,\n        googleTagManagerId: 'GTM-PB72WQ3',\n        googleAnalyticsId: 'G-LJY98QLWYT',\n      },\n      {\n        vendor: LoggingVendor.SENTRY,\n        projectName: 'snap',\n        dsn: 'https://fdd828e30c9c423cb0653ae452415f77@sentry.sc-prod.net/81',\n      },\n    ],\n  },\n  csp: [\n    // Newsroom block integration\n    {\n      connectSrc: ['https://newsroom.snap.com'],\n    },\n  ],\n};\n", "import {\n  DeploymentType,\n  productionElasticCloudId,\n  productionElasticNode,\n  Site,\n  stagingElasticCloudId,\n  stagingElasticNode,\n} from '@snapchat/mw-common';\nimport { isBrowser } from '@snapchat/mw-common/client';\nimport {\n  ContentfulAlias,\n  contentfulSpaceIds,\n  productionContentTokens,\n} from '@snapchat/mw-contentful-schema';\nimport {\n  globalComponentsAccessToken,\n  globalComponentsEnvName,\n  globalComponentsSpaceId,\n} from '@snapchat/mw-global-components-schema';\nimport { Template } from '@snapchat/snap-design-system-marketing';\n\nimport { clientEnv } from './clientEnv';\nimport type {\n  ContentfulConfiguration,\n  ElasticConfiguration,\n  MarketingWebConfiguration,\n  RequiredTrackingSettings,\n  SiteConfiguration,\n} from './configTypes';\nimport { defaultFontSettings } from './constants/defaultFontSettings';\nimport { getCookieDomain } from './helpers/trackingCookies';\nimport { config as snap523Config } from './sites/523/523Config';\nimport { config as arConfig } from './sites/ar/arConfig';\nimport { config as arcadiaConfig } from './sites/arcadia/arcadiaConfig';\nimport { config as avalonConfig } from './sites/avalon/avalonConfig';\nimport { config as careersConfig } from './sites/careers/careersConfig';\nimport { config as cheeriosConfig } from './sites/cheerios/cheeriosConfig';\nimport { config as citizenConfig } from './sites/citizen/citizenConfig';\nimport { config as creatorsConfig } from './sites/creators/creatorsConfig';\nimport { config as diversityConfig } from './sites/diversity/diversityConfig';\nimport { config as educatorsConfig } from './sites/educators/educatorsConfig';\nimport { config as engBlogConfig } from './sites/eng-blog/engBlogConfig';\nimport { config as experienceConfig } from './sites/experience/experienceConfig';\nimport { config as forBusinessConfig } from './sites/for-business/forBusinessConfig';\nimport { config as newsroomConfig } from './sites/newsroom/newsroomConfig';\nimport { config as parentsConfig } from './sites/parents/parentsConfig';\nimport { config as sandboxConfig } from './sites/sandbox/sandboxConfig';\nimport { config as snapConfig } from './sites/snap/snapConfig';\nimport { config as stinsonConfig } from './sites/stinson/stinsonConfig';\nimport { config as trustConfig } from './sites/trust/trustConfig';\n\nconst environmentNames: Record<DeploymentType, string> = {\n  [DeploymentType.PRODUCTION]: ContentfulAlias.PRODUCTION,\n  [DeploymentType.STAGING]: ContentfulAlias.MASTER,\n  [DeploymentType.LATEST_DEV]: ContentfulAlias.LATEST_DEV,\n};\n\nconst transformTrackingSettings = (site: SiteConfiguration): RequiredTrackingSettings => {\n  return {\n    ...site.trackingSettings,\n    cookieDomain: getCookieDomain(site.domainName, site.trackingSettings.cookieDomain),\n  };\n};\n\nexport const getSiteConfig = (site: Site): SiteConfiguration => {\n  switch (site) {\n    case Site.A523:\n      return snap523Config;\n    case Site.ARCADIA:\n      return arcadiaConfig;\n    case Site.AR:\n      return arConfig;\n    case Site.AVALON:\n      return avalonConfig;\n    case Site.CAREERS:\n      return careersConfig;\n    case Site.CHEERIOS:\n      return cheeriosConfig;\n    case Site.CITIZEN:\n      return citizenConfig;\n    case Site.CREATORS:\n      return creatorsConfig;\n    case Site.DIVERSITY:\n      return diversityConfig;\n    case Site.EDUCATORS:\n      return educatorsConfig;\n    case Site.ENG_BLOG:\n      return engBlogConfig;\n    case Site.EXPERIENCE:\n      return experienceConfig;\n    case Site.FOR_BUSINESS:\n      return forBusinessConfig;\n    case Site.NEWSROOM:\n      return newsroomConfig;\n    case Site.PARENTS:\n      return parentsConfig;\n    case Site.SANDBOX:\n      return sandboxConfig;\n    case Site.STINSON:\n      return stinsonConfig;\n    case Site.TRUST:\n      return trustConfig;\n    case Site.SNAP:\n      return snapConfig;\n    default:\n      break;\n  }\n  throw new Error(\n    `Cannot find config for 'src/sites/${clientEnv.SITE_CONFIG}'. Is it specified correctly in env/\\${SITE}.env?`\n  );\n};\n\n/** Function that merges the site configuration with globally available environment variables. */\nconst createConfig = (): MarketingWebConfiguration => {\n  const requiredEnvVars: (keyof typeof clientEnv)[] = ['NODE_ENV', 'PREVIEW', 'SITE_CONFIG'];\n\n  for (const envVar of requiredEnvVars) {\n    if (!clientEnv[envVar]) {\n      throw Error(\n        `Missing required variable '${envVar}'.\\nOn server, make sure it's in the environment during esbuild execution.\\n`\n      );\n    }\n  }\n\n  const site = clientEnv.SITE_CONFIG as Site;\n  const siteConfig = getSiteConfig(site);\n\n  const isPreview = clientEnv.PREVIEW! === 'true';\n\n  if (isPreview && !clientEnv.CONTENTFUL_PREVIEW_ACCESS_TOKEN) {\n    throw new Error(`Preview access token not set. Do you have 'secrets.env'?`);\n  }\n\n  const isClient = isBrowser();\n  const buildNumber = clientEnv.CI_PIPELINE_ID ?? 'local';\n  const commit = clientEnv.CI_COMMIT ?? 'unknown_commit';\n  // NOTE: This would probably be better checking GAE_VERSION and GAE_SERVICE;\n  // However there's an argument against compiling those into the world readable bundle for\n  // security reasons.\n  const isLocal = buildNumber === 'local';\n  const isTest = !!clientEnv.JEST_WORKER_ID;\n\n  const compilationMode = clientEnv.NODE_ENV === 'production' ? 'production' : 'development';\n  const deploymentType = clientEnv.DEPLOYMENT_TYPE as DeploymentType;\n  const isDeploymentTypeProd = deploymentType === DeploymentType.PRODUCTION;\n  const isCompilationModeProd = compilationMode === 'production';\n  const isSsr = clientEnv.SSR !== 'false'; // Defaults to 'true' so worded as a check for falsehood.\n  const region = clientEnv.GOOGLE_CLOUD_REGION;\n  const googleCloudProjectName = clientEnv.GOOGLE_CLOUD_PROJECT ?? 'entapps-web-dev';\n\n  const contentfulEnvNameOverride =\n    clientEnv.CONTENTFUL_ENVIRONMENT_NAME === 'undefined'\n      ? undefined\n      : clientEnv.CONTENTFUL_ENVIRONMENT_NAME;\n  const contentful: ContentfulConfiguration = {\n    spaceId: contentfulSpaceIds[site],\n    environmentName: contentfulEnvNameOverride ?? environmentNames[deploymentType],\n    accessToken: productionContentTokens[site],\n    devAccessToken: clientEnv.CONTENTFUL_DEV_ACCESS_TOKEN,\n    previewAccessToken: clientEnv.CONTENTFUL_PREVIEW_ACCESS_TOKEN,\n  };\n\n  const contentfulGlobal: ContentfulConfiguration = {\n    spaceId: globalComponentsSpaceId,\n    environmentName: globalComponentsEnvName,\n    accessToken: globalComponentsAccessToken,\n    devAccessToken: clientEnv.GLOBAL_COMPONENTS_CONTENTFUL_DEV_ACCESS_TOKEN,\n    previewAccessToken: clientEnv.GLOBAL_COMPONENTS_CONTENTFUL_PREVIEW_ACCESS_TOKEN,\n  };\n\n  const useLocalElastic = clientEnv.USE_LOCAL_ELASTIC === 'true';\n\n  let elasticConfig: ElasticConfiguration;\n\n  if (useLocalElastic) {\n    elasticConfig = {\n      elasticNode: 'http://localhost:9200',\n      elasticCloudId: undefined,\n      elasticApiKeyOverride: undefined,\n      isApiKeyRequired: false,\n    };\n  } else {\n    const isProduction = deploymentType === DeploymentType.PRODUCTION;\n\n    elasticConfig = {\n      elasticNode:\n        clientEnv.ELASTIC_SERVERLESS_NODE ??\n        (isProduction ? productionElasticNode : stagingElasticNode),\n      elasticCloudId: isProduction ? productionElasticCloudId : stagingElasticCloudId,\n      elasticApiKeyOverride: clientEnv.ELASTIC_SEARCH_READER_API_KEY,\n      isApiKeyRequired: true,\n    };\n  }\n\n  const fontSettings = siteConfig.theme?.fontSettings ?? defaultFontSettings;\n\n  const config: MarketingWebConfiguration = {\n    site,\n    ...siteConfig,\n    theme: {\n      // These are the default breaks.\n      breakTemplates: [\n        Template.Straight,\n        Template.Skirt,\n        Template.Straight,\n        Template.HeadFlipped,\n        Template.Straight,\n        Template.Head,\n      ],\n      fontSettings,\n      ...siteConfig.theme,\n      globalNavProps: {\n        trackingSiteName: siteConfig.domainName,\n        ...siteConfig.theme?.globalNavProps,\n      },\n    },\n    contentful,\n    contentfulGlobal,\n    elastic: elasticConfig,\n    trackingSettings: transformTrackingSettings(siteConfig),\n    compilationMode,\n    isCompilationModeProd,\n    isSSR: isSsr,\n    isPreview,\n    isClient,\n    isLocal,\n    isTest,\n    localeFilter: isPreview ? undefined : siteConfig.localeFilter, // Enable all locales when in Preview mode.\n    homeUrl: `https://${siteConfig.domainName}`,\n    deploymentType,\n    isDeploymentTypeProd,\n    buildNumber,\n    commit,\n    region,\n    googleCloudProjectName,\n  };\n\n  if (siteConfig.init) {\n    siteConfig.init();\n  }\n\n  return config;\n};\n\nexport const Config = createConfig();\n", "/**\n * URL Parameters that override app behavior.\n *\n * Use this for dev purposes only. These should have no behavior on prod.\n */\nexport enum UrlParameter {\n  // NOTE: Techically all of the Feature enums are also in here since they are part of the URL params.\n\n  CONTENTFUL_ENVIRONMENT_NAME = 'contentfulEnvironmentName',\n\n  /**\n   * Overrides apollo behavior. Useful for turning off cache ('no-cache') or ignoring network\n   * ('cache-only').\n   */\n  CONTENTFUL_FETCH_POLICY = 'contentfulFetchPolicy',\n\n  /**\n   * Disables web sockets for the experience site. In an effort to save cost, we don't normally\n   * leave the staging version of the broadcast and bitmoji reaction services running. This flag\n   * allows us to test the experience site without trying (and failing) to connect to those services\n   * when they aren't running.\n   */\n  EXPERIENCE_DISABLE_WEB_SOCKETS = 'experienceDisableWebSockets',\n\n  /** State of the homepage on the experience site. Used for testing and debugging. */\n  EXPERIENCE_EVENT_STATE = 'eventState',\n\n  /**\n   * Used to disable video playing requirement to send bitmoji reactions Purpose: BRS live site\n   * loadtest\n   */\n  EXPERIENCE_REQUIRE_LIVE_VIDEO_FOR_BITMOJI = 'experienceRequireLiveVideo',\n\n  /**\n   * Overrides the final experiment user bucket output determined in `decideExperiment`. Used by\n   * CI/CD pipeline to ensure stable screen-shot tests when an experiment exists, and also in\n   * contentful to let users preview certain variants.\n   */\n  EXPERIMENTS_USER_BUCKET = 'experimentsUserBucket',\n\n  /**\n   * Google Tag Manager Debugging. This flag is appended by GTM Preview feature. When this happens\n   * we want to fire off GTM regardless of user's location because most of our customers are in\n   * California.\n   */\n  GOOGLE_TAG_MANAGER_DEBUG = 'gtm_debug',\n\n  /** Whether to display the debug panel in the lower-right corner. This works in prod. */\n  MWP_DEBUG = 'mwp_debug',\n\n  /**\n   * Overrides the client IP with a hashed version of the IP address. Used for testing purposes with\n   * business personas\n   */\n  OVERRIDE_HASHED_IP = 'overrideHashedIp',\n\n  /** Whether to pause animations, like carousels. Primarily used by release tests. */\n  PAUSE_ANIMATIONS = 'pauseAnimations',\n\n  /** Easter Egg changing the scheme to a custom one (Bynd figma tokens import from 2023-10) */\n  USE_ALTERNATE_MOTIF = 'alternateMotif',\n}\n\nexport const urlParameters: UrlParameter[] = [\n  UrlParameter.CONTENTFUL_ENVIRONMENT_NAME,\n  UrlParameter.CONTENTFUL_FETCH_POLICY,\n  UrlParameter.EXPERIMENTS_USER_BUCKET,\n  UrlParameter.EXPERIENCE_EVENT_STATE,\n  UrlParameter.EXPERIENCE_REQUIRE_LIVE_VIDEO_FOR_BITMOJI,\n  UrlParameter.OVERRIDE_HASHED_IP,\n];\n", "// Based on: https://github.com/pladaria/requestidlecallback-polyfill\n\nexport const requestIdleCallback =\n  globalThis.requestIdleCallback ??\n  ((callback: IdleRequestCallback) => {\n    const start = Date.now();\n    return setTimeout(() => {\n      callback({\n        didTimeout: false,\n        timeRemaining: () => Math.max(0, 50 - (Date.now() - start)),\n      });\n    }, 1);\n  });\n\nexport const cancelIdleCallback =\n  globalThis.cancelIdleCallback ??\n  ((id: number | string) => {\n    clearTimeout(id);\n  });\n\n/** Installs the `requestIdleCallback` and `cancelIdleCallback` pollyfills. */\nexport const polyfillRequestIdleCallback = (): void => {\n  globalThis.requestIdleCallback = requestIdleCallback;\n  globalThis.cancelIdleCallback = cancelIdleCallback;\n};\n", "interface StructuredCloneOptions {\n  transfer?: Transferable[];\n}\n\n/**\n * Determines if the provided object is a Transferable object.\n *\n * Transferable objects are those that can be transferred between different execution contexts (such\n * as between the main thread and web workers) using the structured clone algorithm. This function\n * checks for common transferable types: ArrayBuffer, MessagePort, and ImageBitmap.\n *\n * @param obj - The object to check.\n * @returns True if the object is transferable, false otherwise.\n */\nconst isTransferable = (obj: unknown): obj is Transferable =>\n  obj instanceof ArrayBuffer ||\n  (typeof MessagePort !== 'undefined' && obj instanceof MessagePort) ||\n  (typeof ImageBitmap !== 'undefined' && obj instanceof ImageBitmap);\n\nconst isTypedArray = (obj: unknown): obj is ArrayBufferView =>\n  obj instanceof Int8Array ||\n  obj instanceof Uint8Array ||\n  obj instanceof Uint8ClampedArray ||\n  obj instanceof Int16Array ||\n  obj instanceof Uint16Array ||\n  obj instanceof Int32Array ||\n  obj instanceof Uint32Array ||\n  obj instanceof Float32Array ||\n  obj instanceof Float64Array ||\n  obj instanceof BigInt64Array ||\n  obj instanceof BigUint64Array;\n\nconst cloneTypedArray = (obj: ArrayBufferView): ArrayBufferView => {\n  const typedArrayTypes = [\n    Int8Array,\n    Uint8Array,\n    Uint8ClampedArray,\n    Int16Array,\n    Uint16Array,\n    Int32Array,\n    Uint32Array,\n    Float32Array,\n    Float64Array,\n    BigInt64Array,\n    BigUint64Array,\n  ];\n\n  for (const Constructor of typedArrayTypes) {\n    if (obj instanceof Constructor) {\n      return new Constructor(obj);\n    }\n  }\n\n  throw new Error('Unsupported TypedArray type', { cause: obj });\n};\n\n/**\n * Clones built-in objects such as Date, RegExp, TypedArrays, and Error objects.\n *\n * @param obj - The object to clone.\n * @returns A cloned instance of the built-in object, or null if the object type is not handled.\n */\nconst cloneBuiltins = (obj: object): unknown => {\n  if (obj instanceof Date) return new Date(obj.getTime());\n  if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);\n  if (isTypedArray(obj)) return cloneTypedArray(obj);\n  if (obj instanceof Error) {\n    const clone = new (obj.constructor as ErrorConstructor)(obj.message);\n    clone.stack = obj.stack;\n    return clone;\n  }\n  return null;\n};\n\nconst cloneCollection = (\n  obj: object,\n  transferSet: Set<Transferable>,\n  cloneMap: WeakMap<object, unknown>\n): unknown => {\n  if (obj instanceof Map) {\n    const clone = new Map();\n    cloneMap.set(obj, clone);\n    for (const [key, val] of obj) {\n      clone.set(\n        internalClone(key, transferSet, cloneMap),\n        internalClone(val, transferSet, cloneMap)\n      );\n    }\n    return clone;\n  }\n\n  if (obj instanceof Set) {\n    const clone = new Set();\n    cloneMap.set(obj, clone);\n    for (const val of obj) {\n      clone.add(internalClone(val, transferSet, cloneMap));\n    }\n    return clone;\n  }\n\n  return null;\n};\n\nconst internalClone = (\n  obj: unknown,\n  transferSet: Set<Transferable>,\n  cloneMap: WeakMap<object, unknown>\n): unknown => {\n  // Handle error cases first\n  if (typeof obj === 'function') throw new Error('Functions cannot be cloned', { cause: obj });\n  if (typeof obj === 'symbol') throw new Error('Symbols cannot be cloned', { cause: obj });\n\n  // Handle primitives\n  if (obj === null || typeof obj !== 'object') return obj;\n  if (isTransferable(obj) && transferSet.has(obj)) return obj;\n  if (cloneMap.has(obj)) return cloneMap.get(obj);\n\n  // Handle arrays\n  if (Array.isArray(obj)) {\n    const clone: unknown[] = [];\n    cloneMap.set(obj, clone);\n    obj.forEach((item, i) => {\n      clone[i] = internalClone(item, transferSet, cloneMap);\n    });\n    return clone;\n  }\n\n  // Handle ArrayBuffer\n  if (obj instanceof ArrayBuffer) return transferSet.has(obj) ? obj : obj.slice(0);\n\n  // Try built-in types\n  const builtinClone = cloneBuiltins(obj);\n  if (builtinClone !== null) return builtinClone;\n\n  // Try collections\n  const collectionClone = cloneCollection(obj, transferSet, cloneMap);\n  if (collectionClone !== null) return collectionClone;\n\n  // Handle objects\n  const isPlainObject = obj.constructor === Object || obj.constructor === undefined;\n  const clone = isPlainObject ? {} : Object.create(Object.getPrototypeOf(obj));\n  cloneMap.set(obj, clone);\n\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      (clone as Record<string, unknown>)[key] = internalClone(\n        (obj as Record<string, unknown>)[key],\n        transferSet,\n        cloneMap\n      );\n    }\n  }\n\n  return clone;\n};\n\n/**\n * Creates a deep clone of a given value using the structured clone algorithm\n *\n * @param value - The object to be cloned\n * @param options - Optional configuration with transfer array\n * @returns A deep copy of the original value\n */\nexport const structuredClone = <T>(value: T, options?: StructuredCloneOptions): T => {\n  const transferableObjects = new Set(options?.transfer || []);\n  const cloneMap = new WeakMap<object, unknown>();\n\n  try {\n    return internalClone(value, transferableObjects, cloneMap) as T;\n  } catch (error) {\n    throw new Error(`Failed to clone object: ${error}`);\n  }\n};\n\n/**\n * Polyfills the global `structuredClone` function if it does not exist.\n *\n * This provides a comprehensive implementation of the structured clone algorithm that supports:\n *\n * - **Deep cloning** of objects, arrays, and nested data structures\n * - **Circular reference handling** with proper identity preservation\n * - **Built-in types**: Date, RegExp, Error, Map, Set, ArrayBuffer, and all TypedArrays\n * - **Transferable objects**: ArrayBuffer (with MessagePort and ImageBitmap in browsers)\n * - **Custom objects** with prototype preservation\n *\n * @remarks\n * This polyfill is designed to be as close as possible to the native implementation while being\n * compatible across environments. It will not override an existing native `structuredClone`\n * implementation.\n * @example\n *\n * ```typescript\n * // Polyfill the global function\n * polyfillStructuredClone();\n *\n * // Now you can use structuredClone globally\n * const original = { data: [1, 2, 3], date: new Date() };\n * const clone = globalThis.structuredClone(original);\n * ```\n *\n * @example\n *\n * ```typescript\n * // Handle circular references\n * polyfillStructuredClone();\n * const obj = { name: 'test' };\n * obj.self = obj;\n * const clone = globalThis.structuredClone(obj); // Works correctly\n * ```\n *\n * ## Limitations\n *\n * - **Functions and symbols**: Throws errors (as per specification)\n * - **Transferable objects**: Limited to ArrayBuffer in Node.js; adds MessagePort/ImageBitmap in\n *   browsers\n * - **Performance**: May be slower than native implementation\n * - **DOM nodes**: Not fully supported (use with caution)\n * - **WeakMap/WeakSet**: Not supported (as per specification)\n * - **Platform APIs**: Some browser-specific or Node.js-specific objects may not clone correctly\n *\n * ## Environment Compatibility\n *\n * - \u2705 **Node.js 14+**: Full support with ArrayBuffer transferables\n * - \u2705 **Modern browsers**: Full support including MessagePort/ImageBitmap transferables\n * - \u2705 **Safe fallback**: Only polyfills when native `structuredClone` is unavailable\n * - \u2705 **TypeScript**: Full type safety with generic support\n *\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/structuredClone | MDN structuredClone}\n * @see {@link https://html.spec.whatwg.org/multipage/structured-data.html#structured-cloning | HTML Specification}\n */\n\nexport const polyfilledStructuredClone = globalThis.structuredClone ?? structuredClone;\n", "/**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\nfunction isNil(value) {\n  return value == null;\n}\n\nexport default isNil;\n", "export interface BatcherConfig {\n  sendBatchSize: number;\n  timeoutMs: number;\n}\n\nconst defaultConfig: BatcherConfig = {\n  sendBatchSize: 8192,\n  timeoutMs: 200,\n};\n\ntype Awaitable<T = void> = T | Promise<T>;\nexport type BatchHandler<T> = (items: T[]) => Awaitable;\n\nexport class Batcher<T> {\n  config: BatcherConfig;\n\n  // A function that handles a batch\n  handler: BatchHandler<T>;\n\n  // A group of items to batch process\n  batch: T[] = [];\n\n  // A number when a timeout is active, else null.\n  private timeoutHandle: null | ReturnType<typeof setTimeout> = null;\n\n  constructor(handler: BatchHandler<T>, config?: Partial<BatcherConfig>) {\n    this.config = { ...defaultConfig, ...config };\n    this.handler = handler;\n  }\n\n  /**\n   * Add an item to the batch, and schedule a flush.\n   *\n   * @param item\n   */\n  add(item: T): void {\n    this.batch.push(item);\n    void this.scheduleFlush();\n  }\n\n  /** Determine if we need to flush immediately or if we need to flush after a timeout. */\n  private scheduleFlush(): Awaitable {\n    // Hit batch limit. Flush immediately.\n    if (this.batch.length >= this.config.sendBatchSize) return this.flushImmediately();\n\n    // No timeout configured, bail\n    if (this.config.timeoutMs <= 0) return;\n\n    // Already scheduled a flush\n    if (this.timeoutHandle !== null) return;\n\n    // Schedule a flush according to the timeout\n    this.timeoutHandle = setTimeout(this.flushImmediately, this.config.timeoutMs);\n  }\n\n  /** Detect if we've got a setTimeout handle active, and if so, clear it. */\n  private clearBatchTimer(): void {\n    if (this.timeoutHandle === null) return;\n\n    clearTimeout(this.timeoutHandle);\n    this.timeoutHandle = null;\n  }\n\n  /** Call the batch handler with the current batch. */\n  private flushImmediately = async () => {\n    // Ensure we cancel any existing timeouts\n    this.clearBatchTimer();\n\n    // Pluck off the batch and reset it\n    const batch = this.batch;\n    this.batch = [];\n\n    // Safely call the batch handler\n    try {\n      await this.handler(batch);\n    } catch (e) {\n      console.error(e);\n    }\n  };\n}\n", "import { SeverityNumber } from './generated/opentelemetry/proto/logs/v1/logs';\n\n/** Basic support for the log levels in OpenTelemetry. */\nexport enum LogLevel {\n  Unspecified = 'UNSPECIFIED',\n  Trace = 'TRACE',\n  Debug = 'DEBUG',\n  Info = 'INFO',\n  Warn = 'WARN',\n  Error = 'ERROR',\n  Fatal = 'FATAL',\n}\n\n/** Static map of log level => otel severity numbers. */\nconst severityLookupTable = {\n  [LogLevel.Unspecified]: SeverityNumber.SEVERITY_NUMBER_UNSPECIFIED,\n  [LogLevel.Trace]: SeverityNumber.SEVERITY_NUMBER_TRACE,\n  [LogLevel.Debug]: SeverityNumber.SEVERITY_NUMBER_DEBUG,\n  [LogLevel.Info]: SeverityNumber.SEVERITY_NUMBER_INFO,\n  [LogLevel.Warn]: SeverityNumber.SEVERITY_NUMBER_WARN,\n  [LogLevel.Error]: SeverityNumber.SEVERITY_NUMBER_ERROR,\n  [LogLevel.Fatal]: SeverityNumber.SEVERITY_NUMBER_FATAL,\n};\n\n/**\n * Convert a log level to an OpenTelemetry SeverityNumber.\n *\n * @param level The level we want to convert.\n * @returns {SeverityNumber} The OpenTelemetry severity number\n */\nexport function getSeverity(level: LogLevel): SeverityNumber {\n  return severityLookupTable[level] ?? SeverityNumber.UNRECOGNIZED;\n}\n", "import type { AnyValue, KeyValue } from './generated/opentelemetry/proto/common/v1/common';\n\nexport type SimpleKeyValue = ConvertableToKeyValues;\nexport type SimpleAnyValue = ConvertableToAnyValue;\nexport type SimpleAttributes = SimpleKeyValue;\n\n/** An approximation of the KeyValue[] type, without the extra boilerplate. */\ntype ConvertableToKeyValues = {\n  [key: string]: ConvertableToAnyValue;\n};\n\n/** An approximation of the AnyValue type, without the extra boilerplate. */\ntype ConvertableToAnyValue =\n  | string\n  | boolean\n  | number\n  | ConvertableToAnyValue[]\n  | ConvertableToKeyValues\n  | Uint8Array;\n\n/**\n * OpenTelemetry has this overcomplicated spec for defining simple key-values. This utility can be\n * used to use a much simpler key-value store and convert into the schema the collector wants.\n *\n * @param data A simplified key value dictionary, to be converted for use with an otel collector.\n * @returns A list of otel KeyValue entries.\n */\nexport function convertToKeyValues(data: ConvertableToKeyValues): KeyValue[] {\n  return Object.entries(data).map(\n    ([key, value]): KeyValue => ({\n      key,\n      value: convertToAnyValue(value),\n    })\n  );\n}\n\n/**\n * See above. Otel has an unweildy spec for simple values too, so convert scalars, bytes, and nested\n * generics into the schema the collector expects.\n *\n * @param value A simple scalar value OR a data structure\n * @returns The schema that open telemetry wants to talk about simple values in.\n */\nexport function convertToAnyValue(value: ConvertableToAnyValue): AnyValue {\n  // scalars\n  switch (typeof value) {\n    case 'string':\n      return { stringValue: value };\n    case 'boolean':\n      return { boolValue: value };\n    case 'number':\n      return { doubleValue: value };\n  }\n\n  // arrays\n  if (Array.isArray(value)) {\n    return {\n      arrayValue: {\n        values: value.map(convertToAnyValue),\n      },\n    };\n  }\n\n  // bytes\n  if (value instanceof Uint8Array) {\n    return { bytesValue: value };\n  }\n\n  // dictionaries\n  return {\n    kvlistValue: {\n      values: convertToKeyValues(value),\n    },\n  };\n}\n", "import type { ExportLogsServiceRequest } from './generated/opentelemetry/proto/collector/logs/v1/logs_service';\nimport type { LogRecord } from './generated/opentelemetry/proto/logs/v1/logs';\nimport type { LogWithTime } from './Log';\nimport { getSeverity } from './LogLevel';\nimport type { OpenTelemetryLoggerConfig } from './OpenTelemetryLoggerConfig';\nimport { convertToAnyValue, convertToKeyValues } from './simpleAttributes';\n\nconst schemaUrl = 'https://opentelemetry.io/schemas/1.5.0';\n\n/**\n * Responsible for converting a batch of Logs and an OpenTelemetryLoggerConfig into a OTLP JSON API\n * request.\n */\nexport class OtlpJsonExporter {\n  readonly config: OpenTelemetryLoggerConfig;\n\n  constructor(config: OpenTelemetryLoggerConfig) {\n    this.config = config;\n  }\n\n  /**\n   * Send a batch of logs to the otlp receiver.\n   *\n   * @param logs\n   */\n  async send(logs: LogWithTime[]): Promise<void> {\n    if (logs.length === 0) return;\n\n    const request = this.createServiceRequest(logs);\n\n    const response = await fetch(this.config.otlpEndpoint, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify(request),\n    });\n\n    if (!response.ok) {\n      throw new Error(`Failed to send logs to the OTLP receiver: ${response.statusText}`);\n    }\n  }\n\n  /**\n   * Convert a batch of logs into an ExportLogsServiceRequest object.\n   *\n   * @param logs A batch of logs to convert.\n   * @returns The converted request object.\n   */\n  private createServiceRequest(logs: LogWithTime[]): ExportLogsServiceRequest {\n    return {\n      resourceLogs: [\n        {\n          resource: {\n            attributes: convertToKeyValues({\n              ...this.config.attributes,\n              'service.name': this.config.serviceName,\n            }),\n            droppedAttributesCount: 0,\n          },\n          schemaUrl: schemaUrl,\n          scopeLogs: [\n            {\n              scope: undefined,\n              logRecords: logs.map(log => this.convertLog(log)),\n              schemaUrl: schemaUrl,\n            },\n          ],\n        },\n      ],\n    };\n  }\n\n  /**\n   * Convert a single log to an Otel LogRecord\n   *\n   * @param log The logger Log instance.\n   * @returns The converted LogRecord.\n   */\n  private convertLog(log: LogWithTime): LogRecord {\n    return {\n      timeUnixNano: log.timestamp,\n      observedTimeUnixNano: log.timestamp,\n      severityNumber: getSeverity(log.level),\n      severityText: log.level,\n      attributes: convertToKeyValues(log.attributes ?? {}),\n      droppedAttributesCount: 0,\n      flags: 0,\n      body: convertToAnyValue(log.body),\n      traceId: log.traceId!,\n      spanId: log.spanId!,\n      eventName: log.eventName!,\n    };\n  }\n}\n", "import { Batcher } from './Batcher';\nimport type { LogWithTime, Log } from './Log';\nimport { LogLevel } from './LogLevel';\nimport { OtlpJsonExporter } from './OtlpJsonExporter';\nimport type { SimpleAttributes } from './simpleAttributes';\nimport type { OpenTelemetryLoggerConfig } from './OpenTelemetryLoggerConfig';\n\nexport const defaultOpenTelemetryLoggerConfig = {\n  serviceName: 'unknown_service',\n  attributes: {} as SimpleAttributes,\n};\n\n/** These props can be optional, since we're providing a default. */\ntype OptionalKeys = keyof typeof defaultOpenTelemetryLoggerConfig;\n\n/**\n * A modified OpenTelemetryConfig type where the values provided by defaultOpenTelemetryLoggerConfig\n * are optional.\n */\nexport type LoggerOptions = Omit<OpenTelemetryLoggerConfig, OptionalKeys> & // Required\n  Partial<Pick<OpenTelemetryLoggerConfig, OptionalKeys>>; // Optional\n\nexport class OpenTelemetryLogger {\n  readonly config: OpenTelemetryLoggerConfig;\n\n  private exporter: OtlpJsonExporter;\n\n  private batch: Batcher<LogWithTime>;\n\n  constructor(config: LoggerOptions) {\n    this.config = { ...defaultOpenTelemetryLoggerConfig, ...config };\n    this.exporter = new OtlpJsonExporter(this.config);\n\n    this.batch = new Batcher<LogWithTime>(\n      (batch: LogWithTime[]) => this.exporter.send(batch),\n      config.batcher\n    );\n  }\n\n  /**\n   * Push a log into the batch. Will either flush immediately or schedule a flush.\n   *\n   * This is the core method for this logger. Every other method is just a simplification of this\n   * signature.\n   *\n   * @param log\n   */\n  push(log: Log): void {\n    // Make sure the timestamp is defined\n    if (!log.timestamp) log.timestamp = (performance.now() + performance.timeOrigin) * 1_000_000;\n\n    // add to the batch.\n    this.batch.add(log as LogWithTime);\n  }\n\n  /**\n   * Log a string message. Takes an optional log level and attributes.\n   *\n   * @param message The log body.\n   * @param level A log level. Defaults to Unspecified.\n   * @param attributes Arbitrary log context.\n   */\n  log(\n    message: string,\n    level: LogLevel = LogLevel.Unspecified,\n    attributes?: SimpleAttributes\n  ): void {\n    this.push({\n      body: message,\n      level,\n      attributes,\n    });\n  }\n\n  /**\n   * Simplified trace logging.\n   *\n   * @param message The log body.\n   * @param attributes Arbitrary log context.\n   */\n  trace(message: string, attributes?: SimpleAttributes): void {\n    this.log(message, LogLevel.Trace, attributes);\n  }\n\n  /**\n   * Simplified debug logging.\n   *\n   * @param message The log body.\n   * @param attributes Arbitrary log context.\n   */\n  debug(message: string, attributes?: SimpleAttributes): void {\n    this.log(message, LogLevel.Debug, attributes);\n  }\n\n  /**\n   * Simplified info logging.\n   *\n   * @param message The log body.\n   * @param attributes Arbitrary log context.\n   */\n  info(message: string, attributes?: SimpleAttributes): void {\n    this.log(message, LogLevel.Info, attributes);\n  }\n\n  /**\n   * Simplified warn logging.\n   *\n   * @param message The log body.\n   * @param attributes Arbitrary log context.\n   */\n  warn(message: string, attributes?: SimpleAttributes): void {\n    this.log(message, LogLevel.Warn, attributes);\n  }\n\n  /**\n   * Log an exception, automatically collecting the trace and type.\n   *\n   * @param error Either an error message, or an error instance.\n   * @param level Probably either Error or Fatal.\n   * @param attributes Arbitrary log context.\n   */\n  private logException(\n    error: Error | string,\n    level?: LogLevel,\n    attributes?: SimpleAttributes\n  ): void {\n    if (typeof error === 'string') {\n      this.log(error, level, attributes);\n      return;\n    }\n\n    this.log(error.toString(), level, {\n      'exception.message': error.message,\n      'exception.stacktrace': error.stack ?? '',\n      'exception.type': error.name,\n      ...attributes,\n    });\n  }\n\n  /**\n   * Simplified error logging.\n   *\n   * @param error The log body OR an Error instance.\n   * @param attributes Arbitrary log context.\n   */\n  error(error: string | Error, attributes?: SimpleAttributes): void {\n    this.logException(error, LogLevel.Error, attributes);\n  }\n\n  /**\n   * Simplified fatal logging.\n   *\n   * @param error The log body OR an Error instance.\n   * @param attributes Arbitrary log context.\n   */\n  fatal(error: string | Error, attributes?: SimpleAttributes): void {\n    this.logException(error, LogLevel.Fatal, attributes);\n  }\n}\n", "import type { BasePermission, EmptyObject, EventListener, LoggedEvent } from './loggingTypes';\nimport { requestIdleCallback } from '@snapchat/polyfills';\n\n// In extreme circumstances we stop logging to avoid memory leaks.\nconst maxQueueSize = 1e3;\n\n// The default timeout for requestIdleCallback\nconst defaultIdleTimeout = 500;\nexport interface BaseEventListenerProps<LoggingContext, CustomEvents> {\n  /** If set, will be a check whether to log the event. */\n  filter?: (event: LoggedEvent<CustomEvents>, context: Partial<LoggingContext>) => boolean;\n  /**\n   * Utility function for rewriting the event.\n   *\n   * This is useful for redacting fields or doing a per-listener context transform.\n   */\n  eventRewrite?: (\n    event: LoggedEvent<CustomEvents>,\n    context: Partial<LoggingContext>\n  ) => LoggedEvent<CustomEvents>;\n  /**\n   * Use this to set whether or not the event listener can run asynchronously. If true, logEvent\n   * will add the event to a queue and requestIdleCallback will be used to process the queue.\n   */\n  useAsync?: boolean;\n  /** If async, use this to set the timeout value. Defaults to 500 */\n  asyncTimeoutMs?: number;\n}\n\nexport interface Props<\n  LoggingContext extends EmptyObject = EmptyObject,\n  CustomEvents extends EmptyObject = EmptyObject,\n  LoggingPermission extends BasePermission = BasePermission\n> extends BaseEventListenerProps<LoggingContext, CustomEvents> {\n  requiredPermissions: Array<keyof LoggingPermission>;\n}\n\n/** Base event listener that can queue up events. */\nexport abstract class AbstractEventListener<\n  LoggingContext extends EmptyObject = EmptyObject,\n  CustomEvents extends EmptyObject = EmptyObject,\n  LoggingPermission extends BasePermission = BasePermission\n> implements EventListener<LoggingContext, CustomEvents, LoggingPermission>\n{\n  protected readonly queuedEvents: Array<Parameters<typeof this.logEvent>> = [];\n  protected readonly permissions = new Set<keyof LoggingPermission>();\n  protected readonly baseProps;\n\n  protected isInitializing = false;\n  protected hasInitalized = false;\n\n  constructor(props: Props<LoggingContext, CustomEvents, LoggingPermission>) {\n    this.baseProps = props;\n  }\n\n  private addToQueue = (\n    event: LoggedEvent<CustomEvents>,\n    context: Partial<LoggingContext>\n  ): void => {\n    if (this.queuedEvents.length >= maxQueueSize) {\n      console.warn('Logging queue is full. Stopping logging.');\n      return;\n    }\n    this.queuedEvents.push([event, context]);\n  };\n\n  /**\n   * Checks for required permissions and if they're not met, queues the event for a later time.\n   *\n   * The queue has a max length, and if it fills up, events will get dropped.\n   *\n   * @override logEvent\n   */\n  public logEvent = (event: LoggedEvent<CustomEvents>, context: Partial<LoggingContext>): void => {\n    if (!!this.baseProps.filter && !this.baseProps.filter?.(event, context)) return;\n    // biome-ignore lint/style/noParameterAssign: This is fine.\n    if (this.baseProps.eventRewrite) event = this.baseProps.eventRewrite(event, context);\n\n    if (!this.hasAllPermissions() || !this.hasInitalized) {\n      this.addToQueue(event, context);\n    } else if (this.baseProps.useAsync) {\n      this.addToQueue(event, context);\n      requestIdleCallback(this.logQueuedEvents, {\n        timeout: this.baseProps.asyncTimeoutMs ?? defaultIdleTimeout,\n      });\n    } else {\n      this.logEventInternal(event, context);\n    }\n  };\n\n  /** Checks whether all of the required permissions have been granted. */\n  protected hasAllPermissions = (): boolean => {\n    for (const permission of this.baseProps.requiredPermissions) {\n      if (!this.permissions.has(permission)) {\n        return false;\n      }\n    }\n\n    return true;\n  };\n\n  /** Any initialization that the logger has to do should be in the override of this method. */\n  protected init(): Promise<void> {\n    return Promise.resolve();\n  }\n\n  /** Actually logs the event to the underlying system. */\n  protected abstract logEventInternal(\n    event: LoggedEvent<CustomEvents>,\n    context?: Partial<LoggingContext>\n  ): void;\n\n  /** Logs any events that have been queued up. */\n  protected logQueuedEvents = (): void => {\n    for (const [event, context] of this.queuedEvents) {\n      this.logEventInternal(event, context);\n    }\n    this.queuedEvents.length = 0;\n  };\n\n  /** @override */\n  public allow = async (permission: keyof LoggingPermission): Promise<void> => {\n    this.permissions.add(permission);\n\n    if (this.hasAllPermissions() && !this.hasInitalized && !this.isInitializing) {\n      this.isInitializing = true;\n      await this.init();\n      this.hasInitalized = true;\n      this.isInitializing = false;\n      this.logQueuedEvents();\n    }\n\n    return;\n  };\n\n  /** @override */\n  public deny = (permission: keyof LoggingPermission): Promise<void> => {\n    this.permissions.delete(permission);\n    return Promise.resolve();\n  };\n\n  /** Forces a flush of the internal cache for the collector client. */\n  protected abstract flushInternal: () => Promise<unknown>;\n\n  /**\n   * Generic flush for all event listener types. Implement listener specific flushes in\n   * flushInternal.\n   *\n   * @override\n   */\n  public flush = (): Promise<unknown> => {\n    if (this.baseProps.useAsync) {\n      // We can't flush if we're not initialized.\n      this.hasAllPermissions() && this.hasInitalized && this.logQueuedEvents();\n    }\n    return this.flushInternal();\n  };\n}\n", "import type { BaseEventListenerProps } from './AbstractEventListener';\nimport { AbstractEventListener } from './AbstractEventListener';\nimport type { BasePermission, EmptyObject, LoggedEvent } from './loggingTypes';\n\nexport type MultipleDataLayerEvents<T = unknown> = {\n  type: 'multiple';\n  events: T[];\n};\n\n/**\n * Any DataLayer driven logger like GA4 or GTM require the user to accept Performance tracking in\n * GDPR regions. So this permission is baked into this implementation.\n */\nexport type DataLayerLoggingPermissions = BasePermission & {\n  performance: boolean;\n};\n\n/**\n * Privacy configuration options for data layer event listeners.\n *\n * These flags control privacy-related behavior (e.g., CCPA, GDPR, or other privacy regulations).\n * The package doesn't determine WHY restrictions are needed - that logic lives in the consuming\n * application. These flags simply describe WHAT restrictions to apply.\n */\nexport type DataLayerPrivacyConfig = {\n  /**\n   * Enable Restricted Data Processing (RDP). When RDP is enabled, Google acts as a Service Provider\n   * and will only use the data for specific \u201Cbusiness purposes\u201D (delivery, reporting, debugging)\n   * and will not use it to build user profiles for its own advertising purposes (Required for CCPA\n   * Compliance)\n   */\n  restrictDataProcessing?: boolean;\n  /**\n   * Deny ad-related storage and data collection via Consent Mode. When true, sets ad_storage,\n   * ad_user_data, and ad_personalization to 'denied'. We set analytics_storage to 'granted' to\n   * allow for reporting and debugging purposes. See:\n   * https://developers.google.com/tag-platform/security/guides/consent\n   */\n  configureConsent?: boolean;\n  /**\n   * Enable ads data redaction. When true, it limits the collection of PII and restricts\n   * user-tracking identifiers when consent is denied. See:\n   * https://support.google.com/analytics/answer/13544947?hl=en\n   */\n  redactAdsData?: boolean;\n};\n\n/**\n * A logger that simply passes events to the dataLayer variable.\n *\n * This is how Google Analytics and Google Tag Manager works.\n */\nexport type DataLayerEventListenerProps<LoggingContext, OtherEvents, GoogleEventType> = {\n  /**\n   * Formats the events into the shape that the particular GTM/GA implementation unerstands.\n   *\n   * Note that because dataLayer accepts arrays as items, we can't return a regular array here for\n   * multiple events. So you have to wrap them in: { type: 'multiple', events: [...events...]} when\n   * returning.\n   */\n  eventFormatter: (\n    event: LoggedEvent<OtherEvents>,\n    context: Partial<LoggingContext>\n  ) => MultipleDataLayerEvents<GoogleEventType> | GoogleEventType | null | undefined;\n  /**\n   * Optional privacy configuration (e.g., for CCPA, GDPR compliance). Configure restrictions based\n   * on your application's privacy requirements.\n   */\n  privacyConfig?: DataLayerPrivacyConfig;\n} & BaseEventListenerProps<LoggingContext, OtherEvents>;\n\n/** Rudimentary event listener that logs to the console. */\nexport abstract class AbstractDataLayerEventListener<\n  LoggingContext extends EmptyObject = EmptyObject,\n  CustomEvents extends EmptyObject = EmptyObject,\n  Permission extends DataLayerLoggingPermissions = DataLayerLoggingPermissions,\n  GoogleEvent extends EmptyObject = EmptyObject\n> extends AbstractEventListener<LoggingContext, CustomEvents, Permission> {\n  private readonly props: DataLayerEventListenerProps<\n    LoggingContext,\n    LoggedEvent<CustomEvents>,\n    GoogleEvent\n  >;\n  private eventCallbacks: Promise<void>[] = [];\n\n  constructor(\n    props: DataLayerEventListenerProps<LoggingContext, LoggedEvent<CustomEvents>, GoogleEvent>\n  ) {\n    super({\n      ...props,\n      requiredPermissions: ['logging', 'performance'],\n    });\n    this.props = props;\n  }\n\n  /** Adds an event to the dataLayer variable. This is handled differently between GA4 and GTM (FFS) */\n  protected abstract addEventToDataLayer(event: GoogleEvent): void;\n\n  /**\n   * Adds the event callback to an event.\n   *\n   * Returns whether the callback was added.\n   */\n  protected abstract addEventCallback: (event: GoogleEvent, callback: () => void) => boolean;\n\n  /**\n   * Applies privacy configuration to the dataLayer. Child classes (GTM/GA4) must implement this to\n   * format events correctly for their respective APIs.\n   *\n   * @param config - Privacy configuration flags\n   */\n  protected abstract applyPrivacyConfig(config: DataLayerPrivacyConfig): void;\n\n  /** @override */\n  protected logEventInternal = (\n    event: LoggedEvent<CustomEvents>,\n    context: Partial<LoggingContext>\n  ): void => {\n    const formattedEvent = this.props.eventFormatter(event, context);\n    if (!formattedEvent) return;\n\n    const hasMultipleEvents =\n      typeof formattedEvent === 'object' &&\n      'type' in formattedEvent &&\n      // @ts-ignore Just checked on the line above.\n      formattedEvent.type === 'multiple';\n\n    if (hasMultipleEvents) {\n      const formattedEvents = formattedEvent;\n\n      for (const singleFormattedEvent of formattedEvents.events) {\n        this.logGoogleEvent(singleFormattedEvent);\n      }\n    } else {\n      this.logGoogleEvent(formattedEvent as GoogleEvent);\n    }\n  };\n\n  /**\n   * Helper function for writting a single event to the dataLayer.\n   *\n   * Adds listeners for event log completion so we can track when they're all done for the {flush}\n   * implementation.\n   */\n  protected logGoogleEvent = (event: GoogleEvent): void => {\n    // If not an event object, skip this value.\n    if (!event || typeof event !== 'object') {\n      return;\n    }\n\n    let onEventLoggedCallback: (value: void | PromiseLike<void>) => void;\n\n    const onEventLogged = new Promise<void>(resolve => {\n      onEventLoggedCallback = resolve;\n    });\n\n    const callbackAdded = this.addEventCallback(event, onEventLoggedCallback!);\n\n    callbackAdded && this.eventCallbacks.push(onEventLogged);\n    this.addEventToDataLayer(event);\n  };\n\n  /**\n   * Waits for all events in the dataLayer to be flagged as delivered (via event callback API)\n   * before resolving.\n   *\n   * @override\n   */\n  protected flushInternal: () => Promise<unknown> = async () => {\n    const resolvedCount = this.eventCallbacks.length;\n    await Promise.allSettled(this.eventCallbacks);\n\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.eventCallbacks = this.eventCallbacks.slice(resolvedCount);\n\n    return;\n  };\n}\n", "import type {\n  BaseNetworkHandler,\n  Config,\n  Dimensions,\n  Graphene,\n  InitializeProps,\n} from '@snapchat/graphene';\nimport { graphene, type Partition } from '@snapchat/graphene';\nimport type { WebMetricCollectorOptions } from '@snapchat/graphene';\nimport { getWebConfig } from '@snapchat/graphene';\nimport isNil from 'lodash/isNil.js';\n\nimport type { BaseEventListenerProps } from './AbstractEventListener';\nimport { AbstractEventListener } from './AbstractEventListener';\nimport type { BasePermission, EmptyObject, FlatContext, LoggedEvent } from './loggingTypes';\nimport { LoggingEventType } from './loggingTypes';\n\n/**\n * The limit of how many dimensions graphene supports. Per event graphene supports 6 slices one\n * going to the `metricsName`.\n */\nconst maxDimensions = 5;\n\nexport interface GrapheneEvent {\n  metricsName: string;\n  /** Value for addHistogram call to Graphene. */\n  value?: number;\n  /** Value for addTiming call to Graphene */\n  timing?: number;\n  dimensions?: Record<string, unknown>;\n}\n\nexport type GrapheneLoggingContext = {\n  /** If there are no values or timings, this will pass this into the addCounter call of graphene. */\n  incrementValue: number;\n};\n\ntype Props<\n  LoggingContext extends GrapheneLoggingContext = GrapheneLoggingContext,\n  CustomEvents extends EmptyObject = EmptyObject\n> = Omit<InitializeProps, 'networkHandler'> &\n  WebMetricCollectorOptions &\n  BaseEventListenerProps<LoggingContext, CustomEvents> & {\n    /**\n     * Function that extracts additional the dimensions from context to add to the default ones.\n     *\n     * Note that graphene can only support 5, so the first non-null 5 will be recorded. The first\n     * few usually come from the event, and not the context, so it's not unlikely that most of the\n     * fields here will not be recorded in all use-cases.\n     */\n    getAdditionalDimensions?: (context: Partial<LoggingContext>) => FlatContext | undefined;\n\n    /** Returns the graphene metric name. If not specifies a sensible default is used. */\n    getMetricName?: (\n      event: LoggedEvent<CustomEvents>,\n      context: Partial<LoggingContext>\n    ) => string | null;\n\n    /** Processor for custom events. */\n    customEventFormat?: (\n      event: CustomEvents,\n      context: Partial<LoggingContext>\n    ) => GrapheneEvent | null | undefined;\n  };\n\n/**\n * Abstract Graphene EventListener that implements formatting but not the delivery. If no\n * partitionName is passed, it will use serviceName. At least one is required.\n */\nexport abstract class AbstractGrapheneEventListener<\n  LoggingContext extends GrapheneLoggingContext = GrapheneLoggingContext,\n  CustomEvents extends EmptyObject = EmptyObject,\n  LoggingPermission extends BasePermission = BasePermission\n> extends AbstractEventListener<LoggingContext, CustomEvents, LoggingPermission> {\n  private readonly props: Props<LoggingContext, CustomEvents>;\n  // TODO: Consider making this strict. I.e. /\\W+/g, but that would convert\n  // characters like ':' into underscores. But I'm not sure if that's better or\n  // worse. Right now, some characters get turned into ':'. So https://localhost/foo\n  // can either be https___localhost_foo or https:::localhost:foo and it's unclear what's\n  // better.\n  private readonly illegalCharRegex = /[\\s.]+/g;\n\n  private client: Graphene = graphene;\n\n  constructor(\n    props: Omit<Props<LoggingContext, CustomEvents>, 'partitionName' | 'serviceName'> & {\n      partitionName?: Partition;\n      serviceName?: string;\n    }\n  ) {\n    super({\n      ...props,\n      requiredPermissions: ['logging'],\n    });\n\n    this.props = {\n      ...props,\n      partitionName: props.partitionName,\n      serviceName: props.serviceName,\n    };\n  }\n\n  /** Returns the network handler for sending Graphene events. */\n  protected abstract getNetworkHandler: (options: Config) => BaseNetworkHandler;\n\n  /** Returns the client for graphene. */\n  protected abstract getClient: () => Graphene;\n\n  /** @override */\n  protected init = (): Promise<void> => {\n    // getClient creates a new client so it is important that we only call it once.\n    this.client = this.getClient();\n\n    // Sanity check that this isn't an already initialized client.\n    if (this.client.isInitialized) {\n      console.warn('Graphene client already initialized. Ignoring init call.');\n      return Promise.resolve();\n    }\n\n    // Check that at least one of partitionName or serviceName is provided\n    if (!this.props.partitionName && !this.props.serviceName) {\n      throw new Error('Either partitionName or serviceName must be provided');\n    }\n\n    // We sanitize the props because graphene silently drops events if they have\n    // special characters in flavor or variant.\n    const grapheneConfigs = {\n      ...this.props,\n      flavor: this.props.flavor ? this.cleanDimensionString(this.props.flavor) : undefined,\n      variant: this.props.variant ? this.cleanDimensionString(this.props.variant) : undefined,\n    };\n\n    this.client.initialize({\n      networkHandler: this.getNetworkHandler(getWebConfig(grapheneConfigs)),\n      ...grapheneConfigs,\n    });\n\n    return Promise.resolve();\n  };\n\n  /** @override */\n  protected logEventInternal(\n    event: LoggedEvent<CustomEvents>,\n    context: Partial<LoggingContext>\n  ): void {\n    const metricsName = this.props.getMetricName?.(event, context);\n\n    switch (event.type) {\n      case LoggingEventType.DEBUG: {\n        // Log nothing for debug events. They are too noisy for graphene.\n        break;\n      }\n\n      case LoggingEventType.INFO: {\n        const dimensions = this.getDimensions(\n          {\n            action: event.action,\n            category: event.component,\n            label: event.label,\n          },\n          context\n        );\n\n        this.client.increment({\n          metricsName: metricsName ?? 'app_event',\n          dimensions,\n          value: context.incrementValue ?? 1,\n        });\n        break;\n      }\n\n      case LoggingEventType.TIMING: {\n        const dimensions = this.getDimensions(\n          {\n            variable: event.variable,\n            category: event.component,\n            label: event.label,\n          },\n          context\n        );\n\n        this.client.addTimer({\n          metricsName: metricsName ?? 'app_timing_event',\n          dimensions,\n          milliSec: Math.round(event.valueMs),\n        });\n        break;\n      }\n\n      case LoggingEventType.VALUE: {\n        const dimensions = this.getDimensions(\n          {\n            variable: event.variable,\n            category: event.component,\n            label: event.label,\n          },\n          context\n        );\n\n        this.client.addHistogram({\n          metricsName: metricsName ?? 'app_measure_event',\n          dimensions,\n          value: event.value,\n        });\n        break;\n      }\n\n      case LoggingEventType.WARNING: {\n        const dimensions = this.getDimensions({ category: event.component }, context);\n\n        this.client.increment({\n          metricsName: metricsName ?? 'app_warning',\n          dimensions,\n        });\n        break;\n      }\n\n      case LoggingEventType.ERROR: {\n        const dimensions = this.getDimensions(\n          { category: event.component, action: event.action },\n          context\n        );\n\n        this.client.increment({\n          metricsName: metricsName ?? 'app_error',\n          dimensions,\n        });\n        break;\n      }\n\n      case LoggingEventType.USER_ACTION: {\n        const dimensions = this.getDimensions(\n          { category: event.component, action: event.action, label: event.label },\n          context\n        );\n\n        this.client.increment({\n          metricsName: metricsName ?? 'user_action',\n          dimensions,\n        });\n        break;\n      }\n\n      case LoggingEventType.CUSTOM: {\n        const customEvent = this.props.customEventFormat?.(event, context);\n        if (!customEvent) break;\n        const { metricsName, value, timing, dimensions: extractedDimensions } = customEvent;\n        const dimensions = this.getDimensions(extractedDimensions ?? {}, context);\n\n        if (value) {\n          this.client.addHistogram({ metricsName, dimensions, value });\n        } else if (timing) {\n          // NOTE: Timing has to be a whole number.\n          this.client.addTimer({ metricsName, dimensions, milliSec: Math.round(timing) });\n        } else {\n          this.client.increment({ metricsName, dimensions, value: context.incrementValue ?? 1 });\n        }\n        break;\n      }\n    }\n  }\n\n  /** Aggregates up to {@link maxDimensions} from the event and context. */\n  protected getDimensions = (\n    eventDimensions: Record<string, unknown>,\n    context: Partial<LoggingContext>\n  ): Dimensions => {\n    const dimensions: Dimensions = {};\n\n    // Copy provided dimensions from the event\n    for (const [key, value] of Object.entries(eventDimensions)) {\n      if (isNil(value)) continue;\n      const dimensionKey = this.cleanDimensionString(key);\n      dimensions[dimensionKey] = this.cleanDimensionString(String(value));\n    }\n\n    // Copies the dimensions from context.\n    if (this.props.getAdditionalDimensions) {\n      const flatContext = this.props.getAdditionalDimensions(context) ?? {};\n\n      for (const [key, value] of Object.entries(flatContext)) {\n        if (isNil(value)) continue;\n        if (Object.keys(dimensions).length >= maxDimensions) break;\n        const dimensionKey = this.cleanDimensionString(String(key));\n        dimensions[dimensionKey] = this.cleanDimensionString(String(value));\n      }\n    }\n\n    return dimensions;\n  };\n\n  /**\n   * Graphene doesn't support empty strings, so replace with 'Unknown'. Also replace any whitespace\n   * or periods in the input string with underscores, this avoids issues finding the logs later due\n   * to the partitions not matching expectations. Example: convert '523.snap.com' to '523_snap_com'\n   * since periods represent partitions in Graphene.\n   */\n  protected cleanDimensionString = (input?: string): string => {\n    if (!input) return 'Unknown';\n    return input.replace(this.illegalCharRegex, '_');\n  };\n\n  /** @override */\n  protected flushInternal = async (): Promise<void> => {\n    await this.client?.flush();\n  };\n}\n", "// ============================================================================\n// Core interfaces for event listeners.\n// ============================================================================\n\n/** Default permissions that all logging event listeners should support */\nexport type BasePermission = {\n  logging: boolean;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: We actually do want an empty object here, and not a Record<string, never> because we use this for typechecking <T extends EmptyObject>\nexport type EmptyObject = {};\n\n/**\n * A flat context (table) that can be written out by loggers that ultimately end up in a tabular\n * format.\n */\nexport type FlatContext = Record<string, string | number | null | undefined>;\n\n/**\n * A listener to events on the logging event bus.\n *\n * @param LoggingContext Interface for the context that be set on the logger via logger.setContext\n *   or via a second parameter to any logEvent/logInfo/... command.\n * @param CustomEvent Interface for any custom events that can be sent over the event bus. This\n *   framework is agnostic to web/node/cli/runtime etc, so users are encouraged to make their own\n *   events through this.\n * @param LoggingPermission Extensions to default permissions for custom listeners. The defautl\n *   permissions are meant to forwarding user permissions from marketing sites as reviewed by legal,\n *   but this is extensible for server-side applications.\n */\nexport type EventListener<\n  LoggingContext extends EmptyObject = EmptyObject,\n  CustomEvent extends EmptyObject = EmptyObject,\n  LoggingPermission extends BasePermission = BasePermission\n> = {\n  /** Logs the event. Can be queuing it, or waiting for a batch. */\n  logEvent: (event: LoggedEvent<CustomEvent>, context: Partial<LoggingContext>) => void;\n  /** Turns on delivery of events that require permissions. */\n  allow: (permission: keyof LoggingPermission) => Promise<void>;\n  deny: (permission: keyof LoggingPermission) => Promise<void>;\n  /** Sends any queued up events. Typically called before process exit. */\n  flush: () => Promise<unknown>;\n};\n\n// ============================================================================\n// Event interfaces\n// ============================================================================\n\n/**\n * The interface for the types of events that can be sent over the event bus. P This can be extended\n * by passing in other events through the @param OtherEvents.\n */\nexport type LoggedEvent<OtherEvents> =\n  | InternalEvent\n  | InternalValueEvent\n  | InternalTimingEvent\n  | UserInteractionEvent\n  | WarningEvent\n  | ErrorEvent\n  | DebugEvent\n  | CustomEvent<OtherEvents>;\n\n/**\n * Types of events that can be sent over the event bus. All event listeners use this to\n * differentiate between events they do and do not listen to.\n *\n * This is an emalgamation of Logging Severity, Count vs Measure and User vs Internal categories.\n *\n * The default is INFO and different listeners handle custom events differently including changing\n * the logging severity for CUSTOM events.\n */\nexport enum LoggingEventType {\n  CUSTOM = 'custom',\n  DEBUG = 'debug',\n  ERROR = 'error',\n  INFO = 'info',\n  TIMING = 'timing',\n  USER_ACTION = 'user_action',\n  VALUE = 'value',\n  WARNING = 'warning',\n}\n\n/** Interface for any events that are not generic. */\nexport type CustomEvent<CustomEvents> = CustomEvents & {\n  type: LoggingEventType.CUSTOM;\n};\n\n/** An error event. To be used for unrecoverable sitations that requires fixing. */\nexport type ErrorEvent = {\n  type: LoggingEventType.ERROR;\n  /** Place where the error occurred. */\n  component: string;\n  /** Error that was thrown. Can be anything, but we do prefer errors. */\n  error?: unknown;\n  /** Human readable text. Usually logged as-is */\n  message?: string;\n  /**\n   * Specific situation that the error is occurring. Helps for specificity and if you want metrics\n   * on it.\n   */\n  action?: string;\n};\n\n/** A warning. To be used for */\nexport type WarningEvent = {\n  type: LoggingEventType.WARNING;\n  /** Place where the error occurred. */\n  component: string;\n  /** Human-readable text. Usually logged as-is. */\n  message?: string;\n  /** Specific action that was being undertaken when the warning occurred. */\n  action?: string;\n};\n\n/**\n * An event that is triggered by a user action.\n *\n * This originates on the web where it's important to track what the user does vs what performance\n * metrics get recorded.\n */\nexport type UserInteractionEvent = {\n  type: LoggingEventType.USER_ACTION;\n  /** Place where the event happened */\n  component: string;\n  /** What action did the user take. Suggestion is to keep this to one verb. */\n  action: string;\n  /**\n   * What did the action relate to. This should be specific like an ID.\n   *\n   * NOTE: This is not nullable because user action _ALWAYS_ has some context, and the label for\n   * that context always exists. I.e. `{ action: 'click', label: 'button' }` or `{ action: 'submit',\n   * label: 'interest form' }`\n   */\n  label: string;\n};\n\n/** An info-level event not originated by the user. */\nexport type InternalEvent = {\n  type: LoggingEventType.INFO;\n  /** Place where the event happened */\n  component: string;\n  /** What happened. Suggest to keep this to one verb */\n  action: string;\n  /** What did the action relate to. Be specific. This should be an ID. */\n  label?: string;\n};\n\n/**\n * An info-level log for a performance event that has a value.\n *\n * Note that this can store any value, but if you need to store duration in milliseconds use the\n * dedicated InternalTimingEvent.\n */\nexport type InternalValueEvent = {\n  type: LoggingEventType.VALUE;\n  /** Place where the measurement happened */\n  component: string;\n  /** Name of a metric */\n  variable: string;\n  /** Metric value */\n  value: number;\n  /** Any ID for the measured object */\n  label?: string;\n};\n\n/**\n * Duration measurement event. Same as InternalValueEvent but the units are whole milliseconds.\n *\n * If you need to measure something other than duration, use InternalValueEvent.\n */\nexport type InternalTimingEvent = {\n  type: LoggingEventType.TIMING;\n  /** Place where the measurement happened */\n  component: string;\n  /** Name of a metric */\n  variable: string;\n  /** Time in milliseconds (always milliseconds) */\n  valueMs: number;\n  /** Any ID for the measured time */\n  label?: string;\n};\n\n/** Any debug-level event. Can be thrown away or not logged */\nexport type DebugEvent = {\n  type: LoggingEventType.DEBUG;\n  /** Place where the event happened */\n  component: string;\n  /** Human-readable text. */\n  message: string;\n};\n\n// ============================================================================\n// Simplified logging interfaces\n// ============================================================================\n\n/**\n * A much simplified logging interface that's only applicable to a single component with no complex\n * context or permissions.\n *\n * This is meant to be used for cases where a console logger is used to keep the interface similar.\n *\n * Note that the logger is disabled by default, so do not forget to enable it by calling\n * `logger.enable()`.\n */\nexport interface ComponentLogger {\n  /** Enables logging. Initially the logger is disabled. */\n  enable: () => void;\n  /** Takes away the 'logging' permission making all events queue up (the first 1000). */\n  disable: () => void;\n  /** Logs a debug level message. */\n  debug: (message: string) => void;\n  /**\n   * NOTE: This just calls `debug(message)` since the logging framework purposefully does not allow\n   * unstructured info-level logging.\n   *\n   * This way the logs will show in `console` and other text-based collectors, but will not\n   * increment any counters or metrics.\n   *\n   * If you want to produce an info-level message, use `increment` instead.\n   */\n  info: (message: string) => void;\n  /** Logs a warning-level message. */\n  warn: (message: string) => void;\n  /** Logs an error. The optional message will override the `error.message` */\n  error: (error: unknown, message?: string) => void;\n  /**\n   * Increments a counter for the action.\n   *\n   * This is useful for metrics (not just logs).\n   */\n  increment: (action: string, label?: string) => void;\n  /**\n   * Logs a timing value in milliseconds.\n   *\n   * This is useful for metrics.\n   */\n  timing: (variable: string, valueMs: number) => void;\n  /**\n   * Logs a non-timing value. The units should be added in your graphing software.\n   *\n   * This is useful for metrics.\n   */\n  value: (variable: string, value: number) => void;\n}\n// ============================================================================\n// Misc interfaces\n// ============================================================================\n\n/**\n * Tracking permissions on the web.\n *\n * These correspond directly to the tracking categories reviewed by Snap Legal as far as cookie\n * storage and what we're allowed to track for users.\n *\n * It is on implementers of EventListener interfaces to adhere to these.\n *\n * See https://snap.com/en-US/cookie-settings\n */\nexport type WebTrackingPermission = BasePermission & {\n  marketing: boolean;\n  performance: boolean;\n};\n\n/** Events collected client side to forward to hermes client event collection. */\nexport interface EventRequest<CustomEvent, LoggingContext> {\n  events: EventPayload<CustomEvent, LoggingContext>[];\n  /** Timestamp request was made. */\n  timestamp: number;\n}\n\n/** Event and context payload request used for forwarding client events to hermes. */\nexport interface EventPayload<CustomEvent, LoggingContext> {\n  event: LoggedEvent<CustomEvent>;\n  context: Partial<LoggingContext>;\n}\n", "import type { ScopeContext, Event, EventHint } from '@sentry/core';\nimport { parseError } from '@snapchat/core';\nimport merge from 'lodash/merge.js';\n\nimport type { BaseEventListenerProps } from './AbstractEventListener';\nimport { AbstractEventListener } from './AbstractEventListener';\nimport type { BasePermission, EmptyObject, LoggedEvent } from './loggingTypes';\nimport { LoggingEventType } from './loggingTypes';\n\n/**\n * Context for sentry logs.\n *\n * Note that `extras` has UNSTRUCTURED data, where as `contexts` has only a flat map of strings\n */\nexport interface SentryContext extends Partial<ScopeContext> {}\n\nexport type SentryEventCapturer = (event: Event, context: EventHint) => void;\nexport type SentryErrorCapturer = (error: Error, context: EventHint) => void;\n\nexport interface SentryLoggingContext {\n  sentry?: SentryContext;\n}\nexport interface SentryEventListenerProps<\n  LoggingContext extends SentryLoggingContext,\n  CustomEvents extends EmptyObject\n> extends BaseEventListenerProps<LoggingContext, CustomEvents> {\n  /**\n   * Returns a `SentryContext` extracted from the generic `LoggingContext`.\n   *\n   * I.e. if you have generic fields in your context, and you want to slot them correctly into\n   * Sentry specific context (fingerprints, tags, etc), this is where you do it.\n   */\n  getContext?: (\n    event: LoggedEvent<CustomEvents>,\n    context: Partial<LoggingContext>\n  ) => Partial<ScopeContext>;\n\n  /** Formatter for the custom events directly into the sentry event format. */\n  customEventFormat?: (\n    event: CustomEvents,\n    context: Partial<LoggingContext>\n  ) => [Event, EventHint] | null | undefined;\n}\n\n/** Base class for sentry event listeners. */\nexport abstract class AbstractSentryEventListener<\n  LoggingContext extends SentryLoggingContext = SentryLoggingContext,\n  CustomEvents extends EmptyObject = EmptyObject,\n  LoggingPermission extends BasePermission = BasePermission\n> extends AbstractEventListener<LoggingContext, CustomEvents, LoggingPermission> {\n  protected readonly props: SentryEventListenerProps<LoggingContext, CustomEvents>;\n  private captureException: SentryErrorCapturer | undefined;\n  private captureEvent: SentryEventCapturer | undefined;\n\n  constructor(props: SentryEventListenerProps<LoggingContext, CustomEvents>) {\n    super({\n      ...props,\n      requiredPermissions: ['logging'],\n    });\n    this.props = props;\n  }\n\n  /** @override */\n  protected init = async (): Promise<void> => {\n    this.captureException = await this.getExceptionCapturer();\n    this.captureEvent = await this.getEventCapturer();\n  };\n\n  /** @override */\n  protected logEventInternal(\n    event: LoggedEvent<CustomEvents>,\n    context: Partial<LoggingContext>\n  ): void {\n    const loggerContext: Record<string, string | undefined> = {};\n    if ('component' in event) loggerContext.component = event.component;\n    if ('action' in event) loggerContext.action = event.action;\n    if ('label' in event) loggerContext.label = event.label;\n    const eventHint: EventHint = {\n      captureContext: merge(\n        { contexts: { logger: loggerContext } },\n        context.sentry,\n        // NOTE: We let the `getContext` function have the final say on any\n        // context overrides.\n        this.props.getContext?.(event, context)\n      ),\n    };\n    switch (event.type) {\n      case LoggingEventType.DEBUG: {\n        this.captureEvent!({ message: event.message, level: 'debug' }, eventHint);\n        break;\n      }\n\n      case LoggingEventType.INFO: {\n        // NOTE: Component is already in the `eventHint` but is duplicated here for context.\n        // Otherwise events like `{component: 'AdBlock', action: 'Exists'}` do not show up\n        // well in the UI.\n        const message = `${event.component}: ${event.action}`;\n        this.captureEvent!({ message: message, level: 'info' }, eventHint);\n        break;\n      }\n\n      case LoggingEventType.WARNING: {\n        this.captureEvent!({ message: event.message, level: 'warning' }, eventHint);\n        break;\n      }\n\n      case LoggingEventType.ERROR: {\n        const error = event.message\n          ? new Error(event.message)\n          : parseError(event.error ?? 'UnknownError');\n\n        this.captureException!(error, eventHint);\n        break;\n      }\n\n      case LoggingEventType.TIMING:\n      // fallthrough\n      case LoggingEventType.VALUE: {\n        // Nothing here. Note that Sentry does have ability to write metrics\n        // into it via:\n        //\n        //  measurements: {\n        //   [event.variable]: {\n        //     unit: 'none' as MeasurementUnit, // can use 'milliseconds' for timing events.\n        //     value: event.value,\n        //   },\n        // },\n        //\n        // But you can't see nor visualize this data in Sentry UI under events.\n        // It is possible to attach this data to performance metric events\n        // under `tracing`, but the logging event bus isn't setup to do tracing\n        // (nor should it be), so currently nothing is logged in this case.\n        //\n        // If you need to emit metrics, we suggesting using Custom events and manually\n        // setting up tracing and metric emitting:\n        // Traces: https://docs.sentry.io/platforms/javascript/tracing/\n        // Metrics: https://docs.sentry.io/platforms/javascript/tracing/instrumentation/performance-metrics/\n        //\n        break;\n      }\n\n      case LoggingEventType.CUSTOM: {\n        if (!this.props.customEventFormat) {\n          break;\n        }\n        const [customEvent, customContext] = this.props.customEventFormat(event, context) ?? [];\n        if (!customEvent) {\n          break;\n        }\n\n        this.captureEvent!(customEvent, merge({}, eventHint, customContext));\n        break;\n      }\n    }\n  }\n\n  /** Lazy loads the library for capturing errors into sentry. */\n  protected abstract getExceptionCapturer: () => Promise<SentryErrorCapturer>;\n\n  /** Lazy loads the library for capturing logs into sentry. */\n  protected abstract getEventCapturer: () => Promise<SentryEventCapturer>;\n\n  /** @override */\n  protected flushInternal: () => Promise<unknown> = () => Promise.resolve();\n}\n", "import omit from 'lodash/omit.js';\n\nimport type { BaseEventListenerProps } from './AbstractEventListener';\nimport { AbstractEventListener } from './AbstractEventListener';\nimport type { BasePermission, EmptyObject, FlatContext, LoggedEvent } from './loggingTypes';\nimport { LoggingEventType } from './loggingTypes';\n\nexport type ConsoleEventListenerProps<LoggingContext, CustomEvents> = {\n  /** Returns a selection fields to log to the console. */\n  getFlatContext?: (context: Partial<LoggingContext>) => FlatContext;\n\n  /**\n   * For custom events allows for custom formatting.\n   *\n   * If this is not specified, custom events are printed using JSON.stringify.\n   */\n  customEventFormatter?: (\n    event: CustomEvents,\n    context: Partial<LoggingContext>\n  ) => unknown | unknown[] | null;\n  /** Transform for the arguments passed to the console. Useful for adding colors. */\n  messageTransform?: (type: LoggingEventType, args: unknown[]) => unknown[];\n} & BaseEventListenerProps<LoggingContext, CustomEvents>;\n\n/** Rudimentary event listener that logs to the console. */\nexport class ConsoleEventListener<\n  LoggingContext extends EmptyObject = EmptyObject,\n  OtherEvents extends EmptyObject = EmptyObject,\n  Permission extends BasePermission = BasePermission\n> extends AbstractEventListener<LoggingContext, OtherEvents, Permission> {\n  private readonly props: ConsoleEventListenerProps<LoggingContext, OtherEvents>;\n  private readonly printConsole: Console;\n\n  constructor(\n    props?: ConsoleEventListenerProps<LoggingContext, OtherEvents>,\n    printConsole: Console = console\n  ) {\n    super({\n      ...props,\n      requiredPermissions: ['logging'],\n    });\n    this.props = props ?? {};\n    this.printConsole = printConsole;\n  }\n\n  protected logEventInternal = (\n    event: LoggedEvent<OtherEvents>,\n    context: Partial<LoggingContext>\n    // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: This is fine.\n  ): void => {\n    let contextDict: Record<string, unknown> | undefined;\n\n    if (this.props.getFlatContext) {\n      const flatContext = this.props.getFlatContext(context) ?? {};\n\n      for (const [key, value] of Object.entries(flatContext)) {\n        if (!value) continue;\n        if (!contextDict) contextDict = {};\n        contextDict[String(key)] = value;\n      }\n    }\n\n    switch (event.type) {\n      case LoggingEventType.DEBUG: {\n        const messageAndArgs = [`${event.component}: ${event.message}`, contextDict ?? ''];\n        this.printConsole.debug(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n\n      case LoggingEventType.INFO: {\n        const maybeLabel = event.label ? ` (${event.label})` : '';\n        const messageAndArgs = [\n          `${event.component}: ${event.action}${maybeLabel}`,\n          contextDict ?? '',\n        ];\n        this.printConsole.info(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n\n      case LoggingEventType.USER_ACTION: {\n        const maybeLabel = event.label ? ` (${event.label})` : '';\n        const messageAndArgs = [\n          `${event.component}: ${event.action}${maybeLabel}`,\n          contextDict ?? '',\n        ];\n        this.printConsole.info(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n\n      case LoggingEventType.VALUE: {\n        const maybeLabel = event.label ? ` (${event.label})` : '';\n        const messageAndArgs = [\n          `${event.component}: ${event.variable} = ${event.value.toLocaleString()}${maybeLabel}`,\n          contextDict ?? '',\n        ];\n        this.printConsole.info(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n\n      case LoggingEventType.TIMING: {\n        const maybeLabel = event.label ? ` (${event.label})` : '';\n        const messageAndArgs = [\n          `${event.component}: ${event.variable} = ${Math.round(event.valueMs)}ms${maybeLabel}`,\n          contextDict ?? '',\n        ];\n        this.printConsole.info(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n\n      case LoggingEventType.WARNING: {\n        const messageAndArgs = [`${event.component}: ${event.message}`, contextDict ?? ''];\n        this.printConsole.warn(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n\n      case LoggingEventType.ERROR: {\n        const maybeAction = event.action ? ` (${event.action})` : '';\n        const messageAndArgs = [\n          `${event.component}: ${event.message}${maybeAction}`,\n          event.error ?? '',\n          contextDict ?? '',\n        ];\n        this.printConsole.error(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n\n      case LoggingEventType.CUSTOM: {\n        const message = this.props.customEventFormatter\n          ? this.props.customEventFormatter(event, context)\n          : omit(event, 'type');\n        if (!message) break;\n\n        const messageAndArgs = [\n          'Custom:',\n          ...(Array.isArray(message) ? message : [message]),\n          contextDict ?? '',\n        ];\n        this.printConsole.info(...this.transform(event.type, messageAndArgs));\n        break;\n      }\n    }\n  };\n\n  protected transform = (type: LoggingEventType, message: unknown[]): unknown[] =>\n    this.props.messageTransform ? this.props.messageTransform(type, message) : message;\n\n  /** @override */\n  protected flushInternal: () => Promise<unknown> = () => Promise.resolve();\n}\n", "import assign from 'lodash/assign.js';\nimport cloneDeep from 'lodash/cloneDeep.js';\n\nimport type {\n  BasePermission,\n  DebugEvent,\n  EmptyObject,\n  ErrorEvent,\n  EventListener,\n  InternalEvent,\n  InternalTimingEvent,\n  InternalValueEvent,\n  LoggedEvent,\n  UserInteractionEvent,\n  WarningEvent,\n} from './loggingTypes';\nimport { LoggingEventType } from './loggingTypes';\n\n// In extreme circumstances we stop logging to avoid memory leaks.\nconst maxQueueSize = 1e3;\n\n/**\n * An event bus for logging.\n *\n * Loggers are registered as event listeners. There's no way to unregister because the design\n * assumes that the logger is instantiated only once per application.\n *\n * Propagates permissions. Logging is disabled by default and needs to be enabled via\n * `logger.allow(TrackingPermission.ESSENTIAL)`\n *\n * Stores global context. When global context changes it is expected that that `logger.setContext({\n * newValue: 'foo', clearValue: undefined })` etc is called.\n *\n * Provides convenience methods like `logger.logInfo` that can be exported.\n *\n * See EventListener for explanation of the generics.\n */\nexport class LoggingEventBus<\n  LoggingContext extends EmptyObject = EmptyObject,\n  CustomEvent extends EmptyObject = EmptyObject,\n  Permission extends BasePermission = BasePermission\n> {\n  private readonly contextProviders = new Set<() => Partial<LoggingContext>>();\n  private readonly eventListeners: EventListener<LoggingContext, CustomEvent, Permission>[] = [];\n  private readonly permissions = new Set<keyof Permission>();\n  protected readonly queuedEvents: Array<[LoggedEvent<CustomEvent>, Partial<LoggingContext>]> = [];\n\n  constructor(...listeners: EventListener<LoggingContext, CustomEvent, Permission>[]) {\n    this.eventListeners.push(...listeners);\n  }\n\n  /**\n   * Adds event listeners.\n   *\n   * Sets the allowed permissions on them.\n   *\n   * Does not do anything fancy, so you can hypothetically register similar listeners multiple\n   * times.\n   */\n  public addEventListeners(\n    ...listeners: EventListener<LoggingContext, CustomEvent, Permission>[]\n  ): void {\n    this.eventListeners.push(...listeners);\n\n    for (const listener of listeners) {\n      for (const permission of this.permissions) {\n        listener.allow(permission).catch(console.error);\n      }\n    }\n  }\n\n  /** Adds a context provider that gets called before an event is logged. */\n  public addContextProvider = (provider: () => Partial<LoggingContext>): void => {\n    this.contextProviders.add(provider);\n  };\n\n  /** Remove a context provider. */\n  public removeContextProvider = (provider: () => Partial<LoggingContext>): void => {\n    this.contextProviders.delete(provider);\n  };\n\n  /**\n   * Sends the event to all of the event listeners.\n   *\n   * Ques up the event if no listeners are present. Ensures that the context is grabbed when the\n   * event is queued.\n   */\n  public logEvent = (event: LoggedEvent<CustomEvent>, context?: Partial<LoggingContext>): void => {\n    const combinedContext = this.getCombinedContext(context);\n\n    // Queue events if we don't have any listeners.\n    if (this.eventListeners.length === 0) {\n      if (this.queuedEvents.length > maxQueueSize) {\n        console.warn('Logging queue is full. Stopping logging.');\n        return;\n      }\n      this.queuedEvents.push([event, combinedContext]);\n      return;\n    }\n\n    this.notifyListeners(event, combinedContext);\n  };\n\n  /** Combines the event context with all the context providers. */\n  protected getCombinedContext = (context?: Partial<LoggingContext>): Partial<LoggingContext> => {\n    const combinedContext: Partial<LoggingContext> = {};\n\n    for (const getContext of this.contextProviders) {\n      // The context provider is external and can crash logging if not caught.\n      try {\n        assign(combinedContext, getContext());\n      } catch (error) {\n        console.error(`Unable to get context from ${getContext.name}`, error);\n      }\n    }\n\n    // Ensure event context gets last values\n    if (context) {\n      assign(combinedContext, cloneDeep(context));\n    }\n\n    return combinedContext;\n  };\n\n  /**\n   * Notifies all the listeners of the event.\n   *\n   * IMPORTANT: This is different from `logEvent` because it doesn't get the new context at the time\n   * of the event record because it may be different (which is bad).\n   */\n  protected notifyListeners = (\n    event: LoggedEvent<CustomEvent>,\n    context: Partial<LoggingContext>\n  ): void => {\n    for (const listener of this.eventListeners) {\n      listener.logEvent(event, context);\n    }\n  };\n\n  /** Logs any events that have been queued up. */\n  protected logQueuedEvents = (): void => {\n    if (this.queuedEvents.length === 0) return;\n    for (const [event, context] of this.queuedEvents) {\n      this.notifyListeners(event, context);\n    }\n    this.queuedEvents.length = 0;\n  };\n\n  /**\n   * Notifies listeners that a permission has been granted.\n   *\n   * NOTE: All listeners require 'logging' to be granted before they can log anything.\n   *\n   * These are primary for client-side logging that is blocked on users accepting a a performance\n   * tracking cookie.\n   */\n  public allow = async (permission: keyof Permission): Promise<void> => {\n    this.permissions.add(permission);\n    await Promise.all(this.eventListeners.map(listener => listener.allow(permission)));\n    this.logQueuedEvents();\n  };\n\n  /**\n   * Notifies listeners that a permission has been given away.\n   *\n   * This typically does not happen except on the web where a user can mid-session turn off\n   * tracking.\n   */\n  public deny = async (permission: keyof Permission): Promise<void> => {\n    this.permissions.delete(permission);\n    await Promise.all(this.eventListeners.map(listener => listener.deny(permission)));\n  };\n\n  /**\n   * Flushes all of the listeners.\n   *\n   * Logs any errors to the console/stderr.\n   */\n  public flush = async (): Promise<void> => {\n    const tryFlushListeners = this.eventListeners.map(listener => {\n      // Need to handle any errors that may occur in a single listener so it doesn't block processing of subsequent listeners.\n      return listener.flush().catch(error => console.error(error));\n    });\n\n    await Promise.allSettled(tryFlushListeners);\n  };\n\n  // ==========================================================================\n  // Convenience methods.\n  // ==========================================================================\n\n  /**\n   * Logs an error event.\n   *\n   * NOTE: This increments a counter where the key is `${data.component}.${data.action}`. The\n   * message field is only written to text collectors notice.\n   *\n   * @param data - The event data for logging.\n   * @param data.error - The error that was thrown. This is used by collectors like Sentry or\n   *   GoogleCloud ErrorReporting for stack traces.\n   * @param data.message - The error message that was throw to override the error message for\n   *   clarity.\n   * @param data.action - The action that was in progress when the error occurred.\n   * @param data.component - The component that the event occurred in. Could be a UI component like\n   *   MyForm, or an endpoint component like JobSubmitHandler\n   * @param context - Optional partial logging context. The event listeners use this to extract\n   *   metadata for logging.\n   */\n  public logError = (data: Omit<ErrorEvent, 'type'>, context?: Partial<LoggingContext>): void => {\n    this.logEvent({ ...data, type: LoggingEventType.ERROR }, context);\n  };\n\n  /**\n   * Logs a warning event.\n   *\n   * NOTE: This increments a counter where the key is `${data.component}.${data.action}`. The\n   * message field is only written to text collectors notice.\n   *\n   * @param data - The event data for logging.\n   * @param data.message - The warning message that was is written to standard err.\n   * @param data.action - The action that was in progress when the warning occurred.\n   * @param data.component - The component that the event occurred in. Could be a UI component like\n   *   MyForm, or an endpoint component like JobSubmitHandler\n   * @param context - Optional partial logging context. The event listeners use this to extract\n   *   metadata for logging.\n   */\n  public logWarning = (\n    data: Omit<WarningEvent, 'type'>,\n    context?: Partial<LoggingContext>\n  ): void => {\n    this.logEvent({ ...data, type: LoggingEventType.WARNING }, context);\n  };\n\n  /**\n   * Logs a debug event.\n   *\n   * NOTE: This does not increment a counter and has a freeform message. The message field is only\n   * written to text collectors notice.\n   *\n   * @param data - The event data for logging.\n   * @param data.message - The informational message that was is written to standard out.\n   * @param data.component - The component that the event occurred in. Could be a UI component like\n   *   MyForm, or an endpoint component like JobSubmitHandler\n   * @param context - Optional partial logging context. The event listeners use this to extract\n   *   metadata for logging.\n   */\n  public logDebug = (data: Omit<DebugEvent, 'type'>, context?: Partial<LoggingContext>): void => {\n    this.logEvent({ ...data, type: LoggingEventType.DEBUG }, context);\n  };\n\n  /**\n   * Logs a structured event (no message field) with information.\n   *\n   * NOTE: This increments a counter where the key is\n   * `${data.component}.${data.action}.${data.label}`. So structure your logs so they make sense.\n   * I.e. `NewsletterForm.Submit.20250101` or `SyncJob.Finish.bulk_edit`. There is no `message`\n   * field. Use `logDebug` if you need to print informational text.\n   *\n   * @param data - The event data for logging.\n   * @param data.component - The component that the event occurred in. Could be a UI component like\n   *   MyForm, or an endpoint component like JobSubmitHandler\n   * @param data.action - The action that occurred.\n   * @param data.label - Label distinguishing between different variants of the `component`. I.e. If\n   *   you have multiple forms, this could be the form id, or if you have a generic endpoint, this\n   *   would be the id of the request.\n   * @param context - Optional partial logging context. The event listeners use this to extract\n   *   metadata for logging.\n   */\n  public logInfo = (data: Omit<InternalEvent, 'type'>, context?: Partial<LoggingContext>): void => {\n    this.logEvent({ ...data, type: LoggingEventType.INFO }, context);\n  };\n\n  /**\n   * Logs a structured event (no message field) with a timing value. Use this for incrementing gauge\n   * metrics where the domain is time in milliseconds (ms).\n   *\n   * NOTE: This increments a gauge metric where the key is\n   * `${data.component}.${data.action}.${data.label}`. So structure your logs so they make sense.\n   * I.e. `Page.Load.loading_time_ms` or `SyncJob.Finish.duration_ms`.\n   *\n   * @param data - The event data for logging.\n   * @param data.component - The component that the event occurred in. Could be a UI component like\n   *   MyForm, or an endpoint component like JobSubmitHandler\n   * @param data.action - The action that occurred.\n   * @param data.label - Label distinguishing between different variants of the `component`. I.e. If\n   *   you have multiple forms, this could be the form id, or if you have a generic endpoint, this\n   *   would be the id of the request.\n   * @param data.valueMs - The timing value in milliseconds.\n   * @param context - Optional partial logging context. The event listeners use this to extract\n   *   metadata for logging.\n   */\n  public logTiming = (\n    data: Omit<InternalTimingEvent, 'type'>,\n    context?: Partial<LoggingContext>\n  ): void => {\n    this.logEvent({ ...data, type: LoggingEventType.TIMING }, context);\n  };\n\n  /**\n   * Logs a structured event (no message field) with a numeric value. Use this for incrementing\n   * gauge metrics where the domain is something other than time (use logTiming for those).\n   *\n   * NOTE: This increments a gauge metric where the key is\n   * `${data.component}.${data.action}.${data.label}`. So structure your logs so they make sense.\n   * I.e. `Page.Load.downloaded_bytes` or `SyncJob.Finish.memory_usage_kb`.\n   *\n   * @param data - The event data for logging.\n   * @param data.component - The component that the event occurred in. Could be a UI component like\n   *   MyForm, or an endpoint component like JobSubmitHandler\n   * @param data.action - The action that occurred.\n   * @param data.label - Label distinguishing between different variants of the `component`. I.e. If\n   *   you have multiple forms, this could be the form id, or if you have a generic endpoint, this\n   *   would be the id of the request.\n   * @param data.value - The value. The record is unitless. You need to configure your graphing\n   *   software to add the units\n   * @param context - Optional partial logging context. The event listeners use this to extract\n   *   metadata for logging.\n   */\n  public logValue = (\n    data: Omit<InternalValueEvent, 'type'>,\n    context?: Partial<LoggingContext>\n  ): void => {\n    this.logEvent({ ...data, type: LoggingEventType.VALUE }, context);\n  };\n\n  /**\n   * Same as `logInfo` except that for some collectors a new flag indicating that the event is\n   * user-intiated is set.\n   */\n  public logUserEvent = (\n    data: Omit<UserInteractionEvent, 'type'>,\n    context?: Partial<LoggingContext>\n  ): void => {\n    this.logEvent({ ...data, type: LoggingEventType.USER_ACTION }, context);\n  };\n\n  /**\n   * Logs a custom event.\n   *\n   * These events do not go to any standard collector unless you provide a custom transformer.\n   *\n   * This is useful when you want to match a custome event table in Blizzard and don't want any\n   * other collector to pick it up for privacy reasons.\n   */\n  public logCustom = (data: CustomEvent, context?: Partial<LoggingContext>): void => {\n    this.logEvent({ ...data, type: LoggingEventType.CUSTOM }, context);\n  };\n}\n", "import type { BaseEventListenerProps } from './AbstractEventListener';\nimport { AbstractEventListener } from './AbstractEventListener';\nimport type { BasePermission, CustomEvent, EmptyObject, LoggedEvent } from './loggingTypes';\nimport { LoggingEventType } from './loggingTypes';\nimport {\n  LogLevel,\n  OpenTelemetryLogger,\n  type LoggerOptions,\n  type SimpleAttributes,\n  type BatcherConfig,\n} from '@snapchat/otel-otlp-logger';\n\nexport type CustomEventFormatter<T> = (event: T) => [LogLevel, string] | string | undefined;\nexport type OpenTelemetryEventListenerProps<OpenTelemetryEvents extends EmptyObject = EmptyObject> =\n  LoggerOptions & {\n    customEventFormat?: CustomEventFormatter<OpenTelemetryEvents>;\n  } & BaseEventListenerProps<SimpleAttributes, EmptyObject>;\n\nexport interface OpenTelemetryBatcherConfig extends Partial<BatcherConfig> {}\nexport interface OpenTelemetryContext extends SimpleAttributes {}\n\nexport { LogLevel as OpenTelemetryLogLevel };\n\n/** This dictionary is used for constant time conversions between event type and log level. */\nconst loggingEventToLogLevel: Map<LoggingEventType, LogLevel> = new Map([\n  [LoggingEventType.DEBUG, LogLevel.Debug],\n  [LoggingEventType.ERROR, LogLevel.Error],\n  [LoggingEventType.INFO, LogLevel.Info],\n  [LoggingEventType.TIMING, LogLevel.Info],\n  [LoggingEventType.USER_ACTION, LogLevel.Info],\n  [LoggingEventType.VALUE, LogLevel.Info],\n  [LoggingEventType.WARNING, LogLevel.Warn],\n]);\n\ntype ExcludeCustomEvents<T extends EmptyObject> = Exclude<\n  LoggedEvent<T>,\n  { type: LoggingEventType.CUSTOM }\n>;\n\n/** Event listener that passes all logs to the OpenTelemetryLogger. */\nexport class OpenTelemetryEventListener<\n  TOpenTelemetryContext extends OpenTelemetryContext = OpenTelemetryContext,\n  TOpenTelemetryEvents extends EmptyObject = EmptyObject,\n  TOpenTelemetryPermission extends BasePermission = BasePermission\n> extends AbstractEventListener<\n  TOpenTelemetryContext,\n  TOpenTelemetryEvents,\n  TOpenTelemetryPermission\n> {\n  logger: OpenTelemetryLogger;\n  formatter?: CustomEventFormatter<TOpenTelemetryEvents>;\n\n  constructor(props: OpenTelemetryEventListenerProps<TOpenTelemetryEvents>) {\n    super({\n      ...props,\n      requiredPermissions: ['logging'],\n    });\n\n    this.logger = new OpenTelemetryLogger(props);\n    this.formatter = props.customEventFormat;\n  }\n\n  /**\n   * Extract the OpenTelemetry Log Level from the LoggedEvent.\n   *\n   * @param event\n   * @returns The extracted log level\n   */\n  private getLogLevel(event: ExcludeCustomEvents<TOpenTelemetryEvents>): LogLevel {\n    return loggingEventToLogLevel.get(event.type) ?? LogLevel.Unspecified;\n  }\n\n  /**\n   * Extract the 'Message' part of the log. Handles mapping different event types to different\n   * properties.\n   *\n   * The final concatted message will be `Component: Message (Parenthetical)`\n   *\n   * @param event\n   * @returns The extracted message.\n   */\n  private getMessage(event: ExcludeCustomEvents<TOpenTelemetryEvents>): string {\n    switch (event.type) {\n      case LoggingEventType.INFO:\n      case LoggingEventType.USER_ACTION:\n        return event.action;\n\n      case LoggingEventType.VALUE:\n        return `${event.variable} = ${event.value.toLocaleString()}`;\n\n      case LoggingEventType.TIMING:\n        return `${event.variable} = ${Math.round(event.valueMs)}ms`;\n\n      default:\n        return event.message ?? '';\n    }\n  }\n\n  /**\n   * Extract the 'Parenthetical' part of the log. Handles mapping different event types to different\n   * properties.\n   *\n   * The final concatted message will be `Component: Message (Parenthetical)`\n   *\n   * @param event\n   * @returns The extracted parenthetical, including parens. Can be an empty string.\n   */\n  private getParenthetical(event: ExcludeCustomEvents<TOpenTelemetryEvents>): string {\n    switch (event.type) {\n      case LoggingEventType.WARNING:\n      case LoggingEventType.DEBUG:\n        return '';\n\n      case LoggingEventType.ERROR:\n        return this.parenthesizeIfPresent(event.action);\n\n      default:\n        return this.parenthesizeIfPresent(event.label);\n    }\n  }\n\n  /**\n   * Given a value, wrap it in parens if it is defined and non-empty.\n   *\n   * @param value Any arbitrary string.\n   * @returns Either `(${value})` or ''.\n   */\n  private parenthesizeIfPresent(value?: string): string {\n    if (!value) return '';\n    return `(${value})`;\n  }\n\n  /**\n   * Extract the 'Component' part of the log. In the case of custom events, returns an empty string.\n   *\n   * The final concatted message will be `Component: Message (Parenthetical)`\n   *\n   * @param event\n   * @returns The extracted Component, including colon. Can be an empty string.\n   */\n  private getComponent(event: ExcludeCustomEvents<TOpenTelemetryEvents>): string {\n    return `${event.component}:`;\n  }\n\n  private isCustomEvent(\n    event: LoggedEvent<TOpenTelemetryEvents>\n  ): event is CustomEvent<TOpenTelemetryEvents> {\n    return event.type === LoggingEventType.CUSTOM;\n  }\n\n  /**\n   * Builds a log message, determines an appropriate log level, and forwards to the otel logger.\n   *\n   * @param event\n   * @param context Any set of logging attributes.\n   */\n  protected override logEventInternal(\n    event: LoggedEvent<TOpenTelemetryEvents>,\n    context?: TOpenTelemetryContext\n  ): void {\n    if (this.isCustomEvent(event)) {\n      this.logCustomEvent(event, context);\n      return;\n    }\n\n    // Determine the log level\n    const logLevel = this.getLogLevel(event);\n\n    // Build the message string\n    const component = this.getComponent(event);\n    const message = this.getMessage(event);\n    const parenthetical = this.getParenthetical(event);\n\n    const pieces: string[] = [component, message];\n    if (parenthetical) pieces.push(parenthetical);\n\n    this.logger.log(pieces.join(' '), logLevel, context);\n  }\n\n  /**\n   * In the case of a custom event, defer log messaging to the provided formatter.\n   *\n   * If the formatter isn't defined, do nothing.\n   *\n   * @param event\n   * @param context\n   */\n  private logCustomEvent(\n    event: CustomEvent<TOpenTelemetryEvents>,\n    context?: TOpenTelemetryContext\n  ): void {\n    if (!this.formatter) return;\n    const response = this.formatter(event);\n\n    // Downstream filtering\n    if (!response) return;\n\n    // Simple case. Infer log level.\n    if (typeof response === 'string') {\n      this.logger.log(response, LogLevel.Unspecified, context);\n      return;\n    }\n\n    // Complete case. Explicit log level.\n    const [logLevel, message] = response;\n    this.logger.log(message, logLevel, context);\n  }\n\n  /** @override */\n  protected flushInternal: () => Promise<unknown> = (): Promise<void> => Promise.resolve();\n}\n", "import type { LoggingEventBus } from './LoggingEventBus';\nimport type { BasePermission, ComponentLogger, EmptyObject } from './loggingTypes';\n\n/**\n * Produces a wrapper around the `logger` with a simplified interface that's similar to simple\n * loggers that have a logging level and that's it.\n *\n * The `component` is a required field for `LoggingEventBus#logEvent` so this conveniently sets it\n * here for you.\n *\n * NOTE: DO NOT make this more complex. For more advanced use-cases use the `logger` directly!\n *\n * Usage:\n *\n *     const logBus = new LoggingEventBus(new ConsoleEventListener());\n *     const logger = withComponent(logBus, 'my-component');\n *     logger.enable();\n */\nexport function withComponent<\n  LoggingContext extends EmptyObject = EmptyObject,\n  CustomEvent extends EmptyObject = EmptyObject,\n  Permission extends BasePermission = BasePermission\n>(\n  logger: LoggingEventBus<LoggingContext, CustomEvent, Permission>,\n  component: string\n): ComponentLogger {\n  return {\n    enable: () => void logger.allow('logging'),\n    disable: () => void logger.deny('logging'),\n    debug: (message: string) => logger.logDebug({ component, message }),\n    // NOTE: This goes to logDebug on purpose. See comment on the interface.\n    info: (message: string) => logger.logDebug({ component, message }),\n    increment: (action: string, label?: string) => logger.logInfo({ component, action, label }),\n    warn: (message: string) => logger.logWarning({ component, message }),\n    error: (error: unknown, message?: string) => logger.logError({ component, error, message }),\n    timing: (variable: string, valueMs: number) =>\n      logger.logTiming({ component, variable, valueMs }),\n    value: (variable: string, value: number) => logger.logValue({ component, variable, value }),\n  };\n}\n", "import type { BaseEventListenerProps } from '../AbstractEventListener';\nimport { AbstractEventListener } from '../AbstractEventListener';\nimport type { BasePermission, EmptyObject, LoggedEvent } from '../loggingTypes';\nimport type { TestCustomEvent, TestLoggingContext } from './testLogEvents';\n\nexport interface TestEventListenerProps<\n  LoggingContext extends EmptyObject = EmptyObject,\n  CustomEvents extends EmptyObject = EmptyObject,\n  LoggingPermission extends BasePermission = BasePermission\n> extends BaseEventListenerProps<LoggingContext, CustomEvents> {\n  requiredPermissions: Array<keyof LoggingPermission>;\n}\n\n/**\n * Event listener for testing.\n *\n * All this does is capture any events it would record in a separate array that is publicly\n * accessible.\n */\nexport class TestEventListener<\n  LoggingContext extends TestLoggingContext = TestLoggingContext,\n  CustomEvents extends TestCustomEvent = TestCustomEvent,\n  LoggingPermission extends BasePermission = BasePermission\n> extends AbstractEventListener<LoggingContext, CustomEvents, LoggingPermission> {\n  public readonly queuedEvents: Array<Parameters<typeof this.logEvent>> = [];\n  public readonly capturedEvents: Array<Parameters<typeof this.logEvent>> = [];\n  public readonly permissions = new Set<keyof LoggingPermission>();\n\n  public hasInitalized = true;\n\n  constructor(props?: TestEventListenerProps<LoggingContext, CustomEvents, LoggingPermission>) {\n    super({\n      ...props,\n      requiredPermissions: props?.requiredPermissions ?? [],\n    });\n  }\n\n  /** @override */\n  protected logEventInternal(\n    event: LoggedEvent<CustomEvents>,\n    context: Partial<LoggingContext>\n  ): void {\n    this.capturedEvents.push([event, context]);\n  }\n\n  /** Resets the state of the listener. */\n  public reset = (): void => {\n    this.queuedEvents.length = 0;\n    this.capturedEvents.length = 0;\n    this.permissions.clear();\n    this.hasInitalized = false;\n  };\n\n  /** @override */\n  protected flushInternal: () => Promise<unknown> = () => Promise.resolve();\n}\n", "import type {\n  CustomEvent,\n  DebugEvent,\n  ErrorEvent,\n  InternalEvent,\n  InternalTimingEvent,\n  InternalValueEvent,\n  LoggedEvent,\n  UserInteractionEvent,\n  WarningEvent,\n} from '../loggingTypes';\nimport { LoggingEventType } from '../loggingTypes';\n\nexport type TestLoggingContext = {\n  errorCode: number;\n  site: string;\n  buildNumber: number;\n  locale: string;\n  empty: string;\n  incrementValue: number;\n  exclude: boolean;\n};\n\nexport const testLoggingContext: Partial<TestLoggingContext> = {\n  errorCode: 500,\n  site: 'snap.com',\n  buildNumber: 68731,\n  locale: 'en-US',\n};\n\nexport interface TestPageLoadEvent {\n  pathname: string;\n  customType: 'page_load';\n}\n\nexport interface TestNavigateEvent {\n  url: string;\n  customType: 'navigate';\n  durationMs: number;\n}\n\nexport type TestCustomEvent = TestPageLoadEvent | TestNavigateEvent;\n\nexport const testPageLoadEvent: CustomEvent<TestPageLoadEvent> = {\n  type: LoggingEventType.CUSTOM,\n  pathname: '/',\n  customType: 'page_load',\n};\n\nexport const testNavigateEvent: CustomEvent<TestNavigateEvent> = {\n  type: LoggingEventType.CUSTOM,\n  url: 'https://snap.com',\n  customType: 'navigate',\n  durationMs: 523,\n};\n\nexport const testErrorEvent: ErrorEvent = {\n  component: 'Test',\n  message: 'Unable to read \"e\" of undefined.',\n  type: LoggingEventType.ERROR,\n  error: new Error('Some error'),\n};\n\nexport const testUserInteractionEvent: UserInteractionEvent = {\n  type: LoggingEventType.USER_ACTION,\n  label: 'test label',\n  action: 'test action',\n  component: 'test category',\n};\n\nexport const testWarningEvent: WarningEvent = {\n  type: LoggingEventType.WARNING,\n  component: 'Contentful',\n  message: 'Returned status code 429. Retrying',\n};\n\nexport const testInternalEvent: InternalEvent = {\n  type: LoggingEventType.INFO,\n  component: 'Image',\n  label: '23562sdfwe',\n  action: 'loaded',\n};\n\nexport const testInternalTimingEvent: InternalTimingEvent = {\n  type: LoggingEventType.TIMING,\n  component: 'Video',\n  label: '03249867dkjfg',\n  variable: 'load_latency',\n  valueMs: 700,\n};\n\nexport const testInternalValueEvent: InternalValueEvent = {\n  type: LoggingEventType.VALUE,\n  component: 'Video',\n  label: '03249867dkjfg',\n  variable: 'bytes_downloaded',\n  value: 1_234_456,\n};\n\nexport const testDebugEvent: DebugEvent = {\n  type: LoggingEventType.DEBUG,\n  component: 'Button',\n  message: 'Hovered over button 2034687gfzks5',\n};\n\nexport const testEvents: Array<LoggedEvent<TestCustomEvent>> = [\n  testErrorEvent,\n  testUserInteractionEvent,\n  testWarningEvent,\n  testDebugEvent,\n  testInternalEvent,\n  testInternalValueEvent,\n  testInternalTimingEvent,\n  testPageLoadEvent,\n  testNavigateEvent,\n];\n", "import { LoggingEventBus } from '@snapchat/logging';\n\nimport { SubscribedEventType } from './eventListenerTypes';\nimport type {\n  ErrorEvent,\n  InternalEvent,\n  InternalTimingEvent,\n  InternalValueEvent,\n  LegacyAllEvents,\n  LoggingContext,\n  LoggingCustomEvents,\n  LoggingPermissions,\n  UserInteractionEvent,\n  WarningEvent,\n} from './loggingTypes';\n\n// =================================================================================================\n// Module Singleton\n// =================================================================================================\n\nexport const logger = new LoggingEventBus<\n  LoggingContext,\n  LoggingCustomEvents,\n  LoggingPermissions\n>();\n\nexport const onMarketingTrackingAccepted = async (): Promise<void> => {\n  logger && (await logger.allow('marketing'));\n};\n\nexport const onPerformanceTrackingAccepted = async (): Promise<void> => {\n  logger && (await logger.allow('performance'));\n};\n\n// =================================================================================================\n// Helper Functions - provides type checking when logging different event types\n// =================================================================================================\n\n// TODO: We need to change the caller signatures to match the new interfaces.\n\nexport const logDebug = logger.logDebug;\n\nexport const logError = (event: Omit<ErrorEvent, 'subscribedEventType'>): void => {\n  logger.logError(\n    {\n      error: event.error,\n      component: event.component,\n      message: event.message,\n      action: event.action ?? 'Unknown',\n    },\n    event.context\n  );\n};\n\nexport const logWarning = (event: Omit<WarningEvent, 'subscribedEventType'>): void => {\n  logger.logWarning(\n    {\n      component: event.component,\n      message: event.message,\n      action: 'Unknown',\n    },\n    event.context\n  );\n};\n\nexport const logInfo = (event: Omit<InternalEvent, 'subscribedEventType'>): void => {\n  logger.logInfo(\n    {\n      component: event.eventCategory,\n      action: event.eventAction,\n      label: event.eventLabel ?? undefined,\n    },\n    event.context\n  );\n};\n\n// eslint-disable-next-line import/no-unused-modules\nexport const logValue = (event: Omit<InternalValueEvent, 'subscribedEventType'>): void => {\n  logger.logValue(\n    {\n      component: event.eventCategory,\n      label: event.eventLabel ?? undefined,\n      value: event.eventValue,\n      variable: event.eventVariable,\n    },\n    event.context\n  );\n};\n\n// eslint-disable-next-line import/no-unused-modules\nexport const logTiming = (event: Omit<InternalTimingEvent, 'subscribedEventType'>): void => {\n  logger.logTiming(\n    {\n      component: event.eventCategory,\n      label: event.eventLabel ?? undefined,\n      valueMs: event.eventValue,\n      variable: event.eventVariable,\n    },\n    event.context\n  );\n};\n\nexport const logUserEvent = (event: Omit<UserInteractionEvent, 'subscribedEventType'>): void => {\n  logger.logUserEvent(\n    {\n      component: event.eventCategory,\n      action: event.eventAction,\n      label: event.eventLabel ?? '',\n    },\n    event.context\n  );\n};\n\nexport const logEvent = (event: LegacyAllEvents): void => {\n  switch (event.subscribedEventType) {\n    case SubscribedEventType.USER_INTERACTION: {\n      logger.logUserEvent({\n        component: event.eventCategory,\n        action: event.eventAction,\n        label: event.eventLabel ?? '',\n      });\n      break;\n    }\n\n    case SubscribedEventType.ERROR: {\n      logger.logError(\n        {\n          error: event.error,\n          component: event.component,\n          message: event.message,\n          action: 'Unknown', // TODO: Add this to the error type.\n        },\n        event.context\n      );\n      break;\n    }\n\n    case SubscribedEventType.INTERNAL: {\n      logger.logInfo(\n        {\n          component: event.eventCategory,\n          action: event.eventAction,\n          label: event.eventLabel ?? undefined,\n        },\n        event.context\n      );\n      break;\n    }\n\n    case SubscribedEventType.INTERNAL_TIMING: {\n      logger.logTiming(\n        {\n          component: event.eventCategory,\n          variable: event.eventVariable,\n          valueMs: event.eventValue,\n          label: event.eventLabel ?? undefined,\n        },\n        event.context\n      );\n      break;\n    }\n\n    case SubscribedEventType.INTERNAL_VALUE: {\n      logger.logValue(\n        {\n          component: event.eventCategory,\n          variable: event.eventVariable,\n          value: event.eventValue,\n          label: event.eventLabel ?? undefined,\n        },\n        event.context\n      );\n      break;\n    }\n\n    case SubscribedEventType.WARNING: {\n      logger.logWarning(\n        {\n          component: event.component,\n          message: event.message,\n          action: 'Unknown',\n          // NOTE: We're discarding context.\n        },\n        event.context\n      );\n      break;\n    }\n\n    case SubscribedEventType.ECOMMERCE:\n    case SubscribedEventType.EXPERIMENT_IMPRESSION:\n    case SubscribedEventType.PAGE_LOAD:\n    case SubscribedEventType.FIRST_PAGE_LOAD:\n\n    // fall through\n    case SubscribedEventType.PHONE_NUMBER_EVENT: {\n      logger.logCustom(event, event.context);\n      break;\n    }\n  }\n};\n\nexport const logCustom = logger.logCustom;\n"],
  "mappings": ";;;;;;;;;;;;;iZAAA,IAAAA,GA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B,UAChB,QAAe,UACf,SAAgB,UAChB,UAAiB,UACjB,UAAiB,UACjB,WAAgB,UAChB,WAAkB,UAClB,eAAoB,UACpB,SAAgB,UAChB,QAAe,UACf,QAAe,UACf,MAAa,UACb,KAAY,UACZ,QAAe,SAClB,EAKaC,GAA6BC,GAAKF,GAA4B,oBAG3E,CAAC,EClCM,IAAMG,GAAgB,IAAI,IAAI,CACnC,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,IACF,CAAC,EC/BM,IAAMC,GAAoC,CAC/C,GAAI,6CACJ,QAAS,oFACT,QAAS,4DACT,QAAS,yDACT,UAAW,2BACX,UAAW,2BACX,QAAS,WACT,QAAS,oBACT,QAAS,QACT,QAAS,yBACT,QAAS,eACT,QAAS,eACT,QAAS,QACT,SAAU,WACV,QAAS,QACT,QAAS,uBACT,QAAS,wBACT,QAAS,mDACT,QAAS,6CACT,QAAS,uCACT,QAAS,SACT,QAAS,mBACT,QAAS,gBACT,QAAS,WACT,QAAS,qBACT,QAAS,yCACT,QAAS,qBACT,QAAS,gBACT,QAAS,gBACT,QAAS,gBACT,QAAS,uCACT,QAAS,QACT,QAAS,iCACT,QAAS,oBACT,QAAS,SACT,QAAS,wBACT,QAAS,0BACT,GAAI,uCACJ,QAAS,iBACT,QAAS,6CACT,QAAS,kBACT,QAAS,wBACT,QAAS,yBACT,GAAI,aACJ,QAAS,yBACT,QAAS,yBACT,QAAS,UACT,QAAS,iCACT,QAAS,uCACT,QAAS,sGACT,QAAS,eACT,QAAS,2BACT,QAAS,+DACT,QAAS,sBACX,ECvDO,IAAMC,GAAqB,KAAK,KAAK,EAAyB,EAWxDC,GAAuB,EASvBC,GAA6B,KAAK,MAC5C,IAAsBD,GAAwB,GACjD,EC5BO,IAAME,GAA0C,CACpD,MAAY,eACZ,GAAU,cACV,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7B,CAAC,EACD,KACF,CAEA,YAAgC,CAC9BN,GAAO,SACL,CACE,MAAOM,EAAM,MACb,UAAWA,EAAM,UACjB,QAASA,EAAM,QACf,OAAQ,SACV,EACAA,EAAM,OACR,EACA,KACF,CAEA,eAAmC,CACjCN,GAAO,QACL,CACE,UAAWM,EAAM,cACjB,OAAQA,EAAM,YACd,MAAOA,EAAM,YAAc,MAC7B,EACAA,EAAM,OACR,EACA,KACF,CAEA,sBAA0C,CACxCN,GAAO,UACL,CACE,UAAWM,EAAM,cACjB,SAAUA,EAAM,cAChB,QAASA,EAAM,WACf,MAAOA,EAAM,YAAc,MAC7B,EACAA,EAAM,OACR,EACA,KACF,CAEA,qBAAyC,CACvCN,GAAO,SACL,CACE,UAAWM,EAAM,cACjB,SAAUA,EAAM,cAChB,MAAOA,EAAM,WACb,MAAOA,EAAM,YAAc,MAC7B,EACAA,EAAM,OACR,EACA,KACF,CAEA,cAAkC,CAChCN,GAAO,WACL,CACE,UAAWM,EAAM,UACjB,QAASA,EAAM,QACf,OAAQ,SAEV,EACAA,EAAM,OACR,EACA,KACF,CAEA,gBACA,4BACA,gBACA,sBAGA,yBAA6C,CAC3CN,GAAO,UAAUM,EAAOA,EAAM,OAAO,EACrC,KACF,CACF,CACF,EAEaO,GAAYb,GAAO",
  "names": ["require_is_plain_obj", "__commonJSMin", "exports", "module", "value", "prototype", "BLOCKS", "INLINES", "MARKS", "TOP_LEVEL_BLOCKS", "LIST_ITEM_BLOCKS", "TABLE_BLOCKS", "VOID_BLOCKS", "CONTAINERS", "_a", "HEADINGS", "TEXT_CONTAINERS", "__spreadArray", "V1_NODE_TYPES", "V1_MARKS", "EMPTY_DOCUMENT", "hasValue", "obj", "value", "_i", "key", "isInline", "node", "isBlock", "isText", "typeMismatchError", "path", "property", "typeName", "minSizeError", "min", "maxSizeError", "max", "enumError", "expected", "unknownPropertyError", "requiredPropertyError", "ObjectAssertion", "_this", "errors", "isPlainObject", "optional", "properties", "unknowns", "assert", "foundErrors", "item", "index", "serializeError", "error", "step", "VOID_CONTENT", "NodeAssertion", "contentRule", "validateData", "$", "_c", "nodeTypes", "_d", "item$", "dataErrors", "_b", "EntityLinkAssertion", "_super", "__extends", "linkType", "contentNodeTypes", "data", "sys$", "HyperLinkAssertion", "assertLink", "Path", "element", "assertText", "text", "mark", "mark$", "assertInlineOrText", "assertList", "assertVoidEntryLink", "assertTableCell", "nodeValidator", "validateNode", "validateRichTextDocument", "document", "documentToPlainTextString", "rootNode", "blockDivisor", "acc", "node", "i", "nodeTextValue", "helpers", "nextNode", "isNextNodeBlock", "divisor", "require_rehackt", "__commonJSMin", "exports", "module", "require_browser_ponyfill", "__commonJSMin", "exports", "module", "__global__", "__globalThis__", "F", "globalThis", "irrelevant", "global", "support", "isDataView", "obj", "viewClasses", "isArrayBufferView", "normalizeName", "name", "normalizeValue", "value", "iteratorFor", "items", "iterator", "Headers", "headers", "header", "oldValue", "callback", "thisArg", "consumed", "body", "fileReaderReady", "reader", "resolve", "reject", "readBlobAsArrayBuffer", "blob", "promise", "readBlobAsText", "readArrayBufferAsText", "buf", "view", "chars", "i", "bufferClone", "Body", "rejected", "isConsumed", "decode", "methods", "normalizeMethod", "method", "upcased", "Request", "input", "options", "reParamSearch", "reQueryString", "form", "bytes", "split", "parseHeaders", "rawHeaders", "preProcessedHeaders", "line", "parts", "key", "Response", "bodyInit", "response", "redirectStatuses", "url", "status", "message", "error", "fetch", "init", "request", "xhr", "abortXhr", "fixUrl", "ctx", "setLocalStorageItem", "key", "value", "getLocalStorageItem", "removeLocalStorageItem", "allBrands", "stagingElasticCloudId", "productionElasticCloudId", "stagingElasticNode", "productionElasticNode", "googleAnalytics4Properties", "productionMwpGa4Properties", "omit", "gdprCountries", "localeMap", "connectionTimeoutS", "contentfulRetryCount", "contentfulRequestTimeoutMs", "productionDomains", "SitesToBrands", "stagingDomains", "defaultGeo", "getTokens", "baseUrl", "url", "withoutExtension", "spaceId", "assetId", "assetHash", "fileName", "getTokensFromAssetUrl", "assetUrl", "getTokensFromVodUrl", "vodUrl", "import_react", "defaultContext", "_", "noop", "AppContext", "getRawData", "data", "localizedRows", "nonLocalizedRows", "row", "i", "mergeLocalizedAndNonLocalizedRows", "nonLocalizedRow", "localizedRow", "series", "mergedRow", "keys", "key", "productionContentTokens", "import_rich_text_plain_text_renderer", "import_rich_text_types", "snapPersonasDisplayTextMap", "baseForOwn", "object", "iteratee", "baseFor_default", "keys_default", "baseForOwn_default", "baseInverter", "object", "setter", "iteratee", "accumulator", "baseForOwn_default", "value", "key", "baseInverter_default", "createInverter", "setter", "toIteratee", "object", "iteratee", "baseInverter_default", "createInverter_default", "objectProto", "nativeObjectToString", "invert", "createInverter_default", "result", "value", "key", "constant_default", "identity_default", "invert_default", "contentfulSpaceIds", "siteBySpaceId", "invert_default", "contentfulDevTokenKeys", "contentfulPreviewTokenKeys", "contentfulPublishedVersionTokenKeys", "extendStatics", "d", "b", "p", "__extends", "__", "__assign", "s", "i", "n", "__rest", "e", "t", "__awaiter", "thisArg", "_arguments", "P", "generator", "adopt", "value", "resolve", "reject", "fulfilled", "step", "e", "rejected", "result", "__generator", "body", "_", "t", "f", "y", "g", "verb", "n", "v", "op", "__spreadArray", "to", "from", "pack", "i", "l", "ar", "genericMessage", "_a", "setPrototypeOf", "obj", "proto", "InvariantError", "_super", "__extends", "message", "_this", "invariant", "condition", "message", "InvariantError", "verbosityLevels", "verbosityLevel", "wrapConsoleMethod", "name", "method", "setVerbosity", "level", "old", "version", "maybe", "thunk", "global_default", "maybe", "prefixCounts", "makeUniqueId", "prefix", "count", "stringifyForDisplay", "value", "space", "undefId", "makeUniqueId", "key", "wrap", "fn", "message", "args", "_i", "arg0", "getHandledErrorMsg", "getFallbackErrorMsg", "invariant", "condition", "newInvariantError", "optionalParams", "InvariantError", "ApolloErrorMessageHandler", "version", "stringify", "arg", "stringifyForDisplay", "messageArgs", "global_default", "DEV", "_typeof", "obj", "isObjectLike", "value", "SYMBOL_ITERATOR", "SYMBOL_ASYNC_ITERATOR", "SYMBOL_TO_STRING_TAG", "getLocation", "source", "position", "lineRegexp", "line", "column", "match", "printLocation", "location", "printSourceLocation", "getLocation", "source", "sourceLocation", "firstLineColumnOffset", "body", "whitespace", "lineIndex", "lineOffset", "lineNum", "columnOffset", "columnNum", "locationStr", "lines", "locationLine", "subLineIndex", "subLineColumnNum", "subLines", "i", "printPrefixedLines", "subLine", "existingLines", "_ref", "_", "line", "padLen", "_ref2", "prefix", "_ref3", "leftPad", "len", "str", "_typeof", "obj", "ownKeys", "object", "enumerableOnly", "keys", "symbols", "sym", "_objectSpread", "target", "i", "source", "key", "_defineProperty", "value", "_classCallCheck", "instance", "Constructor", "_defineProperties", "props", "descriptor", "_createClass", "protoProps", "staticProps", "_inherits", "subClass", "superClass", "_setPrototypeOf", "_createSuper", "Derived", "hasNativeReflectConstruct", "_isNativeReflectConstruct", "Super", "_getPrototypeOf", "result", "NewTarget", "_possibleConstructorReturn", "self", "call", "_assertThisInitialized", "_wrapNativeSuper", "Class", "_cache", "_isNativeFunction", "Wrapper", "_construct", "Parent", "args", "a", "fn", "o", "p", "GraphQLError", "_Error", "_super", "message", "nodes", "positions", "path", "originalError", "extensions", "_nodeLocations", "_nodeLocations2", "_nodeLocations3", "_this", "undefinedIfEmpty", "nodeLocations", "_i2", "_ref3", "_this$nodes", "_ref4", "loc", "pos", "getLocation", "originalExtensions", "isObjectLike", "printError", "SYMBOL_TO_STRING_TAG", "array", "error", "output", "_i4", "_error$nodes2", "node", "printLocation", "_i6", "_error$locations2", "location", "printSourceLocation", "syntaxError", "source", "position", "description", "GraphQLError", "Kind", "invariant", "condition", "message", "booleanCondition", "nodejsCustomInspectSymbol", "nodejsCustomInspectSymbol_default", "defineInspect", "classObject", "fn", "invariant", "nodejsCustomInspectSymbol_default", "Location", "startToken", "endToken", "source", "_proto", "defineInspect", "Token", "kind", "start", "end", "line", "column", "prev", "value", "_proto2", "isNode", "maybeNode", "TokenKind", "_typeof", "obj", "MAX_ARRAY_LENGTH", "MAX_RECURSIVE_DEPTH", "inspect", "value", "formatValue", "seenValues", "formatObjectValue", "previouslySeenValues", "customInspectFn", "getCustomFn", "customValue", "formatArray", "formatObject", "object", "keys", "getObjectTag", "properties", "key", "array", "len", "remaining", "items", "i", "nodejsCustomInspectSymbol_default", "tag", "name", "devAssert", "condition", "message", "booleanCondition", "instanceOf_default", "value", "constructor", "_defineProperties", "target", "props", "i", "descriptor", "_createClass", "Constructor", "protoProps", "staticProps", "Source", "body", "name", "locationOffset", "devAssert", "inspect", "SYMBOL_TO_STRING_TAG", "isSource", "source", "instanceOf_default", "DirectiveLocation", "dedentBlockStringValue", "rawString", "lines", "commonIndent", "getBlockStringIndentation", "i", "startLine", "isBlank", "endLine", "str", "value", "_commonIndent", "isFirstLine", "isEmptyLine", "indent", "printBlockString", "indentation", "preferMultipleLines", "isSingleLine", "hasLeadingSpace", "hasTrailingQuote", "hasTrailingSlash", "printAsMultipleLines", "result", "Lexer", "source", "startOfFileToken", "Token", "TokenKind", "_proto", "token", "_token$next", "readToken", "isPunctuatorTokenKind", "kind", "printCharCode", "code", "lexer", "prev", "body", "bodyLength", "pos", "_line", "_col", "readComment", "readBlockString", "readString", "readNumber", "readName", "syntaxError", "unexpectedCharacterMessage", "line", "col", "start", "position", "firstCode", "isFloat", "readDigits", "isNameStart", "chunkStart", "value", "charCode", "uniCharCode", "invalidSequence", "rawValue", "dedentBlockStringValue", "a", "b", "c", "d", "char2hex", "parse", "source", "options", "parser", "Parser", "Parser", "source", "options", "sourceObj", "isSource", "Source", "Lexer", "_proto", "token", "TokenKind", "Kind", "start", "operation", "name", "operationToken", "nameOrAlias", "alias", "isConst", "item", "hasTypeCondition", "_this$_options", "_this", "_this2", "directives", "type", "keywordToken", "description", "operationTypes", "interfaces", "fields", "_this$_options2", "types", "_this$_options3", "args", "defaultValue", "values", "repeatable", "locations", "DirectiveLocation", "startToken", "_this$_options4", "Location", "kind", "syntaxError", "getTokenKindDesc", "getTokenDesc", "value", "atToken", "openKind", "parseFn", "closeKind", "nodes", "delimiterKind", "isPunctuatorTokenKind", "QueryDocumentKeys", "BREAK", "visit", "root", "visitor", "visitorKeys", "stack", "inArray", "keys", "index", "edits", "node", "key", "parent", "path", "ancestors", "newRoot", "isLeaving", "isEdited", "clone", "_i2", "_Object$keys2", "k", "editOffset", "ii", "editKey", "editValue", "result", "isNode", "inspect", "visitFn", "getVisitFn", "_visitorKeys$node$kin", "getVisitFn", "visitor", "kind", "isLeaving", "kindVisitor", "kindSpecificVisitor", "specificVisitor", "specificKindVisitor", "print", "ast", "visit", "printDocASTReducer", "MAX_LINE_LENGTH", "node", "join", "op", "name", "varDefs", "wrap", "directives", "selectionSet", "_ref", "variable", "type", "defaultValue", "_ref2", "selections", "block", "_ref3", "alias", "args", "prefix", "argsLine", "indent", "_ref4", "value", "_ref5", "_ref6", "typeCondition", "_ref7", "variableDefinitions", "_ref8", "_ref9", "_ref10", "key", "isBlockString", "printBlockString", "_ref11", "_ref12", "_ref13", "values", "_ref14", "fields", "_ref15", "_ref16", "_ref17", "_ref18", "_ref19", "addDescription", "_ref20", "operationTypes", "_ref21", "operation", "_ref22", "_ref23", "interfaces", "_ref24", "hasMultilineItems", "_ref25", "_ref26", "_ref27", "types", "_ref28", "_ref29", "_ref30", "_ref31", "repeatable", "locations", "_ref32", "_ref33", "_ref34", "_ref35", "_ref36", "_ref37", "_ref38", "cb", "maybeArray", "_maybeArray$filter$jo", "separator", "x", "array", "start", "maybeString", "end", "str", "isMultiline", "isSelectionNode", "node", "Kind", "stripIgnoredCharacters", "source", "sourceObj", "isSource", "Source", "body", "lexer", "Lexer", "strippedBody", "wasLastAddedTokenNonPunctuator", "TokenKind", "currentToken", "tokenKind", "isNonPunctuator", "isPunctuatorTokenKind", "tokenBody", "dedentBlockString", "blockStr", "rawStr", "dedentBlockStringValue", "getBlockStringIndentation", "lastChar", "hasTrailingQuote", "shouldInclude", "_a", "variables", "directives", "getInclusionDirectives", "directive", "ifArgument", "evaledValue", "invariant", "hasDirectives", "names", "root", "all", "nameSet", "uniqueCount", "visit", "node", "BREAK", "hasClientExports", "document", "isInclusionDirective", "_a", "value", "getInclusionDirectives", "directives", "result", "directive", "directiveArguments", "directiveName", "invariant", "ifArgument", "ifValue", "defaultMakeData", "forEach", "slice", "hasOwnProperty", "Trie", "_Trie", "weakness", "makeData", "array", "node", "key", "i", "len", "map", "data", "head", "child", "create", "isObjRef", "value", "canUseWeakMap", "maybe", "canUseWeakSet", "canUseSymbol", "canUseAsyncIteratorSymbol", "canUseDOM", "usingJSDOM", "canUseLayoutEffect", "isNonNullObject", "obj", "getFragmentQueryDocument", "document", "fragmentName", "actualFragmentName", "fragments", "definition", "newInvariantError", "invariant", "__assign", "__spreadArray", "query", "createFragmentMap", "symTable", "fragment", "getFragmentFromSelection", "selection", "fragmentMap", "defaultDispose", "StrongCache", "max", "dispose", "key", "node", "older", "newer", "value", "noop", "defaultDispose", "_WeakRef", "value", "_WeakMap", "_FinalizationRegistry", "finalizationBatchSize", "WeakCache", "max", "dispose", "iterator", "i", "node", "key", "older", "newer", "scheduledCleanup", "schedule", "cache", "AutoCleanedWeakCache", "max", "dispose", "WeakCache", "key", "value", "ret", "AutoCleanedStrongCache", "StrongCache", "cacheSizeSymbol", "cacheSizes", "__assign", "global_default", "globalCaches", "registerGlobalCache", "name", "getSize", "getApolloClientMemoryInternals", "_getApolloClientMemoryInternals", "getInMemoryCacheMemoryInternals", "_getInMemoryCacheMemoryInternals", "getApolloCacheMemoryInternals", "_getApolloCacheMemoryInternals", "getCurrentCacheSizes", "defaults", "_a", "k", "v", "cacheSizes", "__assign", "_b", "_c", "linkInfo", "transformInfo", "_e", "_d", "getWrapperInformation", "fragments", "isWrapper", "f", "isDefined", "value", "transform", "recurseTransformInfo", "cache", "__spreadArray", "link", "canonicalStringify", "value", "stableObjectReplacer", "sortingMap", "AutoCleanedStrongCache", "cacheSizes", "registerGlobalCache", "key", "proto", "keys", "everyKeyInOrder", "unsortedKey", "sortedKeys", "sortedKey", "sortedObject_1", "i", "makeReference", "id", "isReference", "obj", "isDocumentNode", "value", "isNonNullObject", "isStringValue", "isBooleanValue", "isIntValue", "isFloatValue", "isVariable", "isObjectValue", "isListValue", "isEnumValue", "isNullValue", "valueToObjectRepresentation", "argObj", "name", "variables", "nestedArgObj_1", "variableValue", "listValue", "nestedArgArrayObj", "newInvariantError", "storeKeyNameFromField", "field", "directivesObj", "directive", "_a", "getStoreKeyName", "KNOWN_DIRECTIVES", "storeKeyNameStringify", "canonicalStringify", "fieldName", "args", "directives", "filterKeys", "filteredArgs_1", "key", "completeFieldName", "stringifiedArgs", "s", "previous", "argumentsObjectFromField", "argObj_1", "resultKeyNameFromField", "getTypenameFromResult", "result", "selectionSet", "fragmentMap", "fragments", "_i", "selection", "isField", "_b", "fragments_1", "typename", "getFragmentFromSelection", "isInlineFragment", "checkDocument", "doc", "invariant", "operations", "d", "definition", "newInvariantError", "getOperationDefinition", "getOperationName", "x", "getFragmentDefinitions", "getQueryDefinition", "queryDef", "getFragmentDefinition", "fragmentDef", "getMainDefinition", "queryDoc", "fragmentDefinition", "_i", "_a", "operation", "getDefaultValues", "defaultValues", "defs", "def", "valueToObjectRepresentation", "currentContext", "MISSING_VALUE", "idCounter", "makeSlotClass", "context", "value", "callback", "args", "thisArg", "slots", "parent", "saved", "maybe", "fn", "globalKey", "host", "globalHost", "Slot", "bind", "noContext", "Slot", "parentEntrySlot", "Slot", "hasOwnProperty", "arrayFromSet", "set", "array", "item", "maybeUnsubscribe", "entryOrDep", "unsubscribe", "emptySetPool", "POOL_TARGET_SIZE", "assert", "condition", "optionalMessage", "valueIs", "a", "b", "len", "valueGet", "value", "valueCopy", "Entry", "_Entry", "fn", "mightBeDirty", "rememberParent", "args", "reallyRecompute", "reportDirty", "maybeUnsubscribe", "forgetChildren", "eachParent", "parent", "child", "forgetChild", "dep", "arrayFromSet", "parentEntrySlot", "reportDirtyChild", "reportCleanChild", "entry", "recomputeNewValue", "maybeSubscribe", "setClean", "normalizeResult", "oldValueCopy", "e", "reportClean", "callback", "parentCount", "parents", "i", "parentWasClean", "childValue", "removeDirtyChild", "dc", "_value", "EntryMethods", "dep", "options", "depsByKey", "subscribe", "depend", "key", "parent", "parentEntrySlot", "maybeUnsubscribe", "entryMethodName", "m", "hasOwnProperty", "arrayFromSet", "entry", "defaultKeyTrie", "defaultMakeCacheKey", "args", "Trie", "caches", "wrap", "originalFunction", "max", "keyArgs", "makeCacheKey", "defaultMakeCacheKey", "normalizeResult", "subscribe", "cacheOption", "StrongCache", "cache", "entry", "optimistic", "key", "Entry", "value", "parentEntrySlot", "dirtyKey", "peekKey", "forgetKey", "identity", "document", "DocumentTransform", "transform", "options", "canUseWeakSet", "predicate", "left", "right", "documentTransform", "_this", "stableCacheKeys_1", "Trie", "canUseWeakMap", "wrap", "cacheKeys", "invariant", "cacheSizes", "WeakCache", "checkDocument", "transformedDocument", "otherTransform", "printCache", "print", "ast", "result", "AutoCleanedWeakCache", "cacheSizes", "registerGlobalCache", "isArray", "isNonEmptyArray", "value", "TYPENAME_FIELD", "Kind", "isEmpty", "op", "fragmentMap", "selection", "nullIfDocIsEmpty", "doc", "getOperationDefinition", "getFragmentDefinition", "createFragmentMap", "getFragmentDefinitions", "getDirectiveMatcher", "configs", "names", "tests", "directive", "config", "testConfig", "test", "makeInUseGetterFunction", "defaultKey", "map", "key", "inUse", "removeDirectivesFromDocument", "directives", "checkDocument", "getInUseByOperationName", "getInUseByFragmentName", "getInUse", "ancestors", "p", "ancestor", "isArray", "invariant", "operationCount", "i", "directiveMatcher", "shouldRemoveField", "nodeDirectives", "isNonEmptyArray", "originalFragmentDefsByPath", "firstVisitMadeChanges", "fieldOrInlineFragmentVisitor", "node", "docWithoutDirectiveSubtrees", "visit", "_key", "_parent", "_path", "path", "originalNode", "populateTransitiveVars", "childFragmentName", "varName", "allFragmentNamesUsed", "def", "fragmentName", "fragmentWillBeRemoved", "enterVisitor", "usedVariableNames_1", "__assign", "varDef", "addTypenameToDocument", "parent", "selections", "skip", "isField", "field", "d", "__spreadArray", "buildQueryFromSelectionSet", "document", "definition", "getMainDefinition", "definitionOperation", "modifiedDoc", "visit", "node", "__assign", "removeClientSetsFromDocument", "checkDocument", "removeDirectivesFromDocument", "directive", "hasOwnProperty", "mergeDeep", "sources", "_i", "mergeDeepArray", "target", "count", "merger", "DeepMerger", "i", "defaultReconciler", "source", "property", "reconciler", "isNonNullObject", "_this", "context", "sourceKey", "targetValue", "result", "__spreadArray", "value", "__assign", "_createForOfIteratorHelperLoose", "o", "allowArrayLike", "it", "_unsupportedIterableToArray", "i", "minLen", "_arrayLikeToArray", "n", "arr", "len", "arr2", "_defineProperties", "target", "props", "descriptor", "_createClass", "Constructor", "protoProps", "staticProps", "hasSymbols", "hasSymbol", "name", "getSymbol", "SymbolIterator", "SymbolObservable", "SymbolSpecies", "getMethod", "obj", "key", "value", "getSpecies", "ctor", "Observable", "isObservable", "x", "hostReportError", "enqueue", "fn", "e", "cleanupSubscription", "subscription", "cleanup", "unsubscribe", "closeSubscription", "flushSubscription", "queue", "notifySubscription", "type", "observer", "m", "onNotify", "Subscription", "subscriber", "subscriptionObserver", "SubscriptionObserver", "_proto", "_proto2", "_proto3", "_this", "resolve", "reject", "done", "_this2", "C", "_this3", "_this4", "hasSeed", "hasValue", "seed", "acc", "first", "_this5", "_len", "sources", "_key", "index", "startNext", "next", "v", "_this6", "subscriptions", "outer", "inner", "completeIfDone", "s", "method", "observable", "_iterator", "_step", "item", "_len2", "items", "_key2", "symbolObservablePonyfill", "root", "result", "Symbol", "root", "result", "symbolObservablePonyfill", "prototype", "Observable", "fakeObsSymbol", "toString", "cloneDeep", "value", "cloneDeepHelper", "val", "seen", "copy_1", "child", "i", "copy_2", "key", "deepFreeze", "value", "workSet", "obj", "isNonNullObject", "shallowFreeze", "name", "e", "maybeDeepFreeze", "iterateObserversSafely", "observers", "method", "argument", "observersWithMethod", "obs", "asyncMap", "observable", "mapFn", "catchFn", "Observable", "observer", "promiseQueue", "callback", "resolve", "makeCallback", "examiner", "key", "arg", "both", "result", "error", "handler", "sub", "fixObservableSubclass", "subclass", "set", "key", "Observable", "canUseSymbol", "isPromiseLike", "value", "Concast", "_super", "__extends", "sources", "_this", "observer", "resolve", "reject", "result", "iterateObserversSafely", "error", "sub", "_a", "_b", "obs", "reason", "_", "Observable", "iterable", "nextOrError", "method", "arg", "nextResultListeners", "listener", "callback", "called", "fixObservableSubclass", "Concast", "isExecutionPatchIncrementalResult", "value", "isExecutionPatchInitialResult", "isExecutionPatchResult", "isApolloPayloadResult", "isNonNullObject", "mergeIncrementalData", "prevResult", "result", "mergedData", "merger", "DeepMerger", "isNonEmptyArray", "_a", "data", "path", "key", "isNumericKey", "parent_1", "graphQLResultHasError", "result", "errors", "getGraphQLErrorsFromResult", "isNonEmptyArray", "graphQLErrors", "isExecutionPatchIncrementalResult", "incrementalResult", "compact", "objects", "_i", "result", "obj", "key", "value", "mergeOptions", "defaults", "options", "compact", "__assign", "fromError", "errorValue", "Observable", "observer", "throwServerError", "response", "result", "message", "error", "validateOperation", "operation", "OPERATION_FIELDS", "_i", "_a", "key", "newInvariantError", "createOperation", "starting", "operation", "context", "__assign", "setContext", "next", "getContext", "transformOperation", "operation", "transformedOperation", "getOperationName", "filterOperationVariables", "variables", "query", "result", "__assign", "unusedNames", "visit", "node", "_key", "parent", "name", "passthrough", "op", "forward", "Observable", "toLink", "handler", "ApolloLink", "isTerminating", "link", "request", "links", "x", "y", "test", "left", "right", "leftLink", "rightLink", "ret", "operation", "createOperation", "transformOperation", "validateOperation", "first", "second", "firstLink", "invariant", "nextLink", "next", "newInvariantError", "error", "observer", "fn", "execute", "ApolloLink", "asyncIterator", "source", "iterator", "_a", "nodeStreamIterator", "stream", "cleanup", "error", "done", "data", "waiting", "onData", "chunk", "shiftedArr", "onError", "err", "all", "pair", "onEnd", "getNext", "resolve", "reject", "iterator", "canUseAsyncIteratorSymbol", "promiseIterator", "promise", "resolved", "iterator", "resolve", "reject", "value", "canUseAsyncIteratorSymbol", "readerIterator", "reader", "iterator", "canUseAsyncIteratorSymbol", "isNodeResponse", "value", "isReadableStream", "isAsyncIterableIterator", "canUseAsyncIteratorSymbol", "isStreamableBlob", "isBlob", "isNodeReadableStream", "responseIterator", "response", "body", "asyncIterator", "readerIterator", "promiseIterator", "nodeStreamIterator", "PROTOCOL_ERRORS_SYMBOL", "graphQLResultHasProtocolErrors", "result", "isApolloError", "err", "generateErrorMessage", "errors", "__spreadArray", "isNonNullObject", "ApolloError", "_super", "__extends", "_a", "graphQLErrors", "protocolErrors", "clientErrors", "networkError", "errorMessage", "extraInfo", "_this", "hasOwnProperty", "readMultipartBody", "response", "nextValue", "decoder", "contentType", "_d", "delimiter", "boundaryVal", "boundary", "buffer", "iterator", "responseIterator", "running", "_a", "_e", "value", "done", "chunk", "searchFrom", "bi", "message", "_b", "i", "headers", "parseHeaders", "contentType_1", "body", "result", "parseJsonBody", "isApolloPayloadResult", "next", "__assign", "_c", "PROTOCOL_ERRORS_SYMBOL", "headerText", "headersInit", "line", "name_1", "bodyText", "getResult", "throwServerError", "err", "parseError", "handleError", "observer", "parseAndCheckHttpResponse", "operations", "op", "serializeFetchParameter", "p", "label", "serialized", "e", "parseError", "newInvariantError", "defaultHttpOptions", "defaultHeaders", "defaultOptions", "fallbackHttpConfig", "defaultPrinter", "ast", "printer", "selectHttpOptionsAndBodyInternal", "operation", "printer", "configs", "_i", "options", "http", "config", "__assign", "removeDuplicateHeaders", "operationName", "extensions", "variables", "query", "body", "print", "headers", "preserveHeaderCase", "normalizedHeaders_1", "name", "headerData", "normalizedHeaders", "checkFetcher", "fetcher", "newInvariantError", "selectURI", "operation", "fallbackURI", "context", "contextURI", "rewriteURIForGET", "chosenURI", "body", "queryParams", "addQueryParam", "key", "value", "serializedVariables", "serializeFetchParameter", "parseError", "serializedExtensions", "fragment", "preFragment", "fragmentStart", "queryParamsPrefix", "newURI", "backupFetch", "maybe", "createHttpLink", "linkOptions", "_a", "uri", "preferredFetch", "_b", "print", "defaultPrinter", "includeExtensions", "preserveHeaderCase", "useGETForQueries", "_c", "includeUnusedVariables", "requestOptions", "__rest", "checkFetcher", "linkConfig", "ApolloLink", "operation", "chosenURI", "selectURI", "context", "clientAwarenessHeaders", "name_1", "version", "contextHeaders", "__assign", "contextConfig", "hasDirectives", "transformedQuery", "removeClientSetsFromDocument", "fromError", "selectHttpOptionsAndBodyInternal", "fallbackHttpConfig", "options", "body", "filterOperationVariables", "controller", "definitionIsMutation", "d", "definitionIsSubscription", "isSubscription", "getMainDefinition", "hasDefer", "acceptHeader", "invariant", "rewriteURIForGET", "newURI", "parseError", "serializeFetchParameter", "Observable", "observer", "currentFetch", "observerNext", "response", "ctype", "readMultipartBody", "parseAndCheckHttpResponse", "err", "handleError", "HttpLink", "_super", "__extends", "options", "_this", "createHttpLink", "ApolloLink", "toString", "hasOwnProperty", "fnToStr", "previousComparisons", "equal", "a", "b", "check", "lib_default", "aTag", "bTag", "previouslyCompared", "aKeys", "definedKeys", "bKeys", "keyCount", "k", "key", "aIterator", "isMap", "info", "aKey", "aValue", "len", "aCode", "endsWith", "nativeCodeSuffix", "obj", "isDefinedKey", "full", "suffix", "fromIndex", "bSet", "ApolloCache", "wrap", "getFragmentQueryDocument", "cacheSizes", "WeakCache", "options", "_this", "optimisticId", "updateResult", "transaction", "document", "object", "optimistic", "__assign", "fragment", "fragmentName", "from", "_a", "diffOptions", "latestDiff", "Observable", "observer", "diff", "equal", "result", "mergeDeepArray", "error", "id", "data", "__rest", "update", "cache", "value", "ApolloCache", "getApolloCacheMemoryInternals", "MissingFieldError", "_super", "__extends", "message", "path", "query", "variables", "_this", "i", "_a", "hasOwn", "isNullish", "value", "defaultDataIdFromObject", "_a", "context", "__typename", "id", "_id", "isNullish", "defaultConfig", "normalizeConfig", "config", "compact", "shouldCanonizeResults", "value", "getTypenameFromStoreObject", "store", "objectOrReference", "isReference", "TypeOrFieldNameRegExp", "fieldNameFromStoreName", "storeFieldName", "match", "selectionSetMatchesResult", "selectionSet", "result", "variables", "isNonNullObject", "isArray", "item", "field", "isField", "shouldInclude", "key", "resultKeyNameFromField", "hasOwn", "storeValueIsStoreObject", "makeProcessedFieldsMerger", "DeepMerger", "extractFragmentContext", "document", "fragments", "fragmentMap", "createFragmentMap", "getFragmentDefinitions", "name", "def", "DELETE", "delModifier", "INVALIDATE", "EntityStore", "policies", "group", "_this", "objectOrReference", "storeFieldName", "maybeDeepFreeze", "isReference", "objOrRef", "objOrIdOrRef", "mergeIntoStore", "makeReference", "id", "ref", "__assign", "dataId", "fieldName", "hasOwn", "storeObject", "Layer", "dependOnExistence", "older", "newer", "existing", "incoming", "invariant", "merged", "DeepMerger", "storeObjectReconciler", "fieldsToDirty_1", "fieldNameFromStoreName", "fields", "changedFields_1", "needToMerge_1", "allDeleted_1", "sharedDetails_1", "fieldNameOrOptions", "from", "fieldValue", "modify", "newValue", "checkReference", "seenReference", "someNonReference", "_i", "newValue_1", "value", "args", "_a", "typename", "options", "limit", "evicted", "obj", "extraRootIds", "newData", "__META", "rest_1", "__rest", "rootId", "count", "ids", "snapshot", "idsToRemove", "root_1", "found_1", "root", "workSet_1", "isNonNullObject", "key", "child", "CacheGroup", "caching", "parent", "dep", "Trie", "canUseWeakMap", "dataId", "storeFieldName", "makeDepKey", "fieldName", "fieldNameFromStoreName", "maybeDependOnExistenceOfEntity", "store", "entityId", "supportsResultCaching", "EntityStore", "Root", "_super", "__extends", "_a", "policies", "_b", "resultCaching", "seed", "_this", "Stump", "layerId", "replay", "Layer", "id", "group", "ownStoreObject", "parentStoreObject", "equal", "__assign", "fromParent", "hasOwn", "p", "root", "older", "newer", "storeObjectReconciler", "existingObject", "incomingObject", "property", "existingValue", "incomingValue", "shallowCopy", "value", "isNonNullObject", "isArray", "__assign", "ObjectCanon", "canUseWeakSet", "Trie", "canUseWeakMap", "copy", "_this", "original", "proto", "array", "node", "proto_1", "array_1", "keys", "firstValueIndex_1", "key", "obj_1", "i", "obj", "json", "execSelectionSetKeyArgs", "options", "StoreReader", "config", "_this", "canUseWeakMap", "compact", "shouldCanonizeResults", "ObjectCanon", "wrap", "canonizeResults", "peekArgs", "other", "_a", "__assign", "maybeDependOnExistenceOfEntity", "cacheSizes", "selectionSet", "parent", "context", "supportsResultCaching", "isReference", "field", "array", "store", "query", "_b", "rootId", "variables", "_c", "returnPartialData", "_d", "policies", "getDefaultValues", "getQueryDefinition", "rootRef", "makeReference", "execResult", "getMainDefinition", "canonicalStringify", "extractFragmentContext", "missing", "MissingFieldError", "firstMissing", "result", "latest", "objectOrReference", "enclosingRef", "typename", "objectsToMerge", "missingMerger", "DeepMerger", "handleMissing", "resultName", "workSet", "selection", "shouldInclude", "isField", "fieldValue", "resultKeyNameFromField", "addTypenameToDocument", "isArray", "fragment", "getFragmentFromSelection", "Kind", "newInvariantError", "mergeDeepArray", "finalResult", "frozen", "maybeDeepFreeze", "childResult", "i", "item", "assertSelectionSetForIdValue", "firstMissing", "tree", "_", "value", "result", "assertSelectionSetForIdValue", "store", "field", "fieldValue", "workSet_1", "isNonNullObject", "invariant", "isReference", "getTypenameFromStoreObject", "cacheSlot", "Slot", "cacheInfoMap", "getCacheInfo", "cache", "info", "dep", "forgetCache", "rv", "recallCache", "makeVar", "value", "caches", "listeners", "newValue", "broadcast", "oldListeners", "listener", "attach", "specifierInfoCache", "lookupSpecifierInfo", "spec", "cacheKey", "keyFieldsFnFromSpecifier", "specifier", "info", "object", "context", "extract", "from", "key", "keyObject", "collectSpecifierPaths", "schemaKeyPath", "extracted", "extractKeyPath", "hasOwn", "extractKey", "invariant", "keyArgsFnFromSpecifier", "args", "_a", "field", "variables", "fieldName", "collected", "keyPath", "firstKey", "firstChar", "isNonEmptyArray", "directiveName_1", "d", "directiveArgs", "argumentsObjectFromField", "variableName", "varKeyPath", "suffix", "extractor", "merger", "DeepMerger", "getSpecifierPaths", "path", "toMerge", "paths_1", "currentPath_1", "i", "isArray", "p", "normalize", "reducer", "obj", "child", "value", "isNonNullObject", "argsFromFieldSpecifier", "spec", "argumentsObjectFromField", "nullKeyFieldsFn", "simpleKeyArgsFn", "_args", "context", "mergeTrueFn", "existing", "incoming", "_a", "mergeObjects", "mergeFalseFn", "_", "Policies", "config", "__assign", "defaultDataIdFromObject", "object", "partialContext", "policies", "typename", "storeObject", "options", "normalizeReadFieldOptions", "id", "policy", "keyFn", "specifierOrId", "isArray", "keyFieldsFnFromSpecifier", "typePolicies", "_this", "queryType", "mutationType", "subscriptionType", "__rest", "hasOwn", "keyFields", "fields", "setMerge", "merge", "fieldName", "keyArgs", "read", "keyArgsFnFromSpecifier", "which", "rootId", "old", "invariant", "possibleTypes", "supertype", "subtype", "match", "TypeOrFieldNameRegExp", "policy_1", "supertypes_1", "regExp", "fuzzy", "fuzzySupertypes", "rest", "inbox", "createIfMissing", "fieldPolicies", "supertypeSet", "fragment", "result", "variables", "typenameSupertypeSet", "workQueue_1", "maybeEnqueue_1", "needToCheckFuzzySubtypes", "checkingFuzzySubtypes", "i", "selectionSetMatchesResult", "fuzzyString", "fieldSpec", "storeFieldName", "args", "specifierOrString", "storeKeyNameFromField", "getStoreKeyName", "fieldNameFromStoreName", "objectOrReference", "nameOrField", "readOptions", "makeFieldFunctionOptions", "isReference", "cacheSlot", "parentTypename", "childTypename", "storage", "field", "makeMergeObjectsFunction", "makeFieldFunctionOptions", "policies", "objectOrReference", "fieldSpec", "context", "storage", "storeFieldName", "fieldName", "fieldNameFromStoreName", "variables", "_a", "toReference", "canRead", "argsFromFieldSpecifier", "isReference", "normalizeReadFieldOptions", "makeMergeObjectsFunction", "readFieldArgs", "fieldNameOrOptions", "from", "argc", "options", "__assign", "hasOwn", "invariant", "stringifyForDisplay", "store", "existing", "incoming", "isArray", "newInvariantError", "isNonNullObject", "eType", "iType", "typesDiffer", "storeValueIsStoreObject", "getContextFlavor", "context", "clientOnly", "deferred", "key", "flavored", "__assign", "StoreWriter", "cache", "reader", "fragments", "store", "_a", "_this", "query", "result", "dataId", "variables", "overwrite", "operationDefinition", "getOperationDefinition", "merger", "makeProcessedFieldsMerger", "getDefaultValues", "existing", "incoming", "canonicalStringify", "extractFragmentContext", "ref", "isReference", "newInvariantError", "storeObject", "mergeTree", "fieldNodeSet", "entityRef", "makeReference", "applied", "fieldsWithSelectionSets_1", "field", "hasSelectionSet_1", "storeFieldName", "fieldNameFromStoreName", "hasMergeFunction_1", "childTree", "warnAboutDataLoss", "selectionSet", "policies", "typename", "getTypenameFromResult", "readField", "options", "normalizeReadFieldOptions", "info", "result_1", "resultFieldKey", "resultKeyNameFromField", "value", "getChildMergeTree", "incomingValue", "childTypename", "storeValueIsStoreObject", "merge", "maybeRecycleChildMergeTree", "addTypenameToDocument", "invariant", "_b", "id", "keyObject", "e", "dataRef", "sets", "previous_1", "mergeMergeTrees", "mergeTreeIsEmpty", "cloneDeep", "isArray", "item", "fieldMap", "limitingTrie", "Trie", "flatten", "inheritedContext", "visitedNode", "selection", "shouldInclude", "isNonEmptyArray", "dir", "name", "args", "argumentsObjectFromField", "isField", "fragment", "getFragmentFromSelection", "Kind", "getStorageArgs", "e_1", "i_1", "changedFields_1", "getValue_1", "from", "eVal", "iVal", "aVal", "emptyMergeTreePool", "getChildMergeTree", "_a", "name", "map", "mergeMergeTrees", "left", "right", "mergeTreeIsEmpty", "info", "__assign", "needToMergeMaps", "merged", "remainingRightKeys_1", "leftTree", "key", "tree", "maybeRecycleChildMergeTree", "childTree", "warnings", "warnAboutDataLoss", "existingRef", "incomingObj", "storeFieldName", "store", "getChild", "objOrRef", "child", "existing", "incoming", "isReference", "equal", "parentType", "fieldName", "fieldNameFromStoreName", "typeDotName", "childTypenames", "isArray", "typename", "invariant", "InMemoryCache", "_super", "__extends", "config", "_this", "DocumentTransform", "addTypenameToDocument", "makeVar", "normalizeConfig", "Policies", "rootStore", "EntityStore", "resetResultIdentities", "previousReader", "fragments", "StoreWriter", "StoreReader", "shouldCanonizeResults", "wrap", "c", "options", "cacheSizes", "store", "supportsResultCaching", "optimistic", "id", "variables", "canonicalStringify", "group", "data", "_a", "returnPartialData", "__assign", "e", "MissingFieldError", "hasOwn", "watch", "recallCache", "forgetCache", "print", "ids", "rootId", "object", "isReference", "invariant", "idToRemove", "newOptimisticData", "update", "removeOptimistic", "onWatchUpdated", "updateResult", "perform", "layer", "optimisticData", "alreadyDirty", "diff", "result", "optimisticId", "document", "lastDiff", "equal", "ApolloCache", "InMemoryCache", "getInMemoryCacheMemoryInternals", "NetworkStatus", "isNetworkRequestInFlight", "networkStatus", "equalByQuery", "query", "_a", "_b", "variables", "aData", "aRest", "__rest", "bData", "bRest", "lib_default", "equalBySelectionSet", "getMainDefinition", "createFragmentMap", "getFragmentDefinitions", "selectionSet", "aResult", "bResult", "context", "seenSelections", "selection", "shouldInclude", "selectionHasNonreactiveDirective", "isField", "resultKey", "resultKeyNameFromField", "aResultChild", "bResultChild", "childSelectionSet", "aChildIsArray", "bChildIsArray", "length_1", "i", "fragment", "getFragmentFromSelection", "directiveIsNonreactive", "dir", "assign", "hasOwnProperty", "ObservableQuery", "_super", "__extends", "_a", "queryManager", "queryInfo", "options", "_this", "observer", "subObserver", "defaultSubscriptionObserverErrorCallback", "first", "last", "skipCacheDataFor", "_b", "_c", "_d", "defaultFetchPolicy", "_e", "fetchPolicy", "_f", "initialFetchPolicy", "__assign", "opDef", "getOperationDefinition", "resolve", "reject", "result", "subscription", "saveAsLastResult", "lastResult", "networkStatus", "NetworkStatus", "isNetworkRequestInFlight", "diff", "equal", "logMissingFieldErrors", "newResult", "variables", "resultIsDifferent", "equalByQuery", "key", "variablesMustMatch", "reobserveOptions", "queryDef", "getQueryDefinition", "vars", "v", "invariant", "fetchMoreOptions", "combinedOptions", "qid", "originalNetworkStatus", "updatedQuerySet", "fetchMoreResult", "cache", "previous", "updateQuery", "watch", "reobserveCacheFirst", "subscriptionData", "err", "newOptions", "mapFn", "pollInterval", "reason", "newNetworkStatus", "query", "pollingInfo", "info", "poll", "maybeFetch", "error", "cloneDeep", "useDisposableConcast", "oldVariables", "oldFetchPolicy", "mergedOptions", "compact", "finishWaitingForOwnResult", "concast", "fromLink", "args", "_i", "lastError", "isDifferent", "iterateObserversSafely", "errorResult", "sub", "document", "Observable", "fixObservableSubclass", "ObservableQuery", "reobserveCacheFirst", "obsQuery", "fetchPolicy", "_a", "nextFetchPolicy", "currentFetchPolicy", "context", "defaultSubscriptionObserverErrorCallback", "error", "invariant", "logMissingFieldErrors", "missing", "skipCacheDataFor", "LocalState", "_a", "cache", "client", "resolvers", "fragmentMatcher", "_this", "resolverGroup", "mergeDeep", "_b", "document", "remoteResult", "context", "variables", "_c", "onlyRunForcedResolvers", "localResult", "__assign", "hasDirectives", "removeClientSetsFromDocument", "obj", "document_1", "data", "forceResolvers", "visit", "node", "arg", "BREAK", "buildQueryFromSelectionSet", "rootValue_1", "rootValue", "mainDefinition", "getMainDefinition", "fragments", "getFragmentDefinitions", "fragmentMap", "createFragmentMap", "selectionsToResolve", "definitionOperation", "defaultOperationType", "execContext", "isClientFieldDescendant", "result", "selectionSet", "resultsToMerge", "execute", "selection", "__awaiter", "shouldInclude", "isField", "fieldResult", "resultKeyNameFromField", "isInlineFragment", "fragment", "invariant", "typeCondition", "fragmentResult", "mergeDeepArray", "field", "fieldName", "aliasedFieldName", "aliasUsed", "defaultResult", "resultPromise", "resolverType", "resolverMap", "resolve", "cacheSlot", "argumentsObjectFromField", "directive", "isClientField", "d", "item", "isSingleASTNode", "selectionsToResolveCache", "collectByDefinition", "definitionNode", "matches_1", "_", "__", "___", "ancestors", "isSelectionNode", "spread", "fragmentSelections", "destructiveMethodCounts", "canUseWeakMap", "wrapDestructiveCacheMethod", "cache", "methodName", "original", "cancelNotifyTimeout", "info", "QueryInfo", "queryManager", "queryId", "query", "networkStatus", "NetworkStatus", "equal", "options", "oq", "diff", "variables", "_a", "_this", "oldDiff", "reobserveCacheFirst", "listener", "isNetworkRequestInFlight", "fetchPolicy", "watchOptions", "__assign", "result", "lastWrite", "document", "cacheWriteBehavior", "merger", "DeepMerger", "graphQLErrors", "isNonEmptyArray", "mergedData", "mergeIncrementalData", "shouldWriteResult", "diffOptions", "error", "shouldWriteResult", "result", "errorPolicy", "ignoreErrors", "writeWithErrors", "graphQLResultHasError", "hasOwnProperty", "IGNORE", "QueryManager", "_a", "cache", "link", "defaultOptions", "documentTransform", "_b", "queryDeduplication", "onBroadcast", "_c", "ssrMode", "_d", "clientAwareness", "localState", "_e", "assumeImmutableResults", "defaultContext", "_this", "AutoCleanedWeakCache", "cacheSizes", "Trie", "defaultDocumentTransform", "DocumentTransform", "document", "LocalState", "_info", "queryId", "newInvariantError", "error", "cancel", "mutation", "variables", "optimisticResponse", "updateQueries", "refetchQueries", "_f", "awaitRefetchQueries", "updateWithProxyFn", "onQueryUpdated", "_g", "fetchPolicy", "_h", "errorPolicy", "keepRootFields", "context", "invariant", "mutationId", "hasClientExports", "_j", "mutationStoreValue", "isOptimistic", "self", "resolve", "reject", "asyncMap", "__assign", "result", "graphQLResultHasError", "ApolloError", "getGraphQLErrorsFromResult", "storeResult", "err", "cacheWrites", "skipCache", "shouldWriteResult", "isExecutionPatchIncrementalResult", "isNonEmptyArray", "diff", "mergedData", "mergeIncrementalData", "updateQueries_1", "observableQuery", "queryName", "updater", "currentQueryResult", "complete", "nextQueryResult", "getOperationName", "results_1", "write", "update", "isFinalResult", "isExecutionPatchResult", "value", "fieldName", "DELETE", "data", "options", "networkStatus", "store", "info", "queryInfo", "transformCache", "cacheEntry", "hasDirectives", "removeDirectivesFromDocument", "getDefaultValues", "getOperationDefinition", "def", "query", "QueryInfo", "observable", "ObservableQuery", "NetworkStatus", "include", "queries", "queryNamesAndDocs", "legacyQueryOptions", "desc", "isDocumentNode", "isNonNullObject", "oq", "makeUniqueId", "included", "nameOrDoc", "includeStandby", "observableQueryPromises", "makeObservable", "hasErrors", "hasProtocolErrors", "graphQLResultHasProtocolErrors", "errors", "PROTOCOL_ERRORS_SYMBOL", "observablePromise_1", "Observable", "observer", "sub", "deduplication", "serverQuery", "inFlightLinkObservables_1", "operation", "printedServerQuery_1", "print", "varJson_1", "canonicalStringify", "entry", "concast", "Concast", "execute", "clientQuery", "cacheWriteBehavior", "requestId", "linkDocument", "graphQLErrors", "aqr", "networkError", "isApolloError", "defaults", "returnPartialData", "notifyOnNetworkStatusChange", "normalized", "fromVariables", "sourcesWithInfo", "cleanupCancelFn", "reason", "containsDataFromLink", "updateCache", "optimistic", "removeOptimistic", "includedQueriesById", "watch", "lastDiff", "results", "refetchWritePolicy", "oldNetworkStatus", "readCache", "resultsFromCache", "equal", "logMissingFieldErrors", "fromData", "isNetworkRequestInFlight", "resolved", "shouldNotify", "resultsFromLink", "newContext", "hasSuggestedDevtools", "ApolloClient", "options", "_this", "newInvariantError", "credentials", "headers", "cache", "documentTransform", "_a", "ssrMode", "_b", "ssrForceFetchDelay", "_c", "connectToDevTools", "_d", "queryDeduplication", "defaultOptions", "defaultContext", "_e", "assumeImmutableResults", "resolvers", "typeDefs", "fragmentMatcher", "clientAwarenessName", "clientAwarenessVersion", "link", "uri", "HttpLink", "ApolloLink", "version", "LocalState", "QueryManager", "windowWithDevTools", "devtoolsSymbol", "hasSuggestedDevtools", "nav", "ua", "url", "invariant", "mergeOptions", "__assign", "ref", "cb", "payload", "execute", "fn", "c", "map", "result", "obsQuery", "queries", "results", "error", "optimistic", "newLink", "getApolloClientMemoryInternals", "docCache", "fragmentSourceMap", "printFragmentWarnings", "experimentalFragmentVariables", "normalize", "string", "cacheKeyFromLoc", "loc", "processFragments", "ast", "seenKeys", "definitions", "fragmentDefinition", "fragmentName", "sourceKey", "sourceKeySet", "__assign", "stripLoc", "doc", "workSet", "node", "key", "value", "parseDocument", "source", "cacheKey", "parsed", "parse", "gql", "literals", "args", "_i", "result", "arg", "i", "resetCaches", "disableFragmentWarnings", "enableExperimentalFragmentVariables", "disableExperimentalFragmentVariables", "extras", "gql_1", "lib_default", "setVerbosity", "React", "contextKey", "canUseSymbol", "getApolloContext", "invariant", "React", "context", "React", "ApolloProvider", "_a", "client", "children", "ApolloContext", "getApolloContext", "parentContext", "context", "__assign", "invariant", "React", "useApolloClient", "override", "context", "getApolloContext", "client", "invariant", "React", "React", "didWarnUncachedGetSnapshot", "uSESKey", "realHook", "React", "useSyncExternalStore", "subscribe", "getSnapshot", "getServerSnapshot", "value", "invariant", "_a", "inst", "forceUpdate", "canUseLayoutEffect", "checkIfSnapshotChanged", "DocumentType", "cache", "operationName", "type", "name", "parser", "document", "AutoCleanedWeakCache", "cacheSizes", "cached", "variables", "invariant", "fragments", "queries", "mutations", "subscriptions", "_i", "_a", "x", "definitions", "definition", "payload", "registerGlobalCache", "verifyDocumentType", "operation", "requiredOperationName", "usedOperationName", "wrapperSymbol", "wrapHook", "hookName", "useHook", "clientOrObsQuery", "queryManager", "wrappers", "wrapper", "hasOwnProperty", "useQuery", "query", "options", "wrapHook", "_useQuery", "useApolloClient", "useInternalState", "client", "stateRef", "InternalState", "state", "tick", "previous", "_this", "maybeDeepFreeze", "NetworkStatus", "canUseWeakMap", "verifyDocumentType", "DocumentType", "previousResult", "previousData", "invariant", "concast", "_a", "resolve", "result", "value", "getApolloContext", "obsQuery", "useSyncExternalStore", "handleStoreChange", "onNext", "equal", "onError", "error", "subscription", "watchQueryOptions", "currentWatchQueryOptions", "toMerge", "globalDefaults", "compact", "mergeOptions", "skip", "ssr", "onCompleted", "defaultOptions", "otherOptions", "__rest", "_c", "fetchPolicy", "_d", "initialFetchPolicy", "_b", "data", "ssrAllowed", "nextResult", "error_1", "isNonEmptyArray", "ApolloError", "queryResult", "partial", "resultWithoutPartial", "__assign", "import_cross_fetch", "globalComponentsAccessToken", "globalComponentsSpaceId", "globalComponentsEnvName", "globalComponentsClientName", "globalComponentsApolloLink", "createHttpLink", "globalComponentsSpaceId", "globalComponentsEnvName", "globalComponentsAccessToken", "useGlobalComponentsContentfulQuery", "query", "context", "options", "currentLocale", "isPreview", "isSSR", "mergedOptions", "globalComponentsClientName", "useQuery", "Template", "escapedChars", "htmlEscape", "__name", "value", "c", "unicodePatternsToReverse", "unsafeUnicodePatternsToReverse", "htmlUnescape", "undoDangerousCharacters", "pattern", "_1", "_2", "characterCode", "code", "jsonStringify", "detectCycles", "space", "visited", "replacer", "_key", "SnapError", "_a", "message", "options", "parseError", "error", "errorObject", "errorString", "sleep", "__name", "timeoutMs", "resolve", "waitFor", "attempt", "options", "intervalMs", "clockMs", "sleepMs", "valueTest", "onEveryError", "onTimeout", "startMs", "lastError", "latest", "error", "parseError", "timeoutWithError", "promise", "timeoutPid", "timeout", "_", "reject", "timeoutWithDefault", "defaultValue", "setFetchHeader", "request", "header", "value", "existingHeaderIndex", "key", "getFetchHeader", "headers", "headerEntry", "fetchWithTimeout", "url", "requestInit", "fetchFn", "controller", "timeoutId", "fetchWithRetries", "maxRetries", "clientEnv", "defaultFontSettings", "cookieSettingsPath", "getCookieDomain", "domain", "cookieDomain", "getTopLevelDomain", "getCookieSettingsUrl", "isInWindow", "__name", "isInWorker", "isInBrowser", "Logger", "_a", "message", "debugMode", "logger", "BaseClient", "binaryPayload", "props", "logTimeInterval", "onIncrement", "v", "onAddHistogram", "onAddTimer", "metric", "mappedMetric", "metricsName", "dimensions", "value", "milliSec", "roundedMilliSec", "AuthType", "Authenticator", "MetricCollector", "BaseNetworkHandler", "options", "FetchError", "args", "FetchNetworkHandler", "payload", "authType", "authenticator", "protocol", "host", "path", "headers", "authedHeaders", "resolve", "reject", "url", "response", "reason", "e", "computeMetricKey", "prefixes", "metricNameFragments", "key", "getRandomIntFromRange", "min", "max", "reservoirSample", "array", "maxSize", "newValueList", "i", "nextIndex", "inlineBtoa", "str", "__defProp", "__name", "target", "value", "sha256", "__name", "data", "hash", "bufferToHex", "buffer", "b", "Partition", "isValidPartitionName", "partitionName", "__name", "activityEvents", "ActivityDetector", "_a", "inactiveThresholdInSecond", "eventName", "defaultInactiveThreshold", "Graphene", "BaseClient", "version", "heartBeatDuration", "sendHeartBeatEvent", "active", "props", "isInWindow", "graphene", "varint64read", "lowBits", "highBits", "shift", "b", "middleByte", "varint64write", "lo", "hi", "bytes", "i", "hasNext", "byte", "splitBits", "hasMoreBits", "TWO_PWR_32_DBL", "int64FromString", "dec", "minus", "base", "add1e6digit", "begin", "end", "digit1e6", "negate", "newBits", "int64ToString", "bits", "negative", "result", "uInt64ToString", "toUnsigned", "low", "mid", "high", "digitA", "digitB", "digitC", "decimalFrom1e7WithLeadingZeros", "digit1e7", "partial", "varint32write", "value", "varint32read", "readBytes", "protoInt64", "makeInt64Support", "dv", "MIN", "MAX", "UMIN", "UMAX", "bi", "assertInt64String", "assertUInt64String", "symbol", "getTextEncoding", "te", "td", "text", "WireType", "FLOAT32_MAX", "FLOAT32_MIN", "UINT32_MAX", "INT32_MAX", "INT32_MIN", "BinaryWriter", "encodeUtf8", "len", "offset", "chunk", "prev", "fieldNo", "type", "assertUInt32", "assertInt32", "assertFloat32", "view", "tc", "sign", "BinaryReader", "buf", "decodeUtf8", "tag", "wireType", "start", "fn", "wt", "zze", "s", "arg", "o", "osTypeFromJSON", "object", "osTypeToJSON", "createBaseAppVersion", "AppVersion", "message", "writer", "AppVersion_VersionNumber", "input", "length", "reader", "isSet", "obj", "createBaseAppVersion_VersionNumber", "createBaseMetric", "Metric", "key", "Metric_CustomDimensionsEntry", "v", "entry3", "longToNumber", "end2", "isObject", "acc", "e", "entries", "k", "createBaseMetric_CustomDimensionsEntry", "createBaseMetricFrame", "MetricFrame", "bytesFromBase64", "base64FromBytes", "b64", "bin", "arr", "int64", "num", "WebMetricCollector", "MetricCollector", "options", "metricsName", "dimensions", "metricKey", "computeMetricKey", "prevMetricObject", "milliSec", "frame", "metric", "shouldAggregate", "metricObject", "existingValueList", "newValue", "metricsToConvert", "appVersion", "reservoirSample", "computeWebAttestation", "binaryPayload", "headerString", "sha256", "isInBrowser", "inlineBtoa", "webAttestationHeader", "WebAuthenticator", "Authenticator", "authType", "payload", "headers", "AuthType", "webAttestationHeaderBase64", "getWebConfig", "collectorOptions", "customLocaleDropdownButtonCss", "css", "m", "mobileMediaQuery", "dropdownButtonIconCss", "dropdownButtonIconDownCss", "CustomLocaleDropdownButton", "children", "onClick", "isExpanded", "ariaLabel", "jsxs", "cx", "customLocaleDropdownButtonCss", "jsx", "Icon", "dropdownButtonIconCss", "dropdownButtonIconDownCss", "snapSiteConfigTheme", "CustomLocaleDropdownButton", "snapFooterCss", "snapHeaderCss", "Template", "snapBrandConfigSharedSettings", "import_react", "import_react", "SitewideConfigurationContext", "defaultFeatureFlags", "useFeatureFlags", "getCurrentUrl", "AppContext", "searchParams", "sitewideValues", "SitewideConfigurationContext", "contentfulFeatureFlags", "combineFeatureFlags", "getUrlFeatureFlags", "urlOverrides", "Config", "feature", "override", "config", "snapSiteConfigTheme", "Partition", "environmentNames", "transformTrackingSettings", "site", "getCookieDomain", "getSiteConfig", "config", "clientEnv", "createConfig", "requiredEnvVars", "envVar", "siteConfig", "isPreview", "isClient", "isBrowser", "buildNumber", "commit", "isLocal", "isTest", "compilationMode", "deploymentType", "isDeploymentTypeProd", "isCompilationModeProd", "isSsr", "region", "googleCloudProjectName", "contentfulEnvNameOverride", "contentful", "contentfulSpaceIds", "productionContentTokens", "contentfulGlobal", "globalComponentsSpaceId", "globalComponentsEnvName", "globalComponentsAccessToken", "useLocalElastic", "elasticConfig", "isProduction", "productionElasticNode", "stagingElasticNode", "productionElasticCloudId", "stagingElasticCloudId", "fontSettings", "defaultFontSettings", "Template", "Config", "urlParameters", "requestIdleCallback", "callback", "start", "__name", "cancelIdleCallback", "id", "isTransferable", "obj", "isTypedArray", "cloneTypedArray", "typedArrayTypes", "Constructor", "cloneBuiltins", "clone", "cloneCollection", "transferSet", "cloneMap", "key", "val", "internalClone", "item", "i", "builtinClone", "collectionClone", "structuredClone", "value", "options", "transferableObjects", "error", "polyfilledStructuredClone", "isNil", "value", "isNil_default", "defaultConfig", "Batcher", "_a", "handler", "config", "__name", "batch", "e", "item", "LogLevel", "severityLookupTable", "getSeverity", "level", "convertToKeyValues", "data", "key", "value", "convertToAnyValue", "schemaUrl", "OtlpJsonExporter", "logs", "request", "response", "log", "defaultOpenTelemetryLoggerConfig", "OpenTelemetryLogger", "message", "attributes", "error", "maxQueueSize", "defaultIdleTimeout", "AbstractEventListener", "_a", "props", "__name", "event", "context", "requestIdleCallback", "permission", "AbstractDataLayerEventListener", "formattedEvent", "formattedEvents", "singleFormattedEvent", "onEventLoggedCallback", "onEventLogged", "resolve", "resolvedCount", "LoggingEventType", "maxDimensions", "AbstractGrapheneEventListener", "graphene", "grapheneConfigs", "getWebConfig", "eventDimensions", "dimensions", "key", "value", "isNil_default", "dimensionKey", "flatContext", "input", "metricsName", "customEvent", "timing", "extractedDimensions", "AbstractSentryEventListener", "loggerContext", "eventHint", "merge_default", "message", "error", "parseError", "customContext", "ConsoleEventListener", "printConsole", "contextDict", "messageAndArgs", "maybeLabel", "maybeAction", "omit_default", "type", "LoggingEventBus", "listeners", "provider", "combinedContext", "getContext", "assign_default", "cloneDeep_default", "listener", "tryFlushListeners", "data", "loggingEventToLogLevel", "LogLevel", "OpenTelemetryEventListener", "OpenTelemetryLogger", "logLevel", "component", "parenthetical", "pieces", "response", "withComponent", "logger", "action", "label", "variable", "valueMs", "TestEventListener", "testErrorEvent", "logger", "LoggingEventBus", "onMarketingTrackingAccepted", "onPerformanceTrackingAccepted", "logDebug", "logError", "event", "logWarning", "logInfo", "logValue", "logTiming", "logUserEvent", "logEvent", "logCustom"]
}
