{"version":3,"file":"datetime-Bz_69HvH.js","sources":["../../../node_modules/@mantine/core/esm/core/utils/units-converters/px.mjs","../../../node_modules/@mantine/core/esm/core/styles-api/use-resolved-styles-api/use-resolved-styles-api.mjs","../../../node_modules/graphql/version.mjs","../../../node_modules/graphql/jsutils/isPromise.mjs","../../../node_modules/graphql/jsutils/memoize3.mjs","../../../node_modules/graphql/jsutils/promiseForObject.mjs","../../../node_modules/graphql/jsutils/promiseReduce.mjs","../../../node_modules/graphql/jsutils/toError.mjs","../../../node_modules/graphql/error/locatedError.mjs","../../../node_modules/graphql/execution/execute.mjs","../../../node_modules/graphql/graphql.mjs","../../../node_modules/graphql/jsutils/isAsyncIterable.mjs","../../../node_modules/graphql/execution/mapAsyncIterator.mjs","../../../node_modules/graphql/execution/subscribe.mjs","../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs","../../../node_modules/graphql/utilities/getOperationAST.mjs","../../../node_modules/graphql/utilities/getOperationRootType.mjs","../../../node_modules/graphql/utilities/introspectionFromSchema.mjs","../../../node_modules/graphql/utilities/extendSchema.mjs","../../../node_modules/graphql/utilities/buildASTSchema.mjs","../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs","../../../node_modules/graphql/utilities/printSchema.mjs","../../../node_modules/graphql/utilities/concatAST.mjs","../../../node_modules/graphql/utilities/separateOperations.mjs","../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs","../../../node_modules/graphql/utilities/assertValidName.mjs","../../../node_modules/graphql/utilities/findBreakingChanges.mjs","../../../node_modules/@apollo/client/utilities/graphql/directives.js","../../../node_modules/@wry/trie/lib/index.js","../../../node_modules/optimism/node_modules/@wry/trie/lib/index.js","../../../node_modules/@wry/context/lib/slot.js","../../../node_modules/optimism/lib/context.js","../../../node_modules/optimism/lib/helpers.js","../../../node_modules/optimism/lib/entry.js","../../../node_modules/optimism/lib/dep.js","../../../node_modules/optimism/lib/index.js","../../../node_modules/@apollo/client/utilities/graphql/DocumentTransform.js","../../../node_modules/@apollo/client/utilities/graphql/print.js","../../../node_modules/@apollo/client/utilities/common/arrays.js","../../../node_modules/@apollo/client/utilities/graphql/transform.js","../../../node_modules/@apollo/client/utilities/common/mergeDeep.js","../../../node_modules/@apollo/client/utilities/policies/pagination.js","../../../node_modules/@apollo/client/utilities/common/cloneDeep.js","../../../node_modules/@apollo/client/utilities/common/maybeDeepFreeze.js","../../../node_modules/@apollo/client/utilities/observables/iteration.js","../../../node_modules/@apollo/client/utilities/observables/asyncMap.js","../../../node_modules/@apollo/client/utilities/observables/subclassing.js","../../../node_modules/@apollo/client/utilities/observables/Concast.js","../../../node_modules/@apollo/client/utilities/common/incrementalResult.js","../../../node_modules/@apollo/client/utilities/common/errorHandling.js","../../../node_modules/@apollo/client/utilities/common/compact.js","../../../node_modules/@apollo/client/utilities/common/mergeOptions.js","../../../node_modules/@apollo/client/link/utils/fromError.js","../../../node_modules/@apollo/client/link/utils/toPromise.js","../../../node_modules/@apollo/client/link/utils/fromPromise.js","../../../node_modules/@apollo/client/link/utils/throwServerError.js","../../../node_modules/@apollo/client/link/utils/filterOperationVariables.js","../../../node_modules/@apollo/client/link/core/empty.js","../../../node_modules/@apollo/client/link/core/from.js","../../../node_modules/@apollo/client/link/core/split.js","../../../node_modules/@apollo/client/link/core/concat.js","../../../node_modules/@apollo/client/link/core/execute.js","../../../node_modules/@apollo/client/link/http/iterators/async.js","../../../node_modules/@apollo/client/link/http/iterators/nodeStream.js","../../../node_modules/@apollo/client/link/http/iterators/promise.js","../../../node_modules/@apollo/client/link/http/iterators/reader.js","../../../node_modules/@apollo/client/link/http/responseIterator.js","../../../node_modules/@apollo/client/errors/index.js","../../../node_modules/@apollo/client/link/http/parseAndCheckHttpResponse.js","../../../node_modules/@apollo/client/link/http/serializeFetchParameter.js","../../../node_modules/@apollo/client/link/http/selectHttpOptionsAndBody.js","../../../node_modules/@apollo/client/link/http/checkFetcher.js","../../../node_modules/@apollo/client/link/http/createSignalIfSupported.js","../../../node_modules/@apollo/client/link/http/selectURI.js","../../../node_modules/@apollo/client/link/http/rewriteURIForGET.js","../../../node_modules/@apollo/client/link/http/createHttpLink.js","../../../node_modules/@apollo/client/link/http/HttpLink.js","../../../node_modules/@wry/equality/lib/index.js","../../../node_modules/@apollo/client/cache/core/cache.js","../../../node_modules/@apollo/client/cache/core/types/Cache.js","../../../node_modules/@apollo/client/cache/core/types/common.js","../../../node_modules/@apollo/client/cache/inmemory/helpers.js","../../../node_modules/@apollo/client/cache/inmemory/entityStore.js","../../../node_modules/@apollo/client/cache/inmemory/object-canon.js","../../../node_modules/@apollo/client/cache/inmemory/readFromStore.js","../../../node_modules/@apollo/client/cache/inmemory/reactiveVars.js","../../../node_modules/@apollo/client/cache/inmemory/key-extractor.js","../../../node_modules/@apollo/client/cache/inmemory/policies.js","../../../node_modules/@apollo/client/cache/inmemory/writeToStore.js","../../../node_modules/@apollo/client/cache/inmemory/inMemoryCache.js","../../../node_modules/@apollo/client/core/networkStatus.js","../../../node_modules/@apollo/client/core/equalByQuery.js","../../../node_modules/@apollo/client/core/ObservableQuery.js","../../../node_modules/@apollo/client/core/LocalState.js","../../../node_modules/@apollo/client/core/QueryInfo.js","../../../node_modules/@apollo/client/core/QueryManager.js","../../../node_modules/@apollo/client/core/ApolloClient.js","../../../node_modules/graphql-tag/lib/index.js","../../../node_modules/@apollo/client/core/index.js","../../../app/helpers/apollo/introspection.generated.ts","../../../app/helpers/apollo/types.ts","../../../node_modules/@apollo/client/link/context/index.js","../../../node_modules/graphql-ruby-client/subscriptions/ActionCableLink.js","../../../node_modules/@rails/actioncable/app/assets/javascripts/actioncable.esm.js","../../../app/helpers/actioncable.ts","../../../app/helpers/apollo/clientLink.ts","../../../app/helpers/apollo/link.ts","../../../app/helpers/navbar.ts","../../../node_modules/luxon/src/errors.js","../../../node_modules/luxon/src/impl/formats.js","../../../node_modules/luxon/src/zone.js","../../../node_modules/luxon/src/zones/systemZone.js","../../../node_modules/luxon/src/zones/IANAZone.js","../../../node_modules/luxon/src/impl/locale.js","../../../node_modules/luxon/src/zones/fixedOffsetZone.js","../../../node_modules/luxon/src/zones/invalidZone.js","../../../node_modules/luxon/src/impl/zoneUtil.js","../../../node_modules/luxon/src/settings.js","../../../node_modules/luxon/src/impl/invalid.js","../../../node_modules/luxon/src/impl/conversions.js","../../../node_modules/luxon/src/impl/util.js","../../../node_modules/luxon/src/impl/english.js","../../../node_modules/luxon/src/impl/formatter.js","../../../node_modules/luxon/src/impl/regexParser.js","../../../node_modules/luxon/src/duration.js","../../../node_modules/luxon/src/interval.js","../../../node_modules/luxon/src/info.js","../../../node_modules/luxon/src/impl/diff.js","../../../node_modules/luxon/src/impl/digits.js","../../../node_modules/luxon/src/impl/tokenParser.js","../../../node_modules/luxon/src/datetime.js"],"sourcesContent":["function getTransformedScaledValue(value) {\n if (typeof value !== \"string\" || !value.includes(\"var(--mantine-scale)\")) {\n return value;\n }\n return value.match(/^calc\\((.*?)\\)$/)?.[1].split(\"*\")[0].trim();\n}\nfunction px(value) {\n const transformedValue = getTransformedScaledValue(value);\n if (typeof transformedValue === \"number\") {\n return transformedValue;\n }\n if (typeof transformedValue === \"string\") {\n if (transformedValue.includes(\"calc\") || transformedValue.includes(\"var\")) {\n return transformedValue;\n }\n if (transformedValue.includes(\"px\")) {\n return Number(transformedValue.replace(\"px\", \"\"));\n }\n if (transformedValue.includes(\"rem\")) {\n return Number(transformedValue.replace(\"rem\", \"\")) * 16;\n }\n if (transformedValue.includes(\"em\")) {\n return Number(transformedValue.replace(\"em\", \"\")) * 16;\n }\n return Number(transformedValue);\n }\n return NaN;\n}\n\nexport { px };\n//# sourceMappingURL=px.mjs.map\n","'use client';\nimport 'react';\nimport '@mantine/hooks';\nimport '../../MantineProvider/Mantine.context.mjs';\nimport '../../MantineProvider/default-theme.mjs';\nimport '../../MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { resolveClassNames } from '../use-styles/get-class-name/resolve-class-names/resolve-class-names.mjs';\nimport { resolveStyles } from '../use-styles/get-style/resolve-styles/resolve-styles.mjs';\n\nfunction useResolvedStylesApi({\n classNames,\n styles,\n props,\n stylesCtx\n}) {\n const theme = useMantineTheme();\n return {\n resolvedClassNames: resolveClassNames({\n theme,\n classNames,\n props,\n stylesCtx: stylesCtx || void 0\n }),\n resolvedStyles: resolveStyles({\n theme,\n styles,\n props,\n stylesCtx: stylesCtx || void 0\n })\n };\n}\n\nexport { useResolvedStylesApi };\n//# sourceMappingURL=use-resolved-styles-api.mjs.map\n","// Note: This file is autogenerated using \"resources/gen-version.js\" script and\n// automatically updated by \"npm version\" command.\n\n/**\n * A string containing the version of the GraphQL.js library\n */\nexport const version = '16.8.1';\n/**\n * An object containing the components of the GraphQL.js version string\n */\n\nexport const versionInfo = Object.freeze({\n major: 16,\n minor: 8,\n patch: 1,\n preReleaseTag: null,\n});\n","/**\n * Returns true if the value acts like a Promise, i.e. has a \"then\" function,\n * otherwise returns false.\n */\nexport function isPromise(value) {\n return (\n typeof (value === null || value === void 0 ? void 0 : value.then) ===\n 'function'\n );\n}\n","/**\n * Memoizes the provided three-argument function.\n */\nexport function memoize3(fn) {\n let cache0;\n return function memoized(a1, a2, a3) {\n if (cache0 === undefined) {\n cache0 = new WeakMap();\n }\n\n let cache1 = cache0.get(a1);\n\n if (cache1 === undefined) {\n cache1 = new WeakMap();\n cache0.set(a1, cache1);\n }\n\n let cache2 = cache1.get(a2);\n\n if (cache2 === undefined) {\n cache2 = new WeakMap();\n cache1.set(a2, cache2);\n }\n\n let fnResult = cache2.get(a3);\n\n if (fnResult === undefined) {\n fnResult = fn(a1, a2, a3);\n cache2.set(a3, fnResult);\n }\n\n return fnResult;\n };\n}\n","/**\n * This function transforms a JS object `ObjMap>` into\n * a `Promise>`\n *\n * This is akin to bluebird's `Promise.props`, but implemented only using\n * `Promise.all` so it will work with any implementation of ES6 promises.\n */\nexport function promiseForObject(object) {\n return Promise.all(Object.values(object)).then((resolvedValues) => {\n const resolvedObject = Object.create(null);\n\n for (const [i, key] of Object.keys(object).entries()) {\n resolvedObject[key] = resolvedValues[i];\n }\n\n return resolvedObject;\n });\n}\n","import { isPromise } from './isPromise.mjs';\n\n/**\n * Similar to Array.prototype.reduce(), however the reducing callback may return\n * a Promise, in which case reduction will continue after each promise resolves.\n *\n * If the callback does not return a Promise, then this function will also not\n * return a Promise.\n */\nexport function promiseReduce(values, callbackFn, initialValue) {\n let accumulator = initialValue;\n\n for (const value of values) {\n accumulator = isPromise(accumulator)\n ? accumulator.then((resolved) => callbackFn(resolved, value))\n : callbackFn(accumulator, value);\n }\n\n return accumulator;\n}\n","import { inspect } from './inspect.mjs';\n/**\n * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface.\n */\n\nexport function toError(thrownValue) {\n return thrownValue instanceof Error\n ? thrownValue\n : new NonErrorThrown(thrownValue);\n}\n\nclass NonErrorThrown extends Error {\n constructor(thrownValue) {\n super('Unexpected error value: ' + inspect(thrownValue));\n this.name = 'NonErrorThrown';\n this.thrownValue = thrownValue;\n }\n}\n","import { toError } from '../jsutils/toError.mjs';\nimport { GraphQLError } from './GraphQLError.mjs';\n/**\n * Given an arbitrary value, presumably thrown while attempting to execute a\n * GraphQL operation, produce a new GraphQLError aware of the location in the\n * document responsible for the original Error.\n */\n\nexport function locatedError(rawOriginalError, nodes, path) {\n var _nodes;\n\n const originalError = toError(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts.\n\n if (isLocatedGraphQLError(originalError)) {\n return originalError;\n }\n\n return new GraphQLError(originalError.message, {\n nodes:\n (_nodes = originalError.nodes) !== null && _nodes !== void 0\n ? _nodes\n : nodes,\n source: originalError.source,\n positions: originalError.positions,\n path,\n originalError,\n });\n}\n\nfunction isLocatedGraphQLError(error) {\n return Array.isArray(error.path);\n}\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { isIterableObject } from '../jsutils/isIterableObject.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { isPromise } from '../jsutils/isPromise.mjs';\nimport { memoize3 } from '../jsutils/memoize3.mjs';\nimport { addPath, pathToArray } from '../jsutils/Path.mjs';\nimport { promiseForObject } from '../jsutils/promiseForObject.mjs';\nimport { promiseReduce } from '../jsutils/promiseReduce.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { locatedError } from '../error/locatedError.mjs';\nimport { OperationTypeNode } from '../language/ast.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport {\n isAbstractType,\n isLeafType,\n isListType,\n isNonNullType,\n isObjectType,\n} from '../type/definition.mjs';\nimport {\n SchemaMetaFieldDef,\n TypeMetaFieldDef,\n TypeNameMetaFieldDef,\n} from '../type/introspection.mjs';\nimport { assertValidSchema } from '../type/validate.mjs';\nimport {\n collectFields,\n collectSubfields as _collectSubfields,\n} from './collectFields.mjs';\nimport { getArgumentValues, getVariableValues } from './values.mjs';\n/**\n * A memoized collection of relevant subfields with regard to the return\n * type. Memoizing ensures the subfields are not repeatedly calculated, which\n * saves overhead when resolving lists of values.\n */\n\nconst collectSubfields = memoize3((exeContext, returnType, fieldNodes) =>\n _collectSubfields(\n exeContext.schema,\n exeContext.fragments,\n exeContext.variableValues,\n returnType,\n fieldNodes,\n ),\n);\n/**\n * Terminology\n *\n * \"Definitions\" are the generic name for top-level statements in the document.\n * Examples of this include:\n * 1) Operations (such as a query)\n * 2) Fragments\n *\n * \"Operations\" are a generic name for requests in the document.\n * Examples of this include:\n * 1) query,\n * 2) mutation\n *\n * \"Selections\" are the definitions that can appear legally and at\n * single level of the query. These include:\n * 1) field references e.g `a`\n * 2) fragment \"spreads\" e.g. `...c`\n * 3) inline fragment \"spreads\" e.g. `...on Type { a }`\n */\n\n/**\n * Data that must be available at all points during query execution.\n *\n * Namely, schema of the type system that is currently executing,\n * and the fragments defined in the query document\n */\n\n/**\n * Implements the \"Executing requests\" section of the GraphQL specification.\n *\n * Returns either a synchronous ExecutionResult (if all encountered resolvers\n * are synchronous), or a Promise of an ExecutionResult that will eventually be\n * resolved and never rejected.\n *\n * If the arguments to this function do not result in a legal execution context,\n * a GraphQLError will be thrown immediately explaining the invalid input.\n */\nexport function execute(args) {\n // Temporary for v15 to v16 migration. Remove in v17\n arguments.length < 2 ||\n devAssert(\n false,\n 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',\n );\n const { schema, document, variableValues, rootValue } = args; // If arguments are missing or incorrect, throw an error.\n\n assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,\n // a \"Response\" with only errors is returned.\n\n const exeContext = buildExecutionContext(args); // Return early errors if execution context failed.\n\n if (!('schema' in exeContext)) {\n return {\n errors: exeContext,\n };\n } // Return a Promise that will eventually resolve to the data described by\n // The \"Response\" section of the GraphQL specification.\n //\n // If errors are encountered while executing a GraphQL field, only that\n // field and its descendants will be omitted, and sibling fields will still\n // be executed. An execution which encounters errors will still result in a\n // resolved Promise.\n //\n // Errors from sub-fields of a NonNull type may propagate to the top level,\n // at which point we still log the error and null the parent field, which\n // in this case is the entire response.\n\n try {\n const { operation } = exeContext;\n const result = executeOperation(exeContext, operation, rootValue);\n\n if (isPromise(result)) {\n return result.then(\n (data) => buildResponse(data, exeContext.errors),\n (error) => {\n exeContext.errors.push(error);\n return buildResponse(null, exeContext.errors);\n },\n );\n }\n\n return buildResponse(result, exeContext.errors);\n } catch (error) {\n exeContext.errors.push(error);\n return buildResponse(null, exeContext.errors);\n }\n}\n/**\n * Also implements the \"Executing requests\" section of the GraphQL specification.\n * However, it guarantees to complete synchronously (or throw an error) assuming\n * that all field resolvers are also synchronous.\n */\n\nexport function executeSync(args) {\n const result = execute(args); // Assert that the execution was synchronous.\n\n if (isPromise(result)) {\n throw new Error('GraphQL execution failed to complete synchronously.');\n }\n\n return result;\n}\n/**\n * Given a completed execution context and data, build the `{ errors, data }`\n * response defined by the \"Response\" section of the GraphQL specification.\n */\n\nfunction buildResponse(data, errors) {\n return errors.length === 0\n ? {\n data,\n }\n : {\n errors,\n data,\n };\n}\n/**\n * Essential assertions before executing to provide developer feedback for\n * improper use of the GraphQL library.\n *\n * @internal\n */\n\nexport function assertValidExecutionArguments(\n schema,\n document,\n rawVariableValues,\n) {\n document || devAssert(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error.\n\n assertValidSchema(schema); // Variables, if provided, must be an object.\n\n rawVariableValues == null ||\n isObjectLike(rawVariableValues) ||\n devAssert(\n false,\n 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.',\n );\n}\n/**\n * Constructs a ExecutionContext object from the arguments passed to\n * execute, which we will pass throughout the other execution methods.\n *\n * Throws a GraphQLError if a valid execution context cannot be created.\n *\n * @internal\n */\n\nexport function buildExecutionContext(args) {\n var _definition$name, _operation$variableDe;\n\n const {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues: rawVariableValues,\n operationName,\n fieldResolver,\n typeResolver,\n subscribeFieldResolver,\n } = args;\n let operation;\n const fragments = Object.create(null);\n\n for (const definition of document.definitions) {\n switch (definition.kind) {\n case Kind.OPERATION_DEFINITION:\n if (operationName == null) {\n if (operation !== undefined) {\n return [\n new GraphQLError(\n 'Must provide operation name if query contains multiple operations.',\n ),\n ];\n }\n\n operation = definition;\n } else if (\n ((_definition$name = definition.name) === null ||\n _definition$name === void 0\n ? void 0\n : _definition$name.value) === operationName\n ) {\n operation = definition;\n }\n\n break;\n\n case Kind.FRAGMENT_DEFINITION:\n fragments[definition.name.value] = definition;\n break;\n\n default: // ignore non-executable definitions\n }\n }\n\n if (!operation) {\n if (operationName != null) {\n return [new GraphQLError(`Unknown operation named \"${operationName}\".`)];\n }\n\n return [new GraphQLError('Must provide an operation.')];\n } // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n\n const variableDefinitions =\n (_operation$variableDe = operation.variableDefinitions) !== null &&\n _operation$variableDe !== void 0\n ? _operation$variableDe\n : [];\n const coercedVariableValues = getVariableValues(\n schema,\n variableDefinitions,\n rawVariableValues !== null && rawVariableValues !== void 0\n ? rawVariableValues\n : {},\n {\n maxErrors: 50,\n },\n );\n\n if (coercedVariableValues.errors) {\n return coercedVariableValues.errors;\n }\n\n return {\n schema,\n fragments,\n rootValue,\n contextValue,\n operation,\n variableValues: coercedVariableValues.coerced,\n fieldResolver:\n fieldResolver !== null && fieldResolver !== void 0\n ? fieldResolver\n : defaultFieldResolver,\n typeResolver:\n typeResolver !== null && typeResolver !== void 0\n ? typeResolver\n : defaultTypeResolver,\n subscribeFieldResolver:\n subscribeFieldResolver !== null && subscribeFieldResolver !== void 0\n ? subscribeFieldResolver\n : defaultFieldResolver,\n errors: [],\n };\n}\n/**\n * Implements the \"Executing operations\" section of the spec.\n */\n\nfunction executeOperation(exeContext, operation, rootValue) {\n const rootType = exeContext.schema.getRootType(operation.operation);\n\n if (rootType == null) {\n throw new GraphQLError(\n `Schema is not configured to execute ${operation.operation} operation.`,\n {\n nodes: operation,\n },\n );\n }\n\n const rootFields = collectFields(\n exeContext.schema,\n exeContext.fragments,\n exeContext.variableValues,\n rootType,\n operation.selectionSet,\n );\n const path = undefined;\n\n switch (operation.operation) {\n case OperationTypeNode.QUERY:\n return executeFields(exeContext, rootType, rootValue, path, rootFields);\n\n case OperationTypeNode.MUTATION:\n return executeFieldsSerially(\n exeContext,\n rootType,\n rootValue,\n path,\n rootFields,\n );\n\n case OperationTypeNode.SUBSCRIPTION:\n // TODO: deprecate `subscribe` and move all logic here\n // Temporary solution until we finish merging execute and subscribe together\n return executeFields(exeContext, rootType, rootValue, path, rootFields);\n }\n}\n/**\n * Implements the \"Executing selection sets\" section of the spec\n * for fields that must be executed serially.\n */\n\nfunction executeFieldsSerially(\n exeContext,\n parentType,\n sourceValue,\n path,\n fields,\n) {\n return promiseReduce(\n fields.entries(),\n (results, [responseName, fieldNodes]) => {\n const fieldPath = addPath(path, responseName, parentType.name);\n const result = executeField(\n exeContext,\n parentType,\n sourceValue,\n fieldNodes,\n fieldPath,\n );\n\n if (result === undefined) {\n return results;\n }\n\n if (isPromise(result)) {\n return result.then((resolvedResult) => {\n results[responseName] = resolvedResult;\n return results;\n });\n }\n\n results[responseName] = result;\n return results;\n },\n Object.create(null),\n );\n}\n/**\n * Implements the \"Executing selection sets\" section of the spec\n * for fields that may be executed in parallel.\n */\n\nfunction executeFields(exeContext, parentType, sourceValue, path, fields) {\n const results = Object.create(null);\n let containsPromise = false;\n\n try {\n for (const [responseName, fieldNodes] of fields.entries()) {\n const fieldPath = addPath(path, responseName, parentType.name);\n const result = executeField(\n exeContext,\n parentType,\n sourceValue,\n fieldNodes,\n fieldPath,\n );\n\n if (result !== undefined) {\n results[responseName] = result;\n\n if (isPromise(result)) {\n containsPromise = true;\n }\n }\n }\n } catch (error) {\n if (containsPromise) {\n // Ensure that any promises returned by other fields are handled, as they may also reject.\n return promiseForObject(results).finally(() => {\n throw error;\n });\n }\n\n throw error;\n } // If there are no promises, we can just return the object\n\n if (!containsPromise) {\n return results;\n } // Otherwise, results is a map from field name to the result of resolving that\n // field, which is possibly a promise. Return a promise that will return this\n // same map, but with any promises replaced with the values they resolved to.\n\n return promiseForObject(results);\n}\n/**\n * Implements the \"Executing fields\" section of the spec\n * In particular, this function figures out the value that the field returns by\n * calling its resolve function, then calls completeValue to complete promises,\n * serialize scalars, or execute the sub-selection-set for objects.\n */\n\nfunction executeField(exeContext, parentType, source, fieldNodes, path) {\n var _fieldDef$resolve;\n\n const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]);\n\n if (!fieldDef) {\n return;\n }\n\n const returnType = fieldDef.type;\n const resolveFn =\n (_fieldDef$resolve = fieldDef.resolve) !== null &&\n _fieldDef$resolve !== void 0\n ? _fieldDef$resolve\n : exeContext.fieldResolver;\n const info = buildResolveInfo(\n exeContext,\n fieldDef,\n fieldNodes,\n parentType,\n path,\n ); // Get the resolve function, regardless of if its result is normal or abrupt (error).\n\n try {\n // Build a JS object of arguments from the field.arguments AST, using the\n // variables scope to fulfill any variable references.\n // TODO: find a way to memoize, in case this field is within a List type.\n const args = getArgumentValues(\n fieldDef,\n fieldNodes[0],\n exeContext.variableValues,\n ); // The resolve function's optional third argument is a context value that\n // is provided to every resolve function within an execution. It is commonly\n // used to represent an authenticated user, or request-specific caches.\n\n const contextValue = exeContext.contextValue;\n const result = resolveFn(source, args, contextValue, info);\n let completed;\n\n if (isPromise(result)) {\n completed = result.then((resolved) =>\n completeValue(exeContext, returnType, fieldNodes, info, path, resolved),\n );\n } else {\n completed = completeValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n }\n\n if (isPromise(completed)) {\n // Note: we don't rely on a `catch` method, but we do expect \"thenable\"\n // to take a second callback for the error case.\n return completed.then(undefined, (rawError) => {\n const error = locatedError(rawError, fieldNodes, pathToArray(path));\n return handleFieldError(error, returnType, exeContext);\n });\n }\n\n return completed;\n } catch (rawError) {\n const error = locatedError(rawError, fieldNodes, pathToArray(path));\n return handleFieldError(error, returnType, exeContext);\n }\n}\n/**\n * @internal\n */\n\nexport function buildResolveInfo(\n exeContext,\n fieldDef,\n fieldNodes,\n parentType,\n path,\n) {\n // The resolve function's optional fourth argument is a collection of\n // information about the current execution state.\n return {\n fieldName: fieldDef.name,\n fieldNodes,\n returnType: fieldDef.type,\n parentType,\n path,\n schema: exeContext.schema,\n fragments: exeContext.fragments,\n rootValue: exeContext.rootValue,\n operation: exeContext.operation,\n variableValues: exeContext.variableValues,\n };\n}\n\nfunction handleFieldError(error, returnType, exeContext) {\n // If the field type is non-nullable, then it is resolved without any\n // protection from errors, however it still properly locates the error.\n if (isNonNullType(returnType)) {\n throw error;\n } // Otherwise, error protection is applied, logging the error and resolving\n // a null value for this field if one is encountered.\n\n exeContext.errors.push(error);\n return null;\n}\n/**\n * Implements the instructions for completeValue as defined in the\n * \"Value Completion\" section of the spec.\n *\n * If the field type is Non-Null, then this recursively completes the value\n * for the inner type. It throws a field error if that completion returns null,\n * as per the \"Nullability\" section of the spec.\n *\n * If the field type is a List, then this recursively completes the value\n * for the inner type on each item in the list.\n *\n * If the field type is a Scalar or Enum, ensures the completed value is a legal\n * value of the type by calling the `serialize` method of GraphQL type\n * definition.\n *\n * If the field is an abstract type, determine the runtime type of the value\n * and then complete based on that type\n *\n * Otherwise, the field type expects a sub-selection set, and will complete the\n * value by executing all sub-selections.\n */\n\nfunction completeValue(exeContext, returnType, fieldNodes, info, path, result) {\n // If result is an Error, throw a located error.\n if (result instanceof Error) {\n throw result;\n } // If field type is NonNull, complete for inner type, and throw field error\n // if result is null.\n\n if (isNonNullType(returnType)) {\n const completed = completeValue(\n exeContext,\n returnType.ofType,\n fieldNodes,\n info,\n path,\n result,\n );\n\n if (completed === null) {\n throw new Error(\n `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`,\n );\n }\n\n return completed;\n } // If result value is null or undefined then return null.\n\n if (result == null) {\n return null;\n } // If field type is List, complete each item in the list with the inner type\n\n if (isListType(returnType)) {\n return completeListValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n } // If field type is a leaf type, Scalar or Enum, serialize to a valid value,\n // returning null if serialization is not possible.\n\n if (isLeafType(returnType)) {\n return completeLeafValue(returnType, result);\n } // If field type is an abstract type, Interface or Union, determine the\n // runtime Object type and complete for that type.\n\n if (isAbstractType(returnType)) {\n return completeAbstractValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n } // If field type is Object, execute and complete all sub-selections.\n\n if (isObjectType(returnType)) {\n return completeObjectValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n }\n /* c8 ignore next 6 */\n // Not reachable, all possible output types have been considered.\n\n false ||\n invariant(\n false,\n 'Cannot complete value of unexpected output type: ' + inspect(returnType),\n );\n}\n/**\n * Complete a list value by completing each item in the list with the\n * inner type\n */\n\nfunction completeListValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n) {\n if (!isIterableObject(result)) {\n throw new GraphQLError(\n `Expected Iterable, but did not find one for field \"${info.parentType.name}.${info.fieldName}\".`,\n );\n } // This is specified as a simple map, however we're optimizing the path\n // where the list contains no Promises by avoiding creating another Promise.\n\n const itemType = returnType.ofType;\n let containsPromise = false;\n const completedResults = Array.from(result, (item, index) => {\n // No need to modify the info object containing the path,\n // since from here on it is not ever accessed by resolver functions.\n const itemPath = addPath(path, index, undefined);\n\n try {\n let completedItem;\n\n if (isPromise(item)) {\n completedItem = item.then((resolved) =>\n completeValue(\n exeContext,\n itemType,\n fieldNodes,\n info,\n itemPath,\n resolved,\n ),\n );\n } else {\n completedItem = completeValue(\n exeContext,\n itemType,\n fieldNodes,\n info,\n itemPath,\n item,\n );\n }\n\n if (isPromise(completedItem)) {\n containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect \"thenable\"\n // to take a second callback for the error case.\n\n return completedItem.then(undefined, (rawError) => {\n const error = locatedError(\n rawError,\n fieldNodes,\n pathToArray(itemPath),\n );\n return handleFieldError(error, itemType, exeContext);\n });\n }\n\n return completedItem;\n } catch (rawError) {\n const error = locatedError(rawError, fieldNodes, pathToArray(itemPath));\n return handleFieldError(error, itemType, exeContext);\n }\n });\n return containsPromise ? Promise.all(completedResults) : completedResults;\n}\n/**\n * Complete a Scalar or Enum by serializing to a valid value, returning\n * null if serialization is not possible.\n */\n\nfunction completeLeafValue(returnType, result) {\n const serializedResult = returnType.serialize(result);\n\n if (serializedResult == null) {\n throw new Error(\n `Expected \\`${inspect(returnType)}.serialize(${inspect(result)})\\` to ` +\n `return non-nullable value, returned: ${inspect(serializedResult)}`,\n );\n }\n\n return serializedResult;\n}\n/**\n * Complete a value of an abstract type by determining the runtime object type\n * of that value, then complete the value for that type.\n */\n\nfunction completeAbstractValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n) {\n var _returnType$resolveTy;\n\n const resolveTypeFn =\n (_returnType$resolveTy = returnType.resolveType) !== null &&\n _returnType$resolveTy !== void 0\n ? _returnType$resolveTy\n : exeContext.typeResolver;\n const contextValue = exeContext.contextValue;\n const runtimeType = resolveTypeFn(result, contextValue, info, returnType);\n\n if (isPromise(runtimeType)) {\n return runtimeType.then((resolvedRuntimeType) =>\n completeObjectValue(\n exeContext,\n ensureValidRuntimeType(\n resolvedRuntimeType,\n exeContext,\n returnType,\n fieldNodes,\n info,\n result,\n ),\n fieldNodes,\n info,\n path,\n result,\n ),\n );\n }\n\n return completeObjectValue(\n exeContext,\n ensureValidRuntimeType(\n runtimeType,\n exeContext,\n returnType,\n fieldNodes,\n info,\n result,\n ),\n fieldNodes,\n info,\n path,\n result,\n );\n}\n\nfunction ensureValidRuntimeType(\n runtimeTypeName,\n exeContext,\n returnType,\n fieldNodes,\n info,\n result,\n) {\n if (runtimeTypeName == null) {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" must resolve to an Object type at runtime for field \"${info.parentType.name}.${info.fieldName}\". Either the \"${returnType.name}\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function.`,\n fieldNodes,\n );\n } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType`\n // TODO: remove in 17.0.0 release\n\n if (isObjectType(runtimeTypeName)) {\n throw new GraphQLError(\n 'Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.',\n );\n }\n\n if (typeof runtimeTypeName !== 'string') {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" must resolve to an Object type at runtime for field \"${info.parentType.name}.${info.fieldName}\" with ` +\n `value ${inspect(result)}, received \"${inspect(runtimeTypeName)}\".`,\n );\n }\n\n const runtimeType = exeContext.schema.getType(runtimeTypeName);\n\n if (runtimeType == null) {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" was resolved to a type \"${runtimeTypeName}\" that does not exist inside the schema.`,\n {\n nodes: fieldNodes,\n },\n );\n }\n\n if (!isObjectType(runtimeType)) {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" was resolved to a non-object type \"${runtimeTypeName}\".`,\n {\n nodes: fieldNodes,\n },\n );\n }\n\n if (!exeContext.schema.isSubType(returnType, runtimeType)) {\n throw new GraphQLError(\n `Runtime Object type \"${runtimeType.name}\" is not a possible type for \"${returnType.name}\".`,\n {\n nodes: fieldNodes,\n },\n );\n }\n\n return runtimeType;\n}\n/**\n * Complete an Object value by executing all sub-selections.\n */\n\nfunction completeObjectValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n) {\n // Collect sub-fields to execute to complete this value.\n const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the\n // current result. If isTypeOf returns false, then raise an error rather\n // than continuing execution.\n\n if (returnType.isTypeOf) {\n const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);\n\n if (isPromise(isTypeOf)) {\n return isTypeOf.then((resolvedIsTypeOf) => {\n if (!resolvedIsTypeOf) {\n throw invalidReturnTypeError(returnType, result, fieldNodes);\n }\n\n return executeFields(\n exeContext,\n returnType,\n result,\n path,\n subFieldNodes,\n );\n });\n }\n\n if (!isTypeOf) {\n throw invalidReturnTypeError(returnType, result, fieldNodes);\n }\n }\n\n return executeFields(exeContext, returnType, result, path, subFieldNodes);\n}\n\nfunction invalidReturnTypeError(returnType, result, fieldNodes) {\n return new GraphQLError(\n `Expected value of type \"${returnType.name}\" but got: ${inspect(result)}.`,\n {\n nodes: fieldNodes,\n },\n );\n}\n/**\n * If a resolveType function is not given, then a default resolve behavior is\n * used which attempts two strategies:\n *\n * First, See if the provided value has a `__typename` field defined, if so, use\n * that value as name of the resolved type.\n *\n * Otherwise, test each possible type for the abstract type by calling\n * isTypeOf for the object being coerced, returning the first type that matches.\n */\n\nexport const defaultTypeResolver = function (\n value,\n contextValue,\n info,\n abstractType,\n) {\n // First, look for `__typename`.\n if (isObjectLike(value) && typeof value.__typename === 'string') {\n return value.__typename;\n } // Otherwise, test each possible type.\n\n const possibleTypes = info.schema.getPossibleTypes(abstractType);\n const promisedIsTypeOfResults = [];\n\n for (let i = 0; i < possibleTypes.length; i++) {\n const type = possibleTypes[i];\n\n if (type.isTypeOf) {\n const isTypeOfResult = type.isTypeOf(value, contextValue, info);\n\n if (isPromise(isTypeOfResult)) {\n promisedIsTypeOfResults[i] = isTypeOfResult;\n } else if (isTypeOfResult) {\n return type.name;\n }\n }\n }\n\n if (promisedIsTypeOfResults.length) {\n return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => {\n for (let i = 0; i < isTypeOfResults.length; i++) {\n if (isTypeOfResults[i]) {\n return possibleTypes[i].name;\n }\n }\n });\n }\n};\n/**\n * If a resolve function is not given, then a default resolve behavior is used\n * which takes the property of the source object of the same name as the field\n * and returns it as the result, or if it's a function, returns the result\n * of calling that function while passing along args and context value.\n */\n\nexport const defaultFieldResolver = function (\n source,\n args,\n contextValue,\n info,\n) {\n // ensure source is a value for which property access is acceptable.\n if (isObjectLike(source) || typeof source === 'function') {\n const property = source[info.fieldName];\n\n if (typeof property === 'function') {\n return source[info.fieldName](args, contextValue, info);\n }\n\n return property;\n }\n};\n/**\n * This method looks up the field on the given type definition.\n * It has special casing for the three introspection fields,\n * __schema, __type and __typename. __typename is special because\n * it can always be queried as a field, even in situations where no\n * other fields are allowed, like on a Union. __schema and __type\n * could get automatically added to the query type, but that would\n * require mutating type definitions, which would cause issues.\n *\n * @internal\n */\n\nexport function getFieldDef(schema, parentType, fieldNode) {\n const fieldName = fieldNode.name.value;\n\n if (\n fieldName === SchemaMetaFieldDef.name &&\n schema.getQueryType() === parentType\n ) {\n return SchemaMetaFieldDef;\n } else if (\n fieldName === TypeMetaFieldDef.name &&\n schema.getQueryType() === parentType\n ) {\n return TypeMetaFieldDef;\n } else if (fieldName === TypeNameMetaFieldDef.name) {\n return TypeNameMetaFieldDef;\n }\n\n return parentType.getFields()[fieldName];\n}\n","import { devAssert } from './jsutils/devAssert.mjs';\nimport { isPromise } from './jsutils/isPromise.mjs';\nimport { parse } from './language/parser.mjs';\nimport { validateSchema } from './type/validate.mjs';\nimport { validate } from './validation/validate.mjs';\nimport { execute } from './execution/execute.mjs';\n/**\n * This is the primary entry point function for fulfilling GraphQL operations\n * by parsing, validating, and executing a GraphQL document along side a\n * GraphQL schema.\n *\n * More sophisticated GraphQL servers, such as those which persist queries,\n * may wish to separate the validation and execution phases to a static time\n * tooling step, and a server runtime step.\n *\n * Accepts either an object with named arguments, or individual arguments:\n *\n * schema:\n * The GraphQL type system to use when validating and executing a query.\n * source:\n * A GraphQL language formatted string representing the requested operation.\n * rootValue:\n * The value provided as the first argument to resolver functions on the top\n * level type (e.g. the query object type).\n * contextValue:\n * The context value is provided as an argument to resolver functions after\n * field arguments. It is used to pass shared information useful at any point\n * during executing this query, for example the currently logged in user and\n * connections to databases or other services.\n * variableValues:\n * A mapping of variable name to runtime value to use for all variables\n * defined in the requestString.\n * operationName:\n * The name of the operation to use if requestString contains multiple\n * possible operations. Can be omitted if requestString contains only\n * one operation.\n * fieldResolver:\n * A resolver function to use when one is not provided by the schema.\n * If not provided, the default field resolver is used (which looks for a\n * value or method on the source value with the field's name).\n * typeResolver:\n * A type resolver function to use when none is provided by the schema.\n * If not provided, the default type resolver is used (which looks for a\n * `__typename` field or alternatively calls the `isTypeOf` method).\n */\n\nexport function graphql(args) {\n // Always return a Promise for a consistent API.\n return new Promise((resolve) => resolve(graphqlImpl(args)));\n}\n/**\n * The graphqlSync function also fulfills GraphQL operations by parsing,\n * validating, and executing a GraphQL document along side a GraphQL schema.\n * However, it guarantees to complete synchronously (or throw an error) assuming\n * that all field resolvers are also synchronous.\n */\n\nexport function graphqlSync(args) {\n const result = graphqlImpl(args); // Assert that the execution was synchronous.\n\n if (isPromise(result)) {\n throw new Error('GraphQL execution failed to complete synchronously.');\n }\n\n return result;\n}\n\nfunction graphqlImpl(args) {\n // Temporary for v15 to v16 migration. Remove in v17\n arguments.length < 2 ||\n devAssert(\n false,\n 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',\n );\n const {\n schema,\n source,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n } = args; // Validate Schema\n\n const schemaValidationErrors = validateSchema(schema);\n\n if (schemaValidationErrors.length > 0) {\n return {\n errors: schemaValidationErrors,\n };\n } // Parse\n\n let document;\n\n try {\n document = parse(source);\n } catch (syntaxError) {\n return {\n errors: [syntaxError],\n };\n } // Validate\n\n const validationErrors = validate(schema, document);\n\n if (validationErrors.length > 0) {\n return {\n errors: validationErrors,\n };\n } // Execute\n\n return execute({\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n });\n}\n","/**\n * Returns true if the provided object implements the AsyncIterator protocol via\n * implementing a `Symbol.asyncIterator` method.\n */\nexport function isAsyncIterable(maybeAsyncIterable) {\n return (\n typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0\n ? void 0\n : maybeAsyncIterable[Symbol.asyncIterator]) === 'function'\n );\n}\n","/**\n * Given an AsyncIterable and a callback function, return an AsyncIterator\n * which produces values mapped via calling the callback function.\n */\nexport function mapAsyncIterator(iterable, callback) {\n const iterator = iterable[Symbol.asyncIterator]();\n\n async function mapResult(result) {\n if (result.done) {\n return result;\n }\n\n try {\n return {\n value: await callback(result.value),\n done: false,\n };\n } catch (error) {\n /* c8 ignore start */\n // FIXME: add test case\n if (typeof iterator.return === 'function') {\n try {\n await iterator.return();\n } catch (_e) {\n /* ignore error */\n }\n }\n\n throw error;\n /* c8 ignore stop */\n }\n }\n\n return {\n async next() {\n return mapResult(await iterator.next());\n },\n\n async return() {\n // If iterator.return() does not exist, then type R must be undefined.\n return typeof iterator.return === 'function'\n ? mapResult(await iterator.return())\n : {\n value: undefined,\n done: true,\n };\n },\n\n async throw(error) {\n if (typeof iterator.throw === 'function') {\n return mapResult(await iterator.throw(error));\n }\n\n throw error;\n },\n\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { isAsyncIterable } from '../jsutils/isAsyncIterable.mjs';\nimport { addPath, pathToArray } from '../jsutils/Path.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { locatedError } from '../error/locatedError.mjs';\nimport { collectFields } from './collectFields.mjs';\nimport {\n assertValidExecutionArguments,\n buildExecutionContext,\n buildResolveInfo,\n execute,\n getFieldDef,\n} from './execute.mjs';\nimport { mapAsyncIterator } from './mapAsyncIterator.mjs';\nimport { getArgumentValues } from './values.mjs';\n/**\n * Implements the \"Subscribe\" algorithm described in the GraphQL specification.\n *\n * Returns a Promise which resolves to either an AsyncIterator (if successful)\n * or an ExecutionResult (error). The promise will be rejected if the schema or\n * other arguments to this function are invalid, or if the resolved event stream\n * is not an async iterable.\n *\n * If the client-provided arguments to this function do not result in a\n * compliant subscription, a GraphQL Response (ExecutionResult) with\n * descriptive errors and no data will be returned.\n *\n * If the source stream could not be created due to faulty subscription\n * resolver logic or underlying systems, the promise will resolve to a single\n * ExecutionResult containing `errors` and no `data`.\n *\n * If the operation succeeded, the promise resolves to an AsyncIterator, which\n * yields a stream of ExecutionResults representing the response stream.\n *\n * Accepts either an object with named arguments, or individual arguments.\n */\n\nexport async function subscribe(args) {\n // Temporary for v15 to v16 migration. Remove in v17\n arguments.length < 2 ||\n devAssert(\n false,\n 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',\n );\n const resultOrStream = await createSourceEventStream(args);\n\n if (!isAsyncIterable(resultOrStream)) {\n return resultOrStream;\n } // For each payload yielded from a subscription, map it over the normal\n // GraphQL `execute` function, with `payload` as the rootValue.\n // This implements the \"MapSourceToResponseEvent\" algorithm described in\n // the GraphQL specification. The `execute` function provides the\n // \"ExecuteSubscriptionEvent\" algorithm, as it is nearly identical to the\n // \"ExecuteQuery\" algorithm, for which `execute` is also used.\n\n const mapSourceToResponse = (payload) =>\n execute({ ...args, rootValue: payload }); // Map every source value to a ExecutionResult value as described above.\n\n return mapAsyncIterator(resultOrStream, mapSourceToResponse);\n}\n\nfunction toNormalizedArgs(args) {\n const firstArg = args[0];\n\n if (firstArg && 'document' in firstArg) {\n return firstArg;\n }\n\n return {\n schema: firstArg,\n // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613\n document: args[1],\n rootValue: args[2],\n contextValue: args[3],\n variableValues: args[4],\n operationName: args[5],\n subscribeFieldResolver: args[6],\n };\n}\n/**\n * Implements the \"CreateSourceEventStream\" algorithm described in the\n * GraphQL specification, resolving the subscription source event stream.\n *\n * Returns a Promise which resolves to either an AsyncIterable (if successful)\n * or an ExecutionResult (error). The promise will be rejected if the schema or\n * other arguments to this function are invalid, or if the resolved event stream\n * is not an async iterable.\n *\n * If the client-provided arguments to this function do not result in a\n * compliant subscription, a GraphQL Response (ExecutionResult) with\n * descriptive errors and no data will be returned.\n *\n * If the the source stream could not be created due to faulty subscription\n * resolver logic or underlying systems, the promise will resolve to a single\n * ExecutionResult containing `errors` and no `data`.\n *\n * If the operation succeeded, the promise resolves to the AsyncIterable for the\n * event stream returned by the resolver.\n *\n * A Source Event Stream represents a sequence of events, each of which triggers\n * a GraphQL execution for that event.\n *\n * This may be useful when hosting the stateful subscription service in a\n * different process or machine than the stateless GraphQL execution engine,\n * or otherwise separating these two steps. For more on this, see the\n * \"Supporting Subscriptions at Scale\" information in the GraphQL specification.\n */\n\nexport async function createSourceEventStream(...rawArgs) {\n const args = toNormalizedArgs(rawArgs);\n const { schema, document, variableValues } = args; // If arguments are missing or incorrectly typed, this is an internal\n // developer mistake which should throw an early error.\n\n assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,\n // a \"Response\" with only errors is returned.\n\n const exeContext = buildExecutionContext(args); // Return early errors if execution context failed.\n\n if (!('schema' in exeContext)) {\n return {\n errors: exeContext,\n };\n }\n\n try {\n const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error.\n\n if (!isAsyncIterable(eventStream)) {\n throw new Error(\n 'Subscription field must return Async Iterable. ' +\n `Received: ${inspect(eventStream)}.`,\n );\n }\n\n return eventStream;\n } catch (error) {\n // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data.\n // Otherwise treat the error as a system-class error and re-throw it.\n if (error instanceof GraphQLError) {\n return {\n errors: [error],\n };\n }\n\n throw error;\n }\n}\n\nasync function executeSubscription(exeContext) {\n const { schema, fragments, operation, variableValues, rootValue } =\n exeContext;\n const rootType = schema.getSubscriptionType();\n\n if (rootType == null) {\n throw new GraphQLError(\n 'Schema is not configured to execute subscription operation.',\n {\n nodes: operation,\n },\n );\n }\n\n const rootFields = collectFields(\n schema,\n fragments,\n variableValues,\n rootType,\n operation.selectionSet,\n );\n const [responseName, fieldNodes] = [...rootFields.entries()][0];\n const fieldDef = getFieldDef(schema, rootType, fieldNodes[0]);\n\n if (!fieldDef) {\n const fieldName = fieldNodes[0].name.value;\n throw new GraphQLError(\n `The subscription field \"${fieldName}\" is not defined.`,\n {\n nodes: fieldNodes,\n },\n );\n }\n\n const path = addPath(undefined, responseName, rootType.name);\n const info = buildResolveInfo(\n exeContext,\n fieldDef,\n fieldNodes,\n rootType,\n path,\n );\n\n try {\n var _fieldDef$subscribe;\n\n // Implements the \"ResolveFieldEventStream\" algorithm from GraphQL specification.\n // It differs from \"ResolveFieldValue\" due to providing a different `resolveFn`.\n // Build a JS object of arguments from the field.arguments AST, using the\n // variables scope to fulfill any variable references.\n const args = getArgumentValues(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that\n // is provided to every resolve function within an execution. It is commonly\n // used to represent an authenticated user, or request-specific caches.\n\n const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an\n // AsyncIterable yielding raw payloads.\n\n const resolveFn =\n (_fieldDef$subscribe = fieldDef.subscribe) !== null &&\n _fieldDef$subscribe !== void 0\n ? _fieldDef$subscribe\n : exeContext.subscribeFieldResolver;\n const eventStream = await resolveFn(rootValue, args, contextValue, info);\n\n if (eventStream instanceof Error) {\n throw eventStream;\n }\n\n return eventStream;\n } catch (error) {\n throw locatedError(error, fieldNodes, pathToArray(path));\n }\n}\n","import { GraphQLError } from '../../../error/GraphQLError.mjs';\nimport { getNamedType } from '../../../type/definition.mjs';\nimport { isIntrospectionType } from '../../../type/introspection.mjs';\n\n/**\n * Prohibit introspection queries\n *\n * A GraphQL document is only valid if all fields selected are not fields that\n * return an introspection type.\n *\n * Note: This rule is optional and is not part of the Validation section of the\n * GraphQL Specification. This rule effectively disables introspection, which\n * does not reflect best practices and should only be done if absolutely necessary.\n */\nexport function NoSchemaIntrospectionCustomRule(context) {\n return {\n Field(node) {\n const type = getNamedType(context.getType());\n\n if (type && isIntrospectionType(type)) {\n context.reportError(\n new GraphQLError(\n `GraphQL introspection has been disabled, but the requested query contained the field \"${node.name.value}\".`,\n {\n nodes: node,\n },\n ),\n );\n }\n },\n };\n}\n","import { Kind } from '../language/kinds.mjs';\n/**\n * Returns an operation AST given a document AST and optionally an operation\n * name. If a name is not provided, an operation is only returned if only one is\n * provided in the document.\n */\n\nexport function getOperationAST(documentAST, operationName) {\n let operation = null;\n\n for (const definition of documentAST.definitions) {\n if (definition.kind === Kind.OPERATION_DEFINITION) {\n var _definition$name;\n\n if (operationName == null) {\n // If no operation name was provided, only return an Operation if there\n // is one defined in the document. Upon encountering the second, return\n // null.\n if (operation) {\n return null;\n }\n\n operation = definition;\n } else if (\n ((_definition$name = definition.name) === null ||\n _definition$name === void 0\n ? void 0\n : _definition$name.value) === operationName\n ) {\n return definition;\n }\n }\n }\n\n return operation;\n}\n","import { GraphQLError } from '../error/GraphQLError.mjs';\n\n/**\n * Extracts the root type of the operation from the schema.\n *\n * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17\n */\nexport function getOperationRootType(schema, operation) {\n if (operation.operation === 'query') {\n const queryType = schema.getQueryType();\n\n if (!queryType) {\n throw new GraphQLError(\n 'Schema does not define the required query root type.',\n {\n nodes: operation,\n },\n );\n }\n\n return queryType;\n }\n\n if (operation.operation === 'mutation') {\n const mutationType = schema.getMutationType();\n\n if (!mutationType) {\n throw new GraphQLError('Schema is not configured for mutations.', {\n nodes: operation,\n });\n }\n\n return mutationType;\n }\n\n if (operation.operation === 'subscription') {\n const subscriptionType = schema.getSubscriptionType();\n\n if (!subscriptionType) {\n throw new GraphQLError('Schema is not configured for subscriptions.', {\n nodes: operation,\n });\n }\n\n return subscriptionType;\n }\n\n throw new GraphQLError(\n 'Can only have query, mutation and subscription operations.',\n {\n nodes: operation,\n },\n );\n}\n","import { invariant } from '../jsutils/invariant.mjs';\nimport { parse } from '../language/parser.mjs';\nimport { executeSync } from '../execution/execute.mjs';\nimport { getIntrospectionQuery } from './getIntrospectionQuery.mjs';\n/**\n * Build an IntrospectionQuery from a GraphQLSchema\n *\n * IntrospectionQuery is useful for utilities that care about type and field\n * relationships, but do not need to traverse through those relationships.\n *\n * This is the inverse of buildClientSchema. The primary use case is outside\n * of the server context, for instance when doing schema comparisons.\n */\n\nexport function introspectionFromSchema(schema, options) {\n const optionsWithDefaults = {\n specifiedByUrl: true,\n directiveIsRepeatable: true,\n schemaDescription: true,\n inputValueDeprecation: true,\n ...options,\n };\n const document = parse(getIntrospectionQuery(optionsWithDefaults));\n const result = executeSync({\n schema,\n document,\n });\n (!result.errors && result.data) || invariant(false);\n return result.data;\n}\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { keyMap } from '../jsutils/keyMap.mjs';\nimport { mapValue } from '../jsutils/mapValue.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport {\n isTypeDefinitionNode,\n isTypeExtensionNode,\n} from '../language/predicates.mjs';\nimport {\n GraphQLEnumType,\n GraphQLInputObjectType,\n GraphQLInterfaceType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n GraphQLScalarType,\n GraphQLUnionType,\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isListType,\n isNonNullType,\n isObjectType,\n isScalarType,\n isUnionType,\n} from '../type/definition.mjs';\nimport {\n GraphQLDeprecatedDirective,\n GraphQLDirective,\n GraphQLSpecifiedByDirective,\n} from '../type/directives.mjs';\nimport {\n introspectionTypes,\n isIntrospectionType,\n} from '../type/introspection.mjs';\nimport {\n isSpecifiedScalarType,\n specifiedScalarTypes,\n} from '../type/scalars.mjs';\nimport { assertSchema, GraphQLSchema } from '../type/schema.mjs';\nimport { assertValidSDLExtension } from '../validation/validate.mjs';\nimport { getDirectiveValues } from '../execution/values.mjs';\nimport { valueFromAST } from './valueFromAST.mjs';\n\n/**\n * Produces a new schema given an existing schema and a document which may\n * contain GraphQL type extensions and definitions. The original schema will\n * remain unaltered.\n *\n * Because a schema represents a graph of references, a schema cannot be\n * extended without effectively making an entire copy. We do not know until it's\n * too late if subgraphs remain unchanged.\n *\n * This algorithm copies the provided schema, applying extensions while\n * producing the copy. The original schema remains unaltered.\n */\nexport function extendSchema(schema, documentAST, options) {\n assertSchema(schema);\n (documentAST != null && documentAST.kind === Kind.DOCUMENT) ||\n devAssert(false, 'Must provide valid Document AST.');\n\n if (\n (options === null || options === void 0 ? void 0 : options.assumeValid) !==\n true &&\n (options === null || options === void 0\n ? void 0\n : options.assumeValidSDL) !== true\n ) {\n assertValidSDLExtension(documentAST, schema);\n }\n\n const schemaConfig = schema.toConfig();\n const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);\n return schemaConfig === extendedConfig\n ? schema\n : new GraphQLSchema(extendedConfig);\n}\n/**\n * @internal\n */\n\nexport function extendSchemaImpl(schemaConfig, documentAST, options) {\n var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid;\n\n // Collect the type definitions and extensions found in the document.\n const typeDefs = [];\n const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can\n // have the same name. For example, a type named \"skip\".\n\n const directiveDefs = [];\n let schemaDef; // Schema extensions are collected which may add additional operation types.\n\n const schemaExtensions = [];\n\n for (const def of documentAST.definitions) {\n if (def.kind === Kind.SCHEMA_DEFINITION) {\n schemaDef = def;\n } else if (def.kind === Kind.SCHEMA_EXTENSION) {\n schemaExtensions.push(def);\n } else if (isTypeDefinitionNode(def)) {\n typeDefs.push(def);\n } else if (isTypeExtensionNode(def)) {\n const extendedTypeName = def.name.value;\n const existingTypeExtensions = typeExtensionsMap[extendedTypeName];\n typeExtensionsMap[extendedTypeName] = existingTypeExtensions\n ? existingTypeExtensions.concat([def])\n : [def];\n } else if (def.kind === Kind.DIRECTIVE_DEFINITION) {\n directiveDefs.push(def);\n }\n } // If this document contains no new types, extensions, or directives then\n // return the same unmodified GraphQLSchema instance.\n\n if (\n Object.keys(typeExtensionsMap).length === 0 &&\n typeDefs.length === 0 &&\n directiveDefs.length === 0 &&\n schemaExtensions.length === 0 &&\n schemaDef == null\n ) {\n return schemaConfig;\n }\n\n const typeMap = Object.create(null);\n\n for (const existingType of schemaConfig.types) {\n typeMap[existingType.name] = extendNamedType(existingType);\n }\n\n for (const typeNode of typeDefs) {\n var _stdTypeMap$name;\n\n const name = typeNode.name.value;\n typeMap[name] =\n (_stdTypeMap$name = stdTypeMap[name]) !== null &&\n _stdTypeMap$name !== void 0\n ? _stdTypeMap$name\n : buildType(typeNode);\n }\n\n const operationTypes = {\n // Get the extended root operation types.\n query: schemaConfig.query && replaceNamedType(schemaConfig.query),\n mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),\n subscription:\n schemaConfig.subscription && replaceNamedType(schemaConfig.subscription),\n // Then, incorporate schema definition and all schema extensions.\n ...(schemaDef && getOperationTypes([schemaDef])),\n ...getOperationTypes(schemaExtensions),\n }; // Then produce and return a Schema config with these types.\n\n return {\n description:\n (_schemaDef = schemaDef) === null || _schemaDef === void 0\n ? void 0\n : (_schemaDef$descriptio = _schemaDef.description) === null ||\n _schemaDef$descriptio === void 0\n ? void 0\n : _schemaDef$descriptio.value,\n ...operationTypes,\n types: Object.values(typeMap),\n directives: [\n ...schemaConfig.directives.map(replaceDirective),\n ...directiveDefs.map(buildDirective),\n ],\n extensions: Object.create(null),\n astNode:\n (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0\n ? _schemaDef2\n : schemaConfig.astNode,\n extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),\n assumeValid:\n (_options$assumeValid =\n options === null || options === void 0\n ? void 0\n : options.assumeValid) !== null && _options$assumeValid !== void 0\n ? _options$assumeValid\n : false,\n }; // Below are functions used for producing this schema that have closed over\n // this scope and have access to the schema, cache, and newly defined types.\n\n function replaceType(type) {\n if (isListType(type)) {\n // @ts-expect-error\n return new GraphQLList(replaceType(type.ofType));\n }\n\n if (isNonNullType(type)) {\n // @ts-expect-error\n return new GraphQLNonNull(replaceType(type.ofType));\n } // @ts-expect-error FIXME\n\n return replaceNamedType(type);\n }\n\n function replaceNamedType(type) {\n // Note: While this could make early assertions to get the correctly\n // typed values, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n return typeMap[type.name];\n }\n\n function replaceDirective(directive) {\n const config = directive.toConfig();\n return new GraphQLDirective({\n ...config,\n args: mapValue(config.args, extendArg),\n });\n }\n\n function extendNamedType(type) {\n if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {\n // Builtin types are not extended.\n return type;\n }\n\n if (isScalarType(type)) {\n return extendScalarType(type);\n }\n\n if (isObjectType(type)) {\n return extendObjectType(type);\n }\n\n if (isInterfaceType(type)) {\n return extendInterfaceType(type);\n }\n\n if (isUnionType(type)) {\n return extendUnionType(type);\n }\n\n if (isEnumType(type)) {\n return extendEnumType(type);\n }\n\n if (isInputObjectType(type)) {\n return extendInputObjectType(type);\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible type definition nodes have been considered.\n\n false || invariant(false, 'Unexpected type: ' + inspect(type));\n }\n\n function extendInputObjectType(type) {\n var _typeExtensionsMap$co;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co !== void 0\n ? _typeExtensionsMap$co\n : [];\n return new GraphQLInputObjectType({\n ...config,\n fields: () => ({\n ...mapValue(config.fields, (field) => ({\n ...field,\n type: replaceType(field.type),\n })),\n ...buildInputFieldMap(extensions),\n }),\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendEnumType(type) {\n var _typeExtensionsMap$ty;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null &&\n _typeExtensionsMap$ty !== void 0\n ? _typeExtensionsMap$ty\n : [];\n return new GraphQLEnumType({\n ...config,\n values: { ...config.values, ...buildEnumValueMap(extensions) },\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendScalarType(type) {\n var _typeExtensionsMap$co2;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co2 !== void 0\n ? _typeExtensionsMap$co2\n : [];\n let specifiedByURL = config.specifiedByURL;\n\n for (const extensionNode of extensions) {\n var _getSpecifiedByURL;\n\n specifiedByURL =\n (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null &&\n _getSpecifiedByURL !== void 0\n ? _getSpecifiedByURL\n : specifiedByURL;\n }\n\n return new GraphQLScalarType({\n ...config,\n specifiedByURL,\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendObjectType(type) {\n var _typeExtensionsMap$co3;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co3 !== void 0\n ? _typeExtensionsMap$co3\n : [];\n return new GraphQLObjectType({\n ...config,\n interfaces: () => [\n ...type.getInterfaces().map(replaceNamedType),\n ...buildInterfaces(extensions),\n ],\n fields: () => ({\n ...mapValue(config.fields, extendField),\n ...buildFieldMap(extensions),\n }),\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendInterfaceType(type) {\n var _typeExtensionsMap$co4;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co4 !== void 0\n ? _typeExtensionsMap$co4\n : [];\n return new GraphQLInterfaceType({\n ...config,\n interfaces: () => [\n ...type.getInterfaces().map(replaceNamedType),\n ...buildInterfaces(extensions),\n ],\n fields: () => ({\n ...mapValue(config.fields, extendField),\n ...buildFieldMap(extensions),\n }),\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendUnionType(type) {\n var _typeExtensionsMap$co5;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co5 !== void 0\n ? _typeExtensionsMap$co5\n : [];\n return new GraphQLUnionType({\n ...config,\n types: () => [\n ...type.getTypes().map(replaceNamedType),\n ...buildUnionTypes(extensions),\n ],\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendField(field) {\n return {\n ...field,\n type: replaceType(field.type),\n args: field.args && mapValue(field.args, extendArg),\n };\n }\n\n function extendArg(arg) {\n return { ...arg, type: replaceType(arg.type) };\n }\n\n function getOperationTypes(nodes) {\n const opTypes = {};\n\n for (const node of nodes) {\n var _node$operationTypes;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const operationTypesNodes =\n /* c8 ignore next */\n (_node$operationTypes = node.operationTypes) !== null &&\n _node$operationTypes !== void 0\n ? _node$operationTypes\n : [];\n\n for (const operationType of operationTypesNodes) {\n // Note: While this could make early assertions to get the correctly\n // typed values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n // @ts-expect-error\n opTypes[operationType.operation] = getNamedType(operationType.type);\n }\n }\n\n return opTypes;\n }\n\n function getNamedType(node) {\n var _stdTypeMap$name2;\n\n const name = node.name.value;\n const type =\n (_stdTypeMap$name2 = stdTypeMap[name]) !== null &&\n _stdTypeMap$name2 !== void 0\n ? _stdTypeMap$name2\n : typeMap[name];\n\n if (type === undefined) {\n throw new Error(`Unknown type: \"${name}\".`);\n }\n\n return type;\n }\n\n function getWrappedType(node) {\n if (node.kind === Kind.LIST_TYPE) {\n return new GraphQLList(getWrappedType(node.type));\n }\n\n if (node.kind === Kind.NON_NULL_TYPE) {\n return new GraphQLNonNull(getWrappedType(node.type));\n }\n\n return getNamedType(node);\n }\n\n function buildDirective(node) {\n var _node$description;\n\n return new GraphQLDirective({\n name: node.name.value,\n description:\n (_node$description = node.description) === null ||\n _node$description === void 0\n ? void 0\n : _node$description.value,\n // @ts-expect-error\n locations: node.locations.map(({ value }) => value),\n isRepeatable: node.repeatable,\n args: buildArgumentMap(node.arguments),\n astNode: node,\n });\n }\n\n function buildFieldMap(nodes) {\n const fieldConfigMap = Object.create(null);\n\n for (const node of nodes) {\n var _node$fields;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const nodeFields =\n /* c8 ignore next */\n (_node$fields = node.fields) !== null && _node$fields !== void 0\n ? _node$fields\n : [];\n\n for (const field of nodeFields) {\n var _field$description;\n\n fieldConfigMap[field.name.value] = {\n // Note: While this could make assertions to get the correctly typed\n // value, that would throw immediately while type system validation\n // with validateSchema() will produce more actionable results.\n type: getWrappedType(field.type),\n description:\n (_field$description = field.description) === null ||\n _field$description === void 0\n ? void 0\n : _field$description.value,\n args: buildArgumentMap(field.arguments),\n deprecationReason: getDeprecationReason(field),\n astNode: field,\n };\n }\n }\n\n return fieldConfigMap;\n }\n\n function buildArgumentMap(args) {\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const argsNodes =\n /* c8 ignore next */\n args !== null && args !== void 0 ? args : [];\n const argConfigMap = Object.create(null);\n\n for (const arg of argsNodes) {\n var _arg$description;\n\n // Note: While this could make assertions to get the correctly typed\n // value, that would throw immediately while type system validation\n // with validateSchema() will produce more actionable results.\n const type = getWrappedType(arg.type);\n argConfigMap[arg.name.value] = {\n type,\n description:\n (_arg$description = arg.description) === null ||\n _arg$description === void 0\n ? void 0\n : _arg$description.value,\n defaultValue: valueFromAST(arg.defaultValue, type),\n deprecationReason: getDeprecationReason(arg),\n astNode: arg,\n };\n }\n\n return argConfigMap;\n }\n\n function buildInputFieldMap(nodes) {\n const inputFieldMap = Object.create(null);\n\n for (const node of nodes) {\n var _node$fields2;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const fieldsNodes =\n /* c8 ignore next */\n (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0\n ? _node$fields2\n : [];\n\n for (const field of fieldsNodes) {\n var _field$description2;\n\n // Note: While this could make assertions to get the correctly typed\n // value, that would throw immediately while type system validation\n // with validateSchema() will produce more actionable results.\n const type = getWrappedType(field.type);\n inputFieldMap[field.name.value] = {\n type,\n description:\n (_field$description2 = field.description) === null ||\n _field$description2 === void 0\n ? void 0\n : _field$description2.value,\n defaultValue: valueFromAST(field.defaultValue, type),\n deprecationReason: getDeprecationReason(field),\n astNode: field,\n };\n }\n }\n\n return inputFieldMap;\n }\n\n function buildEnumValueMap(nodes) {\n const enumValueMap = Object.create(null);\n\n for (const node of nodes) {\n var _node$values;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const valuesNodes =\n /* c8 ignore next */\n (_node$values = node.values) !== null && _node$values !== void 0\n ? _node$values\n : [];\n\n for (const value of valuesNodes) {\n var _value$description;\n\n enumValueMap[value.name.value] = {\n description:\n (_value$description = value.description) === null ||\n _value$description === void 0\n ? void 0\n : _value$description.value,\n deprecationReason: getDeprecationReason(value),\n astNode: value,\n };\n }\n }\n\n return enumValueMap;\n }\n\n function buildInterfaces(nodes) {\n // Note: While this could make assertions to get the correctly typed\n // values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n // @ts-expect-error\n return nodes.flatMap(\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n (node) => {\n var _node$interfaces$map, _node$interfaces;\n\n return (\n /* c8 ignore next */\n (_node$interfaces$map =\n (_node$interfaces = node.interfaces) === null ||\n _node$interfaces === void 0\n ? void 0\n : _node$interfaces.map(getNamedType)) !== null &&\n _node$interfaces$map !== void 0\n ? _node$interfaces$map\n : []\n );\n },\n );\n }\n\n function buildUnionTypes(nodes) {\n // Note: While this could make assertions to get the correctly typed\n // values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n // @ts-expect-error\n return nodes.flatMap(\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n (node) => {\n var _node$types$map, _node$types;\n\n return (\n /* c8 ignore next */\n (_node$types$map =\n (_node$types = node.types) === null || _node$types === void 0\n ? void 0\n : _node$types.map(getNamedType)) !== null &&\n _node$types$map !== void 0\n ? _node$types$map\n : []\n );\n },\n );\n }\n\n function buildType(astNode) {\n var _typeExtensionsMap$na;\n\n const name = astNode.name.value;\n const extensionASTNodes =\n (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null &&\n _typeExtensionsMap$na !== void 0\n ? _typeExtensionsMap$na\n : [];\n\n switch (astNode.kind) {\n case Kind.OBJECT_TYPE_DEFINITION: {\n var _astNode$description;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLObjectType({\n name,\n description:\n (_astNode$description = astNode.description) === null ||\n _astNode$description === void 0\n ? void 0\n : _astNode$description.value,\n interfaces: () => buildInterfaces(allNodes),\n fields: () => buildFieldMap(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.INTERFACE_TYPE_DEFINITION: {\n var _astNode$description2;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLInterfaceType({\n name,\n description:\n (_astNode$description2 = astNode.description) === null ||\n _astNode$description2 === void 0\n ? void 0\n : _astNode$description2.value,\n interfaces: () => buildInterfaces(allNodes),\n fields: () => buildFieldMap(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.ENUM_TYPE_DEFINITION: {\n var _astNode$description3;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLEnumType({\n name,\n description:\n (_astNode$description3 = astNode.description) === null ||\n _astNode$description3 === void 0\n ? void 0\n : _astNode$description3.value,\n values: buildEnumValueMap(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.UNION_TYPE_DEFINITION: {\n var _astNode$description4;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLUnionType({\n name,\n description:\n (_astNode$description4 = astNode.description) === null ||\n _astNode$description4 === void 0\n ? void 0\n : _astNode$description4.value,\n types: () => buildUnionTypes(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.SCALAR_TYPE_DEFINITION: {\n var _astNode$description5;\n\n return new GraphQLScalarType({\n name,\n description:\n (_astNode$description5 = astNode.description) === null ||\n _astNode$description5 === void 0\n ? void 0\n : _astNode$description5.value,\n specifiedByURL: getSpecifiedByURL(astNode),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.INPUT_OBJECT_TYPE_DEFINITION: {\n var _astNode$description6;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLInputObjectType({\n name,\n description:\n (_astNode$description6 = astNode.description) === null ||\n _astNode$description6 === void 0\n ? void 0\n : _astNode$description6.value,\n fields: () => buildInputFieldMap(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n }\n }\n}\nconst stdTypeMap = keyMap(\n [...specifiedScalarTypes, ...introspectionTypes],\n (type) => type.name,\n);\n/**\n * Given a field or enum value node, returns the string value for the\n * deprecation reason.\n */\n\nfunction getDeprecationReason(node) {\n const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues`\n\n return deprecated === null || deprecated === void 0\n ? void 0\n : deprecated.reason;\n}\n/**\n * Given a scalar node, returns the string value for the specifiedByURL.\n */\n\nfunction getSpecifiedByURL(node) {\n const specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues`\n\n return specifiedBy === null || specifiedBy === void 0\n ? void 0\n : specifiedBy.url;\n}\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport { parse } from '../language/parser.mjs';\nimport { specifiedDirectives } from '../type/directives.mjs';\nimport { GraphQLSchema } from '../type/schema.mjs';\nimport { assertValidSDL } from '../validation/validate.mjs';\nimport { extendSchemaImpl } from './extendSchema.mjs';\n\n/**\n * This takes the ast of a schema document produced by the parse function in\n * src/language/parser.js.\n *\n * If no schema definition is provided, then it will look for types named Query,\n * Mutation and Subscription.\n *\n * Given that AST it constructs a GraphQLSchema. The resulting schema\n * has no resolve methods, so execution will use default resolvers.\n */\nexport function buildASTSchema(documentAST, options) {\n (documentAST != null && documentAST.kind === Kind.DOCUMENT) ||\n devAssert(false, 'Must provide valid Document AST.');\n\n if (\n (options === null || options === void 0 ? void 0 : options.assumeValid) !==\n true &&\n (options === null || options === void 0\n ? void 0\n : options.assumeValidSDL) !== true\n ) {\n assertValidSDL(documentAST);\n }\n\n const emptySchemaConfig = {\n description: undefined,\n types: [],\n directives: [],\n extensions: Object.create(null),\n extensionASTNodes: [],\n assumeValid: false,\n };\n const config = extendSchemaImpl(emptySchemaConfig, documentAST, options);\n\n if (config.astNode == null) {\n for (const type of config.types) {\n switch (type.name) {\n // Note: While this could make early assertions to get the correctly\n // typed values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n case 'Query':\n // @ts-expect-error validated in `validateSchema`\n config.query = type;\n break;\n\n case 'Mutation':\n // @ts-expect-error validated in `validateSchema`\n config.mutation = type;\n break;\n\n case 'Subscription':\n // @ts-expect-error validated in `validateSchema`\n config.subscription = type;\n break;\n }\n }\n }\n\n const directives = [\n ...config.directives, // If specified directives were not explicitly declared, add them.\n ...specifiedDirectives.filter((stdDirective) =>\n config.directives.every(\n (directive) => directive.name !== stdDirective.name,\n ),\n ),\n ];\n return new GraphQLSchema({ ...config, directives });\n}\n/**\n * A helper function to build a GraphQLSchema directly from a source\n * document.\n */\n\nexport function buildSchema(source, options) {\n const document = parse(source, {\n noLocation:\n options === null || options === void 0 ? void 0 : options.noLocation,\n allowLegacyFragmentVariables:\n options === null || options === void 0\n ? void 0\n : options.allowLegacyFragmentVariables,\n });\n return buildASTSchema(document, {\n assumeValidSDL:\n options === null || options === void 0 ? void 0 : options.assumeValidSDL,\n assumeValid:\n options === null || options === void 0 ? void 0 : options.assumeValid,\n });\n}\n","import { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { keyValMap } from '../jsutils/keyValMap.mjs';\nimport { naturalCompare } from '../jsutils/naturalCompare.mjs';\nimport {\n GraphQLEnumType,\n GraphQLInputObjectType,\n GraphQLInterfaceType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n GraphQLUnionType,\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isListType,\n isNonNullType,\n isObjectType,\n isScalarType,\n isUnionType,\n} from '../type/definition.mjs';\nimport { GraphQLDirective } from '../type/directives.mjs';\nimport { isIntrospectionType } from '../type/introspection.mjs';\nimport { GraphQLSchema } from '../type/schema.mjs';\n/**\n * Sort GraphQLSchema.\n *\n * This function returns a sorted copy of the given GraphQLSchema.\n */\n\nexport function lexicographicSortSchema(schema) {\n const schemaConfig = schema.toConfig();\n const typeMap = keyValMap(\n sortByName(schemaConfig.types),\n (type) => type.name,\n sortNamedType,\n );\n return new GraphQLSchema({\n ...schemaConfig,\n types: Object.values(typeMap),\n directives: sortByName(schemaConfig.directives).map(sortDirective),\n query: replaceMaybeType(schemaConfig.query),\n mutation: replaceMaybeType(schemaConfig.mutation),\n subscription: replaceMaybeType(schemaConfig.subscription),\n });\n\n function replaceType(type) {\n if (isListType(type)) {\n // @ts-expect-error\n return new GraphQLList(replaceType(type.ofType));\n } else if (isNonNullType(type)) {\n // @ts-expect-error\n return new GraphQLNonNull(replaceType(type.ofType));\n } // @ts-expect-error FIXME: TS Conversion\n\n return replaceNamedType(type);\n }\n\n function replaceNamedType(type) {\n return typeMap[type.name];\n }\n\n function replaceMaybeType(maybeType) {\n return maybeType && replaceNamedType(maybeType);\n }\n\n function sortDirective(directive) {\n const config = directive.toConfig();\n return new GraphQLDirective({\n ...config,\n locations: sortBy(config.locations, (x) => x),\n args: sortArgs(config.args),\n });\n }\n\n function sortArgs(args) {\n return sortObjMap(args, (arg) => ({ ...arg, type: replaceType(arg.type) }));\n }\n\n function sortFields(fieldsMap) {\n return sortObjMap(fieldsMap, (field) => ({\n ...field,\n type: replaceType(field.type),\n args: field.args && sortArgs(field.args),\n }));\n }\n\n function sortInputFields(fieldsMap) {\n return sortObjMap(fieldsMap, (field) => ({\n ...field,\n type: replaceType(field.type),\n }));\n }\n\n function sortTypes(array) {\n return sortByName(array).map(replaceNamedType);\n }\n\n function sortNamedType(type) {\n if (isScalarType(type) || isIntrospectionType(type)) {\n return type;\n }\n\n if (isObjectType(type)) {\n const config = type.toConfig();\n return new GraphQLObjectType({\n ...config,\n interfaces: () => sortTypes(config.interfaces),\n fields: () => sortFields(config.fields),\n });\n }\n\n if (isInterfaceType(type)) {\n const config = type.toConfig();\n return new GraphQLInterfaceType({\n ...config,\n interfaces: () => sortTypes(config.interfaces),\n fields: () => sortFields(config.fields),\n });\n }\n\n if (isUnionType(type)) {\n const config = type.toConfig();\n return new GraphQLUnionType({\n ...config,\n types: () => sortTypes(config.types),\n });\n }\n\n if (isEnumType(type)) {\n const config = type.toConfig();\n return new GraphQLEnumType({\n ...config,\n values: sortObjMap(config.values, (value) => value),\n });\n }\n\n if (isInputObjectType(type)) {\n const config = type.toConfig();\n return new GraphQLInputObjectType({\n ...config,\n fields: () => sortInputFields(config.fields),\n });\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible types have been considered.\n\n false || invariant(false, 'Unexpected type: ' + inspect(type));\n }\n}\n\nfunction sortObjMap(map, sortValueFn) {\n const sortedMap = Object.create(null);\n\n for (const key of Object.keys(map).sort(naturalCompare)) {\n sortedMap[key] = sortValueFn(map[key]);\n }\n\n return sortedMap;\n}\n\nfunction sortByName(array) {\n return sortBy(array, (obj) => obj.name);\n}\n\nfunction sortBy(array, mapToKey) {\n return array.slice().sort((obj1, obj2) => {\n const key1 = mapToKey(obj1);\n const key2 = mapToKey(obj2);\n return naturalCompare(key1, key2);\n });\n}\n","import { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { isPrintableAsBlockString } from '../language/blockString.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport { print } from '../language/printer.mjs';\nimport {\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isObjectType,\n isScalarType,\n isUnionType,\n} from '../type/definition.mjs';\nimport {\n DEFAULT_DEPRECATION_REASON,\n isSpecifiedDirective,\n} from '../type/directives.mjs';\nimport { isIntrospectionType } from '../type/introspection.mjs';\nimport { isSpecifiedScalarType } from '../type/scalars.mjs';\nimport { astFromValue } from './astFromValue.mjs';\nexport function printSchema(schema) {\n return printFilteredSchema(\n schema,\n (n) => !isSpecifiedDirective(n),\n isDefinedType,\n );\n}\nexport function printIntrospectionSchema(schema) {\n return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType);\n}\n\nfunction isDefinedType(type) {\n return !isSpecifiedScalarType(type) && !isIntrospectionType(type);\n}\n\nfunction printFilteredSchema(schema, directiveFilter, typeFilter) {\n const directives = schema.getDirectives().filter(directiveFilter);\n const types = Object.values(schema.getTypeMap()).filter(typeFilter);\n return [\n printSchemaDefinition(schema),\n ...directives.map((directive) => printDirective(directive)),\n ...types.map((type) => printType(type)),\n ]\n .filter(Boolean)\n .join('\\n\\n');\n}\n\nfunction printSchemaDefinition(schema) {\n if (schema.description == null && isSchemaOfCommonNames(schema)) {\n return;\n }\n\n const operationTypes = [];\n const queryType = schema.getQueryType();\n\n if (queryType) {\n operationTypes.push(` query: ${queryType.name}`);\n }\n\n const mutationType = schema.getMutationType();\n\n if (mutationType) {\n operationTypes.push(` mutation: ${mutationType.name}`);\n }\n\n const subscriptionType = schema.getSubscriptionType();\n\n if (subscriptionType) {\n operationTypes.push(` subscription: ${subscriptionType.name}`);\n }\n\n return printDescription(schema) + `schema {\\n${operationTypes.join('\\n')}\\n}`;\n}\n/**\n * GraphQL schema define root types for each type of operation. These types are\n * the same as any other type and can be named in any manner, however there is\n * a common naming convention:\n *\n * ```graphql\n * schema {\n * query: Query\n * mutation: Mutation\n * subscription: Subscription\n * }\n * ```\n *\n * When using this naming convention, the schema description can be omitted.\n */\n\nfunction isSchemaOfCommonNames(schema) {\n const queryType = schema.getQueryType();\n\n if (queryType && queryType.name !== 'Query') {\n return false;\n }\n\n const mutationType = schema.getMutationType();\n\n if (mutationType && mutationType.name !== 'Mutation') {\n return false;\n }\n\n const subscriptionType = schema.getSubscriptionType();\n\n if (subscriptionType && subscriptionType.name !== 'Subscription') {\n return false;\n }\n\n return true;\n}\n\nexport function printType(type) {\n if (isScalarType(type)) {\n return printScalar(type);\n }\n\n if (isObjectType(type)) {\n return printObject(type);\n }\n\n if (isInterfaceType(type)) {\n return printInterface(type);\n }\n\n if (isUnionType(type)) {\n return printUnion(type);\n }\n\n if (isEnumType(type)) {\n return printEnum(type);\n }\n\n if (isInputObjectType(type)) {\n return printInputObject(type);\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible types have been considered.\n\n false || invariant(false, 'Unexpected type: ' + inspect(type));\n}\n\nfunction printScalar(type) {\n return (\n printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type)\n );\n}\n\nfunction printImplementedInterfaces(type) {\n const interfaces = type.getInterfaces();\n return interfaces.length\n ? ' implements ' + interfaces.map((i) => i.name).join(' & ')\n : '';\n}\n\nfunction printObject(type) {\n return (\n printDescription(type) +\n `type ${type.name}` +\n printImplementedInterfaces(type) +\n printFields(type)\n );\n}\n\nfunction printInterface(type) {\n return (\n printDescription(type) +\n `interface ${type.name}` +\n printImplementedInterfaces(type) +\n printFields(type)\n );\n}\n\nfunction printUnion(type) {\n const types = type.getTypes();\n const possibleTypes = types.length ? ' = ' + types.join(' | ') : '';\n return printDescription(type) + 'union ' + type.name + possibleTypes;\n}\n\nfunction printEnum(type) {\n const values = type\n .getValues()\n .map(\n (value, i) =>\n printDescription(value, ' ', !i) +\n ' ' +\n value.name +\n printDeprecated(value.deprecationReason),\n );\n return printDescription(type) + `enum ${type.name}` + printBlock(values);\n}\n\nfunction printInputObject(type) {\n const fields = Object.values(type.getFields()).map(\n (f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f),\n );\n return printDescription(type) + `input ${type.name}` + printBlock(fields);\n}\n\nfunction printFields(type) {\n const fields = Object.values(type.getFields()).map(\n (f, i) =>\n printDescription(f, ' ', !i) +\n ' ' +\n f.name +\n printArgs(f.args, ' ') +\n ': ' +\n String(f.type) +\n printDeprecated(f.deprecationReason),\n );\n return printBlock(fields);\n}\n\nfunction printBlock(items) {\n return items.length !== 0 ? ' {\\n' + items.join('\\n') + '\\n}' : '';\n}\n\nfunction printArgs(args, indentation = '') {\n if (args.length === 0) {\n return '';\n } // If every arg does not have a description, print them on one line.\n\n if (args.every((arg) => !arg.description)) {\n return '(' + args.map(printInputValue).join(', ') + ')';\n }\n\n return (\n '(\\n' +\n args\n .map(\n (arg, i) =>\n printDescription(arg, ' ' + indentation, !i) +\n ' ' +\n indentation +\n printInputValue(arg),\n )\n .join('\\n') +\n '\\n' +\n indentation +\n ')'\n );\n}\n\nfunction printInputValue(arg) {\n const defaultAST = astFromValue(arg.defaultValue, arg.type);\n let argDecl = arg.name + ': ' + String(arg.type);\n\n if (defaultAST) {\n argDecl += ` = ${print(defaultAST)}`;\n }\n\n return argDecl + printDeprecated(arg.deprecationReason);\n}\n\nfunction printDirective(directive) {\n return (\n printDescription(directive) +\n 'directive @' +\n directive.name +\n printArgs(directive.args) +\n (directive.isRepeatable ? ' repeatable' : '') +\n ' on ' +\n directive.locations.join(' | ')\n );\n}\n\nfunction printDeprecated(reason) {\n if (reason == null) {\n return '';\n }\n\n if (reason !== DEFAULT_DEPRECATION_REASON) {\n const astValue = print({\n kind: Kind.STRING,\n value: reason,\n });\n return ` @deprecated(reason: ${astValue})`;\n }\n\n return ' @deprecated';\n}\n\nfunction printSpecifiedByURL(scalar) {\n if (scalar.specifiedByURL == null) {\n return '';\n }\n\n const astValue = print({\n kind: Kind.STRING,\n value: scalar.specifiedByURL,\n });\n return ` @specifiedBy(url: ${astValue})`;\n}\n\nfunction printDescription(def, indentation = '', firstInBlock = true) {\n const { description } = def;\n\n if (description == null) {\n return '';\n }\n\n const blockString = print({\n kind: Kind.STRING,\n value: description,\n block: isPrintableAsBlockString(description),\n });\n const prefix =\n indentation && !firstInBlock ? '\\n' + indentation : indentation;\n return prefix + blockString.replace(/\\n/g, '\\n' + indentation) + '\\n';\n}\n","import { Kind } from '../language/kinds.mjs';\n/**\n * Provided a collection of ASTs, presumably each from different files,\n * concatenate the ASTs together into batched AST, useful for validating many\n * GraphQL source files which together represent one conceptual application.\n */\n\nexport function concatAST(documents) {\n const definitions = [];\n\n for (const doc of documents) {\n definitions.push(...doc.definitions);\n }\n\n return {\n kind: Kind.DOCUMENT,\n definitions,\n };\n}\n","import { Kind } from '../language/kinds.mjs';\nimport { visit } from '../language/visitor.mjs';\n/**\n * separateOperations accepts a single AST document which may contain many\n * operations and fragments and returns a collection of AST documents each of\n * which contains a single operation as well the fragment definitions it\n * refers to.\n */\n\nexport function separateOperations(documentAST) {\n const operations = [];\n const depGraph = Object.create(null); // Populate metadata and build a dependency graph.\n\n for (const definitionNode of documentAST.definitions) {\n switch (definitionNode.kind) {\n case Kind.OPERATION_DEFINITION:\n operations.push(definitionNode);\n break;\n\n case Kind.FRAGMENT_DEFINITION:\n depGraph[definitionNode.name.value] = collectDependencies(\n definitionNode.selectionSet,\n );\n break;\n\n default: // ignore non-executable definitions\n }\n } // For each operation, produce a new synthesized AST which includes only what\n // is necessary for completing that operation.\n\n const separatedDocumentASTs = Object.create(null);\n\n for (const operation of operations) {\n const dependencies = new Set();\n\n for (const fragmentName of collectDependencies(operation.selectionSet)) {\n collectTransitiveDependencies(dependencies, depGraph, fragmentName);\n } // Provides the empty string for anonymous operations.\n\n const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted\n // to retain the same order as the original document.\n\n separatedDocumentASTs[operationName] = {\n kind: Kind.DOCUMENT,\n definitions: documentAST.definitions.filter(\n (node) =>\n node === operation ||\n (node.kind === Kind.FRAGMENT_DEFINITION &&\n dependencies.has(node.name.value)),\n ),\n };\n }\n\n return separatedDocumentASTs;\n}\n\n// From a dependency graph, collects a list of transitive dependencies by\n// recursing through a dependency graph.\nfunction collectTransitiveDependencies(collected, depGraph, fromName) {\n if (!collected.has(fromName)) {\n collected.add(fromName);\n const immediateDeps = depGraph[fromName];\n\n if (immediateDeps !== undefined) {\n for (const toName of immediateDeps) {\n collectTransitiveDependencies(collected, depGraph, toName);\n }\n }\n }\n}\n\nfunction collectDependencies(selectionSet) {\n const dependencies = [];\n visit(selectionSet, {\n FragmentSpread(node) {\n dependencies.push(node.name.value);\n },\n });\n return dependencies;\n}\n","import { printBlockString } from '../language/blockString.mjs';\nimport { isPunctuatorTokenKind, Lexer } from '../language/lexer.mjs';\nimport { isSource, Source } from '../language/source.mjs';\nimport { TokenKind } from '../language/tokenKind.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 * ```graphql\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 *\n * Becomes:\n *\n * ```graphql\n * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}\n * ```\n *\n * SDL example:\n *\n * ```graphql\n * \"\"\"\n * Type description\n * \"\"\"\n * type Foo {\n * \"\"\"\n * Field description\n * \"\"\"\n * bar: String\n * }\n * ```\n *\n * Becomes:\n *\n * ```graphql\n * \"\"\"Type description\"\"\" type Foo{\"\"\"Field description\"\"\" bar:String}\n * ```\n */\n\nexport function stripIgnoredCharacters(source) {\n const sourceObj = isSource(source) ? source : new Source(source);\n const body = sourceObj.body;\n const lexer = new Lexer(sourceObj);\n let strippedBody = '';\n let wasLastAddedTokenNonPunctuator = false;\n\n while (lexer.advance().kind !== TokenKind.EOF) {\n const currentToken = lexer.token;\n const 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 const isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);\n\n if (wasLastAddedTokenNonPunctuator) {\n if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {\n strippedBody += ' ';\n }\n }\n\n const tokenBody = body.slice(currentToken.start, currentToken.end);\n\n if (tokenKind === TokenKind.BLOCK_STRING) {\n strippedBody += printBlockString(currentToken.value, {\n minimize: true,\n });\n } else {\n strippedBody += tokenBody;\n }\n\n wasLastAddedTokenNonPunctuator = isNonPunctuator;\n }\n\n return strippedBody;\n}\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { assertName } from '../type/assertName.mjs';\n/* c8 ignore start */\n\n/**\n * Upholds the spec rules about naming.\n * @deprecated Please use `assertName` instead. Will be removed in v17\n */\n\nexport function assertValidName(name) {\n const error = isValidNameError(name);\n\n if (error) {\n throw error;\n }\n\n return name;\n}\n/**\n * Returns an Error if a name is invalid.\n * @deprecated Please use `assertName` instead. Will be removed in v17\n */\n\nexport function isValidNameError(name) {\n typeof name === 'string' || devAssert(false, 'Expected name to be a string.');\n\n if (name.startsWith('__')) {\n return new GraphQLError(\n `Name \"${name}\" must not begin with \"__\", which is reserved by GraphQL introspection.`,\n );\n }\n\n try {\n assertName(name);\n } catch (error) {\n return error;\n }\n}\n/* c8 ignore stop */\n","import { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { keyMap } from '../jsutils/keyMap.mjs';\nimport { print } from '../language/printer.mjs';\nimport {\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isListType,\n isNamedType,\n isNonNullType,\n isObjectType,\n isRequiredArgument,\n isRequiredInputField,\n isScalarType,\n isUnionType,\n} from '../type/definition.mjs';\nimport { isSpecifiedScalarType } from '../type/scalars.mjs';\nimport { astFromValue } from './astFromValue.mjs';\nimport { sortValueNode } from './sortValueNode.mjs';\nvar BreakingChangeType;\n\n(function (BreakingChangeType) {\n BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED';\n BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND';\n BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION';\n BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM';\n BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] =\n 'REQUIRED_INPUT_FIELD_ADDED';\n BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] =\n 'IMPLEMENTED_INTERFACE_REMOVED';\n BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED';\n BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND';\n BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED';\n BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED';\n BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND';\n BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED';\n BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED';\n BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] =\n 'REQUIRED_DIRECTIVE_ARG_ADDED';\n BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] =\n 'DIRECTIVE_REPEATABLE_REMOVED';\n BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] =\n 'DIRECTIVE_LOCATION_REMOVED';\n})(BreakingChangeType || (BreakingChangeType = {}));\n\nexport { BreakingChangeType };\nvar DangerousChangeType;\n\n(function (DangerousChangeType) {\n DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM';\n DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION';\n DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] =\n 'OPTIONAL_INPUT_FIELD_ADDED';\n DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED';\n DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] =\n 'IMPLEMENTED_INTERFACE_ADDED';\n DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE';\n})(DangerousChangeType || (DangerousChangeType = {}));\n\nexport { DangerousChangeType };\n\n/**\n * Given two schemas, returns an Array containing descriptions of all the types\n * of breaking changes covered by the other functions down below.\n */\nexport function findBreakingChanges(oldSchema, newSchema) {\n // @ts-expect-error\n return findSchemaChanges(oldSchema, newSchema).filter(\n (change) => change.type in BreakingChangeType,\n );\n}\n/**\n * Given two schemas, returns an Array containing descriptions of all the types\n * of potentially dangerous changes covered by the other functions down below.\n */\n\nexport function findDangerousChanges(oldSchema, newSchema) {\n // @ts-expect-error\n return findSchemaChanges(oldSchema, newSchema).filter(\n (change) => change.type in DangerousChangeType,\n );\n}\n\nfunction findSchemaChanges(oldSchema, newSchema) {\n return [\n ...findTypeChanges(oldSchema, newSchema),\n ...findDirectiveChanges(oldSchema, newSchema),\n ];\n}\n\nfunction findDirectiveChanges(oldSchema, newSchema) {\n const schemaChanges = [];\n const directivesDiff = diff(\n oldSchema.getDirectives(),\n newSchema.getDirectives(),\n );\n\n for (const oldDirective of directivesDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.DIRECTIVE_REMOVED,\n description: `${oldDirective.name} was removed.`,\n });\n }\n\n for (const [oldDirective, newDirective] of directivesDiff.persisted) {\n const argsDiff = diff(oldDirective.args, newDirective.args);\n\n for (const newArg of argsDiff.added) {\n if (isRequiredArgument(newArg)) {\n schemaChanges.push({\n type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,\n description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`,\n });\n }\n }\n\n for (const oldArg of argsDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,\n description: `${oldArg.name} was removed from ${oldDirective.name}.`,\n });\n }\n\n if (oldDirective.isRepeatable && !newDirective.isRepeatable) {\n schemaChanges.push({\n type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED,\n description: `Repeatable flag was removed from ${oldDirective.name}.`,\n });\n }\n\n for (const location of oldDirective.locations) {\n if (!newDirective.locations.includes(location)) {\n schemaChanges.push({\n type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,\n description: `${location} was removed from ${oldDirective.name}.`,\n });\n }\n }\n }\n\n return schemaChanges;\n}\n\nfunction findTypeChanges(oldSchema, newSchema) {\n const schemaChanges = [];\n const typesDiff = diff(\n Object.values(oldSchema.getTypeMap()),\n Object.values(newSchema.getTypeMap()),\n );\n\n for (const oldType of typesDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: isSpecifiedScalarType(oldType)\n ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.`\n : `${oldType.name} was removed.`,\n });\n }\n\n for (const [oldType, newType] of typesDiff.persisted) {\n if (isEnumType(oldType) && isEnumType(newType)) {\n schemaChanges.push(...findEnumTypeChanges(oldType, newType));\n } else if (isUnionType(oldType) && isUnionType(newType)) {\n schemaChanges.push(...findUnionTypeChanges(oldType, newType));\n } else if (isInputObjectType(oldType) && isInputObjectType(newType)) {\n schemaChanges.push(...findInputObjectTypeChanges(oldType, newType));\n } else if (isObjectType(oldType) && isObjectType(newType)) {\n schemaChanges.push(\n ...findFieldChanges(oldType, newType),\n ...findImplementedInterfacesChanges(oldType, newType),\n );\n } else if (isInterfaceType(oldType) && isInterfaceType(newType)) {\n schemaChanges.push(\n ...findFieldChanges(oldType, newType),\n ...findImplementedInterfacesChanges(oldType, newType),\n );\n } else if (oldType.constructor !== newType.constructor) {\n schemaChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description:\n `${oldType.name} changed from ` +\n `${typeKindName(oldType)} to ${typeKindName(newType)}.`,\n });\n }\n }\n\n return schemaChanges;\n}\n\nfunction findInputObjectTypeChanges(oldType, newType) {\n const schemaChanges = [];\n const fieldsDiff = diff(\n Object.values(oldType.getFields()),\n Object.values(newType.getFields()),\n );\n\n for (const newField of fieldsDiff.added) {\n if (isRequiredInputField(newField)) {\n schemaChanges.push({\n type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,\n description: `A required field ${newField.name} on input type ${oldType.name} was added.`,\n });\n } else {\n schemaChanges.push({\n type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,\n description: `An optional field ${newField.name} on input type ${oldType.name} was added.`,\n });\n }\n }\n\n for (const oldField of fieldsDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.FIELD_REMOVED,\n description: `${oldType.name}.${oldField.name} was removed.`,\n });\n }\n\n for (const [oldField, newField] of fieldsDiff.persisted) {\n const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(\n oldField.type,\n newField.type,\n );\n\n if (!isSafe) {\n schemaChanges.push({\n type: BreakingChangeType.FIELD_CHANGED_KIND,\n description:\n `${oldType.name}.${oldField.name} changed type from ` +\n `${String(oldField.type)} to ${String(newField.type)}.`,\n });\n }\n }\n\n return schemaChanges;\n}\n\nfunction findUnionTypeChanges(oldType, newType) {\n const schemaChanges = [];\n const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes());\n\n for (const newPossibleType of possibleTypesDiff.added) {\n schemaChanges.push({\n type: DangerousChangeType.TYPE_ADDED_TO_UNION,\n description: `${newPossibleType.name} was added to union type ${oldType.name}.`,\n });\n }\n\n for (const oldPossibleType of possibleTypesDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`,\n });\n }\n\n return schemaChanges;\n}\n\nfunction findEnumTypeChanges(oldType, newType) {\n const schemaChanges = [];\n const valuesDiff = diff(oldType.getValues(), newType.getValues());\n\n for (const newValue of valuesDiff.added) {\n schemaChanges.push({\n type: DangerousChangeType.VALUE_ADDED_TO_ENUM,\n description: `${newValue.name} was added to enum type ${oldType.name}.`,\n });\n }\n\n for (const oldValue of valuesDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,\n description: `${oldValue.name} was removed from enum type ${oldType.name}.`,\n });\n }\n\n return schemaChanges;\n}\n\nfunction findImplementedInterfacesChanges(oldType, newType) {\n const schemaChanges = [];\n const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces());\n\n for (const newInterface of interfacesDiff.added) {\n schemaChanges.push({\n type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED,\n description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`,\n });\n }\n\n for (const oldInterface of interfacesDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED,\n description: `${oldType.name} no longer implements interface ${oldInterface.name}.`,\n });\n }\n\n return schemaChanges;\n}\n\nfunction findFieldChanges(oldType, newType) {\n const schemaChanges = [];\n const fieldsDiff = diff(\n Object.values(oldType.getFields()),\n Object.values(newType.getFields()),\n );\n\n for (const oldField of fieldsDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.FIELD_REMOVED,\n description: `${oldType.name}.${oldField.name} was removed.`,\n });\n }\n\n for (const [oldField, newField] of fieldsDiff.persisted) {\n schemaChanges.push(...findArgChanges(oldType, oldField, newField));\n const isSafe = isChangeSafeForObjectOrInterfaceField(\n oldField.type,\n newField.type,\n );\n\n if (!isSafe) {\n schemaChanges.push({\n type: BreakingChangeType.FIELD_CHANGED_KIND,\n description:\n `${oldType.name}.${oldField.name} changed type from ` +\n `${String(oldField.type)} to ${String(newField.type)}.`,\n });\n }\n }\n\n return schemaChanges;\n}\n\nfunction findArgChanges(oldType, oldField, newField) {\n const schemaChanges = [];\n const argsDiff = diff(oldField.args, newField.args);\n\n for (const oldArg of argsDiff.removed) {\n schemaChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`,\n });\n }\n\n for (const [oldArg, newArg] of argsDiff.persisted) {\n const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(\n oldArg.type,\n newArg.type,\n );\n\n if (!isSafe) {\n schemaChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description:\n `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` +\n `${String(oldArg.type)} to ${String(newArg.type)}.`,\n });\n } else if (oldArg.defaultValue !== undefined) {\n if (newArg.defaultValue === undefined) {\n schemaChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`,\n });\n } else {\n // Since we looking only for client's observable changes we should\n // compare default values in the same representation as they are\n // represented inside introspection.\n const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type);\n const newValueStr = stringifyValue(newArg.defaultValue, newArg.type);\n\n if (oldValueStr !== newValueStr) {\n schemaChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`,\n });\n }\n }\n }\n }\n\n for (const newArg of argsDiff.added) {\n if (isRequiredArgument(newArg)) {\n schemaChanges.push({\n type: BreakingChangeType.REQUIRED_ARG_ADDED,\n description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`,\n });\n } else {\n schemaChanges.push({\n type: DangerousChangeType.OPTIONAL_ARG_ADDED,\n description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`,\n });\n }\n }\n\n return schemaChanges;\n}\n\nfunction isChangeSafeForObjectOrInterfaceField(oldType, newType) {\n if (isListType(oldType)) {\n return (\n // if they're both lists, make sure the underlying types are compatible\n (isListType(newType) &&\n isChangeSafeForObjectOrInterfaceField(\n oldType.ofType,\n newType.ofType,\n )) || // moving from nullable to non-null of the same underlying type is safe\n (isNonNullType(newType) &&\n isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))\n );\n }\n\n if (isNonNullType(oldType)) {\n // if they're both non-null, make sure the underlying types are compatible\n return (\n isNonNullType(newType) &&\n isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType)\n );\n }\n\n return (\n // if they're both named types, see if their names are equivalent\n (isNamedType(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe\n (isNonNullType(newType) &&\n isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))\n );\n}\n\nfunction isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) {\n if (isListType(oldType)) {\n // if they're both lists, make sure the underlying types are compatible\n return (\n isListType(newType) &&\n isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType)\n );\n }\n\n if (isNonNullType(oldType)) {\n return (\n // if they're both non-null, make sure the underlying types are\n // compatible\n (isNonNullType(newType) &&\n isChangeSafeForInputObjectFieldOrFieldArg(\n oldType.ofType,\n newType.ofType,\n )) || // moving from non-null to nullable of the same underlying type is safe\n (!isNonNullType(newType) &&\n isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType))\n );\n } // if they're both named types, see if their names are equivalent\n\n return isNamedType(newType) && oldType.name === newType.name;\n}\n\nfunction typeKindName(type) {\n if (isScalarType(type)) {\n return 'a Scalar type';\n }\n\n if (isObjectType(type)) {\n return 'an Object type';\n }\n\n if (isInterfaceType(type)) {\n return 'an Interface type';\n }\n\n if (isUnionType(type)) {\n return 'a Union type';\n }\n\n if (isEnumType(type)) {\n return 'an Enum type';\n }\n\n if (isInputObjectType(type)) {\n return 'an Input type';\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible types have been considered.\n\n false || invariant(false, 'Unexpected type: ' + inspect(type));\n}\n\nfunction stringifyValue(value, type) {\n const ast = astFromValue(value, type);\n ast != null || invariant(false);\n return print(sortValueNode(ast));\n}\n\nfunction diff(oldArray, newArray) {\n const added = [];\n const removed = [];\n const persisted = [];\n const oldMap = keyMap(oldArray, ({ name }) => name);\n const newMap = keyMap(newArray, ({ name }) => name);\n\n for (const oldItem of oldArray) {\n const newItem = newMap[oldItem.name];\n\n if (newItem === undefined) {\n removed.push(oldItem);\n } else {\n persisted.push([oldItem, newItem]);\n }\n }\n\n for (const newItem of newArray) {\n if (oldMap[newItem.name] === undefined) {\n added.push(newItem);\n }\n }\n\n return {\n added,\n persisted,\n removed,\n };\n}\n","import { invariant } from \"../globals/index.js\";\nimport { visit, BREAK } from \"graphql\";\nexport function shouldInclude(_a, variables) {\n var directives = _a.directives;\n if (!directives || !directives.length) {\n return true;\n }\n return getInclusionDirectives(directives).every(function (_a) {\n var directive = _a.directive, ifArgument = _a.ifArgument;\n var evaledValue = false;\n if (ifArgument.value.kind === \"Variable\") {\n evaledValue =\n variables && variables[ifArgument.value.name.value];\n invariant(evaledValue !== void 0, 67, directive.name.value);\n }\n else {\n evaledValue = ifArgument.value.value;\n }\n return directive.name.value === \"skip\" ? !evaledValue : evaledValue;\n });\n}\nexport function getDirectiveNames(root) {\n var names = [];\n visit(root, {\n Directive: function (node) {\n names.push(node.name.value);\n },\n });\n return names;\n}\nexport var hasAnyDirectives = function (names, root) {\n return hasDirectives(names, root, false);\n};\nexport var hasAllDirectives = function (names, root) {\n return hasDirectives(names, root, true);\n};\nexport function hasDirectives(names, root, all) {\n var nameSet = new Set(names);\n var uniqueCount = nameSet.size;\n visit(root, {\n Directive: function (node) {\n if (nameSet.delete(node.name.value) && (!all || !nameSet.size)) {\n return BREAK;\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}\nexport function hasClientExports(document) {\n return document && hasDirectives([\"client\", \"export\"], document, true);\n}\nfunction isInclusionDirective(_a) {\n var value = _a.name.value;\n return value === \"skip\" || value === \"include\";\n}\nexport function getInclusionDirectives(directives) {\n var result = [];\n if (directives && directives.length) {\n directives.forEach(function (directive) {\n if (!isInclusionDirective(directive))\n return;\n var directiveArguments = directive.arguments;\n var directiveName = directive.name.value;\n invariant(directiveArguments && directiveArguments.length === 1, 68, directiveName);\n var ifArgument = directiveArguments[0];\n invariant(ifArgument.name && ifArgument.name.value === \"if\", 69, directiveName);\n var ifValue = ifArgument.value;\n // means it has to be a variable value if this is a valid @skip or @include directive\n invariant(ifValue &&\n (ifValue.kind === \"Variable\" || ifValue.kind === \"BooleanValue\"), 70, directiveName);\n result.push({ directive: directive, ifArgument: ifArgument });\n });\n }\n return result;\n}\n//# sourceMappingURL=directives.js.map","// 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// If no makeData function is supplied, the looked-up data will be an empty,\n// null-prototype Object.\nconst defaultMakeData = () => Object.create(null);\n// Useful for processing arguments objects as well as arrays.\nconst { forEach, slice } = Array.prototype;\nconst { hasOwnProperty } = Object.prototype;\nexport class Trie {\n constructor(weakness = true, makeData = defaultMakeData) {\n this.weakness = weakness;\n this.makeData = makeData;\n }\n lookup() {\n return this.lookupArray(arguments);\n }\n lookupArray(array) {\n let node = this;\n forEach.call(array, key => node = node.getChildTrie(key));\n return hasOwnProperty.call(node, \"data\")\n ? node.data\n : node.data = this.makeData(slice.call(array));\n }\n peek() {\n return this.peekArray(arguments);\n }\n peekArray(array) {\n let node = this;\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 return node && node.data;\n }\n remove() {\n return this.removeArray(arguments);\n }\n removeArray(array) {\n let data;\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 }\n else {\n data = this.data;\n delete this.data;\n }\n return data;\n }\n getChildTrie(key) {\n const map = this.mapFor(key, true);\n let child = map.get(key);\n if (!child)\n map.set(key, child = new Trie(this.weakness, this.makeData));\n return child;\n }\n mapFor(key, create) {\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}\nfunction isObjRef(value) {\n switch (typeof value) {\n case \"object\":\n if (value === null)\n break;\n // Fall through to return true...\n case \"function\":\n return true;\n }\n return false;\n}\n//# sourceMappingURL=index.js.map","// 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// If no makeData function is supplied, the looked-up data will be an empty,\n// null-prototype Object.\nconst defaultMakeData = () => Object.create(null);\n// Useful for processing arguments objects as well as arrays.\nconst { forEach, slice } = Array.prototype;\nconst { hasOwnProperty } = Object.prototype;\nexport class Trie {\n constructor(weakness = true, makeData = defaultMakeData) {\n this.weakness = weakness;\n this.makeData = makeData;\n }\n lookup(...array) {\n return this.lookupArray(array);\n }\n lookupArray(array) {\n let node = this;\n forEach.call(array, key => node = node.getChildTrie(key));\n return hasOwnProperty.call(node, \"data\")\n ? node.data\n : node.data = this.makeData(slice.call(array));\n }\n peek(...array) {\n return this.peekArray(array);\n }\n peekArray(array) {\n let node = this;\n for (let i = 0, len = array.length; node && i < len; ++i) {\n const map = this.weakness && isObjRef(array[i]) ? node.weak : node.strong;\n node = map && map.get(array[i]);\n }\n return node && node.data;\n }\n getChildTrie(key) {\n const map = this.weakness && isObjRef(key)\n ? this.weak || (this.weak = new WeakMap())\n : this.strong || (this.strong = new Map());\n let child = map.get(key);\n if (!child)\n map.set(key, child = new Trie(this.weakness, this.makeData));\n return child;\n }\n}\nfunction isObjRef(value) {\n switch (typeof value) {\n case \"object\":\n if (value === null)\n break;\n // Fall through to return true...\n case \"function\":\n return true;\n }\n return false;\n}\n//# sourceMappingURL=index.js.map","// 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 = null;\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 = {};\nlet idCounter = 1;\n// Although we can't do anything about the cost of duplicated code from\n// accidentally bundling multiple copies of the @wry/context package, we can\n// avoid creating the Slot class more than once using makeSlotClass.\nconst makeSlotClass = () => class Slot {\n constructor() {\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 this.id = [\n \"slot\",\n idCounter++,\n Date.now(),\n Math.random().toString(36).slice(2),\n ].join(\":\");\n }\n 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)\n 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 getValue() {\n if (this.hasValue()) {\n return currentContext.slots[this.id];\n }\n }\n withValue(value, callback, \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, thisArg) {\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 }\n finally {\n currentContext = parent;\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(callback) {\n const context = currentContext;\n return function () {\n const saved = currentContext;\n try {\n currentContext = context;\n return callback.apply(this, arguments);\n }\n finally {\n currentContext = saved;\n }\n };\n }\n // Immediately run a callback function without any captured context.\n static noContext(callback, \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, thisArg) {\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 }\n finally {\n currentContext = saved;\n }\n }\n else {\n return callback.apply(thisArg, args);\n }\n }\n};\nfunction maybe(fn) {\n try {\n return fn();\n }\n catch (ignored) { }\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\";\nconst host = \n// Prefer globalThis when available.\n// https://github.com/benjamn/wryware/issues/347\nmaybe(() => 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);\n// Whichever globalHost we're using, make TypeScript happy about the additional\n// globalKey property.\nconst globalHost = host;\nexport const Slot = 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[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 }\n finally {\n return Slot;\n }\n })(makeSlotClass());\n//# sourceMappingURL=slot.js.map","import { Slot } from \"@wry/context\";\nexport const parentEntrySlot = new Slot();\nexport function nonReactive(fn) {\n return parentEntrySlot.withValue(void 0, fn);\n}\nexport { Slot };\nexport { bind as bindContext, noContext, setTimeout, asyncFromGen, } from \"@wry/context\";\n//# sourceMappingURL=context.js.map","export const { hasOwnProperty, } = Object.prototype;\nexport const arrayFromSet = Array.from ||\n function (set) {\n const array = [];\n set.forEach(item => array.push(item));\n return array;\n };\nexport function maybeUnsubscribe(entryOrDep) {\n const { unsubscribe } = entryOrDep;\n if (typeof unsubscribe === \"function\") {\n entryOrDep.unsubscribe = void 0;\n unsubscribe();\n }\n}\n//# sourceMappingURL=helpers.js.map","import { parentEntrySlot } from \"./context.js\";\nimport { maybeUnsubscribe, arrayFromSet } from \"./helpers.js\";\nconst emptySetPool = [];\nconst POOL_TARGET_SIZE = 100;\n// Since this package might be used browsers, we should avoid using the\n// Node built-in assert module.\nfunction assert(condition, optionalMessage) {\n if (!condition) {\n throw new Error(optionalMessage || \"assertion failure\");\n }\n}\nfunction valueIs(a, b) {\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}\nfunction valueGet(value) {\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}\nfunction valueCopy(value) {\n return value.slice(0);\n}\nexport class Entry {\n constructor(fn) {\n this.fn = fn;\n this.parents = new Set();\n this.childValues = new Map();\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 this.dirtyChildren = null;\n this.dirty = true;\n this.recomputing = false;\n this.value = [];\n this.deps = null;\n ++Entry.count;\n }\n peek() {\n if (this.value.length === 1 && !mightBeDirty(this)) {\n rememberParent(this);\n return this.value[0];\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 recompute(args) {\n assert(!this.recomputing, \"already recomputing\");\n rememberParent(this);\n return mightBeDirty(this)\n ? reallyRecompute(this, args)\n : valueGet(this.value);\n }\n setDirty() {\n if (this.dirty)\n 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 dispose() {\n this.setDirty();\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 // 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 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 dependOn(dep) {\n dep.add(this);\n if (!this.deps) {\n this.deps = emptySetPool.pop() || new Set();\n }\n this.deps.add(dep);\n }\n 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}\nEntry.count = 0;\nfunction rememberParent(child) {\n const parent = parentEntrySlot.getValue();\n if (parent) {\n child.parents.add(parent);\n if (!parent.childValues.has(child)) {\n parent.childValues.set(child, []);\n }\n if (mightBeDirty(child)) {\n reportDirtyChild(parent, child);\n }\n else {\n reportCleanChild(parent, child);\n }\n return parent;\n }\n}\nfunction reallyRecompute(entry, args) {\n forgetChildren(entry);\n // Set entry as the parent entry while calling recomputeNewValue(entry).\n parentEntrySlot.withValue(entry, recomputeNewValue, [entry, args]);\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 return valueGet(entry.value);\n}\nfunction recomputeNewValue(entry, args) {\n entry.recomputing = true;\n const { normalizeResult } = entry;\n let oldValueCopy;\n if (normalizeResult && entry.value.length === 1) {\n oldValueCopy = valueCopy(entry.value);\n }\n // Make entry.value an empty array, representing an unknown value.\n entry.value.length = 0;\n try {\n // If entry.fn succeeds, entry.value will become a normal Value.\n entry.value[0] = entry.fn.apply(null, args);\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 }\n catch (_a) {\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 // Either way, this line is always reached.\n entry.recomputing = false;\n}\nfunction mightBeDirty(entry) {\n return entry.dirty || !!(entry.dirtyChildren && entry.dirtyChildren.size);\n}\nfunction setClean(entry) {\n entry.dirty = false;\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 reportClean(entry);\n}\nfunction reportDirty(child) {\n eachParent(child, reportDirtyChild);\n}\nfunction reportClean(child) {\n eachParent(child, reportCleanChild);\n}\nfunction eachParent(child, callback) {\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// Let a parent Entry know that one of its children may be dirty.\nfunction reportDirtyChild(parent, child) {\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 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 parent.dirtyChildren.add(child);\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// Let a parent Entry know that one of its children is no longer dirty.\nfunction reportCleanChild(parent, child) {\n // Must have called rememberChild(child) before calling\n // reportCleanChild(parent, child).\n assert(parent.childValues.has(child));\n assert(!mightBeDirty(child));\n const childValue = parent.childValues.get(child);\n if (childValue.length === 0) {\n parent.childValues.set(child, valueCopy(child.value));\n }\n else if (!valueIs(childValue, child.value)) {\n parent.setDirty();\n }\n removeDirtyChild(parent, child);\n if (mightBeDirty(parent)) {\n return;\n }\n reportClean(parent);\n}\nfunction removeDirtyChild(parent, child) {\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// Removes all children from this entry and returns an array of the\n// removed children.\nfunction forgetChildren(parent) {\n if (parent.childValues.size > 0) {\n parent.childValues.forEach((_value, child) => {\n forgetChild(parent, child);\n });\n }\n // Remove this parent Entry from any sets to which it was added by the\n // addToSet method.\n parent.forgetDeps();\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}\nfunction forgetChild(parent, child) {\n child.parents.delete(parent);\n parent.childValues.delete(child);\n removeDirtyChild(parent, child);\n}\nfunction maybeSubscribe(entry, args) {\n if (typeof entry.subscribe === \"function\") {\n try {\n maybeUnsubscribe(entry); // Prevent double subscriptions.\n entry.unsubscribe = entry.subscribe.apply(null, args);\n }\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 // Returning true indicates either that there was no entry.subscribe\n // function or that it succeeded.\n return true;\n}\n//# sourceMappingURL=entry.js.map","import { parentEntrySlot } from \"./context.js\";\nimport { hasOwnProperty, maybeUnsubscribe, arrayFromSet, } from \"./helpers.js\";\nconst EntryMethods = {\n setDirty: true,\n dispose: true,\n forget: true, // Fully remove parent Entry from LRU cache and computation graph\n};\nexport function dep(options) {\n const depsByKey = new Map();\n const subscribe = options && options.subscribe;\n function depend(key) {\n const parent = parentEntrySlot.getValue();\n if (parent) {\n let dep = depsByKey.get(key);\n if (!dep) {\n depsByKey.set(key, dep = new Set);\n }\n parent.dependOn(dep);\n if (typeof subscribe === \"function\") {\n maybeUnsubscribe(dep);\n dep.unsubscribe = subscribe(key);\n }\n }\n }\n depend.dirty = function dirty(key, entryMethodName) {\n const dep = depsByKey.get(key);\n if (dep) {\n const m = (entryMethodName &&\n hasOwnProperty.call(EntryMethods, entryMethodName)) ? 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 return depend;\n}\n//# sourceMappingURL=dep.js.map","import { Trie } from \"@wry/trie\";\nimport { StrongCache } from \"@wry/caches\";\nimport { Entry } from \"./entry.js\";\nimport { parentEntrySlot } from \"./context.js\";\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 { bindContext, noContext, nonReactive, setTimeout, asyncFromGen, Slot, } from \"./context.js\";\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 } from \"./dep.js\";\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;\nexport function defaultMakeCacheKey(...args) {\n const trie = defaultKeyTrie || (defaultKeyTrie = new Trie(typeof WeakMap === \"function\"));\n return trie.lookupArray(args);\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;\nconst caches = new Set();\nexport function wrap(originalFunction, { max = Math.pow(2, 16), keyArgs, makeCacheKey = defaultMakeCacheKey, normalizeResult, subscribe, cache: cacheOption = StrongCache, } = Object.create(null)) {\n const cache = typeof cacheOption === \"function\"\n ? new cacheOption(max, entry => entry.dispose())\n : cacheOption;\n const optimistic = function () {\n const key = makeCacheKey.apply(null, keyArgs ? keyArgs.apply(null, arguments) : arguments);\n if (key === void 0) {\n return originalFunction.apply(null, arguments);\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 const value = entry.recompute(Array.prototype.slice.call(arguments));\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 caches.add(cache);\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 return value;\n };\n Object.defineProperty(optimistic, \"size\", {\n get: () => cache.size,\n configurable: false,\n enumerable: false,\n });\n Object.freeze(optimistic.options = {\n max,\n keyArgs,\n makeCacheKey,\n normalizeResult,\n subscribe,\n cache,\n });\n function dirtyKey(key) {\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));\n };\n function peekKey(key) {\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));\n };\n function forgetKey(key) {\n return key ? cache.delete(key) : false;\n }\n optimistic.forgetKey = forgetKey;\n optimistic.forget = function forget() {\n return forgetKey(makeCacheKey.apply(null, arguments));\n };\n optimistic.makeCacheKey = makeCacheKey;\n optimistic.getKey = keyArgs ? function getKey() {\n return makeCacheKey.apply(null, keyArgs.apply(null, arguments));\n } : makeCacheKey;\n return Object.freeze(optimistic);\n}\n//# sourceMappingURL=index.js.map","import { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet } from \"../common/canUse.js\";\nimport { checkDocument } from \"./getFromAST.js\";\nimport { invariant } from \"../globals/index.js\";\nimport { WeakCache } from \"@wry/caches\";\nimport { wrap } from \"optimism\";\nimport { cacheSizes } from \"../caching/index.js\";\nfunction identity(document) {\n return document;\n}\nvar DocumentTransform = /** @class */ (function () {\n function DocumentTransform(transform, options) {\n if (options === void 0) { options = Object.create(null); }\n this.resultCache = canUseWeakSet ? new WeakSet() : new Set();\n this.transform = transform;\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 this.resetCache();\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 DocumentTransform.prototype.getCacheKey = function (document) {\n return [document];\n };\n DocumentTransform.identity = function () {\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 DocumentTransform.split = function (predicate, left, right) {\n if (right === void 0) { right = DocumentTransform.identity(); }\n return Object.assign(new DocumentTransform(function (document) {\n var documentTransform = predicate(document) ? left : right;\n return documentTransform.transformDocument(document);\n }, \n // Reasonably assume both `left` and `right` transforms handle their own caching\n { cache: false }), { left: left, right: right });\n };\n /**\n * Resets the internal cache of this transform, if it has one.\n */\n DocumentTransform.prototype.resetCache = function () {\n var _this = this;\n if (this.cached) {\n var stableCacheKeys_1 = new Trie(canUseWeakMap);\n this.performWork = wrap(DocumentTransform.prototype.performWork.bind(this), {\n makeCacheKey: function (document) {\n var cacheKeys = _this.getCacheKey(document);\n if (cacheKeys) {\n invariant(Array.isArray(cacheKeys), 66);\n return stableCacheKeys_1.lookupArray(cacheKeys);\n }\n },\n max: cacheSizes[\"documentTransform.cache\"],\n cache: (WeakCache),\n });\n }\n };\n DocumentTransform.prototype.performWork = function (document) {\n checkDocument(document);\n return this.transform(document);\n };\n DocumentTransform.prototype.transformDocument = function (document) {\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 var transformedDocument = this.performWork(document);\n this.resultCache.add(transformedDocument);\n return transformedDocument;\n };\n DocumentTransform.prototype.concat = function (otherTransform) {\n var _this = this;\n return Object.assign(new DocumentTransform(function (document) {\n return otherTransform.transformDocument(_this.transformDocument(document));\n }, \n // Reasonably assume both transforms handle their own caching\n { cache: false }), {\n left: this,\n right: otherTransform,\n });\n };\n return DocumentTransform;\n}());\nexport { DocumentTransform };\n//# sourceMappingURL=DocumentTransform.js.map","import { print as origPrint } from \"graphql\";\nimport { AutoCleanedWeakCache, cacheSizes, } from \"../caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\nvar printCache;\nexport var print = Object.assign(function (ast) {\n var result = printCache.get(ast);\n if (!result) {\n result = origPrint(ast);\n printCache.set(ast, result);\n }\n return result;\n}, {\n reset: function () {\n printCache = new AutoCleanedWeakCache(cacheSizes.print || 2000 /* defaultCacheSizes.print */);\n },\n});\nprint.reset();\nif (globalThis.__DEV__ !== false) {\n registerGlobalCache(\"print\", function () { return (printCache ? printCache.size : 0); });\n}\n//# sourceMappingURL=print.js.map","// A version of Array.isArray that works better with readonly arrays.\nexport var isArray = Array.isArray;\nexport function isNonEmptyArray(value) {\n return Array.isArray(value) && value.length > 0;\n}\n//# sourceMappingURL=arrays.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { invariant } from \"../globals/index.js\";\nimport { visit, Kind } from \"graphql\";\nimport { checkDocument, getOperationDefinition, getFragmentDefinition, getFragmentDefinitions, getMainDefinition, } from \"./getFromAST.js\";\nimport { isField } from \"./storeUtils.js\";\nimport { createFragmentMap } from \"./fragments.js\";\nimport { isArray, isNonEmptyArray } from \"../common/arrays.js\";\nvar TYPENAME_FIELD = {\n kind: Kind.FIELD,\n name: {\n kind: Kind.NAME,\n value: \"__typename\",\n },\n};\nfunction isEmpty(op, fragmentMap) {\n return (!op ||\n op.selectionSet.selections.every(function (selection) {\n return selection.kind === Kind.FRAGMENT_SPREAD &&\n isEmpty(fragmentMap[selection.name.value], fragmentMap);\n }));\n}\nfunction nullIfDocIsEmpty(doc) {\n return (isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))) ?\n null\n : doc;\n}\nfunction getDirectiveMatcher(configs) {\n var names = new Map();\n var tests = new Map();\n configs.forEach(function (directive) {\n if (directive) {\n if (directive.name) {\n names.set(directive.name, directive);\n }\n else if (directive.test) {\n tests.set(directive.test, directive);\n }\n }\n });\n return function (directive) {\n var config = names.get(directive.name.value);\n if (!config && tests.size) {\n tests.forEach(function (testConfig, test) {\n if (test(directive)) {\n config = testConfig;\n }\n });\n }\n return config;\n };\n}\nfunction makeInUseGetterFunction(defaultKey) {\n var map = new Map();\n return function inUseGetterFunction(key) {\n if (key === void 0) { key = defaultKey; }\n var inUse = map.get(key);\n if (!inUse) {\n map.set(key, (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 return inUse;\n };\n}\nexport function removeDirectivesFromDocument(directives, doc) {\n checkDocument(doc);\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 var getInUseByOperationName = makeInUseGetterFunction(\"\");\n var getInUseByFragmentName = makeInUseGetterFunction(\"\");\n var getInUse = function (ancestors) {\n for (var p = 0, ancestor = void 0; p < ancestors.length && (ancestor = ancestors[p]); ++p) {\n if (isArray(ancestor))\n 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 globalThis.__DEV__ !== false && invariant.error(83);\n return null;\n };\n var operationCount = 0;\n for (var i = doc.definitions.length - 1; i >= 0; --i) {\n if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {\n ++operationCount;\n }\n }\n var directiveMatcher = getDirectiveMatcher(directives);\n var shouldRemoveField = function (nodeDirectives) {\n return isNonEmptyArray(nodeDirectives) &&\n nodeDirectives\n .map(directiveMatcher)\n .some(function (config) { return config && config.remove; });\n };\n var originalFragmentDefsByPath = new Map();\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 var firstVisitMadeChanges = false;\n var fieldOrInlineFragmentVisitor = {\n enter: function (node) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n },\n };\n var docWithoutDirectiveSubtrees = visit(doc, {\n // These two AST node types share the same implementation, defined above.\n Field: fieldOrInlineFragmentVisitor,\n InlineFragment: fieldOrInlineFragmentVisitor,\n VariableDefinition: {\n enter: function () {\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 Variable: {\n enter: function (node, _key, _parent, _path, ancestors) {\n var inUse = getInUse(ancestors);\n if (inUse) {\n inUse.variables.add(node.name.value);\n }\n },\n },\n FragmentSpread: {\n enter: function (node, _key, _parent, _path, ancestors) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n var 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 FragmentDefinition: {\n enter: function (node, _key, _parent, path) {\n originalFragmentDefsByPath.set(JSON.stringify(path), node);\n },\n leave: function (node, _key, _parent, path) {\n var originalNode = originalFragmentDefsByPath.get(JSON.stringify(path));\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 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(function (selection) {\n return selection.kind === Kind.FIELD &&\n selection.name.value === \"__typename\";\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 Directive: {\n leave: function (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 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 // 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 var populateTransitiveVars = function (inUse) {\n if (!inUse.transitiveVars) {\n inUse.transitiveVars = new Set(inUse.variables);\n if (!inUse.removed) {\n inUse.fragmentSpreads.forEach(function (childFragmentName) {\n populateTransitiveVars(getInUseByFragmentName(childFragmentName)).transitiveVars.forEach(function (varName) {\n inUse.transitiveVars.add(varName);\n });\n });\n }\n }\n return inUse;\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 var allFragmentNamesUsed = new Set();\n docWithoutDirectiveSubtrees.definitions.forEach(function (def) {\n if (def.kind === Kind.OPERATION_DEFINITION) {\n populateTransitiveVars(getInUseByOperationName(def.name && def.name.value)).fragmentSpreads.forEach(function (childFragmentName) {\n allFragmentNamesUsed.add(childFragmentName);\n });\n }\n else if (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 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(function (fragmentName) {\n // Once all the childFragmentName strings added here have been seen already,\n // the top-level allFragmentNamesUsed.forEach loop will terminate.\n populateTransitiveVars(getInUseByFragmentName(fragmentName)).fragmentSpreads.forEach(function (childFragmentName) {\n allFragmentNamesUsed.add(childFragmentName);\n });\n });\n var fragmentWillBeRemoved = function (fragmentName) {\n return !!(\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 (!allFragmentNamesUsed.has(fragmentName) ||\n getInUseByFragmentName(fragmentName).removed));\n };\n var enterVisitor = {\n enter: function (node) {\n if (fragmentWillBeRemoved(node.name.value)) {\n return null;\n }\n },\n };\n return nullIfDocIsEmpty(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 // This is where the fragment definition is actually removed.\n FragmentDefinition: enterVisitor,\n OperationDefinition: {\n leave: function (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 var usedVariableNames_1 = populateTransitiveVars(\n // If an operation is anonymous, we use the empty string as its key.\n getInUseByOperationName(node.name && node.name.value)).transitiveVars;\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_1.size < node.variableDefinitions.length) {\n return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions.filter(function (varDef) {\n return usedVariableNames_1.has(varDef.variable.name.value);\n }) });\n }\n }\n },\n },\n }));\n}\nexport var addTypenameToDocument = Object.assign(function (doc) {\n return visit(doc, {\n SelectionSet: {\n enter: function (node, _key, parent) {\n // Don't add __typename to OperationDefinitions.\n if (parent &&\n parent.kind ===\n Kind.OPERATION_DEFINITION) {\n return;\n }\n // No changes if no selections.\n var selections = node.selections;\n if (!selections) {\n return;\n }\n // If selections already have a __typename, or are part of an\n // introspection query, do nothing.\n var skip = selections.some(function (selection) {\n return (isField(selection) &&\n (selection.name.value === \"__typename\" ||\n selection.name.value.lastIndexOf(\"__\", 0) === 0));\n });\n if (skip) {\n return;\n }\n // If this SelectionSet is @export-ed as an input variable, it should\n // not have a __typename field (see issue #4691).\n var field = parent;\n if (isField(field) &&\n field.directives &&\n field.directives.some(function (d) { return d.name.value === \"export\"; })) {\n return;\n }\n // Create and return a new SelectionSet with a __typename Field.\n return __assign(__assign({}, node), { selections: __spreadArray(__spreadArray([], selections, true), [TYPENAME_FIELD], false) });\n },\n },\n });\n}, {\n added: function (field) {\n return field === TYPENAME_FIELD;\n },\n});\nvar connectionRemoveConfig = {\n test: function (directive) {\n var willRemove = directive.name.value === \"connection\";\n if (willRemove) {\n if (!directive.arguments ||\n !directive.arguments.some(function (arg) { return arg.name.value === \"key\"; })) {\n globalThis.__DEV__ !== false && invariant.warn(84);\n }\n }\n return willRemove;\n },\n};\nexport function removeConnectionDirectiveFromDocument(doc) {\n return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));\n}\nfunction hasDirectivesInSelectionSet(directives, selectionSet, nestedCheck) {\n if (nestedCheck === void 0) { nestedCheck = true; }\n return (!!selectionSet &&\n selectionSet.selections &&\n selectionSet.selections.some(function (selection) {\n return hasDirectivesInSelection(directives, selection, nestedCheck);\n }));\n}\nfunction hasDirectivesInSelection(directives, selection, nestedCheck) {\n if (nestedCheck === void 0) { nestedCheck = true; }\n if (!isField(selection)) {\n return true;\n }\n if (!selection.directives) {\n return false;\n }\n return (selection.directives.some(getDirectiveMatcher(directives)) ||\n (nestedCheck &&\n hasDirectivesInSelectionSet(directives, selection.selectionSet, nestedCheck)));\n}\nfunction getArgumentMatcher(config) {\n return function argumentMatcher(argument) {\n return config.some(function (aConfig) {\n return 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}\nexport function removeArgumentsFromDocument(config, doc) {\n var argMatcher = getArgumentMatcher(config);\n return nullIfDocIsEmpty(visit(doc, {\n OperationDefinition: {\n enter: function (node) {\n return __assign(__assign({}, node), { \n // Remove matching top level variables definitions.\n variableDefinitions: node.variableDefinitions ?\n node.variableDefinitions.filter(function (varDef) {\n return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });\n })\n : [] });\n },\n },\n Field: {\n enter: function (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 var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });\n if (shouldRemoveField) {\n var argMatchCount_1 = 0;\n if (node.arguments) {\n node.arguments.forEach(function (arg) {\n if (argMatcher(arg)) {\n argMatchCount_1 += 1;\n }\n });\n }\n if (argMatchCount_1 === 1) {\n return null;\n }\n }\n },\n },\n Argument: {\n enter: function (node) {\n // Remove all matching arguments.\n if (argMatcher(node)) {\n return null;\n }\n },\n },\n }));\n}\nexport function removeFragmentSpreadFromDocument(config, doc) {\n function enter(node) {\n if (config.some(function (def) { return def.name === node.name.value; })) {\n return null;\n }\n }\n return nullIfDocIsEmpty(visit(doc, {\n FragmentSpread: { enter: enter },\n FragmentDefinition: { enter: enter },\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(document) {\n var definition = getMainDefinition(document);\n var definitionOperation = definition.operation;\n if (definitionOperation === \"query\") {\n // Already a query, so return the existing document.\n return document;\n }\n // Build a new query using the selection set of the main operation.\n var modifiedDoc = visit(document, {\n OperationDefinition: {\n enter: function (node) {\n return __assign(__assign({}, node), { operation: \"query\" });\n },\n },\n });\n return modifiedDoc;\n}\n// Remove fields / selection sets that include an @client directive.\nexport function removeClientSetsFromDocument(document) {\n checkDocument(document);\n var modifiedDoc = removeDirectivesFromDocument([\n {\n test: function (directive) { return directive.name.value === \"client\"; },\n remove: true,\n },\n ], document);\n return modifiedDoc;\n}\n//# sourceMappingURL=transform.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { isNonNullObject } from \"./objects.js\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function mergeDeep() {\n var sources = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n sources[_i] = arguments[_i];\n }\n return mergeDeepArray(sources);\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(sources) {\n var target = sources[0] || {};\n var count = sources.length;\n if (count > 1) {\n var merger = new DeepMerger();\n for (var i = 1; i < count; ++i) {\n target = merger.merge(target, sources[i]);\n }\n }\n return target;\n}\nvar defaultReconciler = function (target, source, property) {\n return this.merge(target[property], source[property]);\n};\nvar DeepMerger = /** @class */ (function () {\n function DeepMerger(reconciler) {\n if (reconciler === void 0) { reconciler = defaultReconciler; }\n this.reconciler = reconciler;\n this.isObject = isNonNullObject;\n this.pastCopies = new Set();\n }\n DeepMerger.prototype.merge = function (target, source) {\n var _this = this;\n var context = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n context[_i - 2] = arguments[_i];\n }\n if (isNonNullObject(source) && isNonNullObject(target)) {\n Object.keys(source).forEach(function (sourceKey) {\n if (hasOwnProperty.call(target, sourceKey)) {\n var targetValue = target[sourceKey];\n if (source[sourceKey] !== targetValue) {\n var result = _this.reconciler.apply(_this, __spreadArray([target,\n source,\n sourceKey], context, false));\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 }\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 return target;\n }\n // If source (or target) is not an object, let source replace target.\n return source;\n };\n DeepMerger.prototype.shallowCopyForMerge = function (value) {\n if (isNonNullObject(value)) {\n if (!this.pastCopies.has(value)) {\n if (Array.isArray(value)) {\n value = value.slice(0);\n }\n else {\n value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);\n }\n this.pastCopies.add(value);\n }\n }\n return value;\n };\n return DeepMerger;\n}());\nexport { DeepMerger };\n//# sourceMappingURL=mergeDeep.js.map","import { __assign, __rest as __rest_1, __spreadArray } from \"tslib\";\nimport { __rest } from \"tslib\";\nimport { mergeDeep } from \"../common/mergeDeep.js\";\n// A very basic pagination field policy that always concatenates new\n// results onto the existing array, without examining options.args.\nexport function concatPagination(keyArgs) {\n if (keyArgs === void 0) { keyArgs = false; }\n return {\n keyArgs: keyArgs,\n merge: function (existing, incoming) {\n return existing ? __spreadArray(__spreadArray([], existing, true), incoming, true) : incoming;\n },\n };\n}\n// A basic field policy that uses options.args.{offset,limit} to splice\n// the incoming data into the existing array. If your arguments are called\n// something different (like args.{start,count}), feel free to copy/paste\n// this implementation and make the appropriate changes.\nexport function offsetLimitPagination(keyArgs) {\n if (keyArgs === void 0) { keyArgs = false; }\n return {\n keyArgs: keyArgs,\n merge: function (existing, incoming, _a) {\n var args = _a.args;\n var merged = existing ? existing.slice(0) : [];\n if (incoming) {\n if (args) {\n // Assume an offset of 0 if args.offset omitted.\n var _b = args.offset, offset = _b === void 0 ? 0 : _b;\n for (var i = 0; i < incoming.length; ++i) {\n merged[offset + i] = incoming[i];\n }\n }\n else {\n // It's unusual (probably a mistake) for a paginated field not\n // to receive any arguments, so you might prefer to throw an\n // exception here, instead of recovering by appending incoming\n // onto the existing array.\n merged.push.apply(merged, incoming);\n }\n }\n return merged;\n },\n };\n}\n// As proof of the flexibility of field policies, this function generates\n// one that handles Relay-style pagination, without Apollo Client knowing\n// anything about connections, edges, cursors, or pageInfo objects.\nexport function relayStylePagination(keyArgs) {\n if (keyArgs === void 0) { keyArgs = false; }\n return {\n keyArgs: keyArgs,\n read: function (existing, _a) {\n var canRead = _a.canRead, readField = _a.readField;\n if (!existing)\n return existing;\n var edges = [];\n var firstEdgeCursor = \"\";\n var lastEdgeCursor = \"\";\n existing.edges.forEach(function (edge) {\n // Edges themselves could be Reference objects, so it's important\n // to use readField to access the edge.edge.node property.\n if (canRead(readField(\"node\", edge))) {\n edges.push(edge);\n if (edge.cursor) {\n firstEdgeCursor = firstEdgeCursor || edge.cursor || \"\";\n lastEdgeCursor = edge.cursor || lastEdgeCursor;\n }\n }\n });\n if (edges.length > 1 && firstEdgeCursor === lastEdgeCursor) {\n firstEdgeCursor = \"\";\n }\n var _b = existing.pageInfo || {}, startCursor = _b.startCursor, endCursor = _b.endCursor;\n return __assign(__assign({}, getExtras(existing)), { edges: edges, pageInfo: __assign(__assign({}, existing.pageInfo), { \n // If existing.pageInfo.{start,end}Cursor are undefined or \"\", default\n // to firstEdgeCursor and/or lastEdgeCursor.\n startCursor: startCursor || firstEdgeCursor, endCursor: endCursor || lastEdgeCursor }) });\n },\n merge: function (existing, incoming, _a) {\n var args = _a.args, isReference = _a.isReference, readField = _a.readField;\n if (!existing) {\n existing = makeEmptyData();\n }\n if (!incoming) {\n return existing;\n }\n var incomingEdges = incoming.edges ?\n incoming.edges.map(function (edge) {\n if (isReference((edge = __assign({}, edge)))) {\n // In case edge is a Reference, we read out its cursor field and\n // store it as an extra property of the Reference object.\n edge.cursor = readField(\"cursor\", edge);\n }\n return edge;\n })\n : [];\n if (incoming.pageInfo) {\n var pageInfo_1 = incoming.pageInfo;\n var startCursor = pageInfo_1.startCursor, endCursor = pageInfo_1.endCursor;\n var firstEdge = incomingEdges[0];\n var lastEdge = incomingEdges[incomingEdges.length - 1];\n // In case we did not request the cursor field for edges in this\n // query, we can still infer cursors from pageInfo.\n if (firstEdge && startCursor) {\n firstEdge.cursor = startCursor;\n }\n if (lastEdge && endCursor) {\n lastEdge.cursor = endCursor;\n }\n // Cursors can also come from edges, so we default\n // pageInfo.{start,end}Cursor to {first,last}Edge.cursor.\n var firstCursor = firstEdge && firstEdge.cursor;\n if (firstCursor && !startCursor) {\n incoming = mergeDeep(incoming, {\n pageInfo: {\n startCursor: firstCursor,\n },\n });\n }\n var lastCursor = lastEdge && lastEdge.cursor;\n if (lastCursor && !endCursor) {\n incoming = mergeDeep(incoming, {\n pageInfo: {\n endCursor: lastCursor,\n },\n });\n }\n }\n var prefix = existing.edges;\n var suffix = [];\n if (args && args.after) {\n // This comparison does not need to use readField(\"cursor\", edge),\n // because we stored the cursor field of any Reference edges as an\n // extra property of the Reference object.\n var index = prefix.findIndex(function (edge) { return edge.cursor === args.after; });\n if (index >= 0) {\n prefix = prefix.slice(0, index + 1);\n // suffix = []; // already true\n }\n }\n else if (args && args.before) {\n var index = prefix.findIndex(function (edge) { return edge.cursor === args.before; });\n suffix = index < 0 ? prefix : prefix.slice(index);\n prefix = [];\n }\n else if (incoming.edges) {\n // If we have neither args.after nor args.before, the incoming\n // edges cannot be spliced into the existing edges, so they must\n // replace the existing edges. See #6592 for a motivating example.\n prefix = [];\n }\n var edges = __spreadArray(__spreadArray(__spreadArray([], prefix, true), incomingEdges, true), suffix, true);\n var pageInfo = __assign(__assign({}, incoming.pageInfo), existing.pageInfo);\n if (incoming.pageInfo) {\n var _b = incoming.pageInfo, hasPreviousPage = _b.hasPreviousPage, hasNextPage = _b.hasNextPage, startCursor = _b.startCursor, endCursor = _b.endCursor, extras = __rest_1(_b, [\"hasPreviousPage\", \"hasNextPage\", \"startCursor\", \"endCursor\"]);\n // If incoming.pageInfo had any extra non-standard properties,\n // assume they should take precedence over any existing properties\n // of the same name, regardless of where this page falls with\n // respect to the existing data.\n Object.assign(pageInfo, extras);\n // Keep existing.pageInfo.has{Previous,Next}Page unless the\n // placement of the incoming edges means incoming.hasPreviousPage\n // or incoming.hasNextPage should become the new values for those\n // properties in existing.pageInfo. Note that these updates are\n // only permitted when the beginning or end of the incoming page\n // coincides with the beginning or end of the existing data, as\n // determined using prefix.length and suffix.length.\n if (!prefix.length) {\n if (void 0 !== hasPreviousPage)\n pageInfo.hasPreviousPage = hasPreviousPage;\n if (void 0 !== startCursor)\n pageInfo.startCursor = startCursor;\n }\n if (!suffix.length) {\n if (void 0 !== hasNextPage)\n pageInfo.hasNextPage = hasNextPage;\n if (void 0 !== endCursor)\n pageInfo.endCursor = endCursor;\n }\n }\n return __assign(__assign(__assign({}, getExtras(existing)), getExtras(incoming)), { edges: edges, pageInfo: pageInfo });\n },\n };\n}\n// Returns any unrecognized properties of the given object.\nvar getExtras = function (obj) { return __rest(obj, notExtras); };\nvar notExtras = [\"edges\", \"pageInfo\"];\nfunction makeEmptyData() {\n return {\n edges: [],\n pageInfo: {\n hasPreviousPage: false,\n hasNextPage: true,\n startCursor: \"\",\n endCursor: \"\",\n },\n };\n}\n//# sourceMappingURL=pagination.js.map","var toString = Object.prototype.toString;\n/**\n * Deeply clones a value to create a new instance.\n */\nexport function cloneDeep(value) {\n return cloneDeepHelper(value);\n}\nfunction cloneDeepHelper(val, seen) {\n switch (toString.call(val)) {\n case \"[object Array]\": {\n seen = seen || new Map();\n if (seen.has(val))\n return seen.get(val);\n var copy_1 = val.slice(0);\n seen.set(val, copy_1);\n copy_1.forEach(function (child, i) {\n copy_1[i] = cloneDeepHelper(child, seen);\n });\n return copy_1;\n }\n case \"[object Object]\": {\n seen = seen || new Map();\n if (seen.has(val))\n 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 var copy_2 = Object.create(Object.getPrototypeOf(val));\n seen.set(val, copy_2);\n Object.keys(val).forEach(function (key) {\n copy_2[key] = cloneDeepHelper(val[key], seen);\n });\n return copy_2;\n }\n default:\n return val;\n }\n}\n//# sourceMappingURL=cloneDeep.js.map","import { isNonNullObject } from \"./objects.js\";\nfunction deepFreeze(value) {\n var workSet = new Set([value]);\n workSet.forEach(function (obj) {\n if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {\n Object.getOwnPropertyNames(obj).forEach(function (name) {\n if (isNonNullObject(obj[name]))\n workSet.add(obj[name]);\n });\n }\n });\n return value;\n}\nfunction shallowFreeze(obj) {\n if (globalThis.__DEV__ !== false && !Object.isFrozen(obj)) {\n try {\n Object.freeze(obj);\n }\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)\n return null;\n throw e;\n }\n }\n return obj;\n}\nexport function maybeDeepFreeze(obj) {\n if (globalThis.__DEV__ !== false) {\n deepFreeze(obj);\n }\n return obj;\n}\n//# sourceMappingURL=maybeDeepFreeze.js.map","export function iterateObserversSafely(observers, method, argument) {\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 var observersWithMethod = [];\n observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });\n observersWithMethod.forEach(function (obs) { return obs[method](argument); });\n}\n//# sourceMappingURL=iteration.js.map","import { Observable } from \"./Observable.js\";\n// Like Observable.prototype.map, except that the mapping function can\n// optionally return a Promise (or be async).\nexport function asyncMap(observable, mapFn, catchFn) {\n return new Observable(function (observer) {\n var 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: function (callback) {\n return new Promise(function (resolve) { return resolve(callback()); });\n },\n };\n function makeCallback(examiner, key) {\n return function (arg) {\n if (examiner) {\n var both = function () {\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 return observer.closed ?\n /* will be swallowed */ 0\n : examiner(arg);\n };\n promiseQueue = promiseQueue.then(both, both).then(function (result) { return observer.next(result); }, function (error) { return observer.error(error); });\n }\n else {\n observer[key](arg);\n }\n };\n }\n var handler = {\n next: makeCallback(mapFn, \"next\"),\n error: makeCallback(catchFn, \"error\"),\n complete: function () {\n // no need to reassign `promiseQueue`, after `observer.complete`,\n // the observer will be closed and short-circuit everything anyways\n /*promiseQueue = */ promiseQueue.then(function () { return observer.complete(); });\n },\n };\n var sub = observable.subscribe(handler);\n return function () { return sub.unsubscribe(); };\n });\n}\n//# sourceMappingURL=asyncMap.js.map","import { Observable } from \"./Observable.js\";\nimport { canUseSymbol } from \"../common/canUse.js\";\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(subclass) {\n function set(key) {\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//# sourceMappingURL=subclassing.js.map","import { __extends } from \"tslib\";\nimport { Observable } from \"./Observable.js\";\nimport { iterateObserversSafely } from \"./iteration.js\";\nimport { fixObservableSubclass } from \"./subclassing.js\";\nfunction isPromiseLike(value) {\n return value && typeof value.then === \"function\";\n}\n// A Concast observable concatenates the given sources into a single\n// non-overlapping sequence of Ts, automatically unwrapping any promises,\n// and broadcasts the T elements of that sequence to any number of\n// subscribers, all without creating a bunch of intermediary Observable\n// wrapper objects.\n//\n// Even though any number of observers can subscribe to the Concast, each\n// source observable is guaranteed to receive at most one subscribe call,\n// and the results are multicast to all observers.\n//\n// In addition to broadcasting every next/error message to this.observers,\n// the Concast stores the most recent message using this.latest, so any\n// new observers can immediately receive the latest message, even if it\n// was originally delivered in the past. This behavior means we can assume\n// every active observer in this.observers has received the same most\n// recent message.\n//\n// With the exception of this.latest replay, a Concast is a \"hot\"\n// observable in the sense that it does not replay past results from the\n// beginning of time for each new observer.\n//\n// Could we have used some existing RxJS class instead? Concast is\n// similar to a BehaviorSubject, because it is multicast and redelivers\n// the latest next/error message to new subscribers. Unlike Subject,\n// Concast does not expose an Observer interface (this.handlers is\n// intentionally private), since Concast gets its inputs from the\n// concatenated sources. If we ever switch to RxJS, there may be some\n// value in reusing their code, but for now we use zen-observable, which\n// does not contain any Subject implementations.\nvar Concast = /** @class */ (function (_super) {\n __extends(Concast, _super);\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 function Concast(sources) {\n var _this = _super.call(this, function (observer) {\n _this.addObserver(observer);\n return function () { return _this.removeObserver(observer); };\n }) || this;\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 _this.observers = new Set();\n _this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n // Bound handler functions that can be reused for every internal\n // subscription.\n _this.handlers = {\n next: function (result) {\n if (_this.sub !== null) {\n _this.latest = [\"next\", result];\n _this.notify(\"next\", result);\n iterateObserversSafely(_this.observers, \"next\", result);\n }\n },\n error: function (error) {\n var sub = _this.sub;\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)\n setTimeout(function () { return 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 complete: function () {\n var _a = _this, sub = _a.sub, _b = _a.sources, sources = _b === void 0 ? [] : _b;\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 var value = sources.shift();\n if (!value) {\n if (sub)\n setTimeout(function () { return sub.unsubscribe(); });\n _this.sub = null;\n if (_this.latest && _this.latest[0] === \"next\") {\n _this.resolve(_this.latest[1]);\n }\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 }\n else if (isPromiseLike(value)) {\n value.then(function (obs) { return (_this.sub = obs.subscribe(_this.handlers)); }, _this.handlers.error);\n }\n else {\n _this.sub = value.subscribe(_this.handlers);\n }\n }\n },\n };\n _this.nextResultListeners = new Set();\n // A public way to abort observation and broadcast.\n _this.cancel = function (reason) {\n _this.reject(reason);\n _this.sources = [];\n _this.handlers.complete();\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(function (_) { });\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 if (isPromiseLike(sources)) {\n sources.then(function (iterable) { return _this.start(iterable); }, _this.handlers.error);\n }\n else {\n _this.start(sources);\n }\n return _this;\n }\n Concast.prototype.start = function (sources) {\n if (this.sub !== void 0)\n return;\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 // 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 Concast.prototype.deliverLastMessage = function (observer) {\n if (this.latest) {\n var nextOrError = this.latest[0];\n var 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 Concast.prototype.addObserver = function (observer) {\n if (!this.observers.has(observer)) {\n // Immediately deliver the most recent message, so we can always\n // be sure all observers have the latest information.\n this.deliverLastMessage(observer);\n this.observers.add(observer);\n }\n };\n Concast.prototype.removeObserver = function (observer) {\n if (this.observers.delete(observer) && this.observers.size < 1) {\n // In case there are still any listeners in this.nextResultListeners, and\n // no error or completion has been broadcast yet, make sure those\n // observers have a chance to run and then remove themselves from\n // this.observers.\n this.handlers.complete();\n }\n };\n Concast.prototype.notify = function (method, arg) {\n var nextResultListeners = this.nextResultListeners;\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(function (listener) { return listener(method, arg); });\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 Concast.prototype.beforeNext = function (callback) {\n var called = false;\n this.nextResultListeners.add(function (method, arg) {\n if (!called) {\n called = true;\n callback(method, arg);\n }\n });\n };\n return Concast;\n}(Observable));\nexport { Concast };\n// Necessary because the Concast constructor has a different signature\n// than the Observable constructor.\nfixObservableSubclass(Concast);\n//# sourceMappingURL=Concast.js.map","import { isNonNullObject } from \"./objects.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { DeepMerger } from \"./mergeDeep.js\";\nexport function isExecutionPatchIncrementalResult(value) {\n return \"incremental\" in value;\n}\nexport function isExecutionPatchInitialResult(value) {\n return \"hasNext\" in value && \"data\" in value;\n}\nexport function isExecutionPatchResult(value) {\n return (isExecutionPatchIncrementalResult(value) ||\n isExecutionPatchInitialResult(value));\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(value) {\n return isNonNullObject(value) && \"payload\" in value;\n}\nexport function mergeIncrementalData(prevResult, result) {\n var mergedData = prevResult;\n var merger = new DeepMerger();\n if (isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)) {\n result.incremental.forEach(function (_a) {\n var data = _a.data, path = _a.path;\n for (var i = path.length - 1; i >= 0; --i) {\n var key = path[i];\n var isNumericKey = !isNaN(+key);\n var parent_1 = isNumericKey ? [] : {};\n parent_1[key] = data;\n data = parent_1;\n }\n mergedData = merger.merge(mergedData, data);\n });\n }\n return mergedData;\n}\n//# sourceMappingURL=incrementalResult.js.map","import { isNonEmptyArray } from \"./arrays.js\";\nimport { isExecutionPatchIncrementalResult } from \"./incrementalResult.js\";\nexport function graphQLResultHasError(result) {\n var errors = getGraphQLErrorsFromResult(result);\n return isNonEmptyArray(errors);\n}\nexport function getGraphQLErrorsFromResult(result) {\n var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n if (isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)) {\n result.incremental.forEach(function (incrementalResult) {\n if (incrementalResult.errors) {\n graphQLErrors.push.apply(graphQLErrors, incrementalResult.errors);\n }\n });\n }\n return graphQLErrors;\n}\n//# sourceMappingURL=errorHandling.js.map","/**\n * Merges the provided objects shallowly and removes\n * all properties with an `undefined` value\n */\nexport function compact() {\n var objects = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n objects[_i] = arguments[_i];\n }\n var result = Object.create(null);\n objects.forEach(function (obj) {\n if (!obj)\n return;\n Object.keys(obj).forEach(function (key) {\n var value = obj[key];\n if (value !== void 0) {\n result[key] = value;\n }\n });\n });\n return result;\n}\n//# sourceMappingURL=compact.js.map","import { __assign } from \"tslib\";\nimport { compact } from \"./compact.js\";\nexport function mergeOptions(defaults, options) {\n return compact(defaults, options, options.variables && {\n variables: compact(__assign(__assign({}, (defaults && defaults.variables)), options.variables)),\n });\n}\n//# sourceMappingURL=mergeOptions.js.map","import { Observable } from \"../../utilities/index.js\";\nexport function fromError(errorValue) {\n return new Observable(function (observer) {\n observer.error(errorValue);\n });\n}\n//# sourceMappingURL=fromError.js.map","import { invariant } from \"../../utilities/globals/index.js\";\nexport function toPromise(observable) {\n var completed = false;\n return new Promise(function (resolve, reject) {\n observable.subscribe({\n next: function (data) {\n if (completed) {\n globalThis.__DEV__ !== false && invariant.warn(42);\n }\n else {\n completed = true;\n resolve(data);\n }\n },\n error: reject,\n });\n });\n}\n//# sourceMappingURL=toPromise.js.map","import { Observable } from \"../../utilities/index.js\";\nexport function fromPromise(promise) {\n return new Observable(function (observer) {\n promise\n .then(function (value) {\n observer.next(value);\n observer.complete();\n })\n .catch(observer.error.bind(observer));\n });\n}\n//# sourceMappingURL=fromPromise.js.map","export var throwServerError = function (response, result, message) {\n var error = new Error(message);\n error.name = \"ServerError\";\n error.response = response;\n error.statusCode = response.status;\n error.result = result;\n throw error;\n};\n//# sourceMappingURL=throwServerError.js.map","import { __assign } from \"tslib\";\nimport { visit } from \"graphql\";\nexport function filterOperationVariables(variables, query) {\n var result = __assign({}, variables);\n var unusedNames = new Set(Object.keys(variables));\n visit(query, {\n Variable: function (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 (parent &&\n parent.kind !== \"VariableDefinition\") {\n unusedNames.delete(node.name.value);\n }\n },\n });\n unusedNames.forEach(function (name) {\n delete result[name];\n });\n return result;\n}\n//# sourceMappingURL=filterOperationVariables.js.map","import { ApolloLink } from \"./ApolloLink.js\";\nexport var empty = ApolloLink.empty;\n//# sourceMappingURL=empty.js.map","import { ApolloLink } from \"./ApolloLink.js\";\nexport var from = ApolloLink.from;\n//# sourceMappingURL=from.js.map","import { ApolloLink } from \"./ApolloLink.js\";\nexport var split = ApolloLink.split;\n//# sourceMappingURL=split.js.map","import { ApolloLink } from \"./ApolloLink.js\";\nexport var concat = ApolloLink.concat;\n//# sourceMappingURL=concat.js.map","import { ApolloLink } from \"./ApolloLink.js\";\nexport var execute = ApolloLink.execute;\n//# sourceMappingURL=execute.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts\n */\nexport default function asyncIterator(source) {\n var _a;\n var iterator = source[Symbol.asyncIterator]();\n return _a = {\n next: function () {\n return iterator.next();\n }\n },\n _a[Symbol.asyncIterator] = function () {\n return this;\n },\n _a;\n}\n//# sourceMappingURL=async.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/nodeStream.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\nexport default function nodeStreamIterator(stream) {\n var cleanup = null;\n var error = null;\n var done = false;\n var data = [];\n var waiting = [];\n function onData(chunk) {\n if (error)\n return;\n if (waiting.length) {\n var 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) {\n error = err;\n var all = waiting.slice();\n all.forEach(function (pair) {\n pair[1](err);\n });\n !cleanup || cleanup();\n }\n function onEnd() {\n done = true;\n var all = waiting.slice();\n all.forEach(function (pair) {\n pair[0]({ value: undefined, done: true });\n });\n !cleanup || cleanup();\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 function getNext() {\n return new Promise(function (resolve, reject) {\n if (error)\n return reject(error);\n if (data.length)\n return resolve({ value: data.shift(), done: false });\n if (done)\n return resolve({ value: undefined, done: true });\n waiting.push([resolve, reject]);\n });\n }\n var iterator = {\n next: function () {\n return getNext();\n },\n };\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function () {\n return this;\n };\n }\n return iterator;\n}\n//# sourceMappingURL=nodeStream.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\nexport default function promiseIterator(promise) {\n var resolved = false;\n var iterator = {\n next: function () {\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, done: false });\n })\n .catch(reject);\n });\n },\n };\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function () {\n return this;\n };\n }\n return iterator;\n}\n//# sourceMappingURL=promise.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\nexport default function readerIterator(reader) {\n var iterator = {\n next: function () {\n return reader.read();\n },\n };\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function () {\n return this;\n };\n }\n return iterator;\n}\n//# sourceMappingURL=reader.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/index.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../utilities/index.js\";\nimport asyncIterator from \"./iterators/async.js\";\nimport nodeStreamIterator from \"./iterators/nodeStream.js\";\nimport promiseIterator from \"./iterators/promise.js\";\nimport readerIterator from \"./iterators/reader.js\";\nfunction isNodeResponse(value) {\n return !!value.body;\n}\nfunction isReadableStream(value) {\n return !!value.getReader;\n}\nfunction isAsyncIterableIterator(value) {\n return !!(canUseAsyncIteratorSymbol &&\n value[Symbol.asyncIterator]);\n}\nfunction isStreamableBlob(value) {\n return !!value.stream;\n}\nfunction isBlob(value) {\n return !!value.arrayBuffer;\n}\nfunction isNodeReadableStream(value) {\n return !!value.pipe;\n}\nexport function responseIterator(response) {\n var body = response;\n if (isNodeResponse(response))\n body = response.body;\n if (isAsyncIterableIterator(body))\n return asyncIterator(body);\n if (isReadableStream(body))\n return readerIterator(body.getReader());\n // this errors without casting to ReadableStream\n // because Blob.stream() returns a NodeJS ReadableStream\n if (isStreamableBlob(body)) {\n return readerIterator(body.stream().getReader());\n }\n if (isBlob(body))\n return promiseIterator(body.arrayBuffer());\n if (isNodeReadableStream(body))\n return nodeStreamIterator(body);\n throw new Error(\"Unknown body type for responseIterator. Please pass a streamable response.\");\n}\n//# sourceMappingURL=responseIterator.js.map","import { __extends, __spreadArray } from \"tslib\";\nimport \"../utilities/globals/index.js\";\nimport { isNonNullObject } from \"../utilities/index.js\";\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 var PROTOCOL_ERRORS_SYMBOL = Symbol();\nexport function graphQLResultHasProtocolErrors(result) {\n if (result.extensions) {\n return Array.isArray(result.extensions[PROTOCOL_ERRORS_SYMBOL]);\n }\n return false;\n}\nexport function isApolloError(err) {\n return err.hasOwnProperty(\"graphQLErrors\");\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.\nvar generateErrorMessage = function (err) {\n var errors = __spreadArray(__spreadArray(__spreadArray([], err.graphQLErrors, true), err.clientErrors, true), err.protocolErrors, true);\n if (err.networkError)\n errors.push(err.networkError);\n return (errors\n // The rest of the code sometimes unsafely types non-Error objects as GraphQLErrors\n .map(function (err) {\n return (isNonNullObject(err) && err.message) || \"Error message not found.\";\n })\n .join(\"\\n\"));\n};\nvar ApolloError = /** @class */ (function (_super) {\n __extends(ApolloError, _super);\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 function ApolloError(_a) {\n var graphQLErrors = _a.graphQLErrors, protocolErrors = _a.protocolErrors, clientErrors = _a.clientErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;\n var _this = _super.call(this, errorMessage) || this;\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 // We're not using `Object.setPrototypeOf` here as it isn't fully\n // supported on Android (see issue #3236).\n _this.__proto__ = ApolloError.prototype;\n return _this;\n }\n return ApolloError;\n}(Error));\nexport { ApolloError };\n//# sourceMappingURL=index.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { responseIterator } from \"./responseIterator.js\";\nimport { throwServerError } from \"../utils/index.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../../errors/index.js\";\nimport { isApolloPayloadResult } from \"../../utilities/common/incrementalResult.js\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function readMultipartBody(response, nextValue) {\n return __awaiter(this, void 0, void 0, function () {\n var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _a, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;\n var _b, _c;\n var _d;\n return __generator(this, function (_e) {\n switch (_e.label) {\n case 0:\n if (TextDecoder === undefined) {\n throw new Error(\"TextDecoder must be defined in the environment: please import a polyfill.\");\n }\n decoder = new TextDecoder(\"utf-8\");\n contentType = (_d = response.headers) === null || _d === void 0 ? void 0 : _d.get(\"content-type\");\n delimiter = \"boundary=\";\n boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter)) ?\n contentType === null || contentType === void 0 ? void 0 : contentType.substring((contentType === null || contentType === void 0 ? void 0 : contentType.indexOf(delimiter)) + delimiter.length).replace(/['\"]/g, \"\").replace(/\\;(.*)/gm, \"\").trim()\n : \"-\";\n boundary = \"\\r\\n--\".concat(boundaryVal);\n buffer = \"\";\n iterator = responseIterator(response);\n running = true;\n _e.label = 1;\n case 1:\n if (!running) return [3 /*break*/, 3];\n return [4 /*yield*/, iterator.next()];\n case 2:\n _a = _e.sent(), value = _a.value, done = _a.done;\n chunk = typeof value === \"string\" ? value : decoder.decode(value);\n searchFrom = buffer.length - boundary.length + 1;\n running = !done;\n buffer += chunk;\n bi = buffer.indexOf(boundary, searchFrom);\n while (bi > -1) {\n message = void 0;\n _b = [\n buffer.slice(0, bi),\n buffer.slice(bi + boundary.length),\n ], message = _b[0], buffer = _b[1];\n i = message.indexOf(\"\\r\\n\\r\\n\");\n headers = parseHeaders(message.slice(0, i));\n contentType_1 = headers[\"content-type\"];\n if (contentType_1 &&\n contentType_1.toLowerCase().indexOf(\"application/json\") === -1) {\n throw new Error(\"Unsupported patch content type: application/json is required.\");\n }\n body = message.slice(i);\n if (body) {\n result = parseJsonBody(response, body);\n if (Object.keys(result).length > 1 ||\n \"data\" in result ||\n \"incremental\" in result ||\n \"errors\" in result ||\n \"payload\" in result) {\n if (isApolloPayloadResult(result)) {\n next = {};\n if (\"payload\" in result) {\n if (Object.keys(result).length === 1 && result.payload === null) {\n return [2 /*return*/];\n }\n next = __assign({}, result.payload);\n }\n if (\"errors\" in result) {\n next = __assign(__assign({}, next), { extensions: __assign(__assign({}, (\"extensions\" in next ? next.extensions : null)), (_c = {}, _c[PROTOCOL_ERRORS_SYMBOL] = result.errors, _c)) });\n }\n nextValue(next);\n }\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 }\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 return [2 /*return*/];\n }\n }\n bi = buffer.indexOf(boundary);\n }\n return [3 /*break*/, 1];\n case 3: return [2 /*return*/];\n }\n });\n });\n}\nexport function parseHeaders(headerText) {\n var headersInit = {};\n headerText.split(\"\\n\").forEach(function (line) {\n var i = line.indexOf(\":\");\n if (i > -1) {\n // normalize headers to lowercase\n var name_1 = line.slice(0, i).trim().toLowerCase();\n var value = line.slice(i + 1).trim();\n headersInit[name_1] = value;\n }\n });\n return headersInit;\n}\nexport function parseJsonBody(response, bodyText) {\n if (response.status >= 300) {\n // Network error\n var getResult = function () {\n try {\n return JSON.parse(bodyText);\n }\n catch (err) {\n return bodyText;\n }\n };\n throwServerError(response, getResult(), \"Response not successful: Received status code \".concat(response.status));\n }\n try {\n return JSON.parse(bodyText);\n }\n catch (err) {\n var parseError = err;\n parseError.name = \"ServerParseError\";\n parseError.response = response;\n parseError.statusCode = response.status;\n parseError.bodyText = bodyText;\n throw parseError;\n }\n}\nexport function handleError(err, observer) {\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 observer.error(err);\n}\nexport function parseAndCheckHttpResponse(operations) {\n return function (response) {\n return response\n .text()\n .then(function (bodyText) { return parseJsonBody(response, bodyText); })\n .then(function (result) {\n if (!Array.isArray(result) &&\n !hasOwnProperty.call(result, \"data\") &&\n !hasOwnProperty.call(result, \"errors\")) {\n // Data error\n throwServerError(response, result, \"Server response was missing for query '\".concat(Array.isArray(operations) ?\n operations.map(function (op) { return op.operationName; })\n : operations.operationName, \"'.\"));\n }\n return result;\n });\n };\n}\n//# sourceMappingURL=parseAndCheckHttpResponse.js.map","import { newInvariantError } from \"../../utilities/globals/index.js\";\nexport var serializeFetchParameter = function (p, label) {\n var serialized;\n try {\n serialized = JSON.stringify(p);\n }\n catch (e) {\n var parseError = newInvariantError(39, label, e.message);\n parseError.parseError = e;\n throw parseError;\n }\n return serialized;\n};\n//# sourceMappingURL=serializeFetchParameter.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { print } from \"../../utilities/index.js\";\nvar defaultHttpOptions = {\n includeQuery: true,\n includeExtensions: false,\n preserveHeaderCase: false,\n};\nvar 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};\nvar defaultOptions = {\n method: \"POST\",\n};\nexport var fallbackHttpConfig = {\n http: defaultHttpOptions,\n headers: defaultHeaders,\n options: defaultOptions,\n};\nexport var defaultPrinter = function (ast, printer) { return printer(ast); };\nexport function selectHttpOptionsAndBody(operation, fallbackConfig) {\n var configs = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n configs[_i - 2] = arguments[_i];\n }\n configs.unshift(fallbackConfig);\n return selectHttpOptionsAndBodyInternal.apply(void 0, __spreadArray([operation,\n defaultPrinter], configs, false));\n}\nexport function selectHttpOptionsAndBodyInternal(operation, printer) {\n var configs = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n configs[_i - 2] = arguments[_i];\n }\n var options = {};\n var http = {};\n configs.forEach(function (config) {\n options = __assign(__assign(__assign({}, options), config.options), { headers: __assign(__assign({}, options.headers), config.headers) });\n if (config.credentials) {\n options.credentials = config.credentials;\n }\n http = __assign(__assign({}, http), config.http);\n });\n if (options.headers) {\n options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);\n }\n //The body depends on the http options\n var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;\n var body = { operationName: operationName, variables: variables };\n if (http.includeExtensions)\n body.extensions = extensions;\n // not sending the query (i.e persisted queries)\n if (http.includeQuery)\n body.query = printer(query, print);\n return {\n options: options,\n body: body,\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(headers, preserveHeaderCase) {\n // If we're not preserving the case, just remove duplicates w/ normalization.\n if (!preserveHeaderCase) {\n var normalizedHeaders_1 = Object.create(null);\n Object.keys(Object(headers)).forEach(function (name) {\n normalizedHeaders_1[name.toLowerCase()] = headers[name];\n });\n return normalizedHeaders_1;\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 var headerData = Object.create(null);\n Object.keys(Object(headers)).forEach(function (name) {\n headerData[name.toLowerCase()] = {\n originalName: name,\n value: headers[name],\n };\n });\n var normalizedHeaders = Object.create(null);\n Object.keys(headerData).forEach(function (name) {\n normalizedHeaders[headerData[name].originalName] = headerData[name].value;\n });\n return normalizedHeaders;\n}\n//# sourceMappingURL=selectHttpOptionsAndBody.js.map","import { newInvariantError } from \"../../utilities/globals/index.js\";\nexport var checkFetcher = function (fetcher) {\n if (!fetcher && typeof fetch === \"undefined\") {\n throw newInvariantError(37);\n }\n};\n//# sourceMappingURL=checkFetcher.js.map","/**\n * @deprecated\n * This is not used internally any more and will be removed in\n * the next major version of Apollo Client.\n */\nexport var createSignalIfSupported = function () {\n if (typeof AbortController === \"undefined\")\n return { controller: false, signal: false };\n var controller = new AbortController();\n var signal = controller.signal;\n return { controller: controller, signal: signal };\n};\n//# sourceMappingURL=createSignalIfSupported.js.map","export var selectURI = function (operation, fallbackURI) {\n var context = operation.getContext();\n var contextURI = context.uri;\n if (contextURI) {\n return contextURI;\n }\n else if (typeof fallbackURI === \"function\") {\n return fallbackURI(operation);\n }\n else {\n return fallbackURI || \"/graphql\";\n }\n};\n//# sourceMappingURL=selectURI.js.map","import { serializeFetchParameter } from \"./serializeFetchParameter.js\";\n// For GET operations, returns the given URI rewritten with parameters, or a\n// parse error.\nexport function rewriteURIForGET(chosenURI, body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(\"\".concat(key, \"=\").concat(encodeURIComponent(value)));\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 var serializedVariables = void 0;\n try {\n serializedVariables = serializeFetchParameter(body.variables, \"Variables map\");\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam(\"variables\", serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = serializeFetchParameter(body.extensions, \"Extensions map\");\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam(\"extensions\", serializedExtensions);\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 var fragment = \"\", preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf(\"#\");\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf(\"?\") === -1 ? \"?\" : \"&\";\n var newURI = preFragment + queryParamsPrefix + queryParams.join(\"&\") + fragment;\n return { newURI: newURI };\n}\n//# sourceMappingURL=rewriteURIForGET.js.map","import { __assign, __rest } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\nimport { Observable, hasDirectives } from \"../../utilities/index.js\";\nimport { serializeFetchParameter } from \"./serializeFetchParameter.js\";\nimport { selectURI } from \"./selectURI.js\";\nimport { handleError, readMultipartBody, parseAndCheckHttpResponse, } from \"./parseAndCheckHttpResponse.js\";\nimport { checkFetcher } from \"./checkFetcher.js\";\nimport { selectHttpOptionsAndBodyInternal, defaultPrinter, fallbackHttpConfig, } from \"./selectHttpOptionsAndBody.js\";\nimport { rewriteURIForGET } from \"./rewriteURIForGET.js\";\nimport { fromError, filterOperationVariables } from \"../utils/index.js\";\nimport { maybe, getMainDefinition, removeClientSetsFromDocument, } from \"../../utilities/index.js\";\nvar backupFetch = maybe(function () { return fetch; });\nexport var createHttpLink = function (linkOptions) {\n if (linkOptions === void 0) { linkOptions = {}; }\n var _a = linkOptions.uri, uri = _a === void 0 ? \"/graphql\" : _a, \n // use default global fetch if nothing passed in\n preferredFetch = linkOptions.fetch, _b = linkOptions.print, print = _b === void 0 ? defaultPrinter : _b, includeExtensions = linkOptions.includeExtensions, preserveHeaderCase = linkOptions.preserveHeaderCase, useGETForQueries = linkOptions.useGETForQueries, _c = linkOptions.includeUnusedVariables, includeUnusedVariables = _c === void 0 ? false : _c, requestOptions = __rest(linkOptions, [\"uri\", \"fetch\", \"print\", \"includeExtensions\", \"preserveHeaderCase\", \"useGETForQueries\", \"includeUnusedVariables\"]);\n if (globalThis.__DEV__ !== false) {\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 var linkConfig = {\n http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n return new ApolloLink(function (operation) {\n var chosenURI = selectURI(operation, uri);\n var context = operation.getContext();\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 var clientAwarenessHeaders = {};\n if (context.clientAwareness) {\n var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;\n if (name_1) {\n clientAwarenessHeaders[\"apollographql-client-name\"] = name_1;\n }\n if (version) {\n clientAwarenessHeaders[\"apollographql-client-version\"] = version;\n }\n }\n var contextHeaders = __assign(__assign({}, clientAwarenessHeaders), context.headers);\n var contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: contextHeaders,\n };\n if (hasDirectives([\"client\"], operation.query)) {\n var transformedQuery = removeClientSetsFromDocument(operation.query);\n if (!transformedQuery) {\n return fromError(new Error(\"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 operation.query = transformedQuery;\n }\n //uses fallback, link, and then context to build options\n var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;\n if (body.variables && !includeUnusedVariables) {\n body.variables = filterOperationVariables(body.variables, operation.query);\n }\n var controller;\n if (!options.signal && typeof AbortController !== \"undefined\") {\n controller = new AbortController();\n options.signal = controller.signal;\n }\n // If requested, set method to GET if there are no mutations.\n var definitionIsMutation = function (d) {\n return d.kind === \"OperationDefinition\" && d.operation === \"mutation\";\n };\n var definitionIsSubscription = function (d) {\n return d.kind === \"OperationDefinition\" && d.operation === \"subscription\";\n };\n var isSubscription = definitionIsSubscription(getMainDefinition(operation.query));\n // does not match custom directives beginning with @defer\n var hasDefer = hasDirectives([\"defer\"], operation.query);\n if (useGETForQueries &&\n !operation.query.definitions.some(definitionIsMutation)) {\n options.method = \"GET\";\n }\n if (hasDefer || isSubscription) {\n options.headers = options.headers || {};\n var 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 globalThis.__DEV__ !== false && invariant.warn(38);\n }\n if (isSubscription) {\n acceptHeader +=\n \"boundary=graphql;subscriptionSpec=1.0,application/json\";\n }\n else if (hasDefer) {\n acceptHeader += \"deferSpec=20220824,application/json\";\n }\n options.headers.accept = acceptHeader;\n }\n if (options.method === \"GET\") {\n var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;\n if (parseError) {\n return fromError(parseError);\n }\n chosenURI = newURI;\n }\n else {\n try {\n options.body = serializeFetchParameter(body, \"Payload\");\n }\n catch (parseError) {\n return fromError(parseError);\n }\n }\n return new Observable(function (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 var currentFetch = preferredFetch || maybe(function () { return fetch; }) || backupFetch;\n var observerNext = observer.next.bind(observer);\n currentFetch(chosenURI, options)\n .then(function (response) {\n var _a;\n operation.setContext({ response: response });\n var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get(\"content-type\");\n if (ctype !== null && /^multipart\\/mixed/i.test(ctype)) {\n return readMultipartBody(response, observerNext);\n }\n else {\n return parseAndCheckHttpResponse(operation)(response).then(observerNext);\n }\n })\n .then(function () {\n controller = undefined;\n observer.complete();\n })\n .catch(function (err) {\n controller = undefined;\n handleError(err, observer);\n });\n return function () {\n // XXX support canceling this request\n // https://developers.google.com/web/updates/2017/09/abortable-fetch\n if (controller)\n controller.abort();\n };\n });\n });\n};\n//# sourceMappingURL=createHttpLink.js.map","import { __extends } from \"tslib\";\nimport { ApolloLink } from \"../core/index.js\";\nimport { createHttpLink } from \"./createHttpLink.js\";\nvar HttpLink = /** @class */ (function (_super) {\n __extends(HttpLink, _super);\n function HttpLink(options) {\n if (options === void 0) { options = {}; }\n var _this = _super.call(this, createHttpLink(options).request) || this;\n _this.options = options;\n return _this;\n }\n return HttpLink;\n}(ApolloLink));\nexport { HttpLink };\n//# sourceMappingURL=HttpLink.js.map","const { toString, hasOwnProperty } = Object.prototype;\nconst fnToStr = Function.prototype.toString;\nconst previousComparisons = new Map();\n/**\n * Performs a deep equality check on two JavaScript values, tolerating cycles.\n */\nexport function equal(a, b) {\n try {\n return check(a, b);\n }\n finally {\n previousComparisons.clear();\n }\n}\n// Allow default imports as well.\nexport default equal;\nfunction check(a, b) {\n // If the two values are strictly equal, our job is easy.\n if (a === b) {\n return true;\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 // 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 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)\n return false;\n // Fall through to object case...\n case '[object Object]': {\n if (previouslyCompared(a, b))\n return true;\n const aKeys = definedKeys(a);\n const bKeys = definedKeys(b);\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)\n return false;\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 // 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 return true;\n }\n case '[object Error]':\n return a.name === b.name && a.message === b.message;\n case '[object Number]':\n // Handle NaN, which is !== itself.\n if (a !== a)\n return b !== b;\n // Fall through to shared +a === +b case...\n case '[object Boolean]':\n case '[object Date]':\n return +a === +b;\n case '[object RegExp]':\n case '[object String]':\n return a == `${b}`;\n case '[object Map]':\n case '[object Set]': {\n if (a.size !== b.size)\n return false;\n if (previouslyCompared(a, b))\n return true;\n const aIterator = a.entries();\n const isMap = aTag === '[object Map]';\n while (true) {\n const info = aIterator.next();\n if (info.done)\n break;\n // If a instanceof Set, aValue === aKey.\n const [aKey, aValue] = info.value;\n // So this works the same way for both Set and Map.\n if (!b.has(aKey)) {\n return false;\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 return true;\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 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 // 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 // Otherwise the values are not equal.\n return false;\n}\nfunction definedKeys(obj) {\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(key) {\n return this[key] !== void 0;\n}\nconst nativeCodeSuffix = \"{ [native code] }\";\nfunction endsWith(full, suffix) {\n const fromIndex = full.length - suffix.length;\n return fromIndex >= 0 &&\n full.indexOf(suffix, fromIndex) === fromIndex;\n}\nfunction previouslyCompared(a, b) {\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))\n return true;\n }\n else {\n previousComparisons.set(a, bSet = new Set);\n }\n bSet.add(b);\n return false;\n}\n//# sourceMappingURL=index.js.map","import { __assign, __rest } from \"tslib\";\nimport { wrap } from \"optimism\";\nimport { cacheSizes, getFragmentQueryDocument, } from \"../../utilities/index.js\";\nimport { WeakCache } from \"@wry/caches\";\nimport { getApolloCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nvar ApolloCache = /** @class */ (function () {\n function ApolloCache() {\n this.assumeImmutableResults = false;\n // Make sure we compute the same (===) fragment query document every\n // time we receive the same fragment in readFragment.\n this.getFragmentDoc = wrap(getFragmentQueryDocument, {\n max: cacheSizes[\"cache.fragmentQueryDocuments\"] ||\n 1000 /* defaultCacheSizes[\"cache.fragmentQueryDocuments\"] */,\n cache: WeakCache,\n });\n }\n // Transactional API\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 ApolloCache.prototype.batch = function (options) {\n var _this = this;\n var optimisticId = typeof options.optimistic === \"string\" ? options.optimistic\n : options.optimistic === false ? null\n : void 0;\n var updateResult;\n this.performTransaction(function () { return (updateResult = options.update(_this)); }, optimisticId);\n return updateResult;\n };\n ApolloCache.prototype.recordOptimisticTransaction = function (transaction, optimisticId) {\n this.performTransaction(transaction, optimisticId);\n };\n // Optional API\n // Called once per input document, allowing the cache to make static changes\n // to the query, such as adding __typename fields.\n ApolloCache.prototype.transformDocument = function (document) {\n return document;\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 ApolloCache.prototype.transformForLink = function (document) {\n return document;\n };\n ApolloCache.prototype.identify = function (object) {\n return;\n };\n ApolloCache.prototype.gc = function () {\n return [];\n };\n ApolloCache.prototype.modify = function (options) {\n return false;\n };\n // DataProxy API\n ApolloCache.prototype.readQuery = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = !!options.optimistic; }\n return this.read(__assign(__assign({}, options), { rootId: options.id || \"ROOT_QUERY\", optimistic: optimistic }));\n };\n ApolloCache.prototype.readFragment = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = !!options.optimistic; }\n return this.read(__assign(__assign({}, options), { query: this.getFragmentDoc(options.fragment, options.fragmentName), rootId: options.id, optimistic: optimistic }));\n };\n ApolloCache.prototype.writeQuery = function (_a) {\n var id = _a.id, data = _a.data, options = __rest(_a, [\"id\", \"data\"]);\n return this.write(Object.assign(options, {\n dataId: id || \"ROOT_QUERY\",\n result: data,\n }));\n };\n ApolloCache.prototype.writeFragment = function (_a) {\n var id = _a.id, data = _a.data, fragment = _a.fragment, fragmentName = _a.fragmentName, options = __rest(_a, [\"id\", \"data\", \"fragment\", \"fragmentName\"]);\n return this.write(Object.assign(options, {\n query: this.getFragmentDoc(fragment, fragmentName),\n dataId: id,\n result: data,\n }));\n };\n ApolloCache.prototype.updateQuery = function (options, update) {\n return this.batch({\n update: function (cache) {\n var value = cache.readQuery(options);\n var data = update(value);\n if (data === void 0 || data === null)\n return value;\n cache.writeQuery(__assign(__assign({}, options), { data: data }));\n return data;\n },\n });\n };\n ApolloCache.prototype.updateFragment = function (options, update) {\n return this.batch({\n update: function (cache) {\n var value = cache.readFragment(options);\n var data = update(value);\n if (data === void 0 || data === null)\n return value;\n cache.writeFragment(__assign(__assign({}, options), { data: data }));\n return data;\n },\n });\n };\n return ApolloCache;\n}());\nexport { ApolloCache };\nif (globalThis.__DEV__ !== false) {\n ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;\n}\n//# sourceMappingURL=cache.js.map","export var Cache;\n(function (Cache) {\n})(Cache || (Cache = {}));\n//# sourceMappingURL=Cache.js.map","import { __extends } from \"tslib\";\nvar MissingFieldError = /** @class */ (function (_super) {\n __extends(MissingFieldError, _super);\n function MissingFieldError(message, path, query, variables) {\n var _a;\n // 'Error' breaks prototype chain here\n var _this = _super.call(this, message) || this;\n _this.message = message;\n _this.path = path;\n _this.query = query;\n _this.variables = variables;\n if (Array.isArray(_this.path)) {\n _this.missing = _this.message;\n for (var i = _this.path.length - 1; i >= 0; --i) {\n _this.missing = (_a = {}, _a[_this.path[i]] = _this.missing, _a);\n }\n }\n else {\n _this.missing = _this.path;\n }\n // We're not using `Object.setPrototypeOf` here as it isn't fully supported\n // on Android (see issue #3236).\n _this.__proto__ = MissingFieldError.prototype;\n return _this;\n }\n return MissingFieldError;\n}(Error));\nexport { MissingFieldError };\n//# sourceMappingURL=common.js.map","import { isReference, isField, DeepMerger, resultKeyNameFromField, shouldInclude, isNonNullObject, compact, createFragmentMap, getFragmentDefinitions, isArray, } from \"../../utilities/index.js\";\nexport var hasOwn = Object.prototype.hasOwnProperty;\nexport function isNullish(value) {\n return value === null || value === void 0;\n}\nexport { isArray };\nexport function defaultDataIdFromObject(_a, context) {\n var __typename = _a.__typename, id = _a.id, _id = _a._id;\n if (typeof __typename === \"string\") {\n if (context) {\n context.keyObject =\n !isNullish(id) ? { id: id }\n : !isNullish(_id) ? { _id: _id }\n : void 0;\n }\n // If there is no object.id, fall back to object._id.\n if (isNullish(id) && !isNullish(_id)) {\n id = _id;\n }\n if (!isNullish(id)) {\n return \"\".concat(__typename, \":\").concat(typeof id === \"number\" || typeof id === \"string\" ?\n id\n : JSON.stringify(id));\n }\n }\n}\nvar 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};\nexport function normalizeConfig(config) {\n return compact(defaultConfig, config);\n}\nexport function shouldCanonizeResults(config) {\n var value = config.canonizeResults;\n return value === void 0 ? defaultConfig.canonizeResults : value;\n}\nexport function getTypenameFromStoreObject(store, objectOrReference) {\n return isReference(objectOrReference) ?\n store.get(objectOrReference.__ref, \"__typename\")\n : objectOrReference && objectOrReference.__typename;\n}\nexport var TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;\nexport function fieldNameFromStoreName(storeFieldName) {\n var match = storeFieldName.match(TypeOrFieldNameRegExp);\n return match ? match[0] : storeFieldName;\n}\nexport function selectionSetMatchesResult(selectionSet, result, variables) {\n if (isNonNullObject(result)) {\n return isArray(result) ?\n result.every(function (item) {\n return selectionSetMatchesResult(selectionSet, item, variables);\n })\n : selectionSet.selections.every(function (field) {\n if (isField(field) && shouldInclude(field, variables)) {\n var key = resultKeyNameFromField(field);\n return (hasOwn.call(result, key) &&\n (!field.selectionSet ||\n selectionSetMatchesResult(field.selectionSet, result[key], variables)));\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}\nexport function storeValueIsStoreObject(value) {\n return isNonNullObject(value) && !isReference(value) && !isArray(value);\n}\nexport function makeProcessedFieldsMerger() {\n return new DeepMerger();\n}\nexport function extractFragmentContext(document, fragments) {\n // FragmentMap consisting only of fragments defined directly in document, not\n // including other fragments registered in the FragmentRegistry.\n var fragmentMap = createFragmentMap(getFragmentDefinitions(document));\n return {\n fragmentMap: fragmentMap,\n lookupFragment: function (name) {\n var def = fragmentMap[name];\n if (!def && fragments) {\n def = fragments.lookup(name);\n }\n return def || null;\n },\n };\n}\n//# sourceMappingURL=helpers.js.map","import { __assign, __extends, __rest } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport { dep } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport { isReference, makeReference, DeepMerger, maybeDeepFreeze, canUseWeakMap, isNonNullObject, } from \"../../utilities/index.js\";\nimport { hasOwn, fieldNameFromStoreName } from \"./helpers.js\";\nvar DELETE = Object.create(null);\nvar delModifier = function () { return DELETE; };\nvar INVALIDATE = Object.create(null);\nvar EntityStore = /** @class */ (function () {\n function EntityStore(policies, group) {\n var _this = this;\n this.policies = policies;\n this.group = group;\n this.data = Object.create(null);\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 this.rootIds = Object.create(null);\n // Lazily tracks { __ref: } strings contained by this.data[dataId].\n this.refs = Object.create(null);\n // Bound function that can be passed around to provide easy access to fields\n // of Reference objects as well as ordinary objects.\n this.getFieldValue = function (objectOrReference, storeFieldName) {\n return maybeDeepFreeze(isReference(objectOrReference) ?\n _this.get(objectOrReference.__ref, storeFieldName)\n : objectOrReference && objectOrReference[storeFieldName]);\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 this.canRead = function (objOrRef) {\n return isReference(objOrRef) ?\n _this.has(objOrRef.__ref)\n : typeof objOrRef === \"object\";\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 this.toReference = function (objOrIdOrRef, mergeIntoStore) {\n if (typeof objOrIdOrRef === \"string\") {\n return makeReference(objOrIdOrRef);\n }\n if (isReference(objOrIdOrRef)) {\n return objOrIdOrRef;\n }\n var id = _this.policies.identify(objOrIdOrRef)[0];\n if (id) {\n var ref = makeReference(id);\n if (mergeIntoStore) {\n _this.merge(id, objOrIdOrRef);\n }\n return ref;\n }\n };\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 EntityStore.prototype.toObject = function () {\n return __assign({}, this.data);\n };\n EntityStore.prototype.has = function (dataId) {\n return this.lookup(dataId, true) !== void 0;\n };\n EntityStore.prototype.get = function (dataId, fieldName) {\n this.group.depend(dataId, fieldName);\n if (hasOwn.call(this.data, dataId)) {\n var storeObject = this.data[dataId];\n if (storeObject && hasOwn.call(storeObject, fieldName)) {\n return storeObject[fieldName];\n }\n }\n if (fieldName === \"__typename\" &&\n hasOwn.call(this.policies.rootTypenamesById, dataId)) {\n return this.policies.rootTypenamesById[dataId];\n }\n if (this instanceof Layer) {\n return this.parent.get(dataId, fieldName);\n }\n };\n EntityStore.prototype.lookup = function (dataId, dependOnExistence) {\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)\n this.group.depend(dataId, \"__exists\");\n if (hasOwn.call(this.data, dataId)) {\n return this.data[dataId];\n }\n if (this instanceof Layer) {\n return this.parent.lookup(dataId, dependOnExistence);\n }\n if (this.policies.rootTypenamesById[dataId]) {\n return Object.create(null);\n }\n };\n EntityStore.prototype.merge = function (older, newer) {\n var _this = this;\n var dataId;\n // Convert unexpected references to ID strings.\n if (isReference(older))\n older = older.__ref;\n if (isReference(newer))\n newer = newer.__ref;\n var existing = typeof older === \"string\" ? this.lookup((dataId = older)) : older;\n var incoming = typeof newer === \"string\" ? this.lookup((dataId = newer)) : newer;\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)\n return;\n invariant(typeof dataId === \"string\", 1);\n var merged = new DeepMerger(storeObjectReconciler).merge(existing, incoming);\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 if (merged !== existing) {\n delete this.refs[dataId];\n if (this.group.caching) {\n var fieldsToDirty_1 = Object.create(null);\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)\n fieldsToDirty_1.__exists = 1;\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(function (storeFieldName) {\n if (!existing ||\n existing[storeFieldName] !== merged[storeFieldName]) {\n // Always dirty the full storeFieldName, which may include\n // serialized arguments following the fieldName prefix.\n fieldsToDirty_1[storeFieldName] = 1;\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 var fieldName = fieldNameFromStoreName(storeFieldName);\n if (fieldName !== storeFieldName &&\n !_this.policies.hasKeyArgs(merged.__typename, fieldName)) {\n fieldsToDirty_1[fieldName] = 1;\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 if (fieldsToDirty_1.__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 delete fieldsToDirty_1.__typename;\n }\n Object.keys(fieldsToDirty_1).forEach(function (fieldName) {\n return _this.group.dirty(dataId, fieldName);\n });\n }\n }\n };\n EntityStore.prototype.modify = function (dataId, fields) {\n var _this = this;\n var storeObject = this.lookup(dataId);\n if (storeObject) {\n var changedFields_1 = Object.create(null);\n var needToMerge_1 = false;\n var allDeleted_1 = true;\n var sharedDetails_1 = {\n DELETE: DELETE,\n INVALIDATE: INVALIDATE,\n isReference: isReference,\n toReference: this.toReference,\n canRead: this.canRead,\n readField: function (fieldNameOrOptions, from) {\n return _this.policies.readField(typeof fieldNameOrOptions === \"string\" ?\n {\n fieldName: fieldNameOrOptions,\n from: from || makeReference(dataId),\n }\n : fieldNameOrOptions, { store: _this });\n },\n };\n Object.keys(storeObject).forEach(function (storeFieldName) {\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var fieldValue = storeObject[storeFieldName];\n if (fieldValue === void 0)\n return;\n var modify = typeof fields === \"function\" ? fields : (fields[storeFieldName] || fields[fieldName]);\n if (modify) {\n var newValue = modify === delModifier ? DELETE : (modify(maybeDeepFreeze(fieldValue), __assign(__assign({}, sharedDetails_1), { fieldName: fieldName, storeFieldName: storeFieldName, storage: _this.getStorage(dataId, storeFieldName) })));\n if (newValue === INVALIDATE) {\n _this.group.dirty(dataId, storeFieldName);\n }\n else {\n if (newValue === DELETE)\n newValue = void 0;\n if (newValue !== fieldValue) {\n changedFields_1[storeFieldName] = newValue;\n needToMerge_1 = true;\n fieldValue = newValue;\n if (globalThis.__DEV__ !== false) {\n var checkReference = function (ref) {\n if (_this.lookup(ref.__ref) === undefined) {\n globalThis.__DEV__ !== false && invariant.warn(2, ref);\n return true;\n }\n };\n if (isReference(newValue)) {\n checkReference(newValue);\n }\n else if (Array.isArray(newValue)) {\n // Warn about writing \"mixed\" arrays of Reference and non-Reference objects\n var seenReference = false;\n var someNonReference = void 0;\n for (var _i = 0, newValue_1 = newValue; _i < newValue_1.length; _i++) {\n var value = newValue_1[_i];\n if (isReference(value)) {\n seenReference = true;\n if (checkReference(value))\n break;\n }\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 var id = _this.policies.identify(value)[0];\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 globalThis.__DEV__ !== false && invariant.warn(3, someNonReference);\n break;\n }\n }\n }\n }\n }\n }\n }\n if (fieldValue !== void 0) {\n allDeleted_1 = false;\n }\n });\n if (needToMerge_1) {\n this.merge(dataId, changedFields_1);\n if (allDeleted_1) {\n if (this instanceof Layer) {\n this.data[dataId] = void 0;\n }\n else {\n delete this.data[dataId];\n }\n this.group.dirty(dataId, \"__exists\");\n }\n return true;\n }\n }\n return false;\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 EntityStore.prototype.delete = function (dataId, fieldName, args) {\n var _a;\n var storeObject = this.lookup(dataId);\n if (storeObject) {\n var typename = this.getFieldValue(storeObject, \"__typename\");\n var storeFieldName = fieldName && args ?\n this.policies.getStoreFieldName({ typename: typename, fieldName: fieldName, args: args })\n : fieldName;\n return this.modify(dataId, storeFieldName ? (_a = {},\n _a[storeFieldName] = delModifier,\n _a) : delModifier);\n }\n return false;\n };\n EntityStore.prototype.evict = function (options, limit) {\n var 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 EntityStore.prototype.clear = function () {\n this.replace(null);\n };\n EntityStore.prototype.extract = function () {\n var _this = this;\n var obj = this.toObject();\n var extraRootIds = [];\n this.getRootIdSet().forEach(function (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 EntityStore.prototype.replace = function (newData) {\n var _this = this;\n Object.keys(this.data).forEach(function (dataId) {\n if (!(newData && hasOwn.call(newData, dataId))) {\n _this.delete(dataId);\n }\n });\n if (newData) {\n var __META = newData.__META, rest_1 = __rest(newData, [\"__META\"]);\n Object.keys(rest_1).forEach(function (dataId) {\n _this.merge(dataId, rest_1[dataId]);\n });\n if (__META) {\n __META.extraRootIds.forEach(this.retain, this);\n }\n }\n };\n EntityStore.prototype.retain = function (rootId) {\n return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);\n };\n EntityStore.prototype.release = function (rootId) {\n if (this.rootIds[rootId] > 0) {\n var count = --this.rootIds[rootId];\n if (!count)\n delete this.rootIds[rootId];\n return count;\n }\n return 0;\n };\n // Return a Set of all the ID strings that have been retained by\n // this layer/root *and* any layers/roots beneath it.\n EntityStore.prototype.getRootIdSet = function (ids) {\n if (ids === void 0) { ids = new Set(); }\n Object.keys(this.rootIds).forEach(ids.add, ids);\n if (this instanceof Layer) {\n this.parent.getRootIdSet(ids);\n }\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 // 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 EntityStore.prototype.gc = function () {\n var _this = this;\n var ids = this.getRootIdSet();\n var snapshot = this.toObject();\n ids.forEach(function (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 var idsToRemove = Object.keys(snapshot);\n if (idsToRemove.length) {\n var root_1 = this;\n while (root_1 instanceof Layer)\n root_1 = root_1.parent;\n idsToRemove.forEach(function (id) { return root_1.delete(id); });\n }\n return idsToRemove;\n };\n EntityStore.prototype.findChildRefIds = function (dataId) {\n if (!hasOwn.call(this.refs, dataId)) {\n var found_1 = (this.refs[dataId] = Object.create(null));\n var root = this.data[dataId];\n if (!root)\n return found_1;\n var workSet_1 = new Set([root]);\n // Within the store, only arrays and objects can contain child entity\n // references, so we can prune the traversal using this predicate:\n workSet_1.forEach(function (obj) {\n if (isReference(obj)) {\n found_1[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(function (key) {\n var 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_1.add(child);\n }\n });\n }\n });\n }\n return this.refs[dataId];\n };\n EntityStore.prototype.makeCacheKey = function () {\n return this.group.keyMaker.lookupArray(arguments);\n };\n return EntityStore;\n}());\nexport { EntityStore };\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.\nvar CacheGroup = /** @class */ (function () {\n function CacheGroup(caching, parent) {\n if (parent === void 0) { parent = null; }\n this.caching = caching;\n this.parent = parent;\n this.d = null;\n this.resetCaching();\n }\n CacheGroup.prototype.resetCaching = function () {\n this.d = this.caching ? dep() : null;\n this.keyMaker = new Trie(canUseWeakMap);\n };\n CacheGroup.prototype.depend = function (dataId, storeFieldName) {\n if (this.d) {\n this.d(makeDepKey(dataId, storeFieldName));\n var 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 CacheGroup.prototype.dirty = function (dataId, storeFieldName) {\n if (this.d) {\n this.d.dirty(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 return CacheGroup;\n}());\nfunction makeDepKey(dataId, storeFieldName) {\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}\nexport function maybeDependOnExistenceOfEntity(store, entityId) {\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(function (EntityStore) {\n // Refer to this class as EntityStore.Root outside this namespace.\n var Root = /** @class */ (function (_super) {\n __extends(Root, _super);\n function Root(_a) {\n var policies = _a.policies, _b = _a.resultCaching, resultCaching = _b === void 0 ? true : _b, seed = _a.seed;\n var _this = _super.call(this, policies, new CacheGroup(resultCaching)) || this;\n _this.stump = new Stump(_this);\n _this.storageTrie = new Trie(canUseWeakMap);\n if (seed)\n _this.replace(seed);\n return _this;\n }\n Root.prototype.addLayer = function (layerId, replay) {\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 Root.prototype.removeLayer = function () {\n // Never remove the root layer.\n return this;\n };\n Root.prototype.getStorage = function () {\n return this.storageTrie.lookupArray(arguments);\n };\n return Root;\n }(EntityStore));\n EntityStore.Root = Root;\n})(EntityStore || (EntityStore = {}));\n// Not exported, since all Layer instances are created by the addLayer method\n// of the EntityStore.Root class.\nvar Layer = /** @class */ (function (_super) {\n __extends(Layer, _super);\n function Layer(id, parent, replay, group) {\n var _this = _super.call(this, parent.policies, group) || this;\n _this.id = id;\n _this.parent = parent;\n _this.replay = replay;\n _this.group = group;\n replay(_this);\n return _this;\n }\n Layer.prototype.addLayer = function (layerId, replay) {\n return new Layer(layerId, this, replay, this.group);\n };\n Layer.prototype.removeLayer = function (layerId) {\n var _this = this;\n // Remove all instances of the given id, not just the first one.\n var parent = this.parent.removeLayer(layerId);\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(function (dataId) {\n var ownStoreObject = _this.data[dataId];\n var 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 }\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(function (storeFieldName) {\n _this.group.dirty(dataId, storeFieldName);\n });\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(function (storeFieldName) {\n if (!equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) {\n _this.group.dirty(dataId, storeFieldName);\n }\n });\n }\n });\n }\n return parent;\n }\n // No changes are necessary if the parent chain remains identical.\n if (parent === this.parent)\n return this;\n // Recreate this layer on top of the new parent.\n return parent.addLayer(this.id, this.replay);\n };\n Layer.prototype.toObject = function () {\n return __assign(__assign({}, this.parent.toObject()), this.data);\n };\n Layer.prototype.findChildRefIds = function (dataId) {\n var fromParent = this.parent.findChildRefIds(dataId);\n return hasOwn.call(this.data, dataId) ? __assign(__assign({}, fromParent), _super.prototype.findChildRefIds.call(this, dataId)) : fromParent;\n };\n Layer.prototype.getStorage = function () {\n var p = this.parent;\n while (p.parent)\n p = p.parent;\n return p.getStorage.apply(p, \n // @ts-expect-error\n arguments);\n };\n return Layer;\n}(EntityStore));\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.\nvar Stump = /** @class */ (function (_super) {\n __extends(Stump, _super);\n function Stump(root) {\n return _super.call(this, \"EntityStore.Stump\", root, function () { }, new CacheGroup(root.group.caching, root.group)) || this;\n }\n Stump.prototype.removeLayer = function () {\n // Never remove the Stump layer.\n return this;\n };\n Stump.prototype.merge = function (older, newer) {\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 return Stump;\n}(Layer));\nfunction storeObjectReconciler(existingObject, incomingObject, property) {\n var existingValue = existingObject[property];\n var 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}\nexport function supportsResultCaching(store) {\n // When result caching is disabled, store.depend will be null.\n return !!(store instanceof EntityStore && store.group.caching);\n}\n//# sourceMappingURL=entityStore.js.map","import { __assign } from \"tslib\";\nimport { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet, isNonNullObject as isObjectOrArray, } from \"../../utilities/index.js\";\nimport { isArray } from \"./helpers.js\";\nfunction shallowCopy(value) {\n if (isObjectOrArray(value)) {\n return isArray(value) ?\n value.slice(0)\n : __assign({ __proto__: Object.getPrototypeOf(value) }, value);\n }\n return value;\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.\nvar ObjectCanon = /** @class */ (function () {\n function ObjectCanon() {\n // Set of all canonical objects this ObjectCanon has admitted, allowing\n // canon.admit to return previously-canonicalized objects immediately.\n this.known = new (canUseWeakSet ? WeakSet : Set)();\n // Efficient storage/lookup structure for canonical objects.\n this.pool = new Trie(canUseWeakMap);\n // Make the ObjectCanon assume this value has already been\n // canonicalized.\n this.passes = new WeakMap();\n // Arrays that contain the same elements in a different order can share\n // the same SortedKeysInfo object, to save memory.\n this.keysByJSON = new Map();\n // This has to come last because it depends on keysByJSON.\n this.empty = this.admit({});\n }\n ObjectCanon.prototype.isKnown = function (value) {\n return isObjectOrArray(value) && this.known.has(value);\n };\n ObjectCanon.prototype.pass = function (value) {\n if (isObjectOrArray(value)) {\n var copy = shallowCopy(value);\n this.passes.set(copy, value);\n return copy;\n }\n return value;\n };\n ObjectCanon.prototype.admit = function (value) {\n var _this = this;\n if (isObjectOrArray(value)) {\n var original = this.passes.get(value);\n if (original)\n return original;\n var proto = Object.getPrototypeOf(value);\n switch (proto) {\n case Array.prototype: {\n if (this.known.has(value))\n return value;\n var array = value.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 var 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 (globalThis.__DEV__ !== false) {\n Object.freeze(array);\n }\n }\n return node.array;\n }\n case null:\n case Object.prototype: {\n if (this.known.has(value))\n return value;\n var proto_1 = Object.getPrototypeOf(value);\n var array_1 = [proto_1];\n var keys = this.sortedKeys(value);\n array_1.push(keys.json);\n var firstValueIndex_1 = array_1.length;\n keys.sorted.forEach(function (key) {\n array_1.push(_this.admit(value[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 var node = this.pool.lookupArray(array_1);\n if (!node.object) {\n var obj_1 = (node.object = Object.create(proto_1));\n this.known.add(obj_1);\n keys.sorted.forEach(function (key, i) {\n obj_1[key] = array_1[firstValueIndex_1 + 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 (globalThis.__DEV__ !== false) {\n Object.freeze(obj_1);\n }\n }\n return node.object;\n }\n }\n }\n return value;\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 ObjectCanon.prototype.sortedKeys = function (obj) {\n var keys = Object.keys(obj);\n var node = this.pool.lookupArray(keys);\n if (!node.keys) {\n keys.sort();\n var json = JSON.stringify(keys);\n if (!(node.keys = this.keysByJSON.get(json))) {\n this.keysByJSON.set(json, (node.keys = { sorted: keys, json: json }));\n }\n }\n return node.keys;\n };\n return ObjectCanon;\n}());\nexport { ObjectCanon };\n//# sourceMappingURL=object-canon.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { Kind } from \"graphql\";\nimport { wrap } from \"optimism\";\nimport { isField, resultKeyNameFromField, isReference, makeReference, shouldInclude, addTypenameToDocument, getDefaultValues, getMainDefinition, getQueryDefinition, getFragmentFromSelection, maybeDeepFreeze, mergeDeepArray, DeepMerger, isNonNullObject, canUseWeakMap, compact, canonicalStringify, cacheSizes, } from \"../../utilities/index.js\";\nimport { maybeDependOnExistenceOfEntity, supportsResultCaching, } from \"./entityStore.js\";\nimport { isArray, extractFragmentContext, getTypenameFromStoreObject, shouldCanonizeResults, } from \"./helpers.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { ObjectCanon } from \"./object-canon.js\";\nfunction execSelectionSetKeyArgs(options) {\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}\nvar StoreReader = /** @class */ (function () {\n function StoreReader(config) {\n var _this = this;\n this.knownResults = new (canUseWeakMap ? WeakMap : Map)();\n this.config = compact(config, {\n addTypename: config.addTypename !== false,\n canonizeResults: shouldCanonizeResults(config),\n });\n this.canon = config.canon || new ObjectCanon();\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(function (options) {\n var _a;\n var canonizeResults = options.context.canonizeResults;\n var peekArgs = execSelectionSetKeyArgs(options);\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 var other = (_a = _this.executeSelectionSet).peek.apply(_a, peekArgs);\n if (other) {\n if (canonizeResults) {\n return __assign(__assign({}, 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 // If we previously read this result with canonization enabled, we can\n // return that canonized result as-is.\n return other;\n }\n maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);\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 max: this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSelectionSet\"] ||\n 50000 /* defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"] */,\n keyArgs: execSelectionSetKeyArgs,\n // Note that the parameters of makeCacheKey are determined by the\n // array returned by keyArgs.\n makeCacheKey: function (selectionSet, parent, context, canonizeResults) {\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(selectionSet, isReference(parent) ? parent.__ref : parent, context.varString, canonizeResults);\n }\n },\n });\n this.executeSubSelectedArray = wrap(function (options) {\n maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);\n return _this.execSubSelectedArrayImpl(options);\n }, {\n max: this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSubSelectedArray\"] ||\n 10000 /* defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"] */,\n makeCacheKey: function (_a) {\n var field = _a.field, array = _a.array, context = _a.context;\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(field, array, context.varString);\n }\n },\n });\n }\n StoreReader.prototype.resetCanon = function () {\n this.canon = new ObjectCanon();\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 StoreReader.prototype.diffQueryAgainstStore = function (_a) {\n var store = _a.store, query = _a.query, _b = _a.rootId, rootId = _b === void 0 ? \"ROOT_QUERY\" : _b, variables = _a.variables, _c = _a.returnPartialData, returnPartialData = _c === void 0 ? true : _c, _d = _a.canonizeResults, canonizeResults = _d === void 0 ? this.config.canonizeResults : _d;\n var policies = this.config.cache.policies;\n variables = __assign(__assign({}, getDefaultValues(getQueryDefinition(query))), variables);\n var rootRef = makeReference(rootId);\n var execResult = this.executeSelectionSet({\n selectionSet: getMainDefinition(query).selectionSet,\n objectOrReference: rootRef,\n enclosingRef: rootRef,\n context: __assign({ store: store, query: query, policies: policies, variables: variables, varString: canonicalStringify(variables), canonizeResults: canonizeResults }, extractFragmentContext(query, this.config.fragments)),\n });\n var missing;\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(firstMissing(execResult.missing), execResult.missing, query, variables),\n ];\n if (!returnPartialData) {\n throw missing[0];\n }\n }\n return {\n result: execResult.result,\n complete: !missing,\n missing: missing,\n };\n };\n StoreReader.prototype.isFresh = function (result, parent, selectionSet, context) {\n if (supportsResultCaching(context.store) &&\n this.knownResults.get(result) === selectionSet) {\n var latest = this.executeSelectionSet.peek(selectionSet, parent, 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 if (latest && result === latest.result) {\n return true;\n }\n }\n return false;\n };\n // Uncached version of executeSelectionSet.\n StoreReader.prototype.execSelectionSetImpl = function (_a) {\n var _this = this;\n var selectionSet = _a.selectionSet, objectOrReference = _a.objectOrReference, enclosingRef = _a.enclosingRef, context = _a.context;\n if (isReference(objectOrReference) &&\n !context.policies.rootTypenamesById[objectOrReference.__ref] &&\n !context.store.has(objectOrReference.__ref)) {\n return {\n result: this.canon.empty,\n missing: \"Dangling reference to missing \".concat(objectOrReference.__ref, \" object\"),\n };\n }\n var variables = context.variables, policies = context.policies, store = context.store;\n var typename = store.getFieldValue(objectOrReference, \"__typename\");\n var objectsToMerge = [];\n var missing;\n var missingMerger = new DeepMerger();\n if (this.config.addTypename &&\n typeof typename === \"string\" &&\n !policies.rootIdsByTypename[typename]) {\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 function handleMissing(result, resultName) {\n var _a;\n if (result.missing) {\n missing = missingMerger.merge(missing, (_a = {},\n _a[resultName] = result.missing,\n _a));\n }\n return result.result;\n }\n var workSet = new Set(selectionSet.selections);\n workSet.forEach(function (selection) {\n var _a, _b;\n // Omit fields with directives @skip(if: ) or\n // @include(if: ).\n if (!shouldInclude(selection, variables))\n return;\n if (isField(selection)) {\n var fieldValue = policies.readField({\n fieldName: selection.name.value,\n field: selection,\n variables: context.variables,\n from: objectOrReference,\n }, context);\n var resultName = resultKeyNameFromField(selection);\n if (fieldValue === void 0) {\n if (!addTypenameToDocument.added(selection)) {\n missing = missingMerger.merge(missing, (_a = {},\n _a[resultName] = \"Can't find field '\".concat(selection.name.value, \"' on \").concat(isReference(objectOrReference) ?\n objectOrReference.__ref + \" object\"\n : \"object \" + JSON.stringify(objectOrReference, null, 2)),\n _a));\n }\n }\n else if (isArray(fieldValue)) {\n fieldValue = handleMissing(_this.executeSubSelectedArray({\n field: selection,\n array: fieldValue,\n enclosingRef: enclosingRef,\n context: context,\n }), resultName);\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 }\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(_this.executeSelectionSet({\n selectionSet: selection.selectionSet,\n objectOrReference: fieldValue,\n enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,\n context: context,\n }), resultName);\n }\n if (fieldValue !== void 0) {\n objectsToMerge.push((_b = {}, _b[resultName] = fieldValue, _b));\n }\n }\n else {\n var fragment = getFragmentFromSelection(selection, context.lookupFragment);\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(9, selection.name.value);\n }\n if (fragment && policies.fragmentMatches(fragment, typename)) {\n fragment.selectionSet.selections.forEach(workSet.add, workSet);\n }\n }\n });\n var result = mergeDeepArray(objectsToMerge);\n var finalResult = { result: result, missing: missing };\n var frozen = 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 // 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 return frozen;\n };\n // Uncached version of executeSubSelectedArray.\n StoreReader.prototype.execSubSelectedArrayImpl = function (_a) {\n var _this = this;\n var field = _a.field, array = _a.array, enclosingRef = _a.enclosingRef, context = _a.context;\n var missing;\n var missingMerger = new DeepMerger();\n function handleMissing(childResult, i) {\n var _a;\n if (childResult.missing) {\n missing = missingMerger.merge(missing, (_a = {}, _a[i] = childResult.missing, _a));\n }\n return childResult.result;\n }\n if (field.selectionSet) {\n array = array.filter(context.store.canRead);\n }\n array = array.map(function (item, i) {\n // null value in array\n if (item === null) {\n return null;\n }\n // This is a nested array, recurse\n if (isArray(item)) {\n return handleMissing(_this.executeSubSelectedArray({\n field: field,\n array: item,\n enclosingRef: enclosingRef,\n context: context,\n }), i);\n }\n // This is an object, run the selection set on it\n if (field.selectionSet) {\n return handleMissing(_this.executeSelectionSet({\n selectionSet: field.selectionSet,\n objectOrReference: item,\n enclosingRef: isReference(item) ? item : enclosingRef,\n context: context,\n }), i);\n }\n if (globalThis.__DEV__ !== false) {\n assertSelectionSetForIdValue(context.store, field, item);\n }\n return item;\n });\n return {\n result: context.canonizeResults ? this.canon.admit(array) : array,\n missing: missing,\n };\n };\n return StoreReader;\n}());\nexport { StoreReader };\nfunction firstMissing(tree) {\n try {\n JSON.stringify(tree, function (_, value) {\n if (typeof value === \"string\")\n throw value;\n return value;\n });\n }\n catch (result) {\n return result;\n }\n}\nfunction assertSelectionSetForIdValue(store, field, fieldValue) {\n if (!field.selectionSet) {\n var workSet_1 = new Set([fieldValue]);\n workSet_1.forEach(function (value) {\n if (isNonNullObject(value)) {\n invariant(\n !isReference(value),\n 10,\n getTypenameFromStoreObject(store, value),\n field.name.value\n );\n Object.values(value).forEach(workSet_1.add, workSet_1);\n }\n });\n }\n}\n//# sourceMappingURL=readFromStore.js.map","import { dep, Slot } from \"optimism\";\n// Contextual Slot that acquires its value when custom read functions are\n// called in Policies#readField.\nexport var cacheSlot = new Slot();\nvar cacheInfoMap = new WeakMap();\nfunction getCacheInfo(cache) {\n var info = cacheInfoMap.get(cache);\n if (!info) {\n cacheInfoMap.set(cache, (info = {\n vars: new Set(),\n dep: dep(),\n }));\n }\n return info;\n}\nexport function forgetCache(cache) {\n getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });\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) {\n getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });\n}\nexport function makeVar(value) {\n var caches = new Set();\n var listeners = new Set();\n var rv = function (newValue) {\n if (arguments.length > 0) {\n if (value !== newValue) {\n value = newValue;\n caches.forEach(function (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 var oldListeners = Array.from(listeners);\n listeners.clear();\n oldListeners.forEach(function (listener) { return listener(value); });\n }\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 var cache = cacheSlot.getValue();\n if (cache) {\n attach(cache);\n getCacheInfo(cache).dep(rv);\n }\n }\n return value;\n };\n rv.onNextChange = function (listener) {\n listeners.add(listener);\n return function () {\n listeners.delete(listener);\n };\n };\n var attach = (rv.attachCache = function (cache) {\n caches.add(cache);\n getCacheInfo(cache).vars.add(rv);\n return rv;\n });\n rv.forgetCache = function (cache) { return caches.delete(cache); };\n return rv;\n}\nfunction broadcast(cache) {\n if (cache.broadcastWatches) {\n cache.broadcastWatches();\n }\n}\n//# sourceMappingURL=reactiveVars.js.map","import { invariant } from \"../../utilities/globals/index.js\";\nimport { argumentsObjectFromField, DeepMerger, isNonEmptyArray, isNonNullObject, } from \"../../utilities/index.js\";\nimport { hasOwn, isArray } from \"./helpers.js\";\n// Mapping from JSON-encoded KeySpecifier strings to associated information.\nvar specifierInfoCache = Object.create(null);\nfunction lookupSpecifierInfo(spec) {\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 var cacheKey = JSON.stringify(spec);\n return (specifierInfoCache[cacheKey] ||\n (specifierInfoCache[cacheKey] = Object.create(null)));\n}\nexport function keyFieldsFnFromSpecifier(specifier) {\n var info = lookupSpecifierInfo(specifier);\n return (info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {\n var extract = function (from, key) {\n return context.readField(key, from);\n };\n var keyObject = (context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {\n var extracted = extractKeyPath(context.storeObject, 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 if (extracted === void 0 &&\n object !== context.storeObject &&\n hasOwn.call(object, schemaKeyPath[0])) {\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 invariant(extracted !== void 0, 4, schemaKeyPath.join(\".\"), object);\n return extracted;\n }));\n return \"\".concat(context.typename, \":\").concat(JSON.stringify(keyObject));\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(specifier) {\n var info = lookupSpecifierInfo(specifier);\n return (info.keyArgsFn ||\n (info.keyArgsFn = function (args, _a) {\n var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;\n var collected = collectSpecifierPaths(specifier, function (keyPath) {\n var firstKey = keyPath[0];\n var firstChar = firstKey.charAt(0);\n if (firstChar === \"@\") {\n if (field && isNonEmptyArray(field.directives)) {\n var directiveName_1 = 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 var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });\n // Fortunately argumentsObjectFromField works for DirectiveNode!\n var 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 (directiveArgs &&\n extractKeyPath(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 // 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 if (firstChar === \"$\") {\n var variableName = firstKey.slice(1);\n if (variables && hasOwn.call(variables, variableName)) {\n var 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 if (args) {\n return extractKeyPath(args, keyPath);\n }\n });\n var suffix = JSON.stringify(collected);\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 return fieldName;\n }));\n}\nexport function collectSpecifierPaths(specifier, extractor) {\n // For each path specified by specifier, invoke the extractor, and repeatedly\n // merge the results together, with appropriate ancestor context.\n var merger = new DeepMerger();\n return getSpecifierPaths(specifier).reduce(function (collected, path) {\n var _a;\n var 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 (var i = path.length - 1; i >= 0; --i) {\n toMerge = (_a = {}, _a[path[i]] = toMerge, _a);\n }\n collected = merger.merge(collected, toMerge);\n }\n return collected;\n }, Object.create(null));\n}\nexport function getSpecifierPaths(spec) {\n var info = lookupSpecifierInfo(spec);\n if (!info.paths) {\n var paths_1 = (info.paths = []);\n var currentPath_1 = [];\n spec.forEach(function (s, i) {\n if (isArray(s)) {\n getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });\n currentPath_1.length = 0;\n }\n else {\n currentPath_1.push(s);\n if (!isArray(spec[i + 1])) {\n paths_1.push(currentPath_1.slice(0));\n currentPath_1.length = 0;\n }\n }\n });\n }\n return info.paths;\n}\nfunction extractKey(object, key) {\n return object[key];\n}\nexport function extractKeyPath(object, path, extract) {\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(path.reduce(function reducer(obj, key) {\n return isArray(obj) ?\n obj.map(function (child) { return reducer(child, key); })\n : obj && extract(obj, key);\n }, object));\n}\nfunction normalize(value) {\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);\n }\n return collectSpecifierPaths(Object.keys(value).sort(), function (path) {\n return extractKeyPath(value, path);\n });\n }\n return value;\n}\n//# sourceMappingURL=key-extractor.js.map","import { __assign, __rest } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { storeKeyNameFromField, argumentsObjectFromField, isReference, getStoreKeyName, isNonNullObject, stringifyForDisplay, } from \"../../utilities/index.js\";\nimport { hasOwn, fieldNameFromStoreName, storeValueIsStoreObject, selectionSetMatchesResult, TypeOrFieldNameRegExp, defaultDataIdFromObject, isArray, } from \"./helpers.js\";\nimport { cacheSlot } from \"./reactiveVars.js\";\nimport { keyArgsFnFromSpecifier, keyFieldsFnFromSpecifier, } from \"./key-extractor.js\";\nfunction argsFromFieldSpecifier(spec) {\n return (spec.args !== void 0 ? spec.args\n : spec.field ? argumentsObjectFromField(spec.field, spec.variables)\n : null);\n}\nvar nullKeyFieldsFn = function () { return void 0; };\nvar simpleKeyArgsFn = function (_args, context) { return context.fieldName; };\n// These merge functions can be selected by specifying merge:true or\n// merge:false in a field policy.\nvar mergeTrueFn = function (existing, incoming, _a) {\n var mergeObjects = _a.mergeObjects;\n return mergeObjects(existing, incoming);\n};\nvar mergeFalseFn = function (_, incoming) { return incoming; };\nvar Policies = /** @class */ (function () {\n function Policies(config) {\n this.config = config;\n this.typePolicies = Object.create(null);\n this.toBeAdded = Object.create(null);\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 this.supertypeMap = new Map();\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 this.fuzzySubtypes = new Map();\n this.rootIdsByTypename = Object.create(null);\n this.rootTypenamesById = Object.create(null);\n this.usingPossibleTypes = false;\n this.config = __assign({ dataIdFromObject: defaultDataIdFromObject }, config);\n this.cache = this.config.cache;\n this.setRootTypename(\"Query\");\n this.setRootTypename(\"Mutation\");\n this.setRootTypename(\"Subscription\");\n if (config.possibleTypes) {\n this.addPossibleTypes(config.possibleTypes);\n }\n if (config.typePolicies) {\n this.addTypePolicies(config.typePolicies);\n }\n }\n Policies.prototype.identify = function (object, partialContext) {\n var _a;\n var policies = this;\n var typename = (partialContext &&\n (partialContext.typename || ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename))) ||\n object.__typename;\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 // Default context.storeObject to object if not otherwise provided.\n var storeObject = (partialContext && partialContext.storeObject) || object;\n var context = __assign(__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: (partialContext && partialContext.readField) ||\n function () {\n var options = normalizeReadFieldOptions(arguments, storeObject);\n return policies.readField(options, {\n store: policies.cache[\"data\"],\n variables: options.variables,\n });\n } });\n var id;\n var policy = typename && this.getTypePolicy(typename);\n var keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;\n while (keyFn) {\n var specifierOrId = keyFn(__assign(__assign({}, object), storeObject), context);\n if (isArray(specifierOrId)) {\n keyFn = keyFieldsFnFromSpecifier(specifierOrId);\n }\n else {\n id = specifierOrId;\n break;\n }\n }\n id = id ? String(id) : void 0;\n return context.keyObject ? [id, context.keyObject] : [id];\n };\n Policies.prototype.addTypePolicies = function (typePolicies) {\n var _this = this;\n Object.keys(typePolicies).forEach(function (typename) {\n var _a = typePolicies[typename], queryType = _a.queryType, mutationType = _a.mutationType, subscriptionType = _a.subscriptionType, incoming = __rest(_a, [\"queryType\", \"mutationType\", \"subscriptionType\"]);\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)\n _this.setRootTypename(\"Query\", typename);\n if (mutationType)\n _this.setRootTypename(\"Mutation\", typename);\n if (subscriptionType)\n _this.setRootTypename(\"Subscription\", typename);\n if (hasOwn.call(_this.toBeAdded, typename)) {\n _this.toBeAdded[typename].push(incoming);\n }\n else {\n _this.toBeAdded[typename] = [incoming];\n }\n });\n };\n Policies.prototype.updateTypePolicy = function (typename, incoming) {\n var _this = this;\n var existing = this.getTypePolicy(typename);\n var keyFields = incoming.keyFields, fields = incoming.fields;\n function setMerge(existing, merge) {\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 // Type policies can define merge functions, as an alternative to\n // using field policies to merge child objects.\n setMerge(existing, incoming.merge);\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 if (fields) {\n Object.keys(fields).forEach(function (fieldName) {\n var existing = _this.getFieldPolicy(typename, fieldName, true);\n var incoming = fields[fieldName];\n if (typeof incoming === \"function\") {\n existing.read = incoming;\n }\n else {\n var keyArgs = incoming.keyArgs, read = incoming.read, merge = incoming.merge;\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 if (typeof read === \"function\") {\n existing.read = read;\n }\n setMerge(existing, merge);\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 Policies.prototype.setRootTypename = function (which, typename) {\n if (typename === void 0) { typename = which; }\n var rootId = \"ROOT_\" + which.toUpperCase();\n var old = this.rootTypenamesById[rootId];\n if (typename !== old) {\n invariant(!old || old === which, 5, which);\n // First, delete any old __typename associated with this rootId from\n // rootIdsByTypename.\n if (old)\n 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 Policies.prototype.addPossibleTypes = function (possibleTypes) {\n var _this = this;\n this.usingPossibleTypes = true;\n Object.keys(possibleTypes).forEach(function (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 possibleTypes[supertype].forEach(function (subtype) {\n _this.getSupertypeSet(subtype, true).add(supertype);\n var 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 Policies.prototype.getTypePolicy = function (typename) {\n var _this = this;\n if (!hasOwn.call(this.typePolicies, typename)) {\n var policy_1 = (this.typePolicies[typename] = Object.create(null));\n policy_1.fields = Object.create(null);\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 var supertypes_1 = this.supertypeMap.get(typename);\n if (!supertypes_1 && 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_1 = 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(function (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 var fuzzySupertypes = _this.supertypeMap.get(fuzzy);\n if (fuzzySupertypes) {\n fuzzySupertypes.forEach(function (supertype) {\n return supertypes_1.add(supertype);\n });\n }\n }\n });\n }\n if (supertypes_1 && supertypes_1.size) {\n supertypes_1.forEach(function (supertype) {\n var _a = _this.getTypePolicy(supertype), fields = _a.fields, rest = __rest(_a, [\"fields\"]);\n Object.assign(policy_1, rest);\n Object.assign(policy_1.fields, fields);\n });\n }\n }\n var 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(function (policy) {\n _this.updateTypePolicy(typename, policy);\n });\n }\n return this.typePolicies[typename];\n };\n Policies.prototype.getFieldPolicy = function (typename, fieldName, createIfMissing) {\n if (typename) {\n var fieldPolicies = this.getTypePolicy(typename).fields;\n return (fieldPolicies[fieldName] ||\n (createIfMissing && (fieldPolicies[fieldName] = Object.create(null))));\n }\n };\n Policies.prototype.getSupertypeSet = function (subtype, createIfMissing) {\n var supertypeSet = this.supertypeMap.get(subtype);\n if (!supertypeSet && createIfMissing) {\n this.supertypeMap.set(subtype, (supertypeSet = new Set()));\n }\n return supertypeSet;\n };\n Policies.prototype.fragmentMatches = function (fragment, typename, result, variables) {\n var _this = this;\n if (!fragment.typeCondition)\n return true;\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)\n return false;\n var supertype = fragment.typeCondition.name.value;\n // Common case: fragment type condition and __typename are the same.\n if (typename === supertype)\n return true;\n if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {\n var typenameSupertypeSet = this.getSupertypeSet(typename, true);\n var workQueue_1 = [typenameSupertypeSet];\n var maybeEnqueue_1 = function (subtype) {\n var supertypeSet = _this.getSupertypeSet(subtype, false);\n if (supertypeSet &&\n supertypeSet.size &&\n workQueue_1.indexOf(supertypeSet) < 0) {\n workQueue_1.push(supertypeSet);\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 var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);\n var checkingFuzzySubtypes = false;\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 (var i = 0; i < workQueue_1.length; ++i) {\n var supertypeSet = workQueue_1[i];\n if (supertypeSet.has(supertype)) {\n if (!typenameSupertypeSet.has(supertype)) {\n if (checkingFuzzySubtypes) {\n globalThis.__DEV__ !== false && invariant.warn(6, typename, supertype);\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 supertypeSet.forEach(maybeEnqueue_1);\n if (needToCheckFuzzySubtypes &&\n // Start checking fuzzy subtypes only after exhausting all\n // non-fuzzy subtypes (after the final iteration of the loop).\n i === workQueue_1.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 // 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 // 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(function (regExp, fuzzyString) {\n var match = typename.match(regExp);\n if (match && match[0] === typename) {\n maybeEnqueue_1(fuzzyString);\n }\n });\n }\n }\n }\n return false;\n };\n Policies.prototype.hasKeyArgs = function (typename, fieldName) {\n var policy = this.getFieldPolicy(typename, fieldName, false);\n return !!(policy && policy.keyFn);\n };\n Policies.prototype.getStoreFieldName = function (fieldSpec) {\n var typename = fieldSpec.typename, fieldName = fieldSpec.fieldName;\n var policy = this.getFieldPolicy(typename, fieldName, false);\n var storeFieldName;\n var keyFn = policy && policy.keyFn;\n if (keyFn && typename) {\n var context = {\n typename: typename,\n fieldName: fieldName,\n field: fieldSpec.field || null,\n variables: fieldSpec.variables,\n };\n var args = argsFromFieldSpecifier(fieldSpec);\n while (keyFn) {\n var specifierOrString = keyFn(args, context);\n if (isArray(specifierOrString)) {\n keyFn = keyArgsFnFromSpecifier(specifierOrString);\n }\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 if (storeFieldName === void 0) {\n storeFieldName =\n fieldSpec.field ?\n storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)\n : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));\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 // 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 Policies.prototype.readField = function (options, context) {\n var objectOrReference = options.from;\n if (!objectOrReference)\n return;\n var nameOrField = options.field || options.fieldName;\n if (!nameOrField)\n return;\n if (options.typename === void 0) {\n var typename = context.store.getFieldValue(objectOrReference, \"__typename\");\n if (typename)\n options.typename = typename;\n }\n var storeFieldName = this.getStoreFieldName(options);\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var existing = context.store.getFieldValue(objectOrReference, storeFieldName);\n var policy = this.getFieldPolicy(options.typename, fieldName, false);\n var read = policy && policy.read;\n if (read) {\n var readOptions = makeFieldFunctionOptions(this, objectOrReference, options, context, context.store.getStorage(isReference(objectOrReference) ?\n objectOrReference.__ref\n : objectOrReference, storeFieldName));\n // Call read(existing, readOptions) with cacheSlot holding this.cache.\n return cacheSlot.withValue(this.cache, read, [\n existing,\n readOptions,\n ]);\n }\n return existing;\n };\n Policies.prototype.getReadFunction = function (typename, fieldName) {\n var policy = this.getFieldPolicy(typename, fieldName, false);\n return policy && policy.read;\n };\n Policies.prototype.getMergeFunction = function (parentTypename, fieldName, childTypename) {\n var policy = this.getFieldPolicy(parentTypename, fieldName, false);\n var merge = policy && policy.merge;\n if (!merge && childTypename) {\n policy = this.getTypePolicy(childTypename);\n merge = policy && policy.merge;\n }\n return merge;\n };\n Policies.prototype.runMergeFunction = function (existing, incoming, _a, context, storage) {\n var field = _a.field, typename = _a.typename, merge = _a.merge;\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)(existing, incoming);\n }\n if (merge === mergeFalseFn) {\n // Likewise for mergeFalseFn, whose implementation is even simpler.\n return incoming;\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 return merge(existing, incoming, makeFieldFunctionOptions(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 typename: typename,\n fieldName: field.name.value,\n field: field,\n variables: context.variables,\n }, context, storage || Object.create(null)));\n };\n return Policies;\n}());\nexport { Policies };\nfunction makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, context, storage) {\n var storeFieldName = policies.getStoreFieldName(fieldSpec);\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var variables = fieldSpec.variables || context.variables;\n var _a = context.store, toReference = _a.toReference, canRead = _a.canRead;\n return {\n args: argsFromFieldSpecifier(fieldSpec),\n field: fieldSpec.field || null,\n fieldName: fieldName,\n storeFieldName: storeFieldName,\n variables: variables,\n isReference: isReference,\n toReference: toReference,\n storage: storage,\n cache: policies.cache,\n canRead: canRead,\n readField: function () {\n return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, variables), context);\n },\n mergeObjects: makeMergeObjectsFunction(context.store),\n };\n}\nexport function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {\n var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;\n var options;\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 }\n else {\n options = __assign({}, 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 if (globalThis.__DEV__ !== false && options.from === void 0) {\n globalThis.__DEV__ !== false && invariant.warn(7, stringifyForDisplay(Array.from(readFieldArgs)));\n }\n if (void 0 === options.variables) {\n options.variables = variables;\n }\n return options;\n}\nfunction makeMergeObjectsFunction(store) {\n return function mergeObjects(existing, incoming) {\n if (isArray(existing) || isArray(incoming)) {\n throw newInvariantError(8);\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 var eType = store.getFieldValue(existing, \"__typename\");\n var iType = store.getFieldValue(incoming, \"__typename\");\n var typesDiffer = eType && iType && eType !== iType;\n if (typesDiffer) {\n return incoming;\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 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 if (storeValueIsStoreObject(existing) &&\n storeValueIsStoreObject(incoming)) {\n return __assign(__assign({}, existing), incoming);\n }\n }\n return incoming;\n };\n}\n//# sourceMappingURL=policies.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport { Kind } from \"graphql\";\nimport { getFragmentFromSelection, getDefaultValues, getOperationDefinition, getTypenameFromResult, makeReference, isField, resultKeyNameFromField, isReference, shouldInclude, cloneDeep, addTypenameToDocument, isNonEmptyArray, argumentsObjectFromField, canonicalStringify, } from \"../../utilities/index.js\";\nimport { isArray, makeProcessedFieldsMerger, fieldNameFromStoreName, storeValueIsStoreObject, extractFragmentContext, } from \"./helpers.js\";\nimport { normalizeReadFieldOptions } from \"./policies.js\";\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(context, clientOnly, deferred) {\n var key = \"\".concat(clientOnly).concat(deferred);\n var flavored = context.flavors.get(key);\n if (!flavored) {\n context.flavors.set(key, (flavored =\n context.clientOnly === clientOnly && context.deferred === deferred ?\n context\n : __assign(__assign({}, context), { clientOnly: clientOnly, deferred: deferred })));\n }\n return flavored;\n}\nvar StoreWriter = /** @class */ (function () {\n function StoreWriter(cache, reader, fragments) {\n this.cache = cache;\n this.reader = reader;\n this.fragments = fragments;\n }\n StoreWriter.prototype.writeToStore = function (store, _a) {\n var _this = this;\n var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;\n var operationDefinition = getOperationDefinition(query);\n var merger = makeProcessedFieldsMerger();\n variables = __assign(__assign({}, getDefaultValues(operationDefinition)), variables);\n var context = __assign(__assign({ store: store, written: Object.create(null), merge: function (existing, incoming) {\n return merger.merge(existing, incoming);\n }, variables: variables, varString: canonicalStringify(variables) }, extractFragmentContext(query, this.fragments)), { overwrite: !!overwrite, incomingById: new Map(), clientOnly: false, deferred: false, flavors: new Map() });\n var ref = this.processSelectionSet({\n result: result || Object.create(null),\n dataId: dataId,\n selectionSet: operationDefinition.selectionSet,\n mergeTree: { map: new Map() },\n context: context,\n });\n if (!isReference(ref)) {\n throw newInvariantError(11, result);\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(function (_a, dataId) {\n var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;\n var entityRef = makeReference(dataId);\n if (mergeTree && mergeTree.map.size) {\n var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);\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 if (globalThis.__DEV__ !== false && !context.overwrite) {\n var fieldsWithSelectionSets_1 = Object.create(null);\n fieldNodeSet.forEach(function (field) {\n if (field.selectionSet) {\n fieldsWithSelectionSets_1[field.name.value] = true;\n }\n });\n var hasSelectionSet_1 = function (storeFieldName) {\n return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] ===\n true;\n };\n var hasMergeFunction_1 = function (storeFieldName) {\n var childTree = mergeTree && mergeTree.map.get(storeFieldName);\n return Boolean(childTree && childTree.info && childTree.info.merge);\n };\n Object.keys(storeObject).forEach(function (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 (hasSelectionSet_1(storeFieldName) &&\n !hasMergeFunction_1(storeFieldName)) {\n warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);\n }\n });\n }\n store.merge(dataId, storeObject);\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 return ref;\n };\n StoreWriter.prototype.processSelectionSet = function (_a) {\n var _this = this;\n var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context, \n // This object allows processSelectionSet to report useful information\n // to its callers without explicitly returning that information.\n mergeTree = _a.mergeTree;\n var policies = this.cache.policies;\n // This variable will be repeatedly updated using context.merge to\n // accumulate all fields that need to be written into the store.\n var incoming = Object.create(null);\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 var typename = (dataId && policies.rootTypenamesById[dataId]) ||\n getTypenameFromResult(result, selectionSet, context.fragmentMap) ||\n (dataId && context.store.get(dataId, \"__typename\"));\n if (\"string\" === typeof typename) {\n incoming.__typename = typename;\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 var readField = function () {\n var options = normalizeReadFieldOptions(arguments, incoming, context.variables);\n if (isReference(options.from)) {\n var info = context.incomingById.get(options.from.__ref);\n if (info) {\n var result_1 = policies.readField(__assign(__assign({}, options), { from: info.storeObject }), context);\n if (result_1 !== void 0) {\n return result_1;\n }\n }\n }\n return policies.readField(options, context);\n };\n var fieldNodeSet = new Set();\n this.flattenFields(selectionSet, 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, typename).forEach(function (context, field) {\n var _a;\n var resultFieldKey = resultKeyNameFromField(field);\n var value = result[resultFieldKey];\n fieldNodeSet.add(field);\n if (value !== void 0) {\n var storeFieldName = policies.getStoreFieldName({\n typename: typename,\n fieldName: field.name.value,\n field: field,\n variables: context.variables,\n });\n var childTree = getChildMergeTree(mergeTree, storeFieldName);\n var incomingValue = _this.processFieldValue(value, 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, childTree);\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 var childTypename = void 0;\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 (field.selectionSet &&\n (isReference(incomingValue) || storeValueIsStoreObject(incomingValue))) {\n childTypename = readField(\"__typename\", incomingValue);\n }\n var merge = policies.getMergeFunction(typename, field.name.value, childTypename);\n if (merge) {\n childTree.info = {\n // TODO Check compatibility against any existing childTree.field?\n field: field,\n typename: typename,\n merge: merge,\n };\n }\n else {\n maybeRecycleChildMergeTree(mergeTree, storeFieldName);\n }\n incoming = context.merge(incoming, (_a = {},\n _a[storeFieldName] = incomingValue,\n _a));\n }\n else if (globalThis.__DEV__ !== false &&\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 globalThis.__DEV__ !== false && invariant.error(12, resultKeyNameFromField(field), result);\n }\n });\n // Identify the result object, even if dataId was already provided,\n // since we always need keyObject below.\n try {\n var _b = policies.identify(result, {\n typename: typename,\n selectionSet: selectionSet,\n fragmentMap: context.fragmentMap,\n storeObject: incoming,\n readField: readField,\n }), id = _b[0], keyObject = _b[1];\n // If dataId was not provided, fall back to the id just generated by\n // policies.identify.\n dataId = dataId || id;\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 }\n catch (e) {\n // If dataId was provided, tolerate failure of policies.identify.\n if (!dataId)\n throw e;\n }\n if (\"string\" === typeof dataId) {\n var dataRef = makeReference(dataId);\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 var sets = context.written[dataId] || (context.written[dataId] = []);\n if (sets.indexOf(selectionSet) >= 0)\n return dataRef;\n sets.push(selectionSet);\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 (this.reader &&\n this.reader.isFresh(result, dataRef, selectionSet, context)) {\n return dataRef;\n }\n var previous_1 = context.incomingById.get(dataId);\n if (previous_1) {\n previous_1.storeObject = context.merge(previous_1.storeObject, incoming);\n previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);\n fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });\n }\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: fieldNodeSet,\n });\n }\n return dataRef;\n }\n return incoming;\n };\n StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {\n var _this = this;\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 globalThis.__DEV__ !== false ? cloneDeep(value) : value;\n }\n if (isArray(value)) {\n return value.map(function (item, i) {\n var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));\n maybeRecycleChildMergeTree(mergeTree, i);\n return value;\n });\n }\n return this.processSelectionSet({\n result: value,\n selectionSet: field.selectionSet,\n context: context,\n mergeTree: mergeTree,\n });\n };\n // Implements https://spec.graphql.org/draft/#sec-Field-Collection, but with\n // some additions for tracking @client and @defer directives.\n StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {\n if (typename === void 0) { typename = getTypenameFromResult(result, selectionSet, context.fragmentMap); }\n var fieldMap = new Map();\n var policies = this.cache.policies;\n var limitingTrie = new Trie(false); // No need for WeakMap, since limitingTrie does not escape.\n (function flatten(selectionSet, inheritedContext) {\n var visitedNode = limitingTrie.lookup(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, inheritedContext.deferred);\n if (visitedNode.visited)\n return;\n visitedNode.visited = true;\n selectionSet.selections.forEach(function (selection) {\n if (!shouldInclude(selection, context.variables))\n return;\n var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;\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 selection.directives.forEach(function (dir) {\n var name = dir.name.value;\n if (name === \"client\")\n clientOnly = true;\n if (name === \"defer\") {\n var 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.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 if (isField(selection)) {\n var 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 fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));\n }\n else {\n var fragment = getFragmentFromSelection(selection, context.lookupFragment);\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(13, selection.name.value);\n }\n if (fragment &&\n policies.fragmentMatches(fragment, typename, result, context.variables)) {\n flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));\n }\n }\n });\n })(selectionSet, context);\n return fieldMap;\n };\n StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {\n var _a;\n var _this = this;\n if (mergeTree.map.size && !isReference(incoming)) {\n var e_1 = \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 (!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 existing\n : void 0;\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 var i_1 = incoming;\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_1 && !getStorageArgs) {\n getStorageArgs = [isReference(e_1) ? e_1.__ref : e_1];\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 var changedFields_1;\n var getValue_1 = function (from, name) {\n return (isArray(from) ?\n typeof name === \"number\" ?\n from[name]\n : void 0\n : context.store.getFieldValue(from, String(name)));\n };\n mergeTree.map.forEach(function (childTree, storeFieldName) {\n var eVal = getValue_1(e_1, storeFieldName);\n var iVal = getValue_1(i_1, storeFieldName);\n // If we have no incoming data, leave any existing data untouched.\n if (void 0 === iVal)\n return;\n if (getStorageArgs) {\n getStorageArgs.push(storeFieldName);\n }\n var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);\n if (aVal !== iVal) {\n changedFields_1 = changedFields_1 || new Map();\n changedFields_1.set(storeFieldName, aVal);\n }\n if (getStorageArgs) {\n invariant(getStorageArgs.pop() === storeFieldName);\n }\n });\n if (changedFields_1) {\n // Shallow clone i so we can add changed fields to it.\n incoming = (isArray(i_1) ? i_1.slice(0) : __assign({}, i_1));\n changedFields_1.forEach(function (value, name) {\n incoming[name] = value;\n });\n }\n }\n if (mergeTree.info) {\n return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));\n }\n return incoming;\n };\n return StoreWriter;\n}());\nexport { StoreWriter };\nvar emptyMergeTreePool = [];\nfunction getChildMergeTree(_a, name) {\n var map = _a.map;\n if (!map.has(name)) {\n map.set(name, emptyMergeTreePool.pop() || { map: new Map() });\n }\n return map.get(name);\n}\nfunction mergeMergeTrees(left, right) {\n if (left === right || !right || mergeTreeIsEmpty(right))\n return left;\n if (!left || mergeTreeIsEmpty(left))\n return right;\n var info = left.info && right.info ? __assign(__assign({}, left.info), right.info) : left.info || right.info;\n var needToMergeMaps = left.map.size && right.map.size;\n var map = needToMergeMaps ? new Map()\n : left.map.size ? left.map\n : right.map;\n var merged = { info: info, map: map };\n if (needToMergeMaps) {\n var remainingRightKeys_1 = new Set(right.map.keys());\n left.map.forEach(function (leftTree, key) {\n merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));\n remainingRightKeys_1.delete(key);\n });\n remainingRightKeys_1.forEach(function (key) {\n merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));\n });\n }\n return merged;\n}\nfunction mergeTreeIsEmpty(tree) {\n return !tree || !(tree.info || tree.map.size);\n}\nfunction maybeRecycleChildMergeTree(_a, name) {\n var map = _a.map;\n var childTree = map.get(name);\n if (childTree && mergeTreeIsEmpty(childTree)) {\n emptyMergeTreePool.push(childTree);\n map.delete(name);\n }\n}\nvar warnings = new Set();\n// Note that this function is unused in production, and thus should be\n// pruned by any well-configured minifier.\nfunction warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {\n var getChild = function (objOrRef) {\n var child = store.getFieldValue(objOrRef, storeFieldName);\n return typeof child === \"object\" && child;\n };\n var existing = getChild(existingRef);\n if (!existing)\n return;\n var incoming = getChild(incomingObj);\n if (!incoming)\n return;\n // It's always safe to replace a reference, since it refers to data\n // safely stored elsewhere.\n if (isReference(existing))\n return;\n // If the values are structurally equivalent, we do not need to worry\n // about incoming replacing existing.\n if (equal(existing, incoming))\n return;\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 (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {\n return;\n }\n var parentType = store.getFieldValue(existingRef, \"__typename\") ||\n store.getFieldValue(incomingObj, \"__typename\");\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var typeDotName = \"\".concat(parentType, \".\").concat(fieldName);\n // Avoid warning more than once for the same type and field name.\n if (warnings.has(typeDotName))\n return;\n warnings.add(typeDotName);\n var childTypenames = [];\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(function (child) {\n var typename = store.getFieldValue(child, \"__typename\");\n if (typeof typename === \"string\" && !childTypenames.includes(typename)) {\n childTypenames.push(typename);\n }\n });\n }\n globalThis.__DEV__ !== false && invariant.warn(14, fieldName, parentType, childTypenames.length ?\n \"either ensure all objects of type \" +\n childTypenames.join(\" and \") +\n \" have an ID or a custom merge function, or \"\n : \"\", typeDotName, existing, incoming);\n}\n//# sourceMappingURL=writeToStore.js.map","import { __assign, __extends } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\n// Make builtins like Map and Set safe to use with non-extensible objects.\nimport \"./fixPolyfills.js\";\nimport { wrap } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { ApolloCache } from \"../core/cache.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { addTypenameToDocument, isReference, DocumentTransform, canonicalStringify, print, cacheSizes, } from \"../../utilities/index.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 { getInMemoryCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nvar InMemoryCache = /** @class */ (function (_super) {\n __extends(InMemoryCache, _super);\n function InMemoryCache(config) {\n if (config === void 0) { config = {}; }\n var _this = _super.call(this) || this;\n _this.watches = new Set();\n _this.addTypenameTransform = new DocumentTransform(addTypenameToDocument);\n // Override the default value, since InMemoryCache result objects are frozen\n // in development and expected to remain logically immutable in production.\n _this.assumeImmutableResults = true;\n _this.makeVar = makeVar;\n _this.txCount = 0;\n _this.config = normalizeConfig(config);\n _this.addTypename = !!_this.config.addTypename;\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 _this.init();\n return _this;\n }\n InMemoryCache.prototype.init = function () {\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 var rootStore = (this.data = new EntityStore.Root({\n policies: this.policies,\n resultCaching: this.config.resultCaching,\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 this.resetResultCache();\n };\n InMemoryCache.prototype.resetResultCache = function (resetResultIdentities) {\n var _this = this;\n var previousReader = this.storeReader;\n var fragments = this.config.fragments;\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(this, (this.storeReader = new StoreReader({\n cache: this,\n addTypename: this.addTypename,\n resultCacheMaxSize: this.config.resultCacheMaxSize,\n canonizeResults: shouldCanonizeResults(this.config),\n canon: resetResultIdentities ? void 0 : (previousReader && previousReader.canon),\n fragments: fragments,\n })), fragments);\n this.maybeBroadcastWatch = wrap(function (c, options) {\n return _this.broadcastWatch(c, options);\n }, {\n max: this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] ||\n 5000 /* defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] */,\n makeCacheKey: function (c) {\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 var store = c.optimistic ? _this.optimisticData : _this.data;\n if (supportsResultCaching(store)) {\n var optimistic = c.optimistic, id = c.id, variables = c.variables;\n return store.makeCacheKey(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, canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));\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(function (group) {\n return group.resetCaching();\n });\n };\n InMemoryCache.prototype.restore = function (data) {\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)\n this.data.replace(data);\n return this;\n };\n InMemoryCache.prototype.extract = function (optimistic) {\n if (optimistic === void 0) { optimistic = false; }\n return (optimistic ? this.optimisticData : this.data).extract();\n };\n InMemoryCache.prototype.read = function (options) {\n var \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 _a = options.returnPartialData, \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 = _a === void 0 ? false : _a;\n try {\n return (this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, config: this.config, returnPartialData: returnPartialData })).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 InMemoryCache.prototype.write = function (options) {\n try {\n ++this.txCount;\n return this.storeWriter.writeToStore(this.data, options);\n }\n finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n };\n InMemoryCache.prototype.modify = function (options) {\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 var store = ((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 }\n finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n };\n InMemoryCache.prototype.diff = function (options) {\n return this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, rootId: options.id || \"ROOT_QUERY\", config: this.config }));\n };\n InMemoryCache.prototype.watch = function (watch) {\n var _this = this;\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 function () {\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 InMemoryCache.prototype.gc = function (options) {\n var _a;\n canonicalStringify.reset();\n print.reset();\n this.addTypenameTransform.resetCache();\n (_a = this.config.fragments) === null || _a === void 0 ? void 0 : _a.resetCaches();\n var ids = this.optimisticData.gc();\n if (options && !this.txCount) {\n if (options.resetResultCache) {\n this.resetResultCache(options.resetResultIdentities);\n }\n else if (options.resetResultIdentities) {\n this.storeReader.resetCanon();\n }\n }\n return ids;\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 InMemoryCache.prototype.retain = function (rootId, optimistic) {\n return (optimistic ? this.optimisticData : this.data).retain(rootId);\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 InMemoryCache.prototype.release = function (rootId, optimistic) {\n return (optimistic ? this.optimisticData : this.data).release(rootId);\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 InMemoryCache.prototype.identify = function (object) {\n if (isReference(object))\n return object.__ref;\n try {\n return this.policies.identify(object)[0];\n }\n catch (e) {\n globalThis.__DEV__ !== false && invariant.warn(e);\n }\n };\n InMemoryCache.prototype.evict = function (options) {\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 = __assign(__assign({}, 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 }\n finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n };\n InMemoryCache.prototype.reset = function (options) {\n var _this = this;\n this.init();\n canonicalStringify.reset();\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(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });\n this.watches.clear();\n forgetCache(this);\n }\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 return Promise.resolve();\n };\n InMemoryCache.prototype.removeOptimistic = function (idToRemove) {\n var newOptimisticData = this.optimisticData.removeLayer(idToRemove);\n if (newOptimisticData !== this.optimisticData) {\n this.optimisticData = newOptimisticData;\n this.broadcastWatches();\n }\n };\n InMemoryCache.prototype.batch = function (options) {\n var _this = this;\n var update = options.update, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, removeOptimistic = options.removeOptimistic, onWatchUpdated = options.onWatchUpdated;\n var updateResult;\n var perform = function (layer) {\n var _a = _this, data = _a.data, optimisticData = _a.optimisticData;\n ++_this.txCount;\n if (layer) {\n _this.data = _this.optimisticData = layer;\n }\n try {\n return (updateResult = update(_this));\n }\n finally {\n --_this.txCount;\n _this.data = data;\n _this.optimisticData = optimisticData;\n }\n };\n var alreadyDirty = new Set();\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(__assign(__assign({}, options), { onWatchUpdated: function (watch) {\n alreadyDirty.add(watch);\n return false;\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 }\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 }\n else {\n // Otherwise, leave this.data and this.optimisticData unchanged and run\n // the update with broadcast batching.\n perform();\n }\n if (typeof removeOptimistic === \"string\") {\n this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);\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(__assign(__assign({}, options), { onWatchUpdated: function (watch, diff) {\n var 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 // 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(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });\n }\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 return updateResult;\n };\n InMemoryCache.prototype.performTransaction = function (update, optimisticId) {\n return this.batch({\n update: update,\n optimistic: optimisticId || optimisticId !== null,\n });\n };\n InMemoryCache.prototype.transformDocument = function (document) {\n return this.addTypenameToDocument(this.addFragmentsToDocument(document));\n };\n InMemoryCache.prototype.broadcastWatches = function (options) {\n var _this = this;\n if (!this.txCount) {\n this.watches.forEach(function (c) { return _this.maybeBroadcastWatch(c, options); });\n }\n };\n InMemoryCache.prototype.addFragmentsToDocument = function (document) {\n var fragments = this.config.fragments;\n return fragments ? fragments.transform(document) : document;\n };\n InMemoryCache.prototype.addTypenameToDocument = function (document) {\n if (this.addTypename) {\n return this.addTypenameTransform.transformDocument(document);\n }\n return document;\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 InMemoryCache.prototype.broadcastWatch = function (c, options) {\n var lastDiff = c.lastDiff;\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 var diff = this.diff(c);\n if (options) {\n if (c.optimistic && typeof options.optimistic === \"string\") {\n diff.fromOptimisticTransaction = true;\n }\n if (options.onWatchUpdated &&\n options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {\n // Returning false from the onWatchUpdated callback will prevent\n // calling c.callback(diff) for this watcher.\n return;\n }\n }\n if (!lastDiff || !equal(lastDiff.result, diff.result)) {\n c.callback((c.lastDiff = diff), lastDiff);\n }\n };\n return InMemoryCache;\n}(ApolloCache));\nexport { InMemoryCache };\nif (globalThis.__DEV__ !== false) {\n InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;\n}\n//# sourceMappingURL=inMemoryCache.js.map","/**\n * The current status of a query’s execution in our system.\n */\nexport var NetworkStatus;\n(function (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 NetworkStatus[NetworkStatus[\"loading\"] = 1] = \"loading\";\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 NetworkStatus[NetworkStatus[\"setVariables\"] = 2] = \"setVariables\";\n /**\n * Indicates that `fetchMore` was called on this query and that the query created is currently in\n * flight.\n */\n NetworkStatus[NetworkStatus[\"fetchMore\"] = 3] = \"fetchMore\";\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 NetworkStatus[NetworkStatus[\"refetch\"] = 4] = \"refetch\";\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 NetworkStatus[NetworkStatus[\"poll\"] = 6] = \"poll\";\n /**\n * No request is in flight for this query, and no errors happened. Everything is OK.\n */\n NetworkStatus[NetworkStatus[\"ready\"] = 7] = \"ready\";\n /**\n * No request is in flight for this query, but one or more errors were detected.\n */\n NetworkStatus[NetworkStatus[\"error\"] = 8] = \"error\";\n})(NetworkStatus || (NetworkStatus = {}));\n/**\n * Returns true if there is currently a network request in flight according to a given network\n * status.\n */\nexport function isNetworkRequestInFlight(networkStatus) {\n return networkStatus ? networkStatus < 7 : false;\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(networkStatus) {\n return networkStatus === 7 || networkStatus === 8;\n}\n//# sourceMappingURL=networkStatus.js.map","import { __rest } from \"tslib\";\nimport equal from \"@wry/equality\";\nimport { createFragmentMap, getFragmentDefinitions, getFragmentFromSelection, getMainDefinition, isField, resultKeyNameFromField, shouldInclude, } from \"../utilities/index.js\";\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(query, _a, _b, variables) {\n var aData = _a.data, aRest = __rest(_a, [\"data\"]);\n var bData = _b.data, bRest = __rest(_b, [\"data\"]);\n return (equal(aRest, bRest) &&\n equalBySelectionSet(getMainDefinition(query).selectionSet, aData, bData, {\n fragmentMap: createFragmentMap(getFragmentDefinitions(query)),\n variables: variables,\n }));\n}\nfunction equalBySelectionSet(selectionSet, aResult, bResult, context) {\n if (aResult === bResult) {\n return true;\n }\n var seenSelections = new Set();\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(function (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))\n return true;\n seenSelections.add(selection);\n // Ignore @skip(if: true) and @include(if: false) fields.\n if (!shouldInclude(selection, context.variables))\n return true;\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))\n return true;\n if (isField(selection)) {\n var resultKey = resultKeyNameFromField(selection);\n var aResultChild = aResult && aResult[resultKey];\n var bResultChild = bResult && bResult[resultKey];\n var childSelectionSet = selection.selectionSet;\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 var aChildIsArray = Array.isArray(aResultChild);\n var bChildIsArray = Array.isArray(bResultChild);\n if (aChildIsArray !== bChildIsArray)\n return false;\n if (aChildIsArray && bChildIsArray) {\n var length_1 = aResultChild.length;\n if (bResultChild.length !== length_1) {\n return false;\n }\n for (var i = 0; i < length_1; ++i) {\n if (!equalBySelectionSet(childSelectionSet, aResultChild[i], bResultChild[i], context)) {\n return false;\n }\n }\n return true;\n }\n return equalBySelectionSet(childSelectionSet, aResultChild, bResultChild, context);\n }\n else {\n var 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))\n return true;\n return equalBySelectionSet(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, bResult, context);\n }\n }\n });\n}\nfunction selectionHasNonreactiveDirective(selection) {\n return (!!selection.directives && selection.directives.some(directiveIsNonreactive));\n}\nfunction directiveIsNonreactive(dir) {\n return dir.name.value === \"nonreactive\";\n}\n//# sourceMappingURL=equalByQuery.js.map","import { __assign, __extends } from \"tslib\";\nimport { invariant } from \"../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport { cloneDeep, compact, getOperationDefinition, Observable, iterateObserversSafely, fixObservableSubclass, getQueryDefinition, } from \"../utilities/index.js\";\nimport { equalByQuery } from \"./equalByQuery.js\";\nvar assign = Object.assign, hasOwnProperty = Object.hasOwnProperty;\nvar ObservableQuery = /** @class */ (function (_super) {\n __extends(ObservableQuery, _super);\n function ObservableQuery(_a) {\n var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;\n var _this = _super.call(this, function (observer) {\n // Zen Observable has its own error function, so in order to log correctly\n // we need to provide a custom error callback.\n try {\n var subObserver = observer._subscription._observer;\n if (subObserver && !subObserver.error) {\n subObserver.error = defaultSubscriptionObserverErrorCallback;\n }\n }\n catch (_a) { }\n var first = !_this.observers.size;\n _this.observers.add(observer);\n // Deliver most recent error or result.\n var last = _this.last;\n if (last && last.error) {\n observer.error && observer.error(last.error);\n }\n else if (last && last.result) {\n observer.next && observer.next(last.result);\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(function () { });\n }\n return function () {\n if (_this.observers.delete(observer) && !_this.observers.size) {\n _this.tearDownQuery();\n }\n };\n }) || this;\n _this.observers = new Set();\n _this.subscriptions = new Set();\n // related classes\n _this.queryInfo = queryInfo;\n _this.queryManager = queryManager;\n // active state\n _this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);\n _this.isTornDown = false;\n var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? \"cache-first\" : _d;\n var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e, \n // Make sure we don't store \"standby\" as the initialFetchPolicy.\n _f = options.initialFetchPolicy, \n // Make sure we don't store \"standby\" as the initialFetchPolicy.\n initialFetchPolicy = _f === void 0 ? fetchPolicy === \"standby\" ? defaultFetchPolicy : (fetchPolicy) : _f;\n _this.options = __assign(__assign({}, options), { \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: initialFetchPolicy, \n // This ensures this.options.fetchPolicy always has a string value, in\n // case options.fetchPolicy was not provided.\n fetchPolicy: fetchPolicy });\n _this.queryId = queryInfo.queryId || queryManager.generateQueryId();\n var opDef = getOperationDefinition(_this.query);\n _this.queryName = opDef && opDef.name && opDef.name.value;\n return _this;\n }\n Object.defineProperty(ObservableQuery.prototype, \"query\", {\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 get: function () {\n return this.lastQuery || this.options.query;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(ObservableQuery.prototype, \"variables\", {\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 get: function () {\n return this.options.variables;\n },\n enumerable: false,\n configurable: true\n });\n ObservableQuery.prototype.result = function () {\n var _this = this;\n return new Promise(function (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 var observer = {\n next: function (result) {\n resolve(result);\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 setTimeout(function () {\n subscription.unsubscribe();\n }, 0);\n },\n error: reject,\n };\n var subscription = _this.subscribe(observer);\n });\n };\n /** @internal */\n ObservableQuery.prototype.resetDiff = function () {\n this.queryInfo.resetDiff();\n };\n ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {\n if (saveAsLastResult === void 0) { saveAsLastResult = true; }\n // Use the last result as long as the variables match this.variables.\n var lastResult = this.getLastResult(true);\n var networkStatus = this.queryInfo.networkStatus ||\n (lastResult && lastResult.networkStatus) ||\n NetworkStatus.ready;\n var result = __assign(__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });\n var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? \"cache-first\" : _a;\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 // Fall through.\n }\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 }\n else {\n var diff = this.queryInfo.getDiff();\n if (diff.complete || this.options.returnPartialData) {\n result.data = diff.result;\n }\n if (equal(result.data, {})) {\n result.data = void 0;\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 // 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 (diff.complete &&\n result.networkStatus === NetworkStatus.loading &&\n (fetchPolicy === \"cache-first\" || fetchPolicy === \"cache-only\")) {\n result.networkStatus = NetworkStatus.ready;\n result.loading = false;\n }\n }\n else {\n result.partial = true;\n }\n if (globalThis.__DEV__ !== false &&\n !diff.complete &&\n !this.options.partialRefetch &&\n !result.loading &&\n !result.data &&\n !result.error) {\n logMissingFieldErrors(diff.missing);\n }\n }\n if (saveAsLastResult) {\n this.updateLastResult(result);\n }\n return result;\n };\n // Compares newResult to the snapshot we took of this.lastResult when it was\n // first received.\n ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {\n if (!this.last) {\n return true;\n }\n var resultIsDifferent = this.queryManager.getDocumentInfo(this.query).hasNonreactiveDirective ?\n !equalByQuery(this.query, this.last.result, newResult, this.variables)\n : !equal(this.last.result, newResult);\n return (resultIsDifferent || (variables && !equal(this.last.variables, variables)));\n };\n ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {\n var last = this.last;\n if (last &&\n last[key] &&\n (!variablesMustMatch || equal(last.variables, this.variables))) {\n return last[key];\n }\n };\n ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {\n return this.getLast(\"result\", variablesMustMatch);\n };\n ObservableQuery.prototype.getLastError = function (variablesMustMatch) {\n return this.getLast(\"error\", variablesMustMatch);\n };\n ObservableQuery.prototype.resetLastResults = function () {\n delete this.last;\n this.isTornDown = false;\n };\n ObservableQuery.prototype.resetQueryStoreErrors = function () {\n this.queryManager.resetErrors(this.queryId);\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 ObservableQuery.prototype.refetch = function (variables) {\n var _a;\n var reobserveOptions = {\n // Always disable polling for refetches.\n pollInterval: 0,\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 var fetchPolicy = this.options.fetchPolicy;\n if (fetchPolicy === \"cache-and-network\") {\n reobserveOptions.fetchPolicy = fetchPolicy;\n }\n else if (fetchPolicy === \"no-cache\") {\n reobserveOptions.fetchPolicy = \"no-cache\";\n }\n else {\n reobserveOptions.fetchPolicy = \"network-only\";\n }\n if (globalThis.__DEV__ !== false && variables && hasOwnProperty.call(variables, \"variables\")) {\n var queryDef = getQueryDefinition(this.query);\n var vars = queryDef.variableDefinitions;\n if (!vars || !vars.some(function (v) { return v.variable.name.value === \"variables\"; })) {\n globalThis.__DEV__ !== false && invariant.warn(\n 20,\n variables,\n ((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || queryDef\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 = __assign(__assign({}, this.options.variables), variables);\n }\n this.queryInfo.resetLastWrite();\n return this.reobserve(reobserveOptions, NetworkStatus.refetch);\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 ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {\n var _this = this;\n var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : (__assign(__assign(__assign(__assign({}, this.options), { query: this.options.query }), fetchMoreOptions), { variables: __assign(__assign({}, this.options.variables), fetchMoreOptions.variables) })))), { \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 combinedOptions.query = this.transformDocument(combinedOptions.query);\n var qid = this.queryManager.generateQueryId();\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 // Simulate a loading result for the original query with\n // result.networkStatus === NetworkStatus.fetchMore.\n var queryInfo = this.queryInfo;\n var originalNetworkStatus = queryInfo.networkStatus;\n queryInfo.networkStatus = NetworkStatus.fetchMore;\n if (combinedOptions.notifyOnNetworkStatusChange) {\n this.observe();\n }\n var updatedQuerySet = new Set();\n return this.queryManager\n .fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore)\n .then(function (fetchMoreResult) {\n _this.queryManager.removeQuery(qid);\n if (queryInfo.networkStatus === NetworkStatus.fetchMore) {\n queryInfo.networkStatus = originalNetworkStatus;\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: function (cache) {\n var updateQuery = fetchMoreOptions.updateQuery;\n if (updateQuery) {\n cache.updateQuery({\n query: _this.query,\n variables: _this.variables,\n returnPartialData: true,\n optimistic: false,\n }, function (previous) {\n return updateQuery(previous, {\n fetchMoreResult: fetchMoreResult.data,\n variables: combinedOptions.variables,\n });\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 onWatchUpdated: function (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 return fetchMoreResult;\n })\n .finally(function () {\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 // 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 ObservableQuery.prototype.subscribeToMore = function (options) {\n var _this = this;\n var subscription = this.queryManager\n .startGraphQLSubscription({\n query: options.document,\n variables: options.variables,\n context: options.context,\n })\n .subscribe({\n next: function (subscriptionData) {\n var updateQuery = options.updateQuery;\n if (updateQuery) {\n _this.updateQuery(function (previous, _a) {\n var variables = _a.variables;\n return updateQuery(previous, {\n subscriptionData: subscriptionData,\n variables: variables,\n });\n });\n }\n },\n error: function (err) {\n if (options.onError) {\n options.onError(err);\n return;\n }\n globalThis.__DEV__ !== false && invariant.error(21, err);\n },\n });\n this.subscriptions.add(subscription);\n return function () {\n if (_this.subscriptions.delete(subscription)) {\n subscription.unsubscribe();\n }\n };\n };\n ObservableQuery.prototype.setOptions = function (newOptions) {\n return this.reobserve(newOptions);\n };\n ObservableQuery.prototype.silentSetOptions = function (newOptions) {\n var mergedOptions = compact(this.options, newOptions || {});\n assign(this.options, mergedOptions);\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 ObservableQuery.prototype.setVariables = function (variables) {\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 this.options.variables = variables;\n // See comment above\n if (!this.observers.size) {\n return Promise.resolve();\n }\n return this.reobserve({\n // Reset options.fetchPolicy to its original value.\n fetchPolicy: this.options.initialFetchPolicy,\n variables: variables,\n }, NetworkStatus.setVariables);\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 ObservableQuery.prototype.updateQuery = function (mapFn) {\n var queryManager = this.queryManager;\n var result = queryManager.cache.diff({\n query: this.options.query,\n variables: this.variables,\n returnPartialData: true,\n optimistic: false,\n }).result;\n var newResult = mapFn(result, {\n variables: this.variables,\n });\n if (newResult) {\n queryManager.cache.writeQuery({\n query: this.options.query,\n data: newResult,\n variables: this.variables,\n });\n queryManager.broadcastQueries();\n }\n };\n /**\n * A function that instructs the query to begin re-executing at a specified interval (in milliseconds).\n */\n ObservableQuery.prototype.startPolling = function (pollInterval) {\n this.options.pollInterval = pollInterval;\n this.updatePolling();\n };\n /**\n * A function that instructs the query to stop polling after a previous call to `startPolling`.\n */\n ObservableQuery.prototype.stopPolling = function () {\n this.options.pollInterval = 0;\n this.updatePolling();\n };\n // Update options.fetchPolicy according to options.nextFetchPolicy.\n ObservableQuery.prototype.applyNextFetchPolicy = function (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) {\n if (options.nextFetchPolicy) {\n var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? \"cache-first\" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;\n if (fetchPolicy === \"standby\") {\n // Do nothing, leaving options.fetchPolicy unchanged.\n }\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: reason,\n options: options,\n observable: this,\n initialFetchPolicy: initialFetchPolicy,\n });\n }\n else if (reason === \"variables-changed\") {\n options.fetchPolicy = initialFetchPolicy;\n }\n else {\n options.fetchPolicy = options.nextFetchPolicy;\n }\n }\n return options.fetchPolicy;\n };\n ObservableQuery.prototype.fetch = function (options, newNetworkStatus, query) {\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\"](this.queryId, options, newNetworkStatus, query);\n };\n // Turns polling on or off based on this.options.pollInterval.\n ObservableQuery.prototype.updatePolling = function () {\n var _this = this;\n // Avoid polling in SSR mode\n if (this.queryManager.ssrMode) {\n return;\n }\n var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;\n if (!pollInterval) {\n if (pollingInfo) {\n clearTimeout(pollingInfo.timeout);\n delete this.pollingInfo;\n }\n return;\n }\n if (pollingInfo && pollingInfo.interval === pollInterval) {\n return;\n }\n invariant(pollInterval, 22);\n var info = pollingInfo || (this.pollingInfo = {});\n info.interval = pollInterval;\n var maybeFetch = function () {\n var _a, _b;\n if (_this.pollingInfo) {\n if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus) &&\n !((_b = (_a = _this.options).skipPollAttempt) === null || _b === void 0 ? void 0 : _b.call(_a))) {\n _this.reobserve({\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: _this.options.initialFetchPolicy === \"no-cache\" ?\n \"no-cache\"\n : \"network-only\",\n }, NetworkStatus.poll).then(poll, poll);\n }\n else {\n poll();\n }\n }\n };\n var poll = function () {\n var info = _this.pollingInfo;\n if (info) {\n clearTimeout(info.timeout);\n info.timeout = setTimeout(maybeFetch, info.interval);\n }\n };\n poll();\n };\n ObservableQuery.prototype.updateLastResult = function (newResult, variables) {\n if (variables === void 0) { variables = this.variables; }\n var error = 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 = __assign({ result: this.queryManager.assumeImmutableResults ?\n newResult\n : cloneDeep(newResult), variables: variables }, (error ? { error: error } : null)));\n };\n ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {\n var _this = this;\n this.isTornDown = false;\n var 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 // Save the old variables, since Object.assign may modify them below.\n var oldVariables = this.options.variables;\n var oldFetchPolicy = this.options.fetchPolicy;\n var mergedOptions = compact(this.options, newOptions || {});\n var options = 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 // 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 var query = this.transformDocument(options.query);\n this.lastQuery = query;\n if (!useDisposableConcast) {\n // We can skip calling updatePolling if we're not changing this.options.\n this.updatePolling();\n // Reset options.fetchPolicy to its original value when variables change,\n // unless a new fetchPolicy was provided by newOptions.\n if (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 this.applyNextFetchPolicy(\"variables-changed\", options);\n if (newNetworkStatus === void 0) {\n newNetworkStatus = NetworkStatus.setVariables;\n }\n }\n }\n this.waitForOwnResult && (this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy));\n var finishWaitingForOwnResult = function () {\n if (_this.concast === concast) {\n _this.waitForOwnResult = false;\n }\n };\n var variables = options.variables && __assign({}, options.variables);\n var _a = this.fetch(options, newNetworkStatus, query), concast = _a.concast, fromLink = _a.fromLink;\n var observer = {\n next: function (result) {\n if (equal(_this.variables, variables)) {\n finishWaitingForOwnResult();\n _this.reportResult(result, variables);\n }\n },\n error: function (error) {\n if (equal(_this.variables, variables)) {\n finishWaitingForOwnResult();\n _this.reportError(error, variables);\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 this.concast = concast;\n this.observer = observer;\n }\n concast.addObserver(observer);\n return concast;\n };\n ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {\n return this.reobserveAsConcast(newOptions, newNetworkStatus)\n .promise;\n };\n ObservableQuery.prototype.resubscribeAfterError = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\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 var last = this.last;\n this.resetLastResults();\n var subscription = this.subscribe.apply(this, args);\n this.last = last;\n return subscription;\n };\n // (Re)deliver the current result to this.observers without applying fetch\n // policies or making network requests.\n ObservableQuery.prototype.observe = function () {\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), this.variables);\n };\n ObservableQuery.prototype.reportResult = function (result, variables) {\n var lastError = this.getLastError();\n var 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 ObservableQuery.prototype.reportError = function (error, variables) {\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 var errorResult = __assign(__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false });\n this.updateLastResult(errorResult, variables);\n iterateObserversSafely(this.observers, \"error\", (this.last.error = error));\n };\n ObservableQuery.prototype.hasObservers = function () {\n return this.observers.size > 0;\n };\n ObservableQuery.prototype.tearDownQuery = function () {\n if (this.isTornDown)\n return;\n if (this.concast && this.observer) {\n this.concast.removeObserver(this.observer);\n delete this.concast;\n delete this.observer;\n }\n this.stopPolling();\n // stop all active GraphQL subscriptions\n this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });\n this.subscriptions.clear();\n this.queryManager.stopQuery(this.queryId);\n this.observers.clear();\n this.isTornDown = true;\n };\n ObservableQuery.prototype.transformDocument = function (document) {\n return this.queryManager.transform(document);\n };\n return ObservableQuery;\n}(Observable));\nexport { ObservableQuery };\n// Necessary because the ObservableQuery constructor has a different\n// signature than the Observable constructor.\nfixObservableSubclass(ObservableQuery);\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(obsQuery) {\n var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;\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: function (currentFetchPolicy, context) {\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 return obsQuery.reobserve();\n}\nfunction defaultSubscriptionObserverErrorCallback(error) {\n globalThis.__DEV__ !== false && invariant.error(23, error.message, error.stack);\n}\nexport function logMissingFieldErrors(missing) {\n if (globalThis.__DEV__ !== false && missing) {\n globalThis.__DEV__ !== false && invariant.debug(24, missing);\n }\n}\nfunction skipCacheDataFor(fetchPolicy /* `undefined` would mean `\"cache-first\"` */) {\n return (fetchPolicy === \"network-only\" ||\n fetchPolicy === \"no-cache\" ||\n fetchPolicy === \"standby\");\n}\n//# sourceMappingURL=ObservableQuery.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { invariant } from \"../utilities/globals/index.js\";\nimport { visit, BREAK, isSelectionNode } from \"graphql\";\nimport { argumentsObjectFromField, buildQueryFromSelectionSet, createFragmentMap, getFragmentDefinitions, getMainDefinition, hasDirectives, isField, isInlineFragment, mergeDeep, mergeDeepArray, removeClientSetsFromDocument, resultKeyNameFromField, shouldInclude, } from \"../utilities/index.js\";\nimport { cacheSlot } from \"../cache/index.js\";\nvar LocalState = /** @class */ (function () {\n function LocalState(_a) {\n var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;\n this.selectionsToResolveCache = new WeakMap();\n this.cache = cache;\n if (client) {\n this.client = client;\n }\n if (resolvers) {\n this.addResolvers(resolvers);\n }\n if (fragmentMatcher) {\n this.setFragmentMatcher(fragmentMatcher);\n }\n }\n LocalState.prototype.addResolvers = function (resolvers) {\n var _this = this;\n this.resolvers = this.resolvers || {};\n if (Array.isArray(resolvers)) {\n resolvers.forEach(function (resolverGroup) {\n _this.resolvers = mergeDeep(_this.resolvers, resolverGroup);\n });\n }\n else {\n this.resolvers = mergeDeep(this.resolvers, resolvers);\n }\n };\n LocalState.prototype.setResolvers = function (resolvers) {\n this.resolvers = {};\n this.addResolvers(resolvers);\n };\n LocalState.prototype.getResolvers = function () {\n return this.resolvers || {};\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 LocalState.prototype.runResolvers = function (_a) {\n return __awaiter(this, arguments, void 0, function (_b) {\n var document = _b.document, remoteResult = _b.remoteResult, context = _b.context, variables = _b.variables, _c = _b.onlyRunForcedResolvers, onlyRunForcedResolvers = _c === void 0 ? false : _c;\n return __generator(this, function (_d) {\n if (document) {\n return [2 /*return*/, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];\n }\n return [2 /*return*/, remoteResult];\n });\n });\n };\n LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {\n this.fragmentMatcher = fragmentMatcher;\n };\n LocalState.prototype.getFragmentMatcher = function () {\n return this.fragmentMatcher;\n };\n // Client queries contain everything in the incoming document (if a @client\n // directive is found).\n LocalState.prototype.clientQuery = function (document) {\n if (hasDirectives([\"client\"], document)) {\n if (this.resolvers) {\n return document;\n }\n }\n return null;\n };\n // Server queries are stripped of all @client based selection sets.\n LocalState.prototype.serverQuery = function (document) {\n return removeClientSetsFromDocument(document);\n };\n LocalState.prototype.prepareContext = function (context) {\n var cache = this.cache;\n return __assign(__assign({}, context), { cache: cache, \n // Getting an entry's cache key is useful for local state resolvers.\n getCacheKey: function (obj) {\n return cache.identify(obj);\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 LocalState.prototype.addExportedVariables = function (document_1) {\n return __awaiter(this, arguments, void 0, function (document, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (context === void 0) { context = {}; }\n return __generator(this, function (_a) {\n if (document) {\n return [2 /*return*/, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];\n }\n return [2 /*return*/, __assign({}, variables)];\n });\n });\n };\n LocalState.prototype.shouldForceResolvers = function (document) {\n var forceResolvers = false;\n visit(document, {\n Directive: {\n enter: function (node) {\n if (node.name.value === \"client\" && node.arguments) {\n forceResolvers = node.arguments.some(function (arg) {\n return 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 // Query the cache and return matching data.\n LocalState.prototype.buildRootValueFromCache = function (document, variables) {\n return this.cache.diff({\n query: buildQueryFromSelectionSet(document),\n variables: variables,\n returnPartialData: true,\n optimistic: false,\n }).result;\n };\n LocalState.prototype.resolveDocument = function (document_1, rootValue_1) {\n return __awaiter(this, arguments, void 0, function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {\n var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;\n if (context === void 0) { context = {}; }\n if (variables === void 0) { variables = {}; }\n if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }\n if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }\n return __generator(this, function (_b) {\n mainDefinition = getMainDefinition(document);\n fragments = getFragmentDefinitions(document);\n fragmentMap = createFragmentMap(fragments);\n selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);\n definitionOperation = mainDefinition.operation;\n defaultOperationType = definitionOperation ?\n definitionOperation.charAt(0).toUpperCase() +\n definitionOperation.slice(1)\n : \"Query\";\n _a = this, cache = _a.cache, client = _a.client;\n execContext = {\n fragmentMap: fragmentMap,\n context: __assign(__assign({}, context), { cache: cache, client: client }),\n variables: variables,\n fragmentMatcher: fragmentMatcher,\n defaultOperationType: defaultOperationType,\n exportedVariables: {},\n selectionsToResolve: selectionsToResolve,\n onlyRunForcedResolvers: onlyRunForcedResolvers,\n };\n isClientFieldDescendant = false;\n return [2 /*return*/, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({\n result: result,\n exportedVariables: execContext.exportedVariables,\n }); })];\n });\n });\n };\n LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {\n return __awaiter(this, void 0, void 0, function () {\n var fragmentMap, context, variables, resultsToMerge, execute;\n var _this = this;\n return __generator(this, function (_a) {\n fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;\n resultsToMerge = [rootValue];\n execute = function (selection) { return __awaiter(_this, void 0, void 0, function () {\n var fragment, typeCondition;\n return __generator(this, function (_a) {\n if (!isClientFieldDescendant &&\n !execContext.selectionsToResolve.has(selection)) {\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 [2 /*return*/];\n }\n if (!shouldInclude(selection, variables)) {\n // Skip this entirely.\n return [2 /*return*/];\n }\n if (isField(selection)) {\n return [2 /*return*/, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {\n var _a;\n if (typeof fieldResult !== \"undefined\") {\n resultsToMerge.push((_a = {},\n _a[resultKeyNameFromField(selection)] = fieldResult,\n _a));\n }\n })];\n }\n if (isInlineFragment(selection)) {\n fragment = selection;\n }\n else {\n // This is a named fragment.\n fragment = fragmentMap[selection.name.value];\n invariant(fragment, 18, selection.name.value);\n }\n if (fragment && fragment.typeCondition) {\n typeCondition = fragment.typeCondition.name.value;\n if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {\n return [2 /*return*/, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {\n resultsToMerge.push(fragmentResult);\n })];\n }\n }\n return [2 /*return*/];\n });\n }); };\n return [2 /*return*/, Promise.all(selectionSet.selections.map(execute)).then(function () {\n return mergeDeepArray(resultsToMerge);\n })];\n });\n });\n };\n LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {\n return __awaiter(this, void 0, void 0, function () {\n var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;\n var _this = this;\n return __generator(this, function (_a) {\n if (!rootValue) {\n return [2 /*return*/, null];\n }\n variables = execContext.variables;\n fieldName = field.name.value;\n aliasedFieldName = resultKeyNameFromField(field);\n aliasUsed = fieldName !== aliasedFieldName;\n defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];\n resultPromise = Promise.resolve(defaultResult);\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 (!execContext.onlyRunForcedResolvers ||\n this.shouldForceResolvers(field)) {\n resolverType = rootValue.__typename || execContext.defaultOperationType;\n resolverMap = this.resolvers && this.resolvers[resolverType];\n if (resolverMap) {\n 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: field, fragmentMap: execContext.fragmentMap },\n ]));\n }\n }\n }\n return [2 /*return*/, resultPromise.then(function (result) {\n var _a, _b;\n if (result === void 0) { 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(function (directive) {\n if (directive.name.value === \"export\" && directive.arguments) {\n directive.arguments.forEach(function (arg) {\n if (arg.name.value === \"as\" && arg.value.kind === \"StringValue\") {\n execContext.exportedVariables[arg.value.value] = result;\n }\n });\n }\n });\n }\n // Handle all scalar types here.\n if (!field.selectionSet) {\n return result;\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 var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === \"client\"; })) !== null && _b !== void 0 ? _b : false;\n if (Array.isArray(result)) {\n return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);\n }\n // Returned value is an object, and the query has a sub-selection. Recurse.\n if (field.selectionSet) {\n return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);\n }\n })];\n });\n });\n };\n LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {\n var _this = this;\n return Promise.all(result.map(function (item) {\n if (item === null) {\n return null;\n }\n // This is a nested array, recurse.\n if (Array.isArray(item)) {\n return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);\n }\n // This is an object, run the selection set on it.\n if (field.selectionSet) {\n return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);\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 LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {\n var isSingleASTNode = function (node) { return !Array.isArray(node); };\n var selectionsToResolveCache = this.selectionsToResolveCache;\n function collectByDefinition(definitionNode) {\n if (!selectionsToResolveCache.has(definitionNode)) {\n var matches_1 = new Set();\n selectionsToResolveCache.set(definitionNode, matches_1);\n visit(definitionNode, {\n Directive: function (node, _, __, ___, ancestors) {\n if (node.name.value === \"client\") {\n ancestors.forEach(function (node) {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches_1.add(node);\n }\n });\n }\n },\n FragmentSpread: function (spread, _, __, ___, ancestors) {\n var fragment = fragmentMap[spread.name.value];\n invariant(fragment, 19, spread.name.value);\n var 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(function (node) {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches_1.add(node);\n }\n });\n matches_1.add(spread);\n fragmentSelections.forEach(function (selection) {\n matches_1.add(selection);\n });\n }\n },\n });\n }\n return selectionsToResolveCache.get(definitionNode);\n }\n return collectByDefinition(mainDefinition);\n };\n return LocalState;\n}());\nexport { LocalState };\n//# sourceMappingURL=LocalState.js.map","import { __assign } from \"tslib\";\nimport { equal } from \"@wry/equality\";\nimport { DeepMerger } from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/index.js\";\nimport { reobserveCacheFirst } from \"./ObservableQuery.js\";\nimport { isNonEmptyArray, graphQLResultHasError, canUseWeakMap, } from \"../utilities/index.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nvar destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)();\nfunction wrapDestructiveCacheMethod(cache, methodName) {\n var 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(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 // @ts-expect-error this is just too generic to be typed correctly\n return original.apply(this, arguments);\n };\n }\n}\nfunction cancelNotifyTimeout(info) {\n if (info[\"notifyTimeout\"]) {\n clearTimeout(info[\"notifyTimeout\"]);\n info[\"notifyTimeout\"] = void 0;\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.\nvar QueryInfo = /** @class */ (function () {\n function QueryInfo(queryManager, queryId) {\n if (queryId === void 0) { queryId = queryManager.generateQueryId(); }\n this.queryId = queryId;\n this.listeners = new Set();\n this.document = null;\n this.lastRequestId = 1;\n this.stopped = false;\n this.dirty = false;\n this.observableQuery = null;\n var cache = (this.cache = queryManager.cache);\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 QueryInfo.prototype.init = function (query) {\n var networkStatus = query.networkStatus || NetworkStatus.loading;\n if (this.variables &&\n this.networkStatus !== NetworkStatus.loading &&\n !equal(this.variables, query.variables)) {\n networkStatus = NetworkStatus.setVariables;\n }\n if (!equal(query.variables, this.variables)) {\n this.lastDiff = void 0;\n }\n Object.assign(this, {\n document: query.document,\n variables: query.variables,\n networkError: null,\n graphQLErrors: this.graphQLErrors || [],\n networkStatus: networkStatus,\n });\n if (query.observableQuery) {\n this.setObservableQuery(query.observableQuery);\n }\n if (query.lastRequestId) {\n this.lastRequestId = query.lastRequestId;\n }\n return this;\n };\n QueryInfo.prototype.reset = function () {\n cancelNotifyTimeout(this);\n this.dirty = false;\n };\n QueryInfo.prototype.resetDiff = function () {\n this.lastDiff = void 0;\n };\n QueryInfo.prototype.getDiff = function () {\n var options = this.getDiffOptions();\n if (this.lastDiff && equal(options, this.lastDiff.options)) {\n return this.lastDiff.diff;\n }\n this.updateWatch(this.variables);\n var oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return { complete: false };\n }\n var diff = this.cache.diff(options);\n this.updateLastDiff(diff, options);\n return diff;\n };\n QueryInfo.prototype.updateLastDiff = function (diff, options) {\n this.lastDiff =\n diff ?\n {\n diff: diff,\n options: options || this.getDiffOptions(),\n }\n : void 0;\n };\n QueryInfo.prototype.getDiffOptions = function (variables) {\n var _a;\n if (variables === void 0) { variables = this.variables; }\n return {\n query: this.document,\n variables: variables,\n returnPartialData: true,\n optimistic: true,\n canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,\n };\n };\n QueryInfo.prototype.setDiff = function (diff) {\n var _this = this;\n var _a;\n var oldDiff = this.lastDiff && this.lastDiff.diff;\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 (diff &&\n !diff.complete &&\n !((_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.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 return;\n }\n this.updateLastDiff(diff);\n if (!this.dirty && !equal(oldDiff && oldDiff.result, diff && diff.result)) {\n this.dirty = true;\n if (!this.notifyTimeout) {\n this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);\n }\n }\n };\n QueryInfo.prototype.setObservableQuery = function (oq) {\n var _this = this;\n if (oq === this.observableQuery)\n return;\n if (this.oqListener) {\n this.listeners.delete(this.oqListener);\n }\n this.observableQuery = oq;\n if (oq) {\n oq[\"queryInfo\"] = this;\n this.listeners.add((this.oqListener = function () {\n var 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 }\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 QueryInfo.prototype.notify = function () {\n var _this = this;\n cancelNotifyTimeout(this);\n if (this.shouldNotify()) {\n this.listeners.forEach(function (listener) { return listener(_this); });\n }\n this.dirty = false;\n };\n QueryInfo.prototype.shouldNotify = function () {\n if (!this.dirty || !this.listeners.size) {\n return false;\n }\n if (isNetworkRequestInFlight(this.networkStatus) && this.observableQuery) {\n var fetchPolicy = this.observableQuery.options.fetchPolicy;\n if (fetchPolicy !== \"cache-only\" && fetchPolicy !== \"cache-and-network\") {\n return false;\n }\n }\n return true;\n };\n QueryInfo.prototype.stop = function () {\n if (!this.stopped) {\n this.stopped = true;\n // Cancel the pending notify timeout\n this.reset();\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 var oq = this.observableQuery;\n if (oq)\n oq.stopPolling();\n }\n };\n // This method is a no-op by default, until/unless overridden by the\n // updateWatch method.\n QueryInfo.prototype.cancel = function () { };\n QueryInfo.prototype.updateWatch = function (variables) {\n var _this = this;\n if (variables === void 0) { variables = this.variables; }\n var oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return;\n }\n var watchOptions = __assign(__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });\n if (!this.lastWatch || !equal(watchOptions, this.lastWatch)) {\n this.cancel();\n this.cancel = this.cache.watch((this.lastWatch = watchOptions));\n }\n };\n QueryInfo.prototype.resetLastWrite = function () {\n this.lastWrite = void 0;\n };\n QueryInfo.prototype.shouldWrite = function (result, variables) {\n var lastWrite = this.lastWrite;\n return !(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 QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {\n var _this = this;\n var merger = new DeepMerger();\n var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\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 if (\"incremental\" in result && isNonEmptyArray(result.incremental)) {\n var mergedData = mergeIncrementalData(this.getDiff().result, result);\n result.data = mergedData;\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 }\n else if (\"hasNext\" in result && result.hasNext) {\n var diff = this.getDiff();\n result.data = merger.merge(diff.result, result.data);\n }\n this.graphQLErrors = graphQLErrors;\n if (options.fetchPolicy === \"no-cache\") {\n this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));\n }\n else if (cacheWriteBehavior !== 0 /* 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(function (cache) {\n if (_this.shouldWrite(result, options.variables)) {\n cache.writeQuery({\n query: document,\n data: result.data,\n variables: options.variables,\n overwrite: cacheWriteBehavior === 1 /* CacheWriteBehavior.OVERWRITE */,\n });\n _this.lastWrite = {\n result: result,\n variables: options.variables,\n dmCount: destructiveMethodCounts.get(_this.cache),\n };\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 var diffOptions = _this.getDiffOptions(options.variables);\n var diff = cache.diff(diffOptions);\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 // 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 }\n else {\n this.lastWrite = void 0;\n }\n }\n };\n QueryInfo.prototype.markReady = function () {\n this.networkError = null;\n return (this.networkStatus = NetworkStatus.ready);\n };\n QueryInfo.prototype.markError = function (error) {\n this.networkStatus = NetworkStatus.error;\n this.lastWrite = void 0;\n this.reset();\n if (error.graphQLErrors) {\n this.graphQLErrors = error.graphQLErrors;\n }\n if (error.networkError) {\n this.networkError = error.networkError;\n }\n return error;\n };\n return QueryInfo;\n}());\nexport { QueryInfo };\nexport function shouldWriteResult(result, errorPolicy) {\n if (errorPolicy === void 0) { errorPolicy = \"none\"; }\n var ignoreErrors = errorPolicy === \"ignore\" || errorPolicy === \"all\";\n var writeWithErrors = !graphQLResultHasError(result);\n if (!writeWithErrors && ignoreErrors && result.data) {\n writeWithErrors = true;\n }\n return writeWithErrors;\n}\n//# sourceMappingURL=QueryInfo.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { invariant, newInvariantError } from \"../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { execute } from \"../link/core/index.js\";\nimport { hasDirectives, isExecutionPatchIncrementalResult, isExecutionPatchResult, removeDirectivesFromDocument, } from \"../utilities/index.js\";\nimport { canonicalStringify } from \"../cache/index.js\";\nimport { getDefaultValues, getOperationDefinition, getOperationName, hasClientExports, graphQLResultHasError, getGraphQLErrorsFromResult, Observable, asyncMap, isNonEmptyArray, Concast, makeUniqueId, isDocumentNode, isNonNullObject, DocumentTransform, } from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/common/incrementalResult.js\";\nimport { ApolloError, isApolloError, graphQLResultHasProtocolErrors, } from \"../errors/index.js\";\nimport { ObservableQuery, logMissingFieldErrors } from \"./ObservableQuery.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport { LocalState } from \"./LocalState.js\";\nimport { QueryInfo, shouldWriteResult, } from \"./QueryInfo.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../errors/index.js\";\nimport { print } from \"../utilities/index.js\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar IGNORE = Object.create(null);\nimport { Trie } from \"@wry/trie\";\nimport { AutoCleanedWeakCache, cacheSizes } from \"../utilities/index.js\";\nvar QueryManager = /** @class */ (function () {\n function QueryManager(_a) {\n var cache = _a.cache, link = _a.link, defaultOptions = _a.defaultOptions, documentTransform = _a.documentTransform, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, onBroadcast = _a.onBroadcast, _c = _a.ssrMode, ssrMode = _c === void 0 ? false : _c, _d = _a.clientAwareness, clientAwareness = _d === void 0 ? {} : _d, localState = _a.localState, _e = _a.assumeImmutableResults, assumeImmutableResults = _e === void 0 ? !!cache.assumeImmutableResults : _e, defaultContext = _a.defaultContext;\n var _this = this;\n this.clientAwareness = {};\n // All the queries that the QueryManager is currently managing (not\n // including mutations and subscriptions).\n this.queries = new Map();\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 this.fetchCancelFns = new Map();\n this.transformCache = new AutoCleanedWeakCache(cacheSizes[\"queryManager.getDocumentInfo\"] ||\n 2000 /* defaultCacheSizes[\"queryManager.getDocumentInfo\"] */);\n this.queryIdCounter = 1;\n this.requestIdCounter = 1;\n this.mutationIdCounter = 1;\n // Use protected instead of private field so\n // @apollo/experimental-nextjs-app-support can access type info.\n this.inFlightLinkObservables = new Trie(false);\n var defaultDocumentTransform = new DocumentTransform(function (document) { return _this.cache.transformDocument(document); }, \n // Allow the apollo cache to manage its own transform caches\n { cache: false });\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: 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 if ((this.onBroadcast = onBroadcast)) {\n this.mutationStore = Object.create(null);\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 QueryManager.prototype.stop = function () {\n var _this = this;\n this.queries.forEach(function (_info, queryId) {\n _this.stopQueryNoBroadcast(queryId);\n });\n this.cancelPendingFetches(newInvariantError(25));\n };\n QueryManager.prototype.cancelPendingFetches = function (error) {\n this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });\n this.fetchCancelFns.clear();\n };\n QueryManager.prototype.mutate = function (_a) {\n return __awaiter(this, arguments, void 0, function (_b) {\n var mutationId, hasClientExports, mutationStoreValue, isOptimistic, self;\n var _c, _d;\n var mutation = _b.mutation, variables = _b.variables, optimisticResponse = _b.optimisticResponse, updateQueries = _b.updateQueries, _e = _b.refetchQueries, refetchQueries = _e === void 0 ? [] : _e, _f = _b.awaitRefetchQueries, awaitRefetchQueries = _f === void 0 ? false : _f, updateWithProxyFn = _b.update, onQueryUpdated = _b.onQueryUpdated, _g = _b.fetchPolicy, fetchPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.fetchPolicy) || \"network-only\" : _g, _h = _b.errorPolicy, errorPolicy = _h === void 0 ? ((_d = this.defaultOptions.mutate) === null || _d === void 0 ? void 0 : _d.errorPolicy) || \"none\" : _h, keepRootFields = _b.keepRootFields, context = _b.context;\n return __generator(this, function (_j) {\n switch (_j.label) {\n case 0:\n invariant(mutation, 26);\n invariant(fetchPolicy === \"network-only\" || fetchPolicy === \"no-cache\", 27);\n mutationId = this.generateMutationId();\n mutation = this.cache.transformForLink(this.transform(mutation));\n hasClientExports = this.getDocumentInfo(mutation).hasClientExports;\n variables = this.getVariables(mutation, variables);\n if (!hasClientExports) return [3 /*break*/, 2];\n return [4 /*yield*/, this.localState.addExportedVariables(mutation, variables, context)];\n case 1:\n variables = (_j.sent());\n _j.label = 2;\n case 2:\n mutationStoreValue = this.mutationStore &&\n (this.mutationStore[mutationId] = {\n mutation: mutation,\n variables: variables,\n loading: true,\n error: null,\n });\n isOptimistic = optimisticResponse &&\n this.markMutationOptimistic(optimisticResponse, {\n mutationId: mutationId,\n document: mutation,\n variables: variables,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n context: context,\n updateQueries: updateQueries,\n update: updateWithProxyFn,\n keepRootFields: keepRootFields,\n });\n this.broadcastQueries();\n self = this;\n return [2 /*return*/, new Promise(function (resolve, reject) {\n return asyncMap(self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: isOptimistic ? optimisticResponse : void 0 }), variables, false), function (result) {\n if (graphQLResultHasError(result) && errorPolicy === \"none\") {\n throw new ApolloError({\n graphQLErrors: getGraphQLErrorsFromResult(result),\n });\n }\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = null;\n }\n var storeResult = __assign({}, result);\n if (typeof refetchQueries === \"function\") {\n refetchQueries = refetchQueries(storeResult);\n }\n if (errorPolicy === \"ignore\" && graphQLResultHasError(storeResult)) {\n delete storeResult.errors;\n }\n return self.markMutationResult({\n mutationId: mutationId,\n result: storeResult,\n document: mutation,\n variables: variables,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n context: context,\n update: updateWithProxyFn,\n updateQueries: updateQueries,\n awaitRefetchQueries: awaitRefetchQueries,\n refetchQueries: refetchQueries,\n removeOptimistic: isOptimistic ? mutationId : void 0,\n onQueryUpdated: onQueryUpdated,\n keepRootFields: keepRootFields,\n });\n }).subscribe({\n next: function (storeResult) {\n self.broadcastQueries();\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 error: function (err) {\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = err;\n }\n if (isOptimistic) {\n self.cache.removeOptimistic(mutationId);\n }\n self.broadcastQueries();\n reject(err instanceof ApolloError ? err : (new ApolloError({\n networkError: err,\n })));\n },\n });\n })];\n }\n });\n });\n };\n QueryManager.prototype.markMutationResult = function (mutation, cache) {\n var _this = this;\n if (cache === void 0) { cache = this.cache; }\n var result = mutation.result;\n var cacheWrites = [];\n var skipCache = mutation.fetchPolicy === \"no-cache\";\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 (isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)) {\n var diff = cache.diff({\n id: \"ROOT_MUTATION\",\n // The cache complains if passed a mutation where it expects a\n // query, so we transform mutations and subscriptions to queries\n // (only once, thanks to this.transformCache).\n query: this.getDocumentInfo(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n var mergedData = void 0;\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.data = mergedData;\n cacheWrites.push({\n result: mergedData,\n dataId: \"ROOT_MUTATION\",\n query: mutation.document,\n variables: mutation.variables,\n });\n }\n }\n var updateQueries_1 = mutation.updateQueries;\n if (updateQueries_1) {\n this.queries.forEach(function (_a, queryId) {\n var observableQuery = _a.observableQuery;\n var queryName = observableQuery && observableQuery.queryName;\n if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {\n return;\n }\n var updater = updateQueries_1[queryName];\n var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;\n // Read the current query result from the store.\n var _c = cache.diff({\n query: document,\n variables: variables,\n returnPartialData: true,\n optimistic: false,\n }), currentQueryResult = _c.result, complete = _c.complete;\n if (complete && currentQueryResult) {\n // Run our reducer using the current query result and the mutation result.\n var nextQueryResult = updater(currentQueryResult, {\n mutationResult: result,\n queryName: (document && getOperationName(document)) || void 0,\n queryVariables: variables,\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: variables,\n });\n }\n }\n });\n }\n }\n if (cacheWrites.length > 0 ||\n (mutation.refetchQueries || \"\").length > 0 ||\n mutation.update ||\n mutation.onQueryUpdated ||\n mutation.removeOptimistic) {\n var results_1 = [];\n this.refetchQueries({\n updateCache: function (cache) {\n if (!skipCache) {\n cacheWrites.forEach(function (write) { return cache.write(write); });\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 var update = mutation.update;\n // Determine whether result is a SingleExecutionResult,\n // or the final ExecutionPatchResult.\n var isFinalResult = !isExecutionPatchResult(result) ||\n (isExecutionPatchIncrementalResult(result) && !result.hasNext);\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 var diff = cache.diff({\n id: \"ROOT_MUTATION\",\n // The cache complains if passed a mutation where it expects a\n // query, so we transform mutations and subscriptions to queries\n // (only once, thanks to this.transformCache).\n query: _this.getDocumentInfo(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n if (diff.complete) {\n result = __assign(__assign({}, result), { 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 // 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, result, {\n context: mutation.context,\n variables: mutation.variables,\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: function (value, _a) {\n var fieldName = _a.fieldName, DELETE = _a.DELETE;\n return fieldName === \"__typename\" ? value : DELETE;\n },\n });\n }\n },\n include: mutation.refetchQueries,\n // Write the final mutation.result to the root layer of the cache.\n optimistic: false,\n // Remove the corresponding optimistic layer at the same time as we\n // write the final non-optimistic result.\n removeOptimistic: mutation.removeOptimistic,\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(function (result) { return results_1.push(result); });\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_1).then(function () { return result; });\n }\n }\n return Promise.resolve(result);\n };\n QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {\n var _this = this;\n var data = typeof optimisticResponse === \"function\" ?\n optimisticResponse(mutation.variables, { IGNORE: IGNORE })\n : optimisticResponse;\n if (data === IGNORE) {\n return false;\n }\n this.cache.recordOptimisticTransaction(function (cache) {\n try {\n _this.markMutationResult(__assign(__assign({}, mutation), { result: { data: data } }), cache);\n }\n catch (error) {\n globalThis.__DEV__ !== false && invariant.error(error);\n }\n }, mutation.mutationId);\n return true;\n };\n QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {\n return this.fetchConcastWithInfo(queryId, options, networkStatus).concast\n .promise;\n };\n QueryManager.prototype.getQueryStore = function () {\n var store = Object.create(null);\n this.queries.forEach(function (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 QueryManager.prototype.resetErrors = function (queryId) {\n var queryInfo = this.queries.get(queryId);\n if (queryInfo) {\n queryInfo.networkError = undefined;\n queryInfo.graphQLErrors = [];\n }\n };\n QueryManager.prototype.transform = function (document) {\n return this.documentTransform.transformDocument(document);\n };\n QueryManager.prototype.getDocumentInfo = function (document) {\n var transformCache = this.transformCache;\n if (!transformCache.has(document)) {\n var cacheEntry = {\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 { name: \"client\", remove: true },\n { name: \"connection\" },\n { name: \"nonreactive\" },\n ], document),\n defaultVars: getDefaultValues(getOperationDefinition(document)),\n // Transform any mutation or subscription operations to query operations\n // so we can read/write them from/to the cache.\n asQuery: __assign(__assign({}, document), { definitions: document.definitions.map(function (def) {\n if (def.kind === \"OperationDefinition\" &&\n def.operation !== \"query\") {\n return __assign(__assign({}, def), { operation: \"query\" });\n }\n return def;\n }) }),\n };\n transformCache.set(document, cacheEntry);\n }\n return transformCache.get(document);\n };\n QueryManager.prototype.getVariables = function (document, variables) {\n return __assign(__assign({}, this.getDocumentInfo(document).defaultVars), variables);\n };\n QueryManager.prototype.watchQuery = function (options) {\n var query = this.transform(options.query);\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 = __assign(__assign({}, options), { variables: this.getVariables(query, options.variables) });\n if (typeof options.notifyOnNetworkStatusChange === \"undefined\") {\n options.notifyOnNetworkStatusChange = false;\n }\n var queryInfo = new QueryInfo(this);\n var observable = new ObservableQuery({\n queryManager: this,\n queryInfo: queryInfo,\n options: options,\n });\n observable[\"lastQuery\"] = query;\n this.queries.set(observable.queryId, queryInfo);\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 return observable;\n };\n QueryManager.prototype.query = function (options, queryId) {\n var _this = this;\n if (queryId === void 0) { queryId = this.generateQueryId(); }\n invariant(options.query, 28);\n invariant(options.query.kind === \"Document\", 29);\n invariant(!options.returnPartialData, 30);\n invariant(!options.pollInterval, 31);\n return this.fetchQuery(queryId, __assign(__assign({}, options), { query: this.transform(options.query) })).finally(function () { return _this.stopQuery(queryId); });\n };\n QueryManager.prototype.generateQueryId = function () {\n return String(this.queryIdCounter++);\n };\n QueryManager.prototype.generateRequestId = function () {\n return this.requestIdCounter++;\n };\n QueryManager.prototype.generateMutationId = function () {\n return String(this.mutationIdCounter++);\n };\n QueryManager.prototype.stopQueryInStore = function (queryId) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.broadcastQueries();\n };\n QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {\n var queryInfo = this.queries.get(queryId);\n if (queryInfo)\n queryInfo.stop();\n };\n QueryManager.prototype.clearStore = function (options) {\n if (options === void 0) { options = {\n discardWatches: true,\n }; }\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(newInvariantError(32));\n this.queries.forEach(function (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 }\n else {\n queryInfo.stop();\n }\n });\n if (this.mutationStore) {\n this.mutationStore = Object.create(null);\n }\n // begin removing data from the store\n return this.cache.reset(options);\n };\n QueryManager.prototype.getObservableQueries = function (include) {\n var _this = this;\n if (include === void 0) { include = \"active\"; }\n var queries = new Map();\n var queryNamesAndDocs = new Map();\n var legacyQueryOptions = new Set();\n if (Array.isArray(include)) {\n include.forEach(function (desc) {\n if (typeof desc === \"string\") {\n queryNamesAndDocs.set(desc, false);\n }\n else if (isDocumentNode(desc)) {\n queryNamesAndDocs.set(_this.transform(desc), false);\n }\n else if (isNonNullObject(desc) && desc.query) {\n legacyQueryOptions.add(desc);\n }\n });\n }\n this.queries.forEach(function (_a, queryId) {\n var oq = _a.observableQuery, document = _a.document;\n if (oq) {\n if (include === \"all\") {\n queries.set(queryId, oq);\n return;\n }\n var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;\n if (fetchPolicy === \"standby\" ||\n (include === \"active\" && !oq.hasObservers())) {\n return;\n }\n if (include === \"active\" ||\n (queryName && queryNamesAndDocs.has(queryName)) ||\n (document && queryNamesAndDocs.has(document))) {\n queries.set(queryId, oq);\n if (queryName)\n queryNamesAndDocs.set(queryName, true);\n if (document)\n queryNamesAndDocs.set(document, true);\n }\n }\n });\n if (legacyQueryOptions.size) {\n legacyQueryOptions.forEach(function (options) {\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 var queryId = makeUniqueId(\"legacyOneTimeQuery\");\n var queryInfo = _this.getQuery(queryId).init({\n document: options.query,\n variables: options.variables,\n });\n var oq = new ObservableQuery({\n queryManager: _this,\n queryInfo: queryInfo,\n options: __assign(__assign({}, options), { fetchPolicy: \"network-only\" }),\n });\n invariant(oq.queryId === queryId);\n queryInfo.setObservableQuery(oq);\n queries.set(queryId, oq);\n });\n }\n if (globalThis.__DEV__ !== false && queryNamesAndDocs.size) {\n queryNamesAndDocs.forEach(function (included, nameOrDoc) {\n if (!included) {\n globalThis.__DEV__ !== false && invariant.warn(typeof nameOrDoc === \"string\" ? 33 : 34, nameOrDoc);\n }\n });\n }\n return queries;\n };\n QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {\n var _this = this;\n if (includeStandby === void 0) { includeStandby = false; }\n var observableQueryPromises = [];\n this.getObservableQueries(includeStandby ? \"all\" : \"active\").forEach(function (observableQuery, queryId) {\n var fetchPolicy = observableQuery.options.fetchPolicy;\n observableQuery.resetLastResults();\n if (includeStandby ||\n (fetchPolicy !== \"standby\" && fetchPolicy !== \"cache-only\")) {\n observableQueryPromises.push(observableQuery.refetch());\n }\n _this.getQuery(queryId).setDiff(null);\n });\n this.broadcastQueries();\n return Promise.all(observableQueryPromises);\n };\n QueryManager.prototype.setObservableQuery = function (observableQuery) {\n this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);\n };\n QueryManager.prototype.startGraphQLSubscription = function (_a) {\n var _this = this;\n var query = _a.query, fetchPolicy = _a.fetchPolicy, _b = _a.errorPolicy, errorPolicy = _b === void 0 ? \"none\" : _b, variables = _a.variables, _c = _a.context, context = _c === void 0 ? {} : _c;\n query = this.transform(query);\n variables = this.getVariables(query, variables);\n var makeObservable = function (variables) {\n return _this.getObservableFromLink(query, context, variables).map(function (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: query,\n result: result.data,\n dataId: \"ROOT_SUBSCRIPTION\",\n variables: variables,\n });\n }\n _this.broadcastQueries();\n }\n var hasErrors = graphQLResultHasError(result);\n var hasProtocolErrors = graphQLResultHasProtocolErrors(result);\n if (hasErrors || hasProtocolErrors) {\n var errors = {};\n if (hasErrors) {\n errors.graphQLErrors = result.errors;\n }\n if (hasProtocolErrors) {\n errors.protocolErrors = result.extensions[PROTOCOL_ERRORS_SYMBOL];\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 if (errorPolicy === \"ignore\") {\n delete result.errors;\n }\n return result;\n });\n };\n if (this.getDocumentInfo(query).hasClientExports) {\n var observablePromise_1 = this.localState\n .addExportedVariables(query, variables, context)\n .then(makeObservable);\n return new Observable(function (observer) {\n var sub = null;\n observablePromise_1.then(function (observable) { return (sub = observable.subscribe(observer)); }, observer.error);\n return function () { return sub && sub.unsubscribe(); };\n });\n }\n return makeObservable(variables);\n };\n QueryManager.prototype.stopQuery = function (queryId) {\n this.stopQueryNoBroadcast(queryId);\n this.broadcastQueries();\n };\n QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.removeQuery(queryId);\n };\n QueryManager.prototype.removeQuery = function (queryId) {\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 QueryManager.prototype.broadcastQueries = function () {\n if (this.onBroadcast)\n this.onBroadcast();\n this.queries.forEach(function (info) { return info.notify(); });\n };\n QueryManager.prototype.getLocalState = function () {\n return this.localState;\n };\n QueryManager.prototype.getObservableFromLink = function (query, context, variables, \n // Prefer context.queryDeduplication if specified.\n deduplication) {\n var _this = this;\n var _a;\n if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }\n var observable;\n var _b = this.getDocumentInfo(query), serverQuery = _b.serverQuery, clientQuery = _b.clientQuery;\n if (serverQuery) {\n var _c = this, inFlightLinkObservables_1 = _c.inFlightLinkObservables, link = _c.link;\n var operation = {\n query: serverQuery,\n variables: variables,\n operationName: getOperationName(serverQuery) || void 0,\n context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),\n };\n context = operation.context;\n if (deduplication) {\n var printedServerQuery_1 = print(serverQuery);\n var varJson_1 = canonicalStringify(variables);\n var entry = inFlightLinkObservables_1.lookup(printedServerQuery_1, varJson_1);\n observable = entry.observable;\n if (!observable) {\n var concast = new Concast([\n execute(link, operation),\n ]);\n observable = entry.observable = concast;\n concast.beforeNext(function () {\n inFlightLinkObservables_1.remove(printedServerQuery_1, varJson_1);\n });\n }\n }\n else {\n observable = new Concast([\n execute(link, operation),\n ]);\n }\n }\n else {\n observable = new Concast([Observable.of({ data: {} })]);\n context = this.prepareContext(context);\n }\n if (clientQuery) {\n observable = asyncMap(observable, function (result) {\n return _this.localState.runResolvers({\n document: clientQuery,\n remoteResult: result,\n context: context,\n variables: variables,\n });\n });\n }\n return observable;\n };\n QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {\n var requestId = (queryInfo.lastRequestId = this.generateRequestId());\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 var linkDocument = this.cache.transformForLink(options.query);\n return asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {\n var graphQLErrors = getGraphQLErrorsFromResult(result);\n var hasErrors = graphQLErrors.length > 0;\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(new ApolloError({\n graphQLErrors: graphQLErrors,\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(result, linkDocument, options, cacheWriteBehavior);\n queryInfo.markReady();\n }\n var aqr = {\n data: result.data,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n if (hasErrors && options.errorPolicy !== \"ignore\") {\n aqr.errors = graphQLErrors;\n aqr.networkStatus = NetworkStatus.error;\n }\n return aqr;\n }, function (networkError) {\n var error = isApolloError(networkError) ? networkError : (new ApolloError({ networkError: networkError }));\n // Avoid storing errors from older interrupted queries.\n if (requestId >= queryInfo.lastRequestId) {\n queryInfo.markError(error);\n }\n throw error;\n });\n };\n QueryManager.prototype.fetchConcastWithInfo = function (queryId, options, \n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus, query) {\n var _this = this;\n if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }\n if (query === void 0) { query = options.query; }\n var variables = this.getVariables(query, options.variables);\n var queryInfo = this.getQuery(queryId);\n var defaults = this.defaultOptions.watchQuery;\n var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? (defaults && defaults.fetchPolicy) || \"cache-first\" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? (defaults && defaults.errorPolicy) || \"none\" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;\n var normalized = Object.assign({}, options, {\n query: query,\n variables: variables,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n returnPartialData: returnPartialData,\n notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,\n context: context,\n });\n var fromVariables = function (variables) {\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 var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);\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 queryInfo.observableQuery[\"applyNextFetchPolicy\"](\"after-fetch\", options);\n }\n return sourcesWithInfo;\n };\n // This cancel function needs to be set before the concast is created,\n // in case concast creation synchronously cancels the request.\n var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };\n this.fetchCancelFns.set(queryId, function (reason) {\n cleanupCancelFn();\n // This delay ensures the concast variable has been initialized.\n setTimeout(function () { return concast.cancel(reason); });\n });\n var concast, containsDataFromLink;\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(this.localState\n .addExportedVariables(normalized.query, normalized.variables, normalized.context)\n .then(fromVariables)\n .then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));\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 }\n else {\n var sourcesWithInfo = fromVariables(normalized.variables);\n containsDataFromLink = sourcesWithInfo.fromLink;\n concast = new Concast(sourcesWithInfo.sources);\n }\n concast.promise.then(cleanupCancelFn, cleanupCancelFn);\n return {\n concast: concast,\n fromLink: containsDataFromLink,\n };\n };\n QueryManager.prototype.refetchQueries = function (_a) {\n var _this = this;\n var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? makeUniqueId(\"refetchQueries\") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;\n var includedQueriesById = new Map();\n if (include) {\n this.getObservableQueries(include).forEach(function (oq, queryId) {\n includedQueriesById.set(queryId, {\n oq: oq,\n lastDiff: _this.getQuery(queryId).getDiff(),\n });\n });\n }\n var results = new Map();\n if (updateCache) {\n this.cache.batch({\n update: updateCache,\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 // 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: removeOptimistic,\n onWatchUpdated: function (watch, diff, lastDiff) {\n var oq = watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;\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 var result = onQueryUpdated(oq, diff, lastDiff);\n if (result === true) {\n // The onQueryUpdated function requested the default refetching\n // behavior by returning true.\n result = oq.refetch();\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(oq, result);\n }\n // Allow the default cache broadcast to happen, except when\n // onQueryUpdated returns false.\n return result;\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: oq, lastDiff: lastDiff, diff: diff });\n }\n }\n },\n });\n }\n if (includedQueriesById.size) {\n includedQueriesById.forEach(function (_a, queryId) {\n var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;\n var result;\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 var 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 // Otherwise, we fall back to refetching.\n if (!onQueryUpdated || result === true) {\n result = oq.refetch();\n }\n if (result !== false) {\n results.set(oq, result);\n }\n if (queryId.indexOf(\"legacyOneTimeQuery\") >= 0) {\n _this.stopQueryNoBroadcast(queryId);\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 return results;\n };\n QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a, \n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus) {\n var _this = this;\n var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;\n var oldNetworkStatus = queryInfo.networkStatus;\n queryInfo.init({\n document: query,\n variables: variables,\n networkStatus: networkStatus,\n });\n var readCache = function () { return queryInfo.getDiff(); };\n var resultsFromCache = function (diff, networkStatus) {\n if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }\n var data = diff.result;\n if (globalThis.__DEV__ !== false && !returnPartialData && !equal(data, {})) {\n logMissingFieldErrors(diff.missing);\n }\n var fromData = function (data) {\n return Observable.of(__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true })));\n };\n if (data && _this.getDocumentInfo(query).hasForcedResolvers) {\n return _this.localState\n .runResolvers({\n document: query,\n remoteResult: { data: data },\n context: context,\n variables: variables,\n onlyRunForcedResolvers: true,\n })\n .then(function (resolved) { return fromData(resolved.data || void 0); });\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 (errorPolicy === \"none\" &&\n networkStatus === NetworkStatus.refetch &&\n Array.isArray(diff.missing)) {\n return fromData(void 0);\n }\n return fromData(data);\n };\n var cacheWriteBehavior = fetchPolicy === \"no-cache\" ? 0 /* CacheWriteBehavior.FORBID */\n // Watched queries must opt into overwriting existing data on refetch,\n // by passing refetchWritePolicy: \"overwrite\" in their WatchQueryOptions.\n : (networkStatus === NetworkStatus.refetch &&\n refetchWritePolicy !== \"merge\") ?\n 1 /* CacheWriteBehavior.OVERWRITE */\n : 2 /* CacheWriteBehavior.MERGE */;\n var resultsFromLink = function () {\n return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {\n query: query,\n variables: variables,\n context: context,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n });\n };\n var shouldNotify = notifyOnNetworkStatusChange &&\n typeof oldNetworkStatus === \"number\" &&\n oldNetworkStatus !== networkStatus &&\n isNetworkRequestInFlight(networkStatus);\n switch (fetchPolicy) {\n default:\n case \"cache-first\": {\n var diff = readCache();\n if (diff.complete) {\n return {\n fromLink: false,\n sources: [resultsFromCache(diff, queryInfo.markReady())],\n };\n }\n if (returnPartialData || shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(diff), resultsFromLink()],\n };\n }\n return { fromLink: true, sources: [resultsFromLink()] };\n }\n case \"cache-and-network\": {\n var diff = readCache();\n if (diff.complete || returnPartialData || shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(diff), resultsFromLink()],\n };\n }\n return { fromLink: true, sources: [resultsFromLink()] };\n }\n case \"cache-only\":\n return {\n fromLink: false,\n sources: [resultsFromCache(readCache(), queryInfo.markReady())],\n };\n case \"network-only\":\n if (shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(readCache()), resultsFromLink()],\n };\n }\n return { fromLink: true, sources: [resultsFromLink()] };\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 return { fromLink: true, sources: [resultsFromLink()] };\n case \"standby\":\n return { fromLink: false, sources: [] };\n }\n };\n QueryManager.prototype.getQuery = function (queryId) {\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 QueryManager.prototype.prepareContext = function (context) {\n if (context === void 0) { context = {}; }\n var newContext = this.localState.prepareContext(context);\n return __assign(__assign(__assign({}, this.defaultContext), newContext), { clientAwareness: this.clientAwareness });\n };\n return QueryManager;\n}());\nexport { QueryManager };\n//# sourceMappingURL=QueryManager.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../utilities/globals/index.js\";\nimport { ApolloLink, execute } from \"../link/core/index.js\";\nimport { version } from \"../version.js\";\nimport { HttpLink } from \"../link/http/index.js\";\nimport { QueryManager } from \"./QueryManager.js\";\nimport { LocalState } from \"./LocalState.js\";\nvar hasSuggestedDevtools = false;\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\";\nexport { mergeOptions };\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 */\nvar ApolloClient = /** @class */ (function () {\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 function ApolloClient(options) {\n var _this = this;\n this.resetStoreCallbacks = [];\n this.clearStoreCallbacks = [];\n if (!options.cache) {\n throw newInvariantError(15);\n }\n var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, documentTransform = options.documentTransform, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, \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 _c = options.connectToDevTools, \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 = _c === void 0 ? typeof window === \"object\" &&\n !window.__APOLLO_CLIENT__ &&\n globalThis.__DEV__ !== false : _c, _d = options.queryDeduplication, queryDeduplication = _d === void 0 ? true : _d, defaultOptions = options.defaultOptions, defaultContext = options.defaultContext, _e = options.assumeImmutableResults, assumeImmutableResults = _e === void 0 ? cache.assumeImmutableResults : _e, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version;\n var link = options.link;\n if (!link) {\n link =\n uri ? new HttpLink({ uri: uri, credentials: credentials, headers: headers }) : ApolloLink.empty();\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 if (ssrForceFetchDelay) {\n setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);\n }\n this.watchQuery = this.watchQuery.bind(this);\n this.query = this.query.bind(this);\n this.mutate = this.mutate.bind(this);\n this.resetStore = this.resetStore.bind(this);\n this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);\n this.version = version;\n this.localState = new LocalState({\n cache: cache,\n client: this,\n resolvers: resolvers,\n fragmentMatcher: fragmentMatcher,\n });\n this.queryManager = new QueryManager({\n cache: this.cache,\n link: this.link,\n defaultOptions: this.defaultOptions,\n defaultContext: defaultContext,\n documentTransform: documentTransform,\n queryDeduplication: queryDeduplication,\n ssrMode: ssrMode,\n clientAwareness: {\n name: clientAwarenessName,\n version: clientAwarenessVersion,\n },\n localState: this.localState,\n assumeImmutableResults: assumeImmutableResults,\n onBroadcast: connectToDevTools ?\n function () {\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 if (connectToDevTools)\n this.connectToDevTools();\n }\n ApolloClient.prototype.connectToDevTools = function () {\n if (typeof window === \"object\") {\n var windowWithDevTools = window;\n var devtoolsSymbol = Symbol.for(\"apollo.devtools\");\n (windowWithDevTools[devtoolsSymbol] =\n windowWithDevTools[devtoolsSymbol] || []).push(this);\n windowWithDevTools.__APOLLO_CLIENT__ = this;\n }\n /**\n * Suggest installing the devtools for developers who don't have them\n */\n if (!hasSuggestedDevtools && globalThis.__DEV__ !== false) {\n hasSuggestedDevtools = true;\n setTimeout(function () {\n if (typeof window !== \"undefined\" &&\n window.document &&\n window.top === window.self &&\n !window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {\n var nav = window.navigator;\n var ua = nav && nav.userAgent;\n var url = void 0;\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 }\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 globalThis.__DEV__ !== false && invariant.log(\"Download the Apollo DevTools for a better development \" +\n \"experience: %s\", url);\n }\n }\n }, 10000);\n }\n };\n Object.defineProperty(ApolloClient.prototype, \"documentTransform\", {\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: function () {\n return this.queryManager.documentTransform;\n },\n enumerable: false,\n configurable: true\n });\n /**\n * Call this method to terminate any active client processes, making it safe\n * to dispose of this `ApolloClient` instance.\n */\n ApolloClient.prototype.stop = function () {\n this.queryManager.stop();\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 a GraphQL 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 ApolloClient.prototype.watchQuery = function (options) {\n if (this.defaultOptions.watchQuery) {\n options = mergeOptions(this.defaultOptions.watchQuery, options);\n }\n // XXX Overwriting options is probably not the best way to do this long term...\n if (this.disableNetworkFetches &&\n (options.fetchPolicy === \"network-only\" ||\n options.fetchPolicy === \"cache-and-network\")) {\n options = __assign(__assign({}, options), { fetchPolicy: \"cache-first\" });\n }\n return this.queryManager.watchQuery(options);\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 ApolloClient.prototype.query = function (options) {\n if (this.defaultOptions.query) {\n options = mergeOptions(this.defaultOptions.query, options);\n }\n invariant(options.fetchPolicy !== \"cache-and-network\", 16);\n if (this.disableNetworkFetches && options.fetchPolicy === \"network-only\") {\n options = __assign(__assign({}, options), { fetchPolicy: \"cache-first\" });\n }\n return this.queryManager.query(options);\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 ApolloClient.prototype.mutate = function (options) {\n if (this.defaultOptions.mutate) {\n options = mergeOptions(this.defaultOptions.mutate, options);\n }\n return this.queryManager.mutate(options);\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 ApolloClient.prototype.subscribe = function (options) {\n return this.queryManager.startGraphQLSubscription(options);\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 ApolloClient.prototype.readQuery = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = false; }\n return this.cache.readQuery(options, optimistic);\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 ApolloClient.prototype.readFragment = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = false; }\n return this.cache.readFragment(options, optimistic);\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 ApolloClient.prototype.writeQuery = function (options) {\n var ref = this.cache.writeQuery(options);\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n return ref;\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 ApolloClient.prototype.writeFragment = function (options) {\n var ref = this.cache.writeFragment(options);\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n return ref;\n };\n ApolloClient.prototype.__actionHookForDevTools = function (cb) {\n this.devToolsHookCb = cb;\n };\n ApolloClient.prototype.__requestRaw = function (payload) {\n return execute(this.link, payload);\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 ApolloClient.prototype.resetStore = function () {\n var _this = this;\n return Promise.resolve()\n .then(function () {\n return _this.queryManager.clearStore({\n discardWatches: false,\n });\n })\n .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })\n .then(function () { return _this.reFetchObservableQueries(); });\n };\n /**\n * Remove all data from the store. Unlike `resetStore`, `clearStore` will\n * not refetch any active queries.\n */\n ApolloClient.prototype.clearStore = function () {\n var _this = this;\n return Promise.resolve()\n .then(function () {\n return _this.queryManager.clearStore({\n discardWatches: true,\n });\n })\n .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });\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 ApolloClient.prototype.onResetStore = function (cb) {\n var _this = this;\n this.resetStoreCallbacks.push(cb);\n return function () {\n _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });\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 ApolloClient.prototype.onClearStore = function (cb) {\n var _this = this;\n this.clearStoreCallbacks.push(cb);\n return function () {\n _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });\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 ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {\n return this.queryManager.reFetchObservableQueries(includeStandby);\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 ApolloClient.prototype.refetchQueries = function (options) {\n var map = this.queryManager.refetchQueries(options);\n var queries = [];\n var results = [];\n map.forEach(function (result, obsQuery) {\n queries.push(obsQuery);\n results.push(result);\n });\n var result = Promise.all(results);\n // In case you need the raw results immediately, without awaiting\n // Promise.all(results):\n result.queries = queries;\n result.results = results;\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(function (error) {\n globalThis.__DEV__ !== false && invariant.debug(17, error);\n });\n return result;\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 ApolloClient.prototype.getObservableQueries = function (include) {\n if (include === void 0) { include = \"active\"; }\n return this.queryManager.getObservableQueries(include);\n };\n /**\n * Exposes the cache's complete state, in a serializable format for later restoration.\n */\n ApolloClient.prototype.extract = function (optimistic) {\n return this.cache.extract(optimistic);\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 ApolloClient.prototype.restore = function (serializedState) {\n return this.cache.restore(serializedState);\n };\n /**\n * Add additional local resolvers.\n */\n ApolloClient.prototype.addResolvers = function (resolvers) {\n this.localState.addResolvers(resolvers);\n };\n /**\n * Set (override existing) local resolvers.\n */\n ApolloClient.prototype.setResolvers = function (resolvers) {\n this.localState.setResolvers(resolvers);\n };\n /**\n * Get all registered local resolvers.\n */\n ApolloClient.prototype.getResolvers = function () {\n return this.localState.getResolvers();\n };\n /**\n * Set a custom local state fragment matcher.\n */\n ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {\n this.localState.setFragmentMatcher(fragmentMatcher);\n };\n /**\n * Define a new ApolloLink (or link chain) that Apollo Client will use.\n */\n ApolloClient.prototype.setLink = function (newLink) {\n this.link = this.queryManager.link = newLink;\n };\n Object.defineProperty(ApolloClient.prototype, \"defaultContext\", {\n get: function () {\n return this.queryManager.defaultContext;\n },\n enumerable: false,\n configurable: true\n });\n return ApolloClient;\n}());\nexport { ApolloClient };\nif (globalThis.__DEV__ !== false) {\n ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;\n}\n//# sourceMappingURL=ApolloClient.js.map","import { __assign } from \"tslib\";\nimport { parse } from 'graphql';\nvar docCache = new Map();\nvar fragmentSourceMap = new Map();\nvar printFragmentWarnings = true;\nvar experimentalFragmentVariables = false;\nfunction normalize(string) {\n return string.replace(/[\\s,]+/g, ' ').trim();\n}\nfunction cacheKeyFromLoc(loc) {\n return normalize(loc.source.body.substring(loc.start, loc.end));\n}\nfunction processFragments(ast) {\n var seenKeys = new Set();\n var definitions = [];\n ast.definitions.forEach(function (fragmentDefinition) {\n if (fragmentDefinition.kind === 'FragmentDefinition') {\n var fragmentName = fragmentDefinition.name.value;\n var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);\n var sourceKeySet = fragmentSourceMap.get(fragmentName);\n if (sourceKeySet && !sourceKeySet.has(sourceKey)) {\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 }\n else if (!sourceKeySet) {\n fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);\n }\n sourceKeySet.add(sourceKey);\n if (!seenKeys.has(sourceKey)) {\n seenKeys.add(sourceKey);\n definitions.push(fragmentDefinition);\n }\n }\n else {\n definitions.push(fragmentDefinition);\n }\n });\n return __assign(__assign({}, ast), { definitions: definitions });\n}\nfunction stripLoc(doc) {\n var workSet = new Set(doc.definitions);\n workSet.forEach(function (node) {\n if (node.loc)\n delete node.loc;\n Object.keys(node).forEach(function (key) {\n var value = node[key];\n if (value && typeof value === 'object') {\n workSet.add(value);\n }\n });\n });\n var loc = doc.loc;\n if (loc) {\n delete loc.startToken;\n delete loc.endToken;\n }\n return doc;\n}\nfunction parseDocument(source) {\n var cacheKey = normalize(source);\n if (!docCache.has(cacheKey)) {\n var parsed = parse(source, {\n experimentalFragmentVariables: experimentalFragmentVariables,\n allowLegacyFragmentVariables: experimentalFragmentVariables\n });\n if (!parsed || parsed.kind !== 'Document') {\n throw new Error('Not a valid GraphQL document.');\n }\n docCache.set(cacheKey, stripLoc(processFragments(parsed)));\n }\n return docCache.get(cacheKey);\n}\nexport function gql(literals) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (typeof literals === 'string') {\n literals = [literals];\n }\n var result = literals[0];\n args.forEach(function (arg, i) {\n if (arg && arg.kind === 'Document') {\n result += arg.loc.source.body;\n }\n else {\n result += arg;\n }\n result += literals[i + 1];\n });\n return parseDocument(result);\n}\nexport function resetCaches() {\n docCache.clear();\n fragmentSourceMap.clear();\n}\nexport function disableFragmentWarnings() {\n printFragmentWarnings = false;\n}\nexport function enableExperimentalFragmentVariables() {\n experimentalFragmentVariables = true;\n}\nexport function disableExperimentalFragmentVariables() {\n experimentalFragmentVariables = false;\n}\nvar extras = {\n gql: gql,\n resetCaches: resetCaches,\n disableFragmentWarnings: disableFragmentWarnings,\n enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables: disableExperimentalFragmentVariables\n};\n(function (gql_1) {\n gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;\n})(gql || (gql = {}));\ngql[\"default\"] = gql;\nexport default gql;\n//# sourceMappingURL=index.js.map","/* Core */\nexport { ApolloClient, mergeOptions } from \"./ApolloClient.js\";\nexport { ObservableQuery } from \"./ObservableQuery.js\";\nexport { NetworkStatus, isNetworkRequestSettled } from \"./networkStatus.js\";\nexport * from \"./types.js\";\nexport { isApolloError, ApolloError } from \"../errors/index.js\";\nexport { Cache, ApolloCache, InMemoryCache, MissingFieldError, defaultDataIdFromObject, makeVar, } from \"../cache/index.js\";\nexport * from \"../cache/inmemory/types.js\";\n/* Link */\nexport * from \"../link/core/index.js\";\nexport * from \"../link/http/index.js\";\nexport { fromError, toPromise, fromPromise, throwServerError, } from \"../link/utils/index.js\";\nexport { DocumentTransform, Observable, isReference, makeReference, } from \"../utilities/index.js\";\n/* Supporting */\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(globalThis.__DEV__ !== false ? \"log\" : \"silent\");\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 { gql, resetCaches, disableFragmentWarnings, enableExperimentalFragmentVariables, disableExperimentalFragmentVariables, } from \"graphql-tag\";\n//# sourceMappingURL=index.js.map","\n export interface PossibleTypesResultData {\n possibleTypes: {\n [key: string]: string[]\n }\n }\n const result: PossibleTypesResultData = {\n \"possibleTypes\": {\n \"Node\": [\n \"Chunk\",\n \"File\",\n \"GptChatCompletion\",\n \"GptChatMessage\",\n \"Image\",\n \"Quote\",\n \"Segment\",\n \"Thread\",\n \"User\",\n \"V0Chunk\",\n \"V0Session\"\n ],\n \"Upload\": [\n \"File\",\n \"Image\"\n ]\n }\n};\n export default result;\n ","import { relayStylePagination } from \"@apollo/client/utilities\";\n\nimport type { StrictTypedTypePolicies } from \"./clientHelpers.generated\";\nimport introspection from \"./introspection.generated\";\n\nexport const typePolicies: StrictTypedTypePolicies = {\n Query: {\n fields: {\n v0_sessions: relayStylePagination(),\n },\n },\n User: {\n fields: {\n threads: relayStylePagination(),\n },\n },\n Segment: {\n fields: {\n responseCompletions: relayStylePagination(),\n },\n },\n};\n\nexport const { possibleTypes } = introspection;\n","import { __rest } from \"tslib\";\nimport { ApolloLink } from \"../core/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nexport function setContext(setter) {\n return new ApolloLink(function (operation, forward) {\n var request = __rest(operation, []);\n return new Observable(function (observer) {\n var handle;\n var closed = false;\n Promise.resolve(request)\n .then(function (req) { return setter(req, operation.getContext()); })\n .then(operation.setContext)\n .then(function () {\n // if the observer is already closed, no need to subscribe.\n if (closed)\n return;\n handle = forward(operation).subscribe({\n next: observer.next.bind(observer),\n error: observer.error.bind(observer),\n complete: observer.complete.bind(observer),\n });\n })\n .catch(observer.error.bind(observer));\n return function () {\n closed = true;\n if (handle)\n handle.unsubscribe();\n };\n });\n });\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core_1 = require(\"@apollo/client/core\");\nconst graphql_1 = require(\"graphql\");\nclass ActionCableLink extends core_1.ApolloLink {\n constructor(options) {\n super();\n this.cable = options.cable;\n this.channelName = options.channelName || \"GraphqlChannel\";\n this.actionName = options.actionName || \"execute\";\n this.connectionParams = options.connectionParams || {};\n }\n // Interestingly, this link does _not_ call through to `next` because\n // instead, it sends the request to ActionCable.\n request(operation, _next) {\n return new core_1.Observable((observer) => {\n var channelId = Math.round(Date.now() + Math.random() * 100000).toString(16);\n var actionName = this.actionName;\n var connectionParams = (typeof this.connectionParams === \"function\") ?\n this.connectionParams(operation) : this.connectionParams;\n var channel = this.cable.subscriptions.create(Object.assign({}, {\n channel: this.channelName,\n channelId: channelId\n }, connectionParams), {\n connected: function () {\n this.perform(actionName, {\n query: operation.query ? (0, graphql_1.print)(operation.query) : null,\n variables: operation.variables,\n // This is added for persisted operation support:\n operationId: operation.operationId,\n operationName: operation.operationName\n });\n },\n received: function (payload) {\n var _a, _b;\n if (((_a = payload === null || payload === void 0 ? void 0 : payload.result) === null || _a === void 0 ? void 0 : _a.data) || ((_b = payload === null || payload === void 0 ? void 0 : payload.result) === null || _b === void 0 ? void 0 : _b.errors)) {\n observer.next(payload.result);\n }\n if (!payload.more) {\n observer.complete();\n }\n }\n });\n // Make the ActionCable subscription behave like an Apollo subscription\n return Object.assign(channel, { closed: false });\n });\n }\n}\nexports.default = ActionCableLink;\n","var adapters = {\n logger: typeof console !== \"undefined\" ? console : undefined,\n WebSocket: typeof WebSocket !== \"undefined\" ? WebSocket : undefined\n};\n\nvar logger = {\n log(...messages) {\n if (this.enabled) {\n messages.push(Date.now());\n adapters.logger.log(\"[ActionCable]\", ...messages);\n }\n }\n};\n\nconst now = () => (new Date).getTime();\n\nconst secondsSince = time => (now() - time) / 1e3;\n\nclass ConnectionMonitor {\n constructor(connection) {\n this.visibilityDidChange = this.visibilityDidChange.bind(this);\n this.connection = connection;\n this.reconnectAttempts = 0;\n }\n start() {\n if (!this.isRunning()) {\n this.startedAt = now();\n delete this.stoppedAt;\n this.startPolling();\n addEventListener(\"visibilitychange\", this.visibilityDidChange);\n logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`);\n }\n }\n stop() {\n if (this.isRunning()) {\n this.stoppedAt = now();\n this.stopPolling();\n removeEventListener(\"visibilitychange\", this.visibilityDidChange);\n logger.log(\"ConnectionMonitor stopped\");\n }\n }\n isRunning() {\n return this.startedAt && !this.stoppedAt;\n }\n recordPing() {\n this.pingedAt = now();\n }\n recordConnect() {\n this.reconnectAttempts = 0;\n this.recordPing();\n delete this.disconnectedAt;\n logger.log(\"ConnectionMonitor recorded connect\");\n }\n recordDisconnect() {\n this.disconnectedAt = now();\n logger.log(\"ConnectionMonitor recorded disconnect\");\n }\n startPolling() {\n this.stopPolling();\n this.poll();\n }\n stopPolling() {\n clearTimeout(this.pollTimeout);\n }\n poll() {\n this.pollTimeout = setTimeout((() => {\n this.reconnectIfStale();\n this.poll();\n }), this.getPollInterval());\n }\n getPollInterval() {\n const {staleThreshold: staleThreshold, reconnectionBackoffRate: reconnectionBackoffRate} = this.constructor;\n const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10));\n const jitterMax = this.reconnectAttempts === 0 ? 1 : reconnectionBackoffRate;\n const jitter = jitterMax * Math.random();\n return staleThreshold * 1e3 * backoff * (1 + jitter);\n }\n reconnectIfStale() {\n if (this.connectionIsStale()) {\n logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`);\n this.reconnectAttempts++;\n if (this.disconnectedRecently()) {\n logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`);\n } else {\n logger.log(\"ConnectionMonitor reopening\");\n this.connection.reopen();\n }\n }\n }\n get refreshedAt() {\n return this.pingedAt ? this.pingedAt : this.startedAt;\n }\n connectionIsStale() {\n return secondsSince(this.refreshedAt) > this.constructor.staleThreshold;\n }\n disconnectedRecently() {\n return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;\n }\n visibilityDidChange() {\n if (document.visibilityState === \"visible\") {\n setTimeout((() => {\n if (this.connectionIsStale() || !this.connection.isOpen()) {\n logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`);\n this.connection.reopen();\n }\n }), 200);\n }\n }\n}\n\nConnectionMonitor.staleThreshold = 6;\n\nConnectionMonitor.reconnectionBackoffRate = .15;\n\nvar INTERNAL = {\n message_types: {\n welcome: \"welcome\",\n disconnect: \"disconnect\",\n ping: \"ping\",\n confirmation: \"confirm_subscription\",\n rejection: \"reject_subscription\"\n },\n disconnect_reasons: {\n unauthorized: \"unauthorized\",\n invalid_request: \"invalid_request\",\n server_restart: \"server_restart\",\n remote: \"remote\"\n },\n default_mount_path: \"/cable\",\n protocols: [ \"actioncable-v1-json\", \"actioncable-unsupported\" ]\n};\n\nconst {message_types: message_types, protocols: protocols} = INTERNAL;\n\nconst supportedProtocols = protocols.slice(0, protocols.length - 1);\n\nconst indexOf = [].indexOf;\n\nclass Connection {\n constructor(consumer) {\n this.open = this.open.bind(this);\n this.consumer = consumer;\n this.subscriptions = this.consumer.subscriptions;\n this.monitor = new ConnectionMonitor(this);\n this.disconnected = true;\n }\n send(data) {\n if (this.isOpen()) {\n this.webSocket.send(JSON.stringify(data));\n return true;\n } else {\n return false;\n }\n }\n open() {\n if (this.isActive()) {\n logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`);\n return false;\n } else {\n const socketProtocols = [ ...protocols, ...this.consumer.subprotocols || [] ];\n logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`);\n if (this.webSocket) {\n this.uninstallEventHandlers();\n }\n this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols);\n this.installEventHandlers();\n this.monitor.start();\n return true;\n }\n }\n close({allowReconnect: allowReconnect} = {\n allowReconnect: true\n }) {\n if (!allowReconnect) {\n this.monitor.stop();\n }\n if (this.isOpen()) {\n return this.webSocket.close();\n }\n }\n reopen() {\n logger.log(`Reopening WebSocket, current state is ${this.getState()}`);\n if (this.isActive()) {\n try {\n return this.close();\n } catch (error) {\n logger.log(\"Failed to reopen WebSocket\", error);\n } finally {\n logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`);\n setTimeout(this.open, this.constructor.reopenDelay);\n }\n } else {\n return this.open();\n }\n }\n getProtocol() {\n if (this.webSocket) {\n return this.webSocket.protocol;\n }\n }\n isOpen() {\n return this.isState(\"open\");\n }\n isActive() {\n return this.isState(\"open\", \"connecting\");\n }\n triedToReconnect() {\n return this.monitor.reconnectAttempts > 0;\n }\n isProtocolSupported() {\n return indexOf.call(supportedProtocols, this.getProtocol()) >= 0;\n }\n isState(...states) {\n return indexOf.call(states, this.getState()) >= 0;\n }\n getState() {\n if (this.webSocket) {\n for (let state in adapters.WebSocket) {\n if (adapters.WebSocket[state] === this.webSocket.readyState) {\n return state.toLowerCase();\n }\n }\n }\n return null;\n }\n installEventHandlers() {\n for (let eventName in this.events) {\n const handler = this.events[eventName].bind(this);\n this.webSocket[`on${eventName}`] = handler;\n }\n }\n uninstallEventHandlers() {\n for (let eventName in this.events) {\n this.webSocket[`on${eventName}`] = function() {};\n }\n }\n}\n\nConnection.reopenDelay = 500;\n\nConnection.prototype.events = {\n message(event) {\n if (!this.isProtocolSupported()) {\n return;\n }\n const {identifier: identifier, message: message, reason: reason, reconnect: reconnect, type: type} = JSON.parse(event.data);\n switch (type) {\n case message_types.welcome:\n if (this.triedToReconnect()) {\n this.reconnectAttempted = true;\n }\n this.monitor.recordConnect();\n return this.subscriptions.reload();\n\n case message_types.disconnect:\n logger.log(`Disconnecting. Reason: ${reason}`);\n return this.close({\n allowReconnect: reconnect\n });\n\n case message_types.ping:\n return this.monitor.recordPing();\n\n case message_types.confirmation:\n this.subscriptions.confirmSubscription(identifier);\n if (this.reconnectAttempted) {\n this.reconnectAttempted = false;\n return this.subscriptions.notify(identifier, \"connected\", {\n reconnected: true\n });\n } else {\n return this.subscriptions.notify(identifier, \"connected\", {\n reconnected: false\n });\n }\n\n case message_types.rejection:\n return this.subscriptions.reject(identifier);\n\n default:\n return this.subscriptions.notify(identifier, \"received\", message);\n }\n },\n open() {\n logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`);\n this.disconnected = false;\n if (!this.isProtocolSupported()) {\n logger.log(\"Protocol is unsupported. Stopping monitor and disconnecting.\");\n return this.close({\n allowReconnect: false\n });\n }\n },\n close(event) {\n logger.log(\"WebSocket onclose event\");\n if (this.disconnected) {\n return;\n }\n this.disconnected = true;\n this.monitor.recordDisconnect();\n return this.subscriptions.notifyAll(\"disconnected\", {\n willAttemptReconnect: this.monitor.isRunning()\n });\n },\n error() {\n logger.log(\"WebSocket onerror event\");\n }\n};\n\nconst extend = function(object, properties) {\n if (properties != null) {\n for (let key in properties) {\n const value = properties[key];\n object[key] = value;\n }\n }\n return object;\n};\n\nclass Subscription {\n constructor(consumer, params = {}, mixin) {\n this.consumer = consumer;\n this.identifier = JSON.stringify(params);\n extend(this, mixin);\n }\n perform(action, data = {}) {\n data.action = action;\n return this.send(data);\n }\n send(data) {\n return this.consumer.send({\n command: \"message\",\n identifier: this.identifier,\n data: JSON.stringify(data)\n });\n }\n unsubscribe() {\n return this.consumer.subscriptions.remove(this);\n }\n}\n\nclass SubscriptionGuarantor {\n constructor(subscriptions) {\n this.subscriptions = subscriptions;\n this.pendingSubscriptions = [];\n }\n guarantee(subscription) {\n if (this.pendingSubscriptions.indexOf(subscription) == -1) {\n logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`);\n this.pendingSubscriptions.push(subscription);\n } else {\n logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`);\n }\n this.startGuaranteeing();\n }\n forget(subscription) {\n logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`);\n this.pendingSubscriptions = this.pendingSubscriptions.filter((s => s !== subscription));\n }\n startGuaranteeing() {\n this.stopGuaranteeing();\n this.retrySubscribing();\n }\n stopGuaranteeing() {\n clearTimeout(this.retryTimeout);\n }\n retrySubscribing() {\n this.retryTimeout = setTimeout((() => {\n if (this.subscriptions && typeof this.subscriptions.subscribe === \"function\") {\n this.pendingSubscriptions.map((subscription => {\n logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`);\n this.subscriptions.subscribe(subscription);\n }));\n }\n }), 500);\n }\n}\n\nclass Subscriptions {\n constructor(consumer) {\n this.consumer = consumer;\n this.guarantor = new SubscriptionGuarantor(this);\n this.subscriptions = [];\n }\n create(channelName, mixin) {\n const channel = channelName;\n const params = typeof channel === \"object\" ? channel : {\n channel: channel\n };\n const subscription = new Subscription(this.consumer, params, mixin);\n return this.add(subscription);\n }\n add(subscription) {\n this.subscriptions.push(subscription);\n this.consumer.ensureActiveConnection();\n this.notify(subscription, \"initialized\");\n this.subscribe(subscription);\n return subscription;\n }\n remove(subscription) {\n this.forget(subscription);\n if (!this.findAll(subscription.identifier).length) {\n this.sendCommand(subscription, \"unsubscribe\");\n }\n return subscription;\n }\n reject(identifier) {\n return this.findAll(identifier).map((subscription => {\n this.forget(subscription);\n this.notify(subscription, \"rejected\");\n return subscription;\n }));\n }\n forget(subscription) {\n this.guarantor.forget(subscription);\n this.subscriptions = this.subscriptions.filter((s => s !== subscription));\n return subscription;\n }\n findAll(identifier) {\n return this.subscriptions.filter((s => s.identifier === identifier));\n }\n reload() {\n return this.subscriptions.map((subscription => this.subscribe(subscription)));\n }\n notifyAll(callbackName, ...args) {\n return this.subscriptions.map((subscription => this.notify(subscription, callbackName, ...args)));\n }\n notify(subscription, callbackName, ...args) {\n let subscriptions;\n if (typeof subscription === \"string\") {\n subscriptions = this.findAll(subscription);\n } else {\n subscriptions = [ subscription ];\n }\n return subscriptions.map((subscription => typeof subscription[callbackName] === \"function\" ? subscription[callbackName](...args) : undefined));\n }\n subscribe(subscription) {\n if (this.sendCommand(subscription, \"subscribe\")) {\n this.guarantor.guarantee(subscription);\n }\n }\n confirmSubscription(identifier) {\n logger.log(`Subscription confirmed ${identifier}`);\n this.findAll(identifier).map((subscription => this.guarantor.forget(subscription)));\n }\n sendCommand(subscription, command) {\n const {identifier: identifier} = subscription;\n return this.consumer.send({\n command: command,\n identifier: identifier\n });\n }\n}\n\nclass Consumer {\n constructor(url) {\n this._url = url;\n this.subscriptions = new Subscriptions(this);\n this.connection = new Connection(this);\n this.subprotocols = [];\n }\n get url() {\n return createWebSocketURL(this._url);\n }\n send(data) {\n return this.connection.send(data);\n }\n connect() {\n return this.connection.open();\n }\n disconnect() {\n return this.connection.close({\n allowReconnect: false\n });\n }\n ensureActiveConnection() {\n if (!this.connection.isActive()) {\n return this.connection.open();\n }\n }\n addSubProtocol(subprotocol) {\n this.subprotocols = [ ...this.subprotocols, subprotocol ];\n }\n}\n\nfunction createWebSocketURL(url) {\n if (typeof url === \"function\") {\n url = url();\n }\n if (url && !/^wss?:/i.test(url)) {\n const a = document.createElement(\"a\");\n a.href = url;\n a.href = a.href;\n a.protocol = a.protocol.replace(\"http\", \"ws\");\n return a.href;\n } else {\n return url;\n }\n}\n\nfunction createConsumer(url = getConfig(\"url\") || INTERNAL.default_mount_path) {\n return new Consumer(url);\n}\n\nfunction getConfig(name) {\n const element = document.head.querySelector(`meta[name='action-cable-${name}']`);\n if (element) {\n return element.getAttribute(\"content\");\n }\n}\n\nexport { Connection, ConnectionMonitor, Consumer, INTERNAL, Subscription, SubscriptionGuarantor, Subscriptions, adapters, createConsumer, createWebSocketURL, getConfig, logger };\n","import { createConsumer } from \"@rails/actioncable\";\n\nexport const getCable = () => createConsumer();\n","// import type { ServerError } from \"@apollo/client\";\nimport { ApolloLink, HttpLink, from, split } from \"@apollo/client\";\n\nimport { setContext } from \"@apollo/client/link/context\";\n// import { RetryLink } from \"@apollo/client/link/retry\";\nimport { getOperationDefinition } from \"@apollo/client/utilities\";\n\nimport ActionCableLink from \"graphql-ruby-client/subscriptions/ActionCableLink\";\n\nimport { getCable } from \"~/helpers/actioncable\";\nimport { requireMeta } from \"~/helpers/meta\";\n\nexport type ClientLinkOptions = {\n readonly initialCSRFToken: string;\n};\n\nexport const createClientLink = ({\n initialCSRFToken,\n}: ClientLinkOptions): ApolloLink => {\n return from([\n // new RetryLink({\n // attempts: {\n // retryIf: (error: ApolloError) => {\n // if (error.name === \"ServerError\") {\n // const { statusCode } = error as ServerError;\n // if (statusCode === 500) {\n // return false;\n // }\n // }\n // return true;\n // },\n // },\n // }),\n createCSRFLink(initialCSRFToken),\n createTerminatingLink(),\n ]);\n};\n\nconst createTerminatingLink = (): ApolloLink => {\n const httpLink = createHttpLink();\n return createSubscriptionsLink(httpLink);\n};\n\nconst createHttpLink = () => {\n const uri = requireMeta(\"graphql-url\");\n return new HttpLink({ uri });\n};\n\nconst createSubscriptionsLink = (link: ApolloLink): ApolloLink => {\n const cableLink = new ActionCableLink({\n cable: getCable(),\n channelName: \"GraphQLChannel\",\n });\n return split(\n ({ query }) => {\n const { operation } = getOperationDefinition(query) || {};\n return operation === \"subscription\";\n },\n cableLink,\n link,\n );\n};\n\nconst createCSRFLink = (initialToken: string): ApolloLink => {\n return setContext(async (operation, { headers }) => {\n const currentToken = getMeta(\"csrf-token\");\n if (!import.meta.env.SSR && !currentToken) {\n console.warn(\"No client-side CSRF token found\");\n }\n return {\n headers: {\n ...headers,\n [\"X-CSRF-Token\"]: currentToken ?? initialToken,\n },\n };\n });\n};\n","import { empty as emptyLink } from \"@apollo/client\";\nimport type { ApolloLink } from \"@apollo/client\";\n\nimport { createClientLink } from \"~/helpers/apollo/clientLink?client\";\n\nexport type ApolloLinkOptions = {\n readonly initialCSRFToken: string;\n};\n\nexport const createApolloLink = ({\n initialCSRFToken,\n}: ApolloLinkOptions): ApolloLink => {\n return import.meta.env.SSR\n ? emptyLink()\n : createClientLink({ initialCSRFToken });\n};\n","import { MantineBreakpoint } from \"@mantine/core\";\nimport { createContext } from \"react\";\n\nexport type NavbarContext = {\n opened: boolean;\n open: () => void;\n close: () => void;\n toggle: () => void;\n};\n\nexport const NavbarContext = createContext({\n opened: false,\n open: () => {},\n close: () => {},\n toggle: () => {},\n});\n\nexport const useNavbar = (): NavbarContext => useContext(NavbarContext);\n\nexport const NAVBAR_VISIBILITY_BREAKPOINT: MantineBreakpoint = \"sm\";\n","// these aren't really private, but nor are they really useful to document\n\n/**\n * @private\n */\nclass LuxonError extends Error {}\n\n/**\n * @private\n */\nexport class InvalidDateTimeError extends LuxonError {\n constructor(reason) {\n super(`Invalid DateTime: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidIntervalError extends LuxonError {\n constructor(reason) {\n super(`Invalid Interval: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidDurationError extends LuxonError {\n constructor(reason) {\n super(`Invalid Duration: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class ConflictingSpecificationError extends LuxonError {}\n\n/**\n * @private\n */\nexport class InvalidUnitError extends LuxonError {\n constructor(unit) {\n super(`Invalid unit ${unit}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidArgumentError extends LuxonError {}\n\n/**\n * @private\n */\nexport class ZoneIsAbstractError extends LuxonError {\n constructor() {\n super(\"Zone is an abstract class\");\n }\n}\n","/**\n * @private\n */\n\nconst n = \"numeric\",\n s = \"short\",\n l = \"long\";\n\nexport const DATE_SHORT = {\n year: n,\n month: n,\n day: n,\n};\n\nexport const DATE_MED = {\n year: n,\n month: s,\n day: n,\n};\n\nexport const DATE_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n};\n\nexport const DATE_FULL = {\n year: n,\n month: l,\n day: n,\n};\n\nexport const DATE_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n};\n\nexport const TIME_SIMPLE = {\n hour: n,\n minute: n,\n};\n\nexport const TIME_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const TIME_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const TIME_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n\nexport const TIME_24_SIMPLE = {\n hour: n,\n minute: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: s,\n};\n\nexport const TIME_24_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: l,\n};\n\nexport const DATETIME_SHORT = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_SHORT_WITH_SECONDS = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_MED_WITH_SECONDS = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_FULL = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_FULL_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n timeZoneName: l,\n};\n\nexport const DATETIME_HUGE_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n","import { ZoneIsAbstractError } from \"./errors.js\";\n\n/**\n * @interface\n */\nexport default class Zone {\n /**\n * The type of zone\n * @abstract\n * @type {string}\n */\n get type() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * The name of this zone.\n * @abstract\n * @type {string}\n */\n get name() {\n throw new ZoneIsAbstractError();\n }\n\n get ianaName() {\n return this.name;\n }\n\n /**\n * Returns whether the offset is known to be fixed for the whole year.\n * @abstract\n * @type {boolean}\n */\n get isUniversal() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's common name (such as EST) at the specified timestamp\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the name\n * @param {Object} opts - Options to affect the format\n * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n * @param {string} opts.locale - What locale to return the offset name in.\n * @return {string}\n */\n offsetName(ts, opts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's value as a string\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\n formatOffset(ts, format) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return the offset in minutes for this zone at the specified timestamp.\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to compute the offset\n * @return {number}\n */\n offset(ts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is equal to another zone\n * @abstract\n * @param {Zone} otherZone - the zone to compare\n * @return {boolean}\n */\n equals(otherZone) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is valid.\n * @abstract\n * @type {boolean}\n */\n get isValid() {\n throw new ZoneIsAbstractError();\n }\n}\n","import { formatOffset, parseZoneInfo } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * Represents the local zone for this JavaScript environment.\n * @implements {Zone}\n */\nexport default class SystemZone extends Zone {\n /**\n * Get a singleton instance of the local zone\n * @return {SystemZone}\n */\n static get instance() {\n if (singleton === null) {\n singleton = new SystemZone();\n }\n return singleton;\n }\n\n /** @override **/\n get type() {\n return \"system\";\n }\n\n /** @override **/\n get name() {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale);\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /** @override **/\n offset(ts) {\n return -new Date(ts).getTimezoneOffset();\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"system\";\n }\n\n /** @override **/\n get isValid() {\n return true;\n }\n}\n","import { formatOffset, parseZoneInfo, isUndefined, objToLocalTS } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet dtfCache = {};\nfunction makeDTF(zone) {\n if (!dtfCache[zone]) {\n dtfCache[zone] = new Intl.DateTimeFormat(\"en-US\", {\n hour12: false,\n timeZone: zone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n era: \"short\",\n });\n }\n return dtfCache[zone];\n}\n\nconst typeToPos = {\n year: 0,\n month: 1,\n day: 2,\n era: 3,\n hour: 4,\n minute: 5,\n second: 6,\n};\n\nfunction hackyOffset(dtf, date) {\n const formatted = dtf.format(date).replace(/\\u200E/g, \"\"),\n parsed = /(\\d+)\\/(\\d+)\\/(\\d+) (AD|BC),? (\\d+):(\\d+):(\\d+)/.exec(formatted),\n [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;\n return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];\n}\n\nfunction partsOffset(dtf, date) {\n const formatted = dtf.formatToParts(date);\n const filled = [];\n for (let i = 0; i < formatted.length; i++) {\n const { type, value } = formatted[i];\n const pos = typeToPos[type];\n\n if (type === \"era\") {\n filled[pos] = value;\n } else if (!isUndefined(pos)) {\n filled[pos] = parseInt(value, 10);\n }\n }\n return filled;\n}\n\nlet ianaZoneCache = {};\n/**\n * A zone identified by an IANA identifier, like America/New_York\n * @implements {Zone}\n */\nexport default class IANAZone extends Zone {\n /**\n * @param {string} name - Zone name\n * @return {IANAZone}\n */\n static create(name) {\n if (!ianaZoneCache[name]) {\n ianaZoneCache[name] = new IANAZone(name);\n }\n return ianaZoneCache[name];\n }\n\n /**\n * Reset local caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCache() {\n ianaZoneCache = {};\n dtfCache = {};\n }\n\n /**\n * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.\n * @param {string} s - The string to check validity on\n * @example IANAZone.isValidSpecifier(\"America/New_York\") //=> true\n * @example IANAZone.isValidSpecifier(\"Sport~~blorp\") //=> false\n * @deprecated This method returns false for some valid IANA names. Use isValidZone instead.\n * @return {boolean}\n */\n static isValidSpecifier(s) {\n return this.isValidZone(s);\n }\n\n /**\n * Returns whether the provided string identifies a real zone\n * @param {string} zone - The string to check\n * @example IANAZone.isValidZone(\"America/New_York\") //=> true\n * @example IANAZone.isValidZone(\"Fantasia/Castle\") //=> false\n * @example IANAZone.isValidZone(\"Sport~~blorp\") //=> false\n * @return {boolean}\n */\n static isValidZone(zone) {\n if (!zone) {\n return false;\n }\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone }).format();\n return true;\n } catch (e) {\n return false;\n }\n }\n\n constructor(name) {\n super();\n /** @private **/\n this.zoneName = name;\n /** @private **/\n this.valid = IANAZone.isValidZone(name);\n }\n\n /** @override **/\n get type() {\n return \"iana\";\n }\n\n /** @override **/\n get name() {\n return this.zoneName;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale, this.name);\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /** @override **/\n offset(ts) {\n const date = new Date(ts);\n\n if (isNaN(date)) return NaN;\n\n const dtf = makeDTF(this.name);\n let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts\n ? partsOffset(dtf, date)\n : hackyOffset(dtf, date);\n\n if (adOrBc === \"BC\") {\n year = -Math.abs(year) + 1;\n }\n\n // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat\n const adjustedHour = hour === 24 ? 0 : hour;\n\n const asUTC = objToLocalTS({\n year,\n month,\n day,\n hour: adjustedHour,\n minute,\n second,\n millisecond: 0,\n });\n\n let asTS = +date;\n const over = asTS % 1000;\n asTS -= over >= 0 ? over : 1000 + over;\n return (asUTC - asTS) / (60 * 1000);\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"iana\" && otherZone.name === this.name;\n }\n\n /** @override **/\n get isValid() {\n return this.valid;\n }\n}\n","import { hasLocaleWeekInfo, hasRelative, padStart, roundTo, validateWeekSettings } from \"./util.js\";\nimport * as English from \"./english.js\";\nimport Settings from \"../settings.js\";\nimport DateTime from \"../datetime.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n// todo - remap caching\n\nlet intlLFCache = {};\nfunction getCachedLF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlLFCache[key];\n if (!dtf) {\n dtf = new Intl.ListFormat(locString, opts);\n intlLFCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlDTCache = {};\nfunction getCachedDTF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlDTCache[key];\n if (!dtf) {\n dtf = new Intl.DateTimeFormat(locString, opts);\n intlDTCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlNumCache = {};\nfunction getCachedINF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let inf = intlNumCache[key];\n if (!inf) {\n inf = new Intl.NumberFormat(locString, opts);\n intlNumCache[key] = inf;\n }\n return inf;\n}\n\nlet intlRelCache = {};\nfunction getCachedRTF(locString, opts = {}) {\n const { base, ...cacheKeyOpts } = opts; // exclude `base` from the options\n const key = JSON.stringify([locString, cacheKeyOpts]);\n let inf = intlRelCache[key];\n if (!inf) {\n inf = new Intl.RelativeTimeFormat(locString, opts);\n intlRelCache[key] = inf;\n }\n return inf;\n}\n\nlet sysLocaleCache = null;\nfunction systemLocale() {\n if (sysLocaleCache) {\n return sysLocaleCache;\n } else {\n sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;\n return sysLocaleCache;\n }\n}\n\nlet weekInfoCache = {};\nfunction getCachedWeekInfo(locString) {\n let data = weekInfoCache[locString];\n if (!data) {\n const locale = new Intl.Locale(locString);\n // browsers currently implement this as a property, but spec says it should be a getter function\n data = \"getWeekInfo\" in locale ? locale.getWeekInfo() : locale.weekInfo;\n weekInfoCache[locString] = data;\n }\n return data;\n}\n\nfunction parseLocaleString(localeStr) {\n // I really want to avoid writing a BCP 47 parser\n // see, e.g. https://github.com/wooorm/bcp-47\n // Instead, we'll do this:\n\n // a) if the string has no -u extensions, just leave it alone\n // b) if it does, use Intl to resolve everything\n // c) if Intl fails, try again without the -u\n\n // private subtags and unicode subtags have ordering requirements,\n // and we're not properly parsing this, so just strip out the\n // private ones if they exist.\n const xIndex = localeStr.indexOf(\"-x-\");\n if (xIndex !== -1) {\n localeStr = localeStr.substring(0, xIndex);\n }\n\n const uIndex = localeStr.indexOf(\"-u-\");\n if (uIndex === -1) {\n return [localeStr];\n } else {\n let options;\n let selectedStr;\n try {\n options = getCachedDTF(localeStr).resolvedOptions();\n selectedStr = localeStr;\n } catch (e) {\n const smaller = localeStr.substring(0, uIndex);\n options = getCachedDTF(smaller).resolvedOptions();\n selectedStr = smaller;\n }\n\n const { numberingSystem, calendar } = options;\n return [selectedStr, numberingSystem, calendar];\n }\n}\n\nfunction intlConfigString(localeStr, numberingSystem, outputCalendar) {\n if (outputCalendar || numberingSystem) {\n if (!localeStr.includes(\"-u-\")) {\n localeStr += \"-u\";\n }\n\n if (outputCalendar) {\n localeStr += `-ca-${outputCalendar}`;\n }\n\n if (numberingSystem) {\n localeStr += `-nu-${numberingSystem}`;\n }\n return localeStr;\n } else {\n return localeStr;\n }\n}\n\nfunction mapMonths(f) {\n const ms = [];\n for (let i = 1; i <= 12; i++) {\n const dt = DateTime.utc(2009, i, 1);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction mapWeekdays(f) {\n const ms = [];\n for (let i = 1; i <= 7; i++) {\n const dt = DateTime.utc(2016, 11, 13 + i);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction listStuff(loc, length, englishFn, intlFn) {\n const mode = loc.listingMode();\n\n if (mode === \"error\") {\n return null;\n } else if (mode === \"en\") {\n return englishFn(length);\n } else {\n return intlFn(length);\n }\n}\n\nfunction supportsFastNumbers(loc) {\n if (loc.numberingSystem && loc.numberingSystem !== \"latn\") {\n return false;\n } else {\n return (\n loc.numberingSystem === \"latn\" ||\n !loc.locale ||\n loc.locale.startsWith(\"en\") ||\n new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === \"latn\"\n );\n }\n}\n\n/**\n * @private\n */\n\nclass PolyNumberFormatter {\n constructor(intl, forceSimple, opts) {\n this.padTo = opts.padTo || 0;\n this.floor = opts.floor || false;\n\n const { padTo, floor, ...otherOpts } = opts;\n\n if (!forceSimple || Object.keys(otherOpts).length > 0) {\n const intlOpts = { useGrouping: false, ...opts };\n if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;\n this.inf = getCachedINF(intl, intlOpts);\n }\n }\n\n format(i) {\n if (this.inf) {\n const fixed = this.floor ? Math.floor(i) : i;\n return this.inf.format(fixed);\n } else {\n // to match the browser's numberformatter defaults\n const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);\n return padStart(fixed, this.padTo);\n }\n }\n}\n\n/**\n * @private\n */\n\nclass PolyDateFormatter {\n constructor(dt, intl, opts) {\n this.opts = opts;\n this.originalZone = undefined;\n\n let z = undefined;\n if (this.opts.timeZone) {\n // Don't apply any workarounds if a timeZone is explicitly provided in opts\n this.dt = dt;\n } else if (dt.zone.type === \"fixed\") {\n // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.\n // That is why fixed-offset TZ is set to that unless it is:\n // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.\n // 2. Unsupported by the browser:\n // - some do not support Etc/\n // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata\n const gmtOffset = -1 * (dt.offset / 60);\n const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;\n if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {\n z = offsetZ;\n this.dt = dt;\n } else {\n // Not all fixed-offset zones like Etc/+4:30 are present in tzdata so\n // we manually apply the offset and substitute the zone as needed.\n z = \"UTC\";\n this.dt = dt.offset === 0 ? dt : dt.setZone(\"UTC\").plus({ minutes: dt.offset });\n this.originalZone = dt.zone;\n }\n } else if (dt.zone.type === \"system\") {\n this.dt = dt;\n } else if (dt.zone.type === \"iana\") {\n this.dt = dt;\n z = dt.zone.name;\n } else {\n // Custom zones can have any offset / offsetName so we just manually\n // apply the offset and substitute the zone as needed.\n z = \"UTC\";\n this.dt = dt.setZone(\"UTC\").plus({ minutes: dt.offset });\n this.originalZone = dt.zone;\n }\n\n const intlOpts = { ...this.opts };\n intlOpts.timeZone = intlOpts.timeZone || z;\n this.dtf = getCachedDTF(intl, intlOpts);\n }\n\n format() {\n if (this.originalZone) {\n // If we have to substitute in the actual zone name, we have to use\n // formatToParts so that the timezone can be replaced.\n return this.formatToParts()\n .map(({ value }) => value)\n .join(\"\");\n }\n return this.dtf.format(this.dt.toJSDate());\n }\n\n formatToParts() {\n const parts = this.dtf.formatToParts(this.dt.toJSDate());\n if (this.originalZone) {\n return parts.map((part) => {\n if (part.type === \"timeZoneName\") {\n const offsetName = this.originalZone.offsetName(this.dt.ts, {\n locale: this.dt.locale,\n format: this.opts.timeZoneName,\n });\n return {\n ...part,\n value: offsetName,\n };\n } else {\n return part;\n }\n });\n }\n return parts;\n }\n\n resolvedOptions() {\n return this.dtf.resolvedOptions();\n }\n}\n\n/**\n * @private\n */\nclass PolyRelFormatter {\n constructor(intl, isEnglish, opts) {\n this.opts = { style: \"long\", ...opts };\n if (!isEnglish && hasRelative()) {\n this.rtf = getCachedRTF(intl, opts);\n }\n }\n\n format(count, unit) {\n if (this.rtf) {\n return this.rtf.format(count, unit);\n } else {\n return English.formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== \"long\");\n }\n }\n\n formatToParts(count, unit) {\n if (this.rtf) {\n return this.rtf.formatToParts(count, unit);\n } else {\n return [];\n }\n }\n}\n\nconst fallbackWeekSettings = {\n firstDay: 1,\n minimalDays: 4,\n weekend: [6, 7],\n};\n\n/**\n * @private\n */\n\nexport default class Locale {\n static fromOpts(opts) {\n return Locale.create(\n opts.locale,\n opts.numberingSystem,\n opts.outputCalendar,\n opts.weekSettings,\n opts.defaultToEN\n );\n }\n\n static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) {\n const specifiedLocale = locale || Settings.defaultLocale;\n // the system locale is useful for human readable strings but annoying for parsing/formatting known formats\n const localeR = specifiedLocale || (defaultToEN ? \"en-US\" : systemLocale());\n const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;\n const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;\n const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings;\n return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale);\n }\n\n static resetCache() {\n sysLocaleCache = null;\n intlDTCache = {};\n intlNumCache = {};\n intlRelCache = {};\n }\n\n static fromObject({ locale, numberingSystem, outputCalendar, weekSettings } = {}) {\n return Locale.create(locale, numberingSystem, outputCalendar, weekSettings);\n }\n\n constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) {\n const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);\n\n this.locale = parsedLocale;\n this.numberingSystem = numbering || parsedNumberingSystem || null;\n this.outputCalendar = outputCalendar || parsedOutputCalendar || null;\n this.weekSettings = weekSettings;\n this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);\n\n this.weekdaysCache = { format: {}, standalone: {} };\n this.monthsCache = { format: {}, standalone: {} };\n this.meridiemCache = null;\n this.eraCache = {};\n\n this.specifiedLocale = specifiedLocale;\n this.fastNumbersCached = null;\n }\n\n get fastNumbers() {\n if (this.fastNumbersCached == null) {\n this.fastNumbersCached = supportsFastNumbers(this);\n }\n\n return this.fastNumbersCached;\n }\n\n listingMode() {\n const isActuallyEn = this.isEnglish();\n const hasNoWeirdness =\n (this.numberingSystem === null || this.numberingSystem === \"latn\") &&\n (this.outputCalendar === null || this.outputCalendar === \"gregory\");\n return isActuallyEn && hasNoWeirdness ? \"en\" : \"intl\";\n }\n\n clone(alts) {\n if (!alts || Object.getOwnPropertyNames(alts).length === 0) {\n return this;\n } else {\n return Locale.create(\n alts.locale || this.specifiedLocale,\n alts.numberingSystem || this.numberingSystem,\n alts.outputCalendar || this.outputCalendar,\n validateWeekSettings(alts.weekSettings) || this.weekSettings,\n alts.defaultToEN || false\n );\n }\n }\n\n redefaultToEN(alts = {}) {\n return this.clone({ ...alts, defaultToEN: true });\n }\n\n redefaultToSystem(alts = {}) {\n return this.clone({ ...alts, defaultToEN: false });\n }\n\n months(length, format = false) {\n return listStuff(this, length, English.months, () => {\n const intl = format ? { month: length, day: \"numeric\" } : { month: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.monthsCache[formatStr][length]) {\n this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, \"month\"));\n }\n return this.monthsCache[formatStr][length];\n });\n }\n\n weekdays(length, format = false) {\n return listStuff(this, length, English.weekdays, () => {\n const intl = format\n ? { weekday: length, year: \"numeric\", month: \"long\", day: \"numeric\" }\n : { weekday: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.weekdaysCache[formatStr][length]) {\n this.weekdaysCache[formatStr][length] = mapWeekdays((dt) =>\n this.extract(dt, intl, \"weekday\")\n );\n }\n return this.weekdaysCache[formatStr][length];\n });\n }\n\n meridiems() {\n return listStuff(\n this,\n undefined,\n () => English.meridiems,\n () => {\n // In theory there could be aribitrary day periods. We're gonna assume there are exactly two\n // for AM and PM. This is probably wrong, but it's makes parsing way easier.\n if (!this.meridiemCache) {\n const intl = { hour: \"numeric\", hourCycle: \"h12\" };\n this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(\n (dt) => this.extract(dt, intl, \"dayperiod\")\n );\n }\n\n return this.meridiemCache;\n }\n );\n }\n\n eras(length) {\n return listStuff(this, length, English.eras, () => {\n const intl = { era: length };\n\n // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates\n // to definitely enumerate them.\n if (!this.eraCache[length]) {\n this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) =>\n this.extract(dt, intl, \"era\")\n );\n }\n\n return this.eraCache[length];\n });\n }\n\n extract(dt, intlOpts, field) {\n const df = this.dtFormatter(dt, intlOpts),\n results = df.formatToParts(),\n matching = results.find((m) => m.type.toLowerCase() === field);\n return matching ? matching.value : null;\n }\n\n numberFormatter(opts = {}) {\n // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)\n // (in contrast, the rest of the condition is used heavily)\n return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);\n }\n\n dtFormatter(dt, intlOpts = {}) {\n return new PolyDateFormatter(dt, this.intl, intlOpts);\n }\n\n relFormatter(opts = {}) {\n return new PolyRelFormatter(this.intl, this.isEnglish(), opts);\n }\n\n listFormatter(opts = {}) {\n return getCachedLF(this.intl, opts);\n }\n\n isEnglish() {\n return (\n this.locale === \"en\" ||\n this.locale.toLowerCase() === \"en-us\" ||\n new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith(\"en-us\")\n );\n }\n\n getWeekSettings() {\n if (this.weekSettings) {\n return this.weekSettings;\n } else if (!hasLocaleWeekInfo()) {\n return fallbackWeekSettings;\n } else {\n return getCachedWeekInfo(this.locale);\n }\n }\n\n getStartOfWeek() {\n return this.getWeekSettings().firstDay;\n }\n\n getMinDaysInFirstWeek() {\n return this.getWeekSettings().minimalDays;\n }\n\n getWeekendDays() {\n return this.getWeekSettings().weekend;\n }\n\n equals(other) {\n return (\n this.locale === other.locale &&\n this.numberingSystem === other.numberingSystem &&\n this.outputCalendar === other.outputCalendar\n );\n }\n}\n","import { formatOffset, signedOffset } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * A zone with a fixed offset (meaning no DST)\n * @implements {Zone}\n */\nexport default class FixedOffsetZone extends Zone {\n /**\n * Get a singleton instance of UTC\n * @return {FixedOffsetZone}\n */\n static get utcInstance() {\n if (singleton === null) {\n singleton = new FixedOffsetZone(0);\n }\n return singleton;\n }\n\n /**\n * Get an instance with a specified offset\n * @param {number} offset - The offset in minutes\n * @return {FixedOffsetZone}\n */\n static instance(offset) {\n return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);\n }\n\n /**\n * Get an instance of FixedOffsetZone from a UTC offset string, like \"UTC+6\"\n * @param {string} s - The offset string to parse\n * @example FixedOffsetZone.parseSpecifier(\"UTC+6\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC+06\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC-6:00\")\n * @return {FixedOffsetZone}\n */\n static parseSpecifier(s) {\n if (s) {\n const r = s.match(/^utc(?:([+-]\\d{1,2})(?::(\\d{2}))?)?$/i);\n if (r) {\n return new FixedOffsetZone(signedOffset(r[1], r[2]));\n }\n }\n return null;\n }\n\n constructor(offset) {\n super();\n /** @private **/\n this.fixed = offset;\n }\n\n /** @override **/\n get type() {\n return \"fixed\";\n }\n\n /** @override **/\n get name() {\n return this.fixed === 0 ? \"UTC\" : `UTC${formatOffset(this.fixed, \"narrow\")}`;\n }\n\n get ianaName() {\n if (this.fixed === 0) {\n return \"Etc/UTC\";\n } else {\n return `Etc/GMT${formatOffset(-this.fixed, \"narrow\")}`;\n }\n }\n\n /** @override **/\n offsetName() {\n return this.name;\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.fixed, format);\n }\n\n /** @override **/\n get isUniversal() {\n return true;\n }\n\n /** @override **/\n offset() {\n return this.fixed;\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"fixed\" && otherZone.fixed === this.fixed;\n }\n\n /** @override **/\n get isValid() {\n return true;\n }\n}\n","import Zone from \"../zone.js\";\n\n/**\n * A zone that failed to parse. You should never need to instantiate this.\n * @implements {Zone}\n */\nexport default class InvalidZone extends Zone {\n constructor(zoneName) {\n super();\n /** @private */\n this.zoneName = zoneName;\n }\n\n /** @override **/\n get type() {\n return \"invalid\";\n }\n\n /** @override **/\n get name() {\n return this.zoneName;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName() {\n return null;\n }\n\n /** @override **/\n formatOffset() {\n return \"\";\n }\n\n /** @override **/\n offset() {\n return NaN;\n }\n\n /** @override **/\n equals() {\n return false;\n }\n\n /** @override **/\n get isValid() {\n return false;\n }\n}\n","/**\n * @private\n */\n\nimport Zone from \"../zone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport InvalidZone from \"../zones/invalidZone.js\";\n\nimport { isUndefined, isString, isNumber } from \"./util.js\";\nimport SystemZone from \"../zones/systemZone.js\";\n\nexport function normalizeZone(input, defaultZone) {\n let offset;\n if (isUndefined(input) || input === null) {\n return defaultZone;\n } else if (input instanceof Zone) {\n return input;\n } else if (isString(input)) {\n const lowered = input.toLowerCase();\n if (lowered === \"default\") return defaultZone;\n else if (lowered === \"local\" || lowered === \"system\") return SystemZone.instance;\n else if (lowered === \"utc\" || lowered === \"gmt\") return FixedOffsetZone.utcInstance;\n else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);\n } else if (isNumber(input)) {\n return FixedOffsetZone.instance(input);\n } else if (typeof input === \"object\" && \"offset\" in input && typeof input.offset === \"function\") {\n // This is dumb, but the instanceof check above doesn't seem to really work\n // so we're duck checking it\n return input;\n } else {\n return new InvalidZone(input);\n }\n}\n","import SystemZone from \"./zones/systemZone.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport Locale from \"./impl/locale.js\";\n\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\nimport { validateWeekSettings } from \"./impl/util.js\";\n\nlet now = () => Date.now(),\n defaultZone = \"system\",\n defaultLocale = null,\n defaultNumberingSystem = null,\n defaultOutputCalendar = null,\n twoDigitCutoffYear = 60,\n throwOnInvalid,\n defaultWeekSettings = null;\n\n/**\n * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.\n */\nexport default class Settings {\n /**\n * Get the callback for returning the current timestamp.\n * @type {function}\n */\n static get now() {\n return now;\n }\n\n /**\n * Set the callback for returning the current timestamp.\n * The function should return a number, which will be interpreted as an Epoch millisecond count\n * @type {function}\n * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future\n * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time\n */\n static set now(n) {\n now = n;\n }\n\n /**\n * Set the default time zone to create DateTimes in. Does not affect existing instances.\n * Use the value \"system\" to reset this value to the system's time zone.\n * @type {string}\n */\n static set defaultZone(zone) {\n defaultZone = zone;\n }\n\n /**\n * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.\n * The default value is the system's time zone (the one set on the machine that runs this code).\n * @type {Zone}\n */\n static get defaultZone() {\n return normalizeZone(defaultZone, SystemZone.instance);\n }\n\n /**\n * Get the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultLocale() {\n return defaultLocale;\n }\n\n /**\n * Set the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultLocale(locale) {\n defaultLocale = locale;\n }\n\n /**\n * Get the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultNumberingSystem() {\n return defaultNumberingSystem;\n }\n\n /**\n * Set the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultNumberingSystem(numberingSystem) {\n defaultNumberingSystem = numberingSystem;\n }\n\n /**\n * Get the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultOutputCalendar() {\n return defaultOutputCalendar;\n }\n\n /**\n * Set the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultOutputCalendar(outputCalendar) {\n defaultOutputCalendar = outputCalendar;\n }\n\n /**\n * @typedef {Object} WeekSettings\n * @property {number} firstDay\n * @property {number} minimalDays\n * @property {number[]} weekend\n */\n\n /**\n * @return {WeekSettings|null}\n */\n static get defaultWeekSettings() {\n return defaultWeekSettings;\n }\n\n /**\n * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and\n * how many days are required in the first week of a year.\n * Does not affect existing instances.\n *\n * @param {WeekSettings|null} weekSettings\n */\n static set defaultWeekSettings(weekSettings) {\n defaultWeekSettings = validateWeekSettings(weekSettings);\n }\n\n /**\n * Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.\n * @type {number}\n */\n static get twoDigitCutoffYear() {\n return twoDigitCutoffYear;\n }\n\n /**\n * Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.\n * @type {number}\n * @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpreted as current century\n * @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050\n * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50\n * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50\n */\n static set twoDigitCutoffYear(cutoffYear) {\n twoDigitCutoffYear = cutoffYear % 100;\n }\n\n /**\n * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static get throwOnInvalid() {\n return throwOnInvalid;\n }\n\n /**\n * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static set throwOnInvalid(t) {\n throwOnInvalid = t;\n }\n\n /**\n * Reset Luxon's global caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCaches() {\n Locale.resetCache();\n IANAZone.resetCache();\n }\n}\n","export default class Invalid {\n constructor(reason, explanation) {\n this.reason = reason;\n this.explanation = explanation;\n }\n\n toMessage() {\n if (this.explanation) {\n return `${this.reason}: ${this.explanation}`;\n } else {\n return this.reason;\n }\n }\n}\n","import {\n integerBetween,\n isLeapYear,\n timeObject,\n daysInYear,\n daysInMonth,\n weeksInWeekYear,\n isInteger,\n isUndefined,\n} from \"./util.js\";\nimport Invalid from \"./invalid.js\";\nimport { ConflictingSpecificationError } from \"../errors.js\";\n\nconst nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\n\nfunction unitOutOfRange(unit, value) {\n return new Invalid(\n \"unit out of range\",\n `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`\n );\n}\n\nexport function dayOfWeek(year, month, day) {\n const d = new Date(Date.UTC(year, month - 1, day));\n\n if (year < 100 && year >= 0) {\n d.setUTCFullYear(d.getUTCFullYear() - 1900);\n }\n\n const js = d.getUTCDay();\n\n return js === 0 ? 7 : js;\n}\n\nfunction computeOrdinal(year, month, day) {\n return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];\n}\n\nfunction uncomputeOrdinal(year, ordinal) {\n const table = isLeapYear(year) ? leapLadder : nonLeapLadder,\n month0 = table.findIndex((i) => i < ordinal),\n day = ordinal - table[month0];\n return { month: month0 + 1, day };\n}\n\nexport function isoWeekdayToLocal(isoWeekday, startOfWeek) {\n return ((isoWeekday - startOfWeek + 7) % 7) + 1;\n}\n\n/**\n * @private\n */\n\nexport function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const { year, month, day } = gregObj,\n ordinal = computeOrdinal(year, month, day),\n weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek);\n\n let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7),\n weekYear;\n\n if (weekNumber < 1) {\n weekYear = year - 1;\n weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek);\n } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) {\n weekYear = year + 1;\n weekNumber = 1;\n } else {\n weekYear = year;\n }\n\n return { weekYear, weekNumber, weekday, ...timeObject(gregObj) };\n}\n\nexport function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const { weekYear, weekNumber, weekday } = weekData,\n weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek),\n yearInDays = daysInYear(weekYear);\n\n let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek,\n year;\n\n if (ordinal < 1) {\n year = weekYear - 1;\n ordinal += daysInYear(year);\n } else if (ordinal > yearInDays) {\n year = weekYear + 1;\n ordinal -= daysInYear(weekYear);\n } else {\n year = weekYear;\n }\n\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(weekData) };\n}\n\nexport function gregorianToOrdinal(gregData) {\n const { year, month, day } = gregData;\n const ordinal = computeOrdinal(year, month, day);\n return { year, ordinal, ...timeObject(gregData) };\n}\n\nexport function ordinalToGregorian(ordinalData) {\n const { year, ordinal } = ordinalData;\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(ordinalData) };\n}\n\n/**\n * Check if local week units like localWeekday are used in obj.\n * If so, validates that they are not mixed with ISO week units and then copies them to the normal week unit properties.\n * Modifies obj in-place!\n * @param obj the object values\n */\nexport function usesLocalWeekValues(obj, loc) {\n const hasLocaleWeekData =\n !isUndefined(obj.localWeekday) ||\n !isUndefined(obj.localWeekNumber) ||\n !isUndefined(obj.localWeekYear);\n if (hasLocaleWeekData) {\n const hasIsoWeekData =\n !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear);\n\n if (hasIsoWeekData) {\n throw new ConflictingSpecificationError(\n \"Cannot mix locale-based week fields with ISO-based week fields\"\n );\n }\n if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday;\n if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber;\n if (!isUndefined(obj.localWeekYear)) obj.weekYear = obj.localWeekYear;\n delete obj.localWeekday;\n delete obj.localWeekNumber;\n delete obj.localWeekYear;\n return {\n minDaysInFirstWeek: loc.getMinDaysInFirstWeek(),\n startOfWeek: loc.getStartOfWeek(),\n };\n } else {\n return { minDaysInFirstWeek: 4, startOfWeek: 1 };\n }\n}\n\nexport function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const validYear = isInteger(obj.weekYear),\n validWeek = integerBetween(\n obj.weekNumber,\n 1,\n weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)\n ),\n validWeekday = integerBetween(obj.weekday, 1, 7);\n\n if (!validYear) {\n return unitOutOfRange(\"weekYear\", obj.weekYear);\n } else if (!validWeek) {\n return unitOutOfRange(\"week\", obj.weekNumber);\n } else if (!validWeekday) {\n return unitOutOfRange(\"weekday\", obj.weekday);\n } else return false;\n}\n\nexport function hasInvalidOrdinalData(obj) {\n const validYear = isInteger(obj.year),\n validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validOrdinal) {\n return unitOutOfRange(\"ordinal\", obj.ordinal);\n } else return false;\n}\n\nexport function hasInvalidGregorianData(obj) {\n const validYear = isInteger(obj.year),\n validMonth = integerBetween(obj.month, 1, 12),\n validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validMonth) {\n return unitOutOfRange(\"month\", obj.month);\n } else if (!validDay) {\n return unitOutOfRange(\"day\", obj.day);\n } else return false;\n}\n\nexport function hasInvalidTimeData(obj) {\n const { hour, minute, second, millisecond } = obj;\n const validHour =\n integerBetween(hour, 0, 23) ||\n (hour === 24 && minute === 0 && second === 0 && millisecond === 0),\n validMinute = integerBetween(minute, 0, 59),\n validSecond = integerBetween(second, 0, 59),\n validMillisecond = integerBetween(millisecond, 0, 999);\n\n if (!validHour) {\n return unitOutOfRange(\"hour\", hour);\n } else if (!validMinute) {\n return unitOutOfRange(\"minute\", minute);\n } else if (!validSecond) {\n return unitOutOfRange(\"second\", second);\n } else if (!validMillisecond) {\n return unitOutOfRange(\"millisecond\", millisecond);\n } else return false;\n}\n","/*\n This is just a junk drawer, containing anything used across multiple classes.\n Because Luxon is small(ish), this should stay small and we won't worry about splitting\n it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.\n*/\n\nimport { InvalidArgumentError } from \"../errors.js\";\nimport Settings from \"../settings.js\";\nimport { dayOfWeek, isoWeekdayToLocal } from \"./conversions.js\";\n\n/**\n * @private\n */\n\n// TYPES\n\nexport function isUndefined(o) {\n return typeof o === \"undefined\";\n}\n\nexport function isNumber(o) {\n return typeof o === \"number\";\n}\n\nexport function isInteger(o) {\n return typeof o === \"number\" && o % 1 === 0;\n}\n\nexport function isString(o) {\n return typeof o === \"string\";\n}\n\nexport function isDate(o) {\n return Object.prototype.toString.call(o) === \"[object Date]\";\n}\n\n// CAPABILITIES\n\nexport function hasRelative() {\n try {\n return typeof Intl !== \"undefined\" && !!Intl.RelativeTimeFormat;\n } catch (e) {\n return false;\n }\n}\n\nexport function hasLocaleWeekInfo() {\n try {\n return (\n typeof Intl !== \"undefined\" &&\n !!Intl.Locale &&\n (\"weekInfo\" in Intl.Locale.prototype || \"getWeekInfo\" in Intl.Locale.prototype)\n );\n } catch (e) {\n return false;\n }\n}\n\n// OBJECTS AND ARRAYS\n\nexport function maybeArray(thing) {\n return Array.isArray(thing) ? thing : [thing];\n}\n\nexport function bestBy(arr, by, compare) {\n if (arr.length === 0) {\n return undefined;\n }\n return arr.reduce((best, next) => {\n const pair = [by(next), next];\n if (!best) {\n return pair;\n } else if (compare(best[0], pair[0]) === best[0]) {\n return best;\n } else {\n return pair;\n }\n }, null)[1];\n}\n\nexport function pick(obj, keys) {\n return keys.reduce((a, k) => {\n a[k] = obj[k];\n return a;\n }, {});\n}\n\nexport function hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nexport function validateWeekSettings(settings) {\n if (settings == null) {\n return null;\n } else if (typeof settings !== \"object\") {\n throw new InvalidArgumentError(\"Week settings must be an object\");\n } else {\n if (\n !integerBetween(settings.firstDay, 1, 7) ||\n !integerBetween(settings.minimalDays, 1, 7) ||\n !Array.isArray(settings.weekend) ||\n settings.weekend.some((v) => !integerBetween(v, 1, 7))\n ) {\n throw new InvalidArgumentError(\"Invalid week settings\");\n }\n return {\n firstDay: settings.firstDay,\n minimalDays: settings.minimalDays,\n weekend: Array.from(settings.weekend),\n };\n }\n}\n\n// NUMBERS AND STRINGS\n\nexport function integerBetween(thing, bottom, top) {\n return isInteger(thing) && thing >= bottom && thing <= top;\n}\n\n// x % n but takes the sign of n instead of x\nexport function floorMod(x, n) {\n return x - n * Math.floor(x / n);\n}\n\nexport function padStart(input, n = 2) {\n const isNeg = input < 0;\n let padded;\n if (isNeg) {\n padded = \"-\" + (\"\" + -input).padStart(n, \"0\");\n } else {\n padded = (\"\" + input).padStart(n, \"0\");\n }\n return padded;\n}\n\nexport function parseInteger(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseInt(string, 10);\n }\n}\n\nexport function parseFloating(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseFloat(string);\n }\n}\n\nexport function parseMillis(fraction) {\n // Return undefined (instead of 0) in these cases, where fraction is not set\n if (isUndefined(fraction) || fraction === null || fraction === \"\") {\n return undefined;\n } else {\n const f = parseFloat(\"0.\" + fraction) * 1000;\n return Math.floor(f);\n }\n}\n\nexport function roundTo(number, digits, towardZero = false) {\n const factor = 10 ** digits,\n rounder = towardZero ? Math.trunc : Math.round;\n return rounder(number * factor) / factor;\n}\n\n// DATE BASICS\n\nexport function isLeapYear(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function daysInYear(year) {\n return isLeapYear(year) ? 366 : 365;\n}\n\nexport function daysInMonth(year, month) {\n const modMonth = floorMod(month - 1, 12) + 1,\n modYear = year + (month - modMonth) / 12;\n\n if (modMonth === 2) {\n return isLeapYear(modYear) ? 29 : 28;\n } else {\n return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];\n }\n}\n\n// convert a calendar object to a local timestamp (epoch, but with the offset baked in)\nexport function objToLocalTS(obj) {\n let d = Date.UTC(\n obj.year,\n obj.month - 1,\n obj.day,\n obj.hour,\n obj.minute,\n obj.second,\n obj.millisecond\n );\n\n // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that\n if (obj.year < 100 && obj.year >= 0) {\n d = new Date(d);\n // set the month and day again, this is necessary because year 2000 is a leap year, but year 100 is not\n // so if obj.year is in 99, but obj.day makes it roll over into year 100,\n // the calculations done by Date.UTC are using year 2000 - which is incorrect\n d.setUTCFullYear(obj.year, obj.month - 1, obj.day);\n }\n return +d;\n}\n\n// adapted from moment.js: https://github.com/moment/moment/blob/000ac1800e620f770f4eb31b5ae908f6167b0ab2/src/lib/units/week-calendar-utils.js\nfunction firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) {\n const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek);\n return -fwdlw + minDaysInFirstWeek - 1;\n}\n\nexport function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek);\n const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek);\n return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7;\n}\n\nexport function untruncateYear(year) {\n if (year > 99) {\n return year;\n } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year;\n}\n\n// PARSING\n\nexport function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {\n const date = new Date(ts),\n intlOpts = {\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n };\n\n if (timeZone) {\n intlOpts.timeZone = timeZone;\n }\n\n const modified = { timeZoneName: offsetFormat, ...intlOpts };\n\n const parsed = new Intl.DateTimeFormat(locale, modified)\n .formatToParts(date)\n .find((m) => m.type.toLowerCase() === \"timezonename\");\n return parsed ? parsed.value : null;\n}\n\n// signedOffset('-5', '30') -> -330\nexport function signedOffset(offHourStr, offMinuteStr) {\n let offHour = parseInt(offHourStr, 10);\n\n // don't || this because we want to preserve -0\n if (Number.isNaN(offHour)) {\n offHour = 0;\n }\n\n const offMin = parseInt(offMinuteStr, 10) || 0,\n offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;\n return offHour * 60 + offMinSigned;\n}\n\n// COERCION\n\nexport function asNumber(value) {\n const numericValue = Number(value);\n if (typeof value === \"boolean\" || value === \"\" || Number.isNaN(numericValue))\n throw new InvalidArgumentError(`Invalid unit value ${value}`);\n return numericValue;\n}\n\nexport function normalizeObject(obj, normalizer) {\n const normalized = {};\n for (const u in obj) {\n if (hasOwnProperty(obj, u)) {\n const v = obj[u];\n if (v === undefined || v === null) continue;\n normalized[normalizer(u)] = asNumber(v);\n }\n }\n return normalized;\n}\n\nexport function formatOffset(offset, format) {\n const hours = Math.trunc(Math.abs(offset / 60)),\n minutes = Math.trunc(Math.abs(offset % 60)),\n sign = offset >= 0 ? \"+\" : \"-\";\n\n switch (format) {\n case \"short\":\n return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;\n case \"narrow\":\n return `${sign}${hours}${minutes > 0 ? `:${minutes}` : \"\"}`;\n case \"techie\":\n return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;\n default:\n throw new RangeError(`Value format ${format} is out of range for property format`);\n }\n}\n\nexport function timeObject(obj) {\n return pick(obj, [\"hour\", \"minute\", \"second\", \"millisecond\"]);\n}\n","import * as Formats from \"./formats.js\";\nimport { pick } from \"./util.js\";\n\nfunction stringify(obj) {\n return JSON.stringify(obj, Object.keys(obj).sort());\n}\n\n/**\n * @private\n */\n\nexport const monthsLong = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nexport const monthsShort = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\nexport const monthsNarrow = [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"];\n\nexport function months(length) {\n switch (length) {\n case \"narrow\":\n return [...monthsNarrow];\n case \"short\":\n return [...monthsShort];\n case \"long\":\n return [...monthsLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"];\n case \"2-digit\":\n return [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"];\n default:\n return null;\n }\n}\n\nexport const weekdaysLong = [\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n \"Sunday\",\n];\n\nexport const weekdaysShort = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\n\nexport const weekdaysNarrow = [\"M\", \"T\", \"W\", \"T\", \"F\", \"S\", \"S\"];\n\nexport function weekdays(length) {\n switch (length) {\n case \"narrow\":\n return [...weekdaysNarrow];\n case \"short\":\n return [...weekdaysShort];\n case \"long\":\n return [...weekdaysLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"];\n default:\n return null;\n }\n}\n\nexport const meridiems = [\"AM\", \"PM\"];\n\nexport const erasLong = [\"Before Christ\", \"Anno Domini\"];\n\nexport const erasShort = [\"BC\", \"AD\"];\n\nexport const erasNarrow = [\"B\", \"A\"];\n\nexport function eras(length) {\n switch (length) {\n case \"narrow\":\n return [...erasNarrow];\n case \"short\":\n return [...erasShort];\n case \"long\":\n return [...erasLong];\n default:\n return null;\n }\n}\n\nexport function meridiemForDateTime(dt) {\n return meridiems[dt.hour < 12 ? 0 : 1];\n}\n\nexport function weekdayForDateTime(dt, length) {\n return weekdays(length)[dt.weekday - 1];\n}\n\nexport function monthForDateTime(dt, length) {\n return months(length)[dt.month - 1];\n}\n\nexport function eraForDateTime(dt, length) {\n return eras(length)[dt.year < 0 ? 0 : 1];\n}\n\nexport function formatRelativeTime(unit, count, numeric = \"always\", narrow = false) {\n const units = {\n years: [\"year\", \"yr.\"],\n quarters: [\"quarter\", \"qtr.\"],\n months: [\"month\", \"mo.\"],\n weeks: [\"week\", \"wk.\"],\n days: [\"day\", \"day\", \"days\"],\n hours: [\"hour\", \"hr.\"],\n minutes: [\"minute\", \"min.\"],\n seconds: [\"second\", \"sec.\"],\n };\n\n const lastable = [\"hours\", \"minutes\", \"seconds\"].indexOf(unit) === -1;\n\n if (numeric === \"auto\" && lastable) {\n const isDay = unit === \"days\";\n switch (count) {\n case 1:\n return isDay ? \"tomorrow\" : `next ${units[unit][0]}`;\n case -1:\n return isDay ? \"yesterday\" : `last ${units[unit][0]}`;\n case 0:\n return isDay ? \"today\" : `this ${units[unit][0]}`;\n default: // fall through\n }\n }\n\n const isInPast = Object.is(count, -0) || count < 0,\n fmtValue = Math.abs(count),\n singular = fmtValue === 1,\n lilUnits = units[unit],\n fmtUnit = narrow\n ? singular\n ? lilUnits[1]\n : lilUnits[2] || lilUnits[1]\n : singular\n ? units[unit][0]\n : unit;\n return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;\n}\n\nexport function formatString(knownFormat) {\n // these all have the offsets removed because we don't have access to them\n // without all the intl stuff this is backfilling\n const filtered = pick(knownFormat, [\n \"weekday\",\n \"era\",\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"timeZoneName\",\n \"hourCycle\",\n ]),\n key = stringify(filtered),\n dateTimeHuge = \"EEEE, LLLL d, yyyy, h:mm a\";\n switch (key) {\n case stringify(Formats.DATE_SHORT):\n return \"M/d/yyyy\";\n case stringify(Formats.DATE_MED):\n return \"LLL d, yyyy\";\n case stringify(Formats.DATE_MED_WITH_WEEKDAY):\n return \"EEE, LLL d, yyyy\";\n case stringify(Formats.DATE_FULL):\n return \"LLLL d, yyyy\";\n case stringify(Formats.DATE_HUGE):\n return \"EEEE, LLLL d, yyyy\";\n case stringify(Formats.TIME_SIMPLE):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_SECONDS):\n return \"h:mm:ss a\";\n case stringify(Formats.TIME_WITH_SHORT_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_LONG_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_24_SIMPLE):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_SECONDS):\n return \"HH:mm:ss\";\n case stringify(Formats.TIME_24_WITH_SHORT_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_LONG_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.DATETIME_SHORT):\n return \"M/d/yyyy, h:mm a\";\n case stringify(Formats.DATETIME_MED):\n return \"LLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL):\n return \"LLLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_HUGE):\n return dateTimeHuge;\n case stringify(Formats.DATETIME_SHORT_WITH_SECONDS):\n return \"M/d/yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_SECONDS):\n return \"LLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_WEEKDAY):\n return \"EEE, d LLL yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL_WITH_SECONDS):\n return \"LLLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_HUGE_WITH_SECONDS):\n return \"EEEE, LLLL d, yyyy, h:mm:ss a\";\n default:\n return dateTimeHuge;\n }\n}\n","import * as English from \"./english.js\";\nimport * as Formats from \"./formats.js\";\nimport { padStart } from \"./util.js\";\n\nfunction stringifyTokens(splits, tokenToString) {\n let s = \"\";\n for (const token of splits) {\n if (token.literal) {\n s += token.val;\n } else {\n s += tokenToString(token.val);\n }\n }\n return s;\n}\n\nconst macroTokenToFormatOpts = {\n D: Formats.DATE_SHORT,\n DD: Formats.DATE_MED,\n DDD: Formats.DATE_FULL,\n DDDD: Formats.DATE_HUGE,\n t: Formats.TIME_SIMPLE,\n tt: Formats.TIME_WITH_SECONDS,\n ttt: Formats.TIME_WITH_SHORT_OFFSET,\n tttt: Formats.TIME_WITH_LONG_OFFSET,\n T: Formats.TIME_24_SIMPLE,\n TT: Formats.TIME_24_WITH_SECONDS,\n TTT: Formats.TIME_24_WITH_SHORT_OFFSET,\n TTTT: Formats.TIME_24_WITH_LONG_OFFSET,\n f: Formats.DATETIME_SHORT,\n ff: Formats.DATETIME_MED,\n fff: Formats.DATETIME_FULL,\n ffff: Formats.DATETIME_HUGE,\n F: Formats.DATETIME_SHORT_WITH_SECONDS,\n FF: Formats.DATETIME_MED_WITH_SECONDS,\n FFF: Formats.DATETIME_FULL_WITH_SECONDS,\n FFFF: Formats.DATETIME_HUGE_WITH_SECONDS,\n};\n\n/**\n * @private\n */\n\nexport default class Formatter {\n static create(locale, opts = {}) {\n return new Formatter(locale, opts);\n }\n\n static parseFormat(fmt) {\n // white-space is always considered a literal in user-provided formats\n // the \" \" token has a special meaning (see unitForToken)\n\n let current = null,\n currentFull = \"\",\n bracketed = false;\n const splits = [];\n for (let i = 0; i < fmt.length; i++) {\n const c = fmt.charAt(i);\n if (c === \"'\") {\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed || /^\\s+$/.test(currentFull), val: currentFull });\n }\n current = null;\n currentFull = \"\";\n bracketed = !bracketed;\n } else if (bracketed) {\n currentFull += c;\n } else if (c === current) {\n currentFull += c;\n } else {\n if (currentFull.length > 0) {\n splits.push({ literal: /^\\s+$/.test(currentFull), val: currentFull });\n }\n currentFull = c;\n current = c;\n }\n }\n\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed || /^\\s+$/.test(currentFull), val: currentFull });\n }\n\n return splits;\n }\n\n static macroTokenToFormatOpts(token) {\n return macroTokenToFormatOpts[token];\n }\n\n constructor(locale, formatOpts) {\n this.opts = formatOpts;\n this.loc = locale;\n this.systemLoc = null;\n }\n\n formatWithSystemDefault(dt, opts) {\n if (this.systemLoc === null) {\n this.systemLoc = this.loc.redefaultToSystem();\n }\n const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.format();\n }\n\n dtFormatter(dt, opts = {}) {\n return this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n }\n\n formatDateTime(dt, opts) {\n return this.dtFormatter(dt, opts).format();\n }\n\n formatDateTimeParts(dt, opts) {\n return this.dtFormatter(dt, opts).formatToParts();\n }\n\n formatInterval(interval, opts) {\n const df = this.dtFormatter(interval.start, opts);\n return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());\n }\n\n resolvedOptions(dt, opts) {\n return this.dtFormatter(dt, opts).resolvedOptions();\n }\n\n num(n, p = 0) {\n // we get some perf out of doing this here, annoyingly\n if (this.opts.forceSimple) {\n return padStart(n, p);\n }\n\n const opts = { ...this.opts };\n\n if (p > 0) {\n opts.padTo = p;\n }\n\n return this.loc.numberFormatter(opts).format(n);\n }\n\n formatDateTimeFromString(dt, fmt) {\n const knownEnglish = this.loc.listingMode() === \"en\",\n useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== \"gregory\",\n string = (opts, extract) => this.loc.extract(dt, opts, extract),\n formatOffset = (opts) => {\n if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {\n return \"Z\";\n }\n\n return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : \"\";\n },\n meridiem = () =>\n knownEnglish\n ? English.meridiemForDateTime(dt)\n : string({ hour: \"numeric\", hourCycle: \"h12\" }, \"dayperiod\"),\n month = (length, standalone) =>\n knownEnglish\n ? English.monthForDateTime(dt, length)\n : string(standalone ? { month: length } : { month: length, day: \"numeric\" }, \"month\"),\n weekday = (length, standalone) =>\n knownEnglish\n ? English.weekdayForDateTime(dt, length)\n : string(\n standalone ? { weekday: length } : { weekday: length, month: \"long\", day: \"numeric\" },\n \"weekday\"\n ),\n maybeMacro = (token) => {\n const formatOpts = Formatter.macroTokenToFormatOpts(token);\n if (formatOpts) {\n return this.formatWithSystemDefault(dt, formatOpts);\n } else {\n return token;\n }\n },\n era = (length) =>\n knownEnglish ? English.eraForDateTime(dt, length) : string({ era: length }, \"era\"),\n tokenToString = (token) => {\n // Where possible: https://cldr.unicode.org/translation/date-time/date-time-symbols\n switch (token) {\n // ms\n case \"S\":\n return this.num(dt.millisecond);\n case \"u\":\n // falls through\n case \"SSS\":\n return this.num(dt.millisecond, 3);\n // seconds\n case \"s\":\n return this.num(dt.second);\n case \"ss\":\n return this.num(dt.second, 2);\n // fractional seconds\n case \"uu\":\n return this.num(Math.floor(dt.millisecond / 10), 2);\n case \"uuu\":\n return this.num(Math.floor(dt.millisecond / 100));\n // minutes\n case \"m\":\n return this.num(dt.minute);\n case \"mm\":\n return this.num(dt.minute, 2);\n // hours\n case \"h\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);\n case \"hh\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);\n case \"H\":\n return this.num(dt.hour);\n case \"HH\":\n return this.num(dt.hour, 2);\n // offset\n case \"Z\":\n // like +6\n return formatOffset({ format: \"narrow\", allowZ: this.opts.allowZ });\n case \"ZZ\":\n // like +06:00\n return formatOffset({ format: \"short\", allowZ: this.opts.allowZ });\n case \"ZZZ\":\n // like +0600\n return formatOffset({ format: \"techie\", allowZ: this.opts.allowZ });\n case \"ZZZZ\":\n // like EST\n return dt.zone.offsetName(dt.ts, { format: \"short\", locale: this.loc.locale });\n case \"ZZZZZ\":\n // like Eastern Standard Time\n return dt.zone.offsetName(dt.ts, { format: \"long\", locale: this.loc.locale });\n // zone\n case \"z\":\n // like America/New_York\n return dt.zoneName;\n // meridiems\n case \"a\":\n return meridiem();\n // dates\n case \"d\":\n return useDateTimeFormatter ? string({ day: \"numeric\" }, \"day\") : this.num(dt.day);\n case \"dd\":\n return useDateTimeFormatter ? string({ day: \"2-digit\" }, \"day\") : this.num(dt.day, 2);\n // weekdays - standalone\n case \"c\":\n // like 1\n return this.num(dt.weekday);\n case \"ccc\":\n // like 'Tues'\n return weekday(\"short\", true);\n case \"cccc\":\n // like 'Tuesday'\n return weekday(\"long\", true);\n case \"ccccc\":\n // like 'T'\n return weekday(\"narrow\", true);\n // weekdays - format\n case \"E\":\n // like 1\n return this.num(dt.weekday);\n case \"EEE\":\n // like 'Tues'\n return weekday(\"short\", false);\n case \"EEEE\":\n // like 'Tuesday'\n return weekday(\"long\", false);\n case \"EEEEE\":\n // like 'T'\n return weekday(\"narrow\", false);\n // months - standalone\n case \"L\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\", day: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"LL\":\n // like 01, doesn't seem to work\n return useDateTimeFormatter\n ? string({ month: \"2-digit\", day: \"numeric\" }, \"month\")\n : this.num(dt.month, 2);\n case \"LLL\":\n // like Jan\n return month(\"short\", true);\n case \"LLLL\":\n // like January\n return month(\"long\", true);\n case \"LLLLL\":\n // like J\n return month(\"narrow\", true);\n // months - format\n case \"M\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"MM\":\n // like 01\n return useDateTimeFormatter\n ? string({ month: \"2-digit\" }, \"month\")\n : this.num(dt.month, 2);\n case \"MMM\":\n // like Jan\n return month(\"short\", false);\n case \"MMMM\":\n // like January\n return month(\"long\", false);\n case \"MMMMM\":\n // like J\n return month(\"narrow\", false);\n // years\n case \"y\":\n // like 2014\n return useDateTimeFormatter ? string({ year: \"numeric\" }, \"year\") : this.num(dt.year);\n case \"yy\":\n // like 14\n return useDateTimeFormatter\n ? string({ year: \"2-digit\" }, \"year\")\n : this.num(dt.year.toString().slice(-2), 2);\n case \"yyyy\":\n // like 0012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 4);\n case \"yyyyyy\":\n // like 000012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 6);\n // eras\n case \"G\":\n // like AD\n return era(\"short\");\n case \"GG\":\n // like Anno Domini\n return era(\"long\");\n case \"GGGGG\":\n return era(\"narrow\");\n case \"kk\":\n return this.num(dt.weekYear.toString().slice(-2), 2);\n case \"kkkk\":\n return this.num(dt.weekYear, 4);\n case \"W\":\n return this.num(dt.weekNumber);\n case \"WW\":\n return this.num(dt.weekNumber, 2);\n case \"n\":\n return this.num(dt.localWeekNumber);\n case \"nn\":\n return this.num(dt.localWeekNumber, 2);\n case \"ii\":\n return this.num(dt.localWeekYear.toString().slice(-2), 2);\n case \"iiii\":\n return this.num(dt.localWeekYear, 4);\n case \"o\":\n return this.num(dt.ordinal);\n case \"ooo\":\n return this.num(dt.ordinal, 3);\n case \"q\":\n // like 1\n return this.num(dt.quarter);\n case \"qq\":\n // like 01\n return this.num(dt.quarter, 2);\n case \"X\":\n return this.num(Math.floor(dt.ts / 1000));\n case \"x\":\n return this.num(dt.ts);\n default:\n return maybeMacro(token);\n }\n };\n\n return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);\n }\n\n formatDurationFromString(dur, fmt) {\n const tokenToField = (token) => {\n switch (token[0]) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"w\":\n return \"week\";\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n default:\n return null;\n }\n },\n tokenToString = (lildur) => (token) => {\n const mapped = tokenToField(token);\n if (mapped) {\n return this.num(lildur.get(mapped), token.length);\n } else {\n return token;\n }\n },\n tokens = Formatter.parseFormat(fmt),\n realTokens = tokens.reduce(\n (found, { literal, val }) => (literal ? found : found.concat(val)),\n []\n ),\n collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));\n return stringifyTokens(tokens, tokenToString(collapsed));\n }\n}\n","import {\n untruncateYear,\n signedOffset,\n parseInteger,\n parseMillis,\n isUndefined,\n parseFloating,\n} from \"./util.js\";\nimport * as English from \"./english.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n/*\n * This file handles parsing for well-specified formats. Here's how it works:\n * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.\n * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object\n * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.\n * Extractors can take a \"cursor\" representing the offset in the match to look at. This makes it easy to combine extractors.\n * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.\n * Some extractions are super dumb and simpleParse and fromStrings help DRY them.\n */\n\nconst ianaRegex = /[A-Za-z_+-]{1,256}(?::?\\/[A-Za-z0-9_+-]{1,256}(?:\\/[A-Za-z0-9_+-]{1,256})?)?/;\n\nfunction combineRegexes(...regexes) {\n const full = regexes.reduce((f, r) => f + r.source, \"\");\n return RegExp(`^${full}$`);\n}\n\nfunction combineExtractors(...extractors) {\n return (m) =>\n extractors\n .reduce(\n ([mergedVals, mergedZone, cursor], ex) => {\n const [val, zone, next] = ex(m, cursor);\n return [{ ...mergedVals, ...val }, zone || mergedZone, next];\n },\n [{}, null, 1]\n )\n .slice(0, 2);\n}\n\nfunction parse(s, ...patterns) {\n if (s == null) {\n return [null, null];\n }\n\n for (const [regex, extractor] of patterns) {\n const m = regex.exec(s);\n if (m) {\n return extractor(m);\n }\n }\n return [null, null];\n}\n\nfunction simpleParse(...keys) {\n return (match, cursor) => {\n const ret = {};\n let i;\n\n for (i = 0; i < keys.length; i++) {\n ret[keys[i]] = parseInteger(match[cursor + i]);\n }\n return [ret, null, cursor + i];\n };\n}\n\n// ISO and SQL parsing\nconst offsetRegex = /(?:(Z)|([+-]\\d\\d)(?::?(\\d\\d))?)/;\nconst isoExtendedZone = `(?:${offsetRegex.source}?(?:\\\\[(${ianaRegex.source})\\\\])?)?`;\nconst isoTimeBaseRegex = /(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:[.,](\\d{1,30}))?)?)?/;\nconst isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);\nconst isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);\nconst isoYmdRegex = /([+-]\\d{6}|\\d{4})(?:-?(\\d\\d)(?:-?(\\d\\d))?)?/;\nconst isoWeekRegex = /(\\d{4})-?W(\\d\\d)(?:-?(\\d))?/;\nconst isoOrdinalRegex = /(\\d{4})-?(\\d{3})/;\nconst extractISOWeekData = simpleParse(\"weekYear\", \"weekNumber\", \"weekDay\");\nconst extractISOOrdinalData = simpleParse(\"year\", \"ordinal\");\nconst sqlYmdRegex = /(\\d{4})-(\\d\\d)-(\\d\\d)/; // dumbed-down version of the ISO one\nconst sqlTimeRegex = RegExp(\n `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`\n);\nconst sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);\n\nfunction int(match, pos, fallback) {\n const m = match[pos];\n return isUndefined(m) ? fallback : parseInteger(m);\n}\n\nfunction extractISOYmd(match, cursor) {\n const item = {\n year: int(match, cursor),\n month: int(match, cursor + 1, 1),\n day: int(match, cursor + 2, 1),\n };\n\n return [item, null, cursor + 3];\n}\n\nfunction extractISOTime(match, cursor) {\n const item = {\n hours: int(match, cursor, 0),\n minutes: int(match, cursor + 1, 0),\n seconds: int(match, cursor + 2, 0),\n milliseconds: parseMillis(match[cursor + 3]),\n };\n\n return [item, null, cursor + 4];\n}\n\nfunction extractISOOffset(match, cursor) {\n const local = !match[cursor] && !match[cursor + 1],\n fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),\n zone = local ? null : FixedOffsetZone.instance(fullOffset);\n return [{}, zone, cursor + 3];\n}\n\nfunction extractIANAZone(match, cursor) {\n const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;\n return [{}, zone, cursor + 1];\n}\n\n// ISO time parsing\n\nconst isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);\n\n// ISO duration parsing\n\nconst isoDuration =\n /^-?P(?:(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)Y)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)W)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)D)?(?:T(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)H)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20})(?:[.,](-?\\d{1,20}))?S)?)?)$/;\n\nfunction extractISODuration(match) {\n const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] =\n match;\n\n const hasNegativePrefix = s[0] === \"-\";\n const negativeSeconds = secondStr && secondStr[0] === \"-\";\n\n const maybeNegate = (num, force = false) =>\n num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;\n\n return [\n {\n years: maybeNegate(parseFloating(yearStr)),\n months: maybeNegate(parseFloating(monthStr)),\n weeks: maybeNegate(parseFloating(weekStr)),\n days: maybeNegate(parseFloating(dayStr)),\n hours: maybeNegate(parseFloating(hourStr)),\n minutes: maybeNegate(parseFloating(minuteStr)),\n seconds: maybeNegate(parseFloating(secondStr), secondStr === \"-0\"),\n milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds),\n },\n ];\n}\n\n// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York\n// and not just that we're in -240 *right now*. But since I don't think these are used that often\n// I'm just going to ignore that\nconst obsOffsets = {\n GMT: 0,\n EDT: -4 * 60,\n EST: -5 * 60,\n CDT: -5 * 60,\n CST: -6 * 60,\n MDT: -6 * 60,\n MST: -7 * 60,\n PDT: -7 * 60,\n PST: -8 * 60,\n};\n\nfunction fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {\n const result = {\n year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),\n month: English.monthsShort.indexOf(monthStr) + 1,\n day: parseInteger(dayStr),\n hour: parseInteger(hourStr),\n minute: parseInteger(minuteStr),\n };\n\n if (secondStr) result.second = parseInteger(secondStr);\n if (weekdayStr) {\n result.weekday =\n weekdayStr.length > 3\n ? English.weekdaysLong.indexOf(weekdayStr) + 1\n : English.weekdaysShort.indexOf(weekdayStr) + 1;\n }\n\n return result;\n}\n\n// RFC 2822/5322\nconst rfc2822 =\n /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\\d\\d)(\\d\\d)))$/;\n\nfunction extractRFC2822(match) {\n const [\n ,\n weekdayStr,\n dayStr,\n monthStr,\n yearStr,\n hourStr,\n minuteStr,\n secondStr,\n obsOffset,\n milOffset,\n offHourStr,\n offMinuteStr,\n ] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n\n let offset;\n if (obsOffset) {\n offset = obsOffsets[obsOffset];\n } else if (milOffset) {\n offset = 0;\n } else {\n offset = signedOffset(offHourStr, offMinuteStr);\n }\n\n return [result, new FixedOffsetZone(offset)];\n}\n\nfunction preprocessRFC2822(s) {\n // Remove comments and folding whitespace and replace multiple-spaces with a single space\n return s\n .replace(/\\([^()]*\\)|[\\n\\t]/g, \" \")\n .replace(/(\\s\\s+)/g, \" \")\n .trim();\n}\n\n// http date\n\nconst rfc1123 =\n /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d\\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n rfc850 =\n /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d\\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n ascii =\n /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \\d|\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) (\\d{4})$/;\n\nfunction extractRFC1123Or850(match) {\n const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nfunction extractASCII(match) {\n const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nconst isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);\nconst isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);\nconst isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);\nconst isoTimeCombinedRegex = combineRegexes(isoTimeRegex);\n\nconst extractISOYmdTimeAndOffset = combineExtractors(\n extractISOYmd,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOWeekTimeAndOffset = combineExtractors(\n extractISOWeekData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOOrdinalDateAndTime = combineExtractors(\n extractISOOrdinalData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOTimeAndOffset = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\n/*\n * @private\n */\n\nexport function parseISODate(s) {\n return parse(\n s,\n [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],\n [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime],\n [isoTimeCombinedRegex, extractISOTimeAndOffset]\n );\n}\n\nexport function parseRFC2822Date(s) {\n return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);\n}\n\nexport function parseHTTPDate(s) {\n return parse(\n s,\n [rfc1123, extractRFC1123Or850],\n [rfc850, extractRFC1123Or850],\n [ascii, extractASCII]\n );\n}\n\nexport function parseISODuration(s) {\n return parse(s, [isoDuration, extractISODuration]);\n}\n\nconst extractISOTimeOnly = combineExtractors(extractISOTime);\n\nexport function parseISOTimeOnly(s) {\n return parse(s, [isoTimeOnly, extractISOTimeOnly]);\n}\n\nconst sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);\nconst sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);\n\nconst extractISOTimeOffsetAndIANAZone = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\nexport function parseSQL(s) {\n return parse(\n s,\n [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]\n );\n}\n","import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from \"./errors.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Locale from \"./impl/locale.js\";\nimport { parseISODuration, parseISOTimeOnly } from \"./impl/regexParser.js\";\nimport {\n asNumber,\n hasOwnProperty,\n isNumber,\n isUndefined,\n normalizeObject,\n roundTo,\n} from \"./impl/util.js\";\nimport Settings from \"./settings.js\";\nimport DateTime from \"./datetime.js\";\n\nconst INVALID = \"Invalid Duration\";\n\n// unit conversion constants\nexport const lowOrderMatrix = {\n weeks: {\n days: 7,\n hours: 7 * 24,\n minutes: 7 * 24 * 60,\n seconds: 7 * 24 * 60 * 60,\n milliseconds: 7 * 24 * 60 * 60 * 1000,\n },\n days: {\n hours: 24,\n minutes: 24 * 60,\n seconds: 24 * 60 * 60,\n milliseconds: 24 * 60 * 60 * 1000,\n },\n hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },\n minutes: { seconds: 60, milliseconds: 60 * 1000 },\n seconds: { milliseconds: 1000 },\n },\n casualMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: 52,\n days: 365,\n hours: 365 * 24,\n minutes: 365 * 24 * 60,\n seconds: 365 * 24 * 60 * 60,\n milliseconds: 365 * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: 13,\n days: 91,\n hours: 91 * 24,\n minutes: 91 * 24 * 60,\n seconds: 91 * 24 * 60 * 60,\n milliseconds: 91 * 24 * 60 * 60 * 1000,\n },\n months: {\n weeks: 4,\n days: 30,\n hours: 30 * 24,\n minutes: 30 * 24 * 60,\n seconds: 30 * 24 * 60 * 60,\n milliseconds: 30 * 24 * 60 * 60 * 1000,\n },\n\n ...lowOrderMatrix,\n },\n daysInYearAccurate = 146097.0 / 400,\n daysInMonthAccurate = 146097.0 / 4800,\n accurateMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: daysInYearAccurate / 7,\n days: daysInYearAccurate,\n hours: daysInYearAccurate * 24,\n minutes: daysInYearAccurate * 24 * 60,\n seconds: daysInYearAccurate * 24 * 60 * 60,\n milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: daysInYearAccurate / 28,\n days: daysInYearAccurate / 4,\n hours: (daysInYearAccurate * 24) / 4,\n minutes: (daysInYearAccurate * 24 * 60) / 4,\n seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,\n milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4,\n },\n months: {\n weeks: daysInMonthAccurate / 7,\n days: daysInMonthAccurate,\n hours: daysInMonthAccurate * 24,\n minutes: daysInMonthAccurate * 24 * 60,\n seconds: daysInMonthAccurate * 24 * 60 * 60,\n milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000,\n },\n ...lowOrderMatrix,\n };\n\n// units ordered by size\nconst orderedUnits = [\n \"years\",\n \"quarters\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\nconst reverseUnits = orderedUnits.slice(0).reverse();\n\n// clone really means \"create another instance just like this one, but with these changes\"\nfunction clone(dur, alts, clear = false) {\n // deep merge for vals\n const conf = {\n values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) },\n loc: dur.loc.clone(alts.loc),\n conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,\n matrix: alts.matrix || dur.matrix,\n };\n return new Duration(conf);\n}\n\nfunction durationToMillis(matrix, vals) {\n let sum = vals.milliseconds ?? 0;\n for (const unit of reverseUnits.slice(1)) {\n if (vals[unit]) {\n sum += vals[unit] * matrix[unit][\"milliseconds\"];\n }\n }\n return sum;\n}\n\n// NB: mutates parameters\nfunction normalizeValues(matrix, vals) {\n // the logic below assumes the overall value of the duration is positive\n // if this is not the case, factor is used to make it so\n const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;\n\n orderedUnits.reduceRight((previous, current) => {\n if (!isUndefined(vals[current])) {\n if (previous) {\n const previousVal = vals[previous] * factor;\n const conv = matrix[current][previous];\n\n // if (previousVal < 0):\n // lower order unit is negative (e.g. { years: 2, days: -2 })\n // normalize this by reducing the higher order unit by the appropriate amount\n // and increasing the lower order unit\n // this can never make the higher order unit negative, because this function only operates\n // on positive durations, so the amount of time represented by the lower order unit cannot\n // be larger than the higher order unit\n // else:\n // lower order unit is positive (e.g. { years: 2, days: 450 } or { years: -2, days: 450 })\n // in this case we attempt to convert as much as possible from the lower order unit into\n // the higher order one\n //\n // Math.floor takes care of both of these cases, rounding away from 0\n // if previousVal < 0 it makes the absolute value larger\n // if previousVal >= it makes the absolute value smaller\n const rollUp = Math.floor(previousVal / conv);\n vals[current] += rollUp * factor;\n vals[previous] -= rollUp * conv * factor;\n }\n return current;\n } else {\n return previous;\n }\n }, null);\n\n // try to convert any decimals into smaller units if possible\n // for example for { years: 2.5, days: 0, seconds: 0 } we want to get { years: 2, days: 182, hours: 12 }\n orderedUnits.reduce((previous, current) => {\n if (!isUndefined(vals[current])) {\n if (previous) {\n const fraction = vals[previous] % 1;\n vals[previous] -= fraction;\n vals[current] += fraction * matrix[previous][current];\n }\n return current;\n } else {\n return previous;\n }\n }, null);\n}\n\n// Remove all properties with a value of 0 from an object\nfunction removeZeroes(vals) {\n const newVals = {};\n for (const [key, value] of Object.entries(vals)) {\n if (value !== 0) {\n newVals[key] = value;\n }\n }\n return newVals;\n}\n\n/**\n * A Duration object represents a period of time, like \"2 months\" or \"1 day, 1 hour\". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.\n *\n * Here is a brief overview of commonly used methods and getters in Duration:\n *\n * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.\n * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.\n * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.\n * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.\n * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}\n *\n * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.\n */\nexport default class Duration {\n /**\n * @private\n */\n constructor(config) {\n const accurate = config.conversionAccuracy === \"longterm\" || false;\n let matrix = accurate ? accurateMatrix : casualMatrix;\n\n if (config.matrix) {\n matrix = config.matrix;\n }\n\n /**\n * @access private\n */\n this.values = config.values;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.conversionAccuracy = accurate ? \"longterm\" : \"casual\";\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.matrix = matrix;\n /**\n * @access private\n */\n this.isLuxonDuration = true;\n }\n\n /**\n * Create Duration from a number of milliseconds.\n * @param {number} count of milliseconds\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n static fromMillis(count, opts) {\n return Duration.fromObject({ milliseconds: count }, opts);\n }\n\n /**\n * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.\n * If this object is empty then a zero milliseconds duration is returned.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.years\n * @param {number} obj.quarters\n * @param {number} obj.months\n * @param {number} obj.weeks\n * @param {number} obj.days\n * @param {number} obj.hours\n * @param {number} obj.minutes\n * @param {number} obj.seconds\n * @param {number} obj.milliseconds\n * @param {Object} [opts=[]] - options for creating this Duration\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n * @param {string} [opts.matrix=Object] - the custom conversion system to use\n * @return {Duration}\n */\n static fromObject(obj, opts = {}) {\n if (obj == null || typeof obj !== \"object\") {\n throw new InvalidArgumentError(\n `Duration.fromObject: argument expected to be an object, got ${\n obj === null ? \"null\" : typeof obj\n }`\n );\n }\n\n return new Duration({\n values: normalizeObject(obj, Duration.normalizeUnit),\n loc: Locale.fromObject(opts),\n conversionAccuracy: opts.conversionAccuracy,\n matrix: opts.matrix,\n });\n }\n\n /**\n * Create a Duration from DurationLike.\n *\n * @param {Object | number | Duration} durationLike\n * One of:\n * - object with keys like 'years' and 'hours'.\n * - number representing milliseconds\n * - Duration instance\n * @return {Duration}\n */\n static fromDurationLike(durationLike) {\n if (isNumber(durationLike)) {\n return Duration.fromMillis(durationLike);\n } else if (Duration.isDuration(durationLike)) {\n return durationLike;\n } else if (typeof durationLike === \"object\") {\n return Duration.fromObject(durationLike);\n } else {\n throw new InvalidArgumentError(\n `Unknown duration argument ${durationLike} of type ${typeof durationLike}`\n );\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 duration string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n * @param {string} [opts.matrix=Object] - the preset conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }\n * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }\n * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }\n * @return {Duration}\n */\n static fromISO(text, opts) {\n const [parsed] = parseISODuration(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 time string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n * @param {string} [opts.matrix=Object] - the conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }\n * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @return {Duration}\n */\n static fromISOTime(text, opts) {\n const [parsed] = parseISOTimeOnly(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create an invalid Duration.\n * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Duration}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Duration is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDurationError(invalid);\n } else {\n return new Duration({ invalid });\n }\n }\n\n /**\n * @private\n */\n static normalizeUnit(unit) {\n const normalized = {\n year: \"years\",\n years: \"years\",\n quarter: \"quarters\",\n quarters: \"quarters\",\n month: \"months\",\n months: \"months\",\n week: \"weeks\",\n weeks: \"weeks\",\n day: \"days\",\n days: \"days\",\n hour: \"hours\",\n hours: \"hours\",\n minute: \"minutes\",\n minutes: \"minutes\",\n second: \"seconds\",\n seconds: \"seconds\",\n millisecond: \"milliseconds\",\n milliseconds: \"milliseconds\",\n }[unit ? unit.toLowerCase() : unit];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n }\n\n /**\n * Check if an object is a Duration. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDuration(o) {\n return (o && o.isLuxonDuration) || false;\n }\n\n /**\n * Get the locale of a Duration, such 'en-GB'\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:\n * * `S` for milliseconds\n * * `s` for seconds\n * * `m` for minutes\n * * `h` for hours\n * * `d` for days\n * * `w` for weeks\n * * `M` for months\n * * `y` for years\n * Notes:\n * * Add padding by repeating the token, e.g. \"yy\" pads the years to two digits, \"hhhh\" pads the hours out to four digits\n * * Tokens can be escaped by wrapping with single quotes.\n * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.\n * @param {string} fmt - the format string\n * @param {Object} opts - options\n * @param {boolean} [opts.floor=true] - floor numerical values\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"y d s\") //=> \"1 6 2\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"yy dd sss\") //=> \"01 06 002\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"M S\") //=> \"12 518402000\"\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n // reverse-compat since 1.2; we always round down now, never up, and we do it by default\n const fmtOpts = {\n ...opts,\n floor: opts.round !== false && opts.floor !== false,\n };\n return this.isValid\n ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a string representation of a Duration with all units included.\n * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options\n * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`.\n * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor.\n * @example\n * ```js\n * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })\n * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'\n * dur.toHuman({ listStyle: \"long\" }) //=> '1 day, 5 hours, and 6 minutes'\n * dur.toHuman({ unitDisplay: \"short\" }) //=> '1 day, 5 hr, 6 min'\n * ```\n */\n toHuman(opts = {}) {\n if (!this.isValid) return INVALID;\n\n const l = orderedUnits\n .map((unit) => {\n const val = this.values[unit];\n if (isUndefined(val)) {\n return null;\n }\n return this.loc\n .numberFormatter({ style: \"unit\", unitDisplay: \"long\", ...opts, unit: unit.slice(0, -1) })\n .format(val);\n })\n .filter((n) => n);\n\n return this.loc\n .listFormatter({ type: \"conjunction\", style: opts.listStyle || \"narrow\", ...opts })\n .format(l);\n }\n\n /**\n * Returns a JavaScript object with this Duration's values.\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }\n * @return {Object}\n */\n toObject() {\n if (!this.isValid) return {};\n return { ...this.values };\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'\n * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'\n * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'\n * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'\n * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'\n * @return {string}\n */\n toISO() {\n // we could use the formatter, but this is an easier way to get the minimum string\n if (!this.isValid) return null;\n\n let s = \"P\";\n if (this.years !== 0) s += this.years + \"Y\";\n if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + \"M\";\n if (this.weeks !== 0) s += this.weeks + \"W\";\n if (this.days !== 0) s += this.days + \"D\";\n if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)\n s += \"T\";\n if (this.hours !== 0) s += this.hours + \"H\";\n if (this.minutes !== 0) s += this.minutes + \"M\";\n if (this.seconds !== 0 || this.milliseconds !== 0)\n // this will handle \"floating point madness\" by removing extra decimal places\n // https://stackoverflow.com/questions/588004/is-floating-point-math-broken\n s += roundTo(this.seconds + this.milliseconds / 1000, 3) + \"S\";\n if (s === \"P\") s += \"T0S\";\n return s;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.\n * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'\n * @return {string}\n */\n toISOTime(opts = {}) {\n if (!this.isValid) return null;\n\n const millis = this.toMillis();\n if (millis < 0 || millis >= 86400000) return null;\n\n opts = {\n suppressMilliseconds: false,\n suppressSeconds: false,\n includePrefix: false,\n format: \"extended\",\n ...opts,\n includeOffset: false,\n };\n\n const dateTime = DateTime.fromMillis(millis, { zone: \"UTC\" });\n return dateTime.toISOTime(opts);\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.\n * @return {string}\n */\n toString() {\n return this.toISO();\n }\n\n /**\n * Returns a string representation of this Duration appropriate for the REPL.\n * @return {string}\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (this.isValid) {\n return `Duration { values: ${JSON.stringify(this.values)} }`;\n } else {\n return `Duration { Invalid, reason: ${this.invalidReason} }`;\n }\n }\n\n /**\n * Returns an milliseconds value of this Duration.\n * @return {number}\n */\n toMillis() {\n if (!this.isValid) return NaN;\n\n return durationToMillis(this.matrix, this.values);\n }\n\n /**\n * Returns an milliseconds value of this Duration. Alias of {@link toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Make this Duration longer by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n plus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration),\n result = {};\n\n for (const k of orderedUnits) {\n if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {\n result[k] = dur.get(k) + this.get(k);\n }\n }\n\n return clone(this, { values: result }, true);\n }\n\n /**\n * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n minus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration);\n return this.plus(dur.negate());\n }\n\n /**\n * Scale this Duration by the specified amount. Return a newly-constructed Duration.\n * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === \"hours\" ? x * 2 : x) //=> { hours: 2, minutes: 30 }\n * @return {Duration}\n */\n mapUnits(fn) {\n if (!this.isValid) return this;\n const result = {};\n for (const k of Object.keys(this.values)) {\n result[k] = asNumber(fn(this.values[k], k));\n }\n return clone(this, { values: result }, true);\n }\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2\n * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0\n * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3\n * @return {number}\n */\n get(unit) {\n return this[Duration.normalizeUnit(unit)];\n }\n\n /**\n * \"Set\" the values of specified units. Return a newly-constructed Duration.\n * @param {Object} values - a mapping of units to numbers\n * @example dur.set({ years: 2017 })\n * @example dur.set({ hours: 8, minutes: 30 })\n * @return {Duration}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };\n return clone(this, { values: mixed });\n }\n\n /**\n * \"Set\" the locale and/or numberingSystem. Returns a newly-constructed Duration.\n * @example dur.reconfigure({ locale: 'en-GB' })\n * @return {Duration}\n */\n reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem });\n const opts = { loc, matrix, conversionAccuracy };\n return clone(this, opts);\n }\n\n /**\n * Return the length of the duration in the specified unit.\n * @param {string} unit - a unit such as 'minutes' or 'days'\n * @example Duration.fromObject({years: 1}).as('days') //=> 365\n * @example Duration.fromObject({years: 1}).as('months') //=> 12\n * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5\n * @return {number}\n */\n as(unit) {\n return this.isValid ? this.shiftTo(unit).get(unit) : NaN;\n }\n\n /**\n * Reduce this Duration to its canonical representation in its current units.\n * Assuming the overall value of the Duration is positive, this means:\n * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)\n * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise\n * the overall value would be negative, see third example)\n * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)\n *\n * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.\n * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }\n * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }\n * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }\n * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }\n * @return {Duration}\n */\n normalize() {\n if (!this.isValid) return this;\n const vals = this.toObject();\n normalizeValues(this.matrix, vals);\n return clone(this, { values: vals }, true);\n }\n\n /**\n * Rescale units to its largest representation\n * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }\n * @return {Duration}\n */\n rescale() {\n if (!this.isValid) return this;\n const vals = removeZeroes(this.normalize().shiftToAll().toObject());\n return clone(this, { values: vals }, true);\n }\n\n /**\n * Convert this Duration into its representation in a different set of units.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }\n * @return {Duration}\n */\n shiftTo(...units) {\n if (!this.isValid) return this;\n\n if (units.length === 0) {\n return this;\n }\n\n units = units.map((u) => Duration.normalizeUnit(u));\n\n const built = {},\n accumulated = {},\n vals = this.toObject();\n let lastUnit;\n\n for (const k of orderedUnits) {\n if (units.indexOf(k) >= 0) {\n lastUnit = k;\n\n let own = 0;\n\n // anything we haven't boiled down yet should get boiled to this unit\n for (const ak in accumulated) {\n own += this.matrix[ak][k] * accumulated[ak];\n accumulated[ak] = 0;\n }\n\n // plus anything that's already in this unit\n if (isNumber(vals[k])) {\n own += vals[k];\n }\n\n // only keep the integer part for now in the hopes of putting any decimal part\n // into a smaller unit later\n const i = Math.trunc(own);\n built[k] = i;\n accumulated[k] = (own * 1000 - i * 1000) / 1000;\n\n // otherwise, keep it in the wings to boil it later\n } else if (isNumber(vals[k])) {\n accumulated[k] = vals[k];\n }\n }\n\n // anything leftover becomes the decimal for the last unit\n // lastUnit must be defined since units is not empty\n for (const key in accumulated) {\n if (accumulated[key] !== 0) {\n built[lastUnit] +=\n key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];\n }\n }\n\n normalizeValues(this.matrix, built);\n return clone(this, { values: built }, true);\n }\n\n /**\n * Shift this Duration to all available units.\n * Same as shiftTo(\"years\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\", \"milliseconds\")\n * @return {Duration}\n */\n shiftToAll() {\n if (!this.isValid) return this;\n return this.shiftTo(\n \"years\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\"\n );\n }\n\n /**\n * Return the negative of this Duration.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }\n * @return {Duration}\n */\n negate() {\n if (!this.isValid) return this;\n const negated = {};\n for (const k of Object.keys(this.values)) {\n negated[k] = this.values[k] === 0 ? 0 : -this.values[k];\n }\n return clone(this, { values: negated }, true);\n }\n\n /**\n * Get the years.\n * @type {number}\n */\n get years() {\n return this.isValid ? this.values.years || 0 : NaN;\n }\n\n /**\n * Get the quarters.\n * @type {number}\n */\n get quarters() {\n return this.isValid ? this.values.quarters || 0 : NaN;\n }\n\n /**\n * Get the months.\n * @type {number}\n */\n get months() {\n return this.isValid ? this.values.months || 0 : NaN;\n }\n\n /**\n * Get the weeks\n * @type {number}\n */\n get weeks() {\n return this.isValid ? this.values.weeks || 0 : NaN;\n }\n\n /**\n * Get the days.\n * @type {number}\n */\n get days() {\n return this.isValid ? this.values.days || 0 : NaN;\n }\n\n /**\n * Get the hours.\n * @type {number}\n */\n get hours() {\n return this.isValid ? this.values.hours || 0 : NaN;\n }\n\n /**\n * Get the minutes.\n * @type {number}\n */\n get minutes() {\n return this.isValid ? this.values.minutes || 0 : NaN;\n }\n\n /**\n * Get the seconds.\n * @return {number}\n */\n get seconds() {\n return this.isValid ? this.values.seconds || 0 : NaN;\n }\n\n /**\n * Get the milliseconds.\n * @return {number}\n */\n get milliseconds() {\n return this.isValid ? this.values.milliseconds || 0 : NaN;\n }\n\n /**\n * Returns whether the Duration is invalid. Invalid durations are returned by diff operations\n * on invalid DateTimes or Intervals.\n * @return {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this Duration became invalid, or null if the Duration is valid\n * @return {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Duration became invalid, or null if the Duration is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Equality check\n * Two Durations are equal iff they have the same units and the same values for each unit.\n * @param {Duration} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n if (!this.loc.equals(other.loc)) {\n return false;\n }\n\n function eq(v1, v2) {\n // Consider 0 and undefined as equal\n if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;\n return v1 === v2;\n }\n\n for (const u of orderedUnits) {\n if (!eq(this.values[u], other.values[u])) {\n return false;\n }\n }\n return true;\n }\n}\n","import DateTime, { friendlyDateTime } from \"./datetime.js\";\nimport Duration from \"./duration.js\";\nimport Settings from \"./settings.js\";\nimport { InvalidArgumentError, InvalidIntervalError } from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport * as Formats from \"./impl/formats.js\";\n\nconst INVALID = \"Invalid Interval\";\n\n// checks if the start is equal to or before the end\nfunction validateStartEnd(start, end) {\n if (!start || !start.isValid) {\n return Interval.invalid(\"missing or invalid start\");\n } else if (!end || !end.isValid) {\n return Interval.invalid(\"missing or invalid end\");\n } else if (end < start) {\n return Interval.invalid(\n \"end before start\",\n `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`\n );\n } else {\n return null;\n }\n}\n\n/**\n * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.\n *\n * Here is a brief overview of the most commonly used methods and getters in Interval:\n *\n * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}.\n * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.\n * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.\n * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.\n * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}\n * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.\n */\nexport default class Interval {\n /**\n * @private\n */\n constructor(config) {\n /**\n * @access private\n */\n this.s = config.start;\n /**\n * @access private\n */\n this.e = config.end;\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.isLuxonInterval = true;\n }\n\n /**\n * Create an invalid Interval.\n * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Interval}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Interval is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidIntervalError(invalid);\n } else {\n return new Interval({ invalid });\n }\n }\n\n /**\n * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.\n * @param {DateTime|Date|Object} start\n * @param {DateTime|Date|Object} end\n * @return {Interval}\n */\n static fromDateTimes(start, end) {\n const builtStart = friendlyDateTime(start),\n builtEnd = friendlyDateTime(end);\n\n const validateError = validateStartEnd(builtStart, builtEnd);\n\n if (validateError == null) {\n return new Interval({\n start: builtStart,\n end: builtEnd,\n });\n } else {\n return validateError;\n }\n }\n\n /**\n * Create an Interval from a start DateTime and a Duration to extend to.\n * @param {DateTime|Date|Object} start\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static after(start, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(start);\n return Interval.fromDateTimes(dt, dt.plus(dur));\n }\n\n /**\n * Create an Interval from an end DateTime and a Duration to extend backwards to.\n * @param {DateTime|Date|Object} end\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static before(end, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(end);\n return Interval.fromDateTimes(dt.minus(dur), dt);\n }\n\n /**\n * Create an Interval from an ISO 8601 string.\n * Accepts `/`, `/`, and `/` formats.\n * @param {string} text - the ISO string to parse\n * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {Interval}\n */\n static fromISO(text, opts) {\n const [s, e] = (text || \"\").split(\"/\", 2);\n if (s && e) {\n let start, startIsValid;\n try {\n start = DateTime.fromISO(s, opts);\n startIsValid = start.isValid;\n } catch (e) {\n startIsValid = false;\n }\n\n let end, endIsValid;\n try {\n end = DateTime.fromISO(e, opts);\n endIsValid = end.isValid;\n } catch (e) {\n endIsValid = false;\n }\n\n if (startIsValid && endIsValid) {\n return Interval.fromDateTimes(start, end);\n }\n\n if (startIsValid) {\n const dur = Duration.fromISO(e, opts);\n if (dur.isValid) {\n return Interval.after(start, dur);\n }\n } else if (endIsValid) {\n const dur = Duration.fromISO(s, opts);\n if (dur.isValid) {\n return Interval.before(end, dur);\n }\n }\n }\n return Interval.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n\n /**\n * Check if an object is an Interval. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isInterval(o) {\n return (o && o.isLuxonInterval) || false;\n }\n\n /**\n * Returns the start of the Interval\n * @type {DateTime}\n */\n get start() {\n return this.isValid ? this.s : null;\n }\n\n /**\n * Returns the end of the Interval\n * @type {DateTime}\n */\n get end() {\n return this.isValid ? this.e : null;\n }\n\n /**\n * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.\n * @type {boolean}\n */\n get isValid() {\n return this.invalidReason === null;\n }\n\n /**\n * Returns an error code if this Interval is invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Interval became invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Returns the length of the Interval in the specified unit.\n * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.\n * @return {number}\n */\n length(unit = \"milliseconds\") {\n return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;\n }\n\n /**\n * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.\n * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'\n * asks 'what dates are included in this interval?', not 'how many days long is this interval?'\n * @param {string} [unit='milliseconds'] - the unit of time to count.\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime\n * @return {number}\n */\n count(unit = \"milliseconds\", opts) {\n if (!this.isValid) return NaN;\n const start = this.start.startOf(unit, opts);\n let end;\n if (opts?.useLocaleWeeks) {\n end = this.end.reconfigure({ locale: start.locale });\n } else {\n end = this.end;\n }\n end = end.startOf(unit, opts);\n return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf());\n }\n\n /**\n * Returns whether this Interval's start and end are both in the same unit of time\n * @param {string} unit - the unit of time to check sameness on\n * @return {boolean}\n */\n hasSame(unit) {\n return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;\n }\n\n /**\n * Return whether this Interval has the same start and end DateTimes.\n * @return {boolean}\n */\n isEmpty() {\n return this.s.valueOf() === this.e.valueOf();\n }\n\n /**\n * Return whether this Interval's start is after the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isAfter(dateTime) {\n if (!this.isValid) return false;\n return this.s > dateTime;\n }\n\n /**\n * Return whether this Interval's end is before the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isBefore(dateTime) {\n if (!this.isValid) return false;\n return this.e <= dateTime;\n }\n\n /**\n * Return whether this Interval contains the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n contains(dateTime) {\n if (!this.isValid) return false;\n return this.s <= dateTime && this.e > dateTime;\n }\n\n /**\n * \"Sets\" the start and/or end dates. Returns a newly-constructed Interval.\n * @param {Object} values - the values to set\n * @param {DateTime} values.start - the starting DateTime\n * @param {DateTime} values.end - the ending DateTime\n * @return {Interval}\n */\n set({ start, end } = {}) {\n if (!this.isValid) return this;\n return Interval.fromDateTimes(start || this.s, end || this.e);\n }\n\n /**\n * Split this Interval at each of the specified DateTimes\n * @param {...DateTime} dateTimes - the unit of time to count.\n * @return {Array}\n */\n splitAt(...dateTimes) {\n if (!this.isValid) return [];\n const sorted = dateTimes\n .map(friendlyDateTime)\n .filter((d) => this.contains(d))\n .sort((a, b) => a.toMillis() - b.toMillis()),\n results = [];\n let { s } = this,\n i = 0;\n\n while (s < this.e) {\n const added = sorted[i] || this.e,\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n i += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into smaller Intervals, each of the specified length.\n * Left over time is grouped into a smaller interval\n * @param {Duration|Object|number} duration - The length of each resulting interval.\n * @return {Array}\n */\n splitBy(duration) {\n const dur = Duration.fromDurationLike(duration);\n\n if (!this.isValid || !dur.isValid || dur.as(\"milliseconds\") === 0) {\n return [];\n }\n\n let { s } = this,\n idx = 1,\n next;\n\n const results = [];\n while (s < this.e) {\n const added = this.start.plus(dur.mapUnits((x) => x * idx));\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n idx += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into the specified number of smaller intervals.\n * @param {number} numberOfParts - The number of Intervals to divide the Interval into.\n * @return {Array}\n */\n divideEqually(numberOfParts) {\n if (!this.isValid) return [];\n return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);\n }\n\n /**\n * Return whether this Interval overlaps with the specified Interval\n * @param {Interval} other\n * @return {boolean}\n */\n overlaps(other) {\n return this.e > other.s && this.s < other.e;\n }\n\n /**\n * Return whether this Interval's end is adjacent to the specified Interval's start.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsStart(other) {\n if (!this.isValid) return false;\n return +this.e === +other.s;\n }\n\n /**\n * Return whether this Interval's start is adjacent to the specified Interval's end.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsEnd(other) {\n if (!this.isValid) return false;\n return +other.e === +this.s;\n }\n\n /**\n * Return whether this Interval engulfs the start and end of the specified Interval.\n * @param {Interval} other\n * @return {boolean}\n */\n engulfs(other) {\n if (!this.isValid) return false;\n return this.s <= other.s && this.e >= other.e;\n }\n\n /**\n * Return whether this Interval has the same start and end as the specified Interval.\n * @param {Interval} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n return this.s.equals(other.s) && this.e.equals(other.e);\n }\n\n /**\n * Return an Interval representing the intersection of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.\n * Returns null if the intersection is empty, meaning, the intervals don't intersect.\n * @param {Interval} other\n * @return {Interval}\n */\n intersection(other) {\n if (!this.isValid) return this;\n const s = this.s > other.s ? this.s : other.s,\n e = this.e < other.e ? this.e : other.e;\n\n if (s >= e) {\n return null;\n } else {\n return Interval.fromDateTimes(s, e);\n }\n }\n\n /**\n * Return an Interval representing the union of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.\n * @param {Interval} other\n * @return {Interval}\n */\n union(other) {\n if (!this.isValid) return this;\n const s = this.s < other.s ? this.s : other.s,\n e = this.e > other.e ? this.e : other.e;\n return Interval.fromDateTimes(s, e);\n }\n\n /**\n * Merge an array of Intervals into a equivalent minimal set of Intervals.\n * Combines overlapping and adjacent Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static merge(intervals) {\n const [found, final] = intervals\n .sort((a, b) => a.s - b.s)\n .reduce(\n ([sofar, current], item) => {\n if (!current) {\n return [sofar, item];\n } else if (current.overlaps(item) || current.abutsStart(item)) {\n return [sofar, current.union(item)];\n } else {\n return [sofar.concat([current]), item];\n }\n },\n [[], null]\n );\n if (final) {\n found.push(final);\n }\n return found;\n }\n\n /**\n * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static xor(intervals) {\n let start = null,\n currentCount = 0;\n const results = [],\n ends = intervals.map((i) => [\n { time: i.s, type: \"s\" },\n { time: i.e, type: \"e\" },\n ]),\n flattened = Array.prototype.concat(...ends),\n arr = flattened.sort((a, b) => a.time - b.time);\n\n for (const i of arr) {\n currentCount += i.type === \"s\" ? 1 : -1;\n\n if (currentCount === 1) {\n start = i.time;\n } else {\n if (start && +start !== +i.time) {\n results.push(Interval.fromDateTimes(start, i.time));\n }\n\n start = null;\n }\n }\n\n return Interval.merge(results);\n }\n\n /**\n * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.\n * @param {...Interval} intervals\n * @return {Array}\n */\n difference(...intervals) {\n return Interval.xor([this].concat(intervals))\n .map((i) => this.intersection(i))\n .filter((i) => i && !i.isEmpty());\n }\n\n /**\n * Returns a string representation of this Interval appropriate for debugging.\n * @return {string}\n */\n toString() {\n if (!this.isValid) return INVALID;\n return `[${this.s.toISO()} – ${this.e.toISO()})`;\n }\n\n /**\n * Returns a string representation of this Interval appropriate for the REPL.\n * @return {string}\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (this.isValid) {\n return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`;\n } else {\n return `Interval { Invalid, reason: ${this.invalidReason} }`;\n }\n }\n\n /**\n * Returns a localized string representing this Interval. Accepts the same options as the\n * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as\n * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method\n * is browser-specific, but in general it will return an appropriate representation of the\n * Interval in the assigned locale. Defaults to the system's locale if no locale has been\n * specified.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or\n * Intl.DateTimeFormat constructor options.\n * @param {Object} opts - Options to override the configuration of the start DateTime.\n * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022\n * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022\n * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022\n * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM\n * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p\n * @return {string}\n */\n toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n return this.isValid\n ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this)\n : INVALID;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Interval.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISO(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of date of this Interval.\n * The time components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {string}\n */\n toISODate() {\n if (!this.isValid) return INVALID;\n return `${this.s.toISODate()}/${this.e.toISODate()}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of time of this Interval.\n * The date components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISOTime(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this Interval formatted according to the specified format\n * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible\n * formatting tool.\n * @param {string} dateFormat - The format string. This string formats the start and end time.\n * See {@link DateTime#toFormat} for details.\n * @param {Object} opts - Options.\n * @param {string} [opts.separator = ' – '] - A separator to place between the start and end\n * representations.\n * @return {string}\n */\n toFormat(dateFormat, { separator = \" – \" } = {}) {\n if (!this.isValid) return INVALID;\n return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;\n }\n\n /**\n * Return a Duration representing the time spanned by this interval.\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }\n * @return {Duration}\n */\n toDuration(unit, opts) {\n if (!this.isValid) {\n return Duration.invalid(this.invalidReason);\n }\n return this.e.diff(this.s, unit, opts);\n }\n\n /**\n * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes\n * @param {function} mapFn\n * @return {Interval}\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))\n */\n mapEndpoints(mapFn) {\n return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));\n }\n}\n","import DateTime from \"./datetime.js\";\nimport Settings from \"./settings.js\";\nimport Locale from \"./impl/locale.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nimport { hasLocaleWeekInfo, hasRelative } from \"./impl/util.js\";\n\n/**\n * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.\n */\nexport default class Info {\n /**\n * Return whether the specified zone contains a DST.\n * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.\n * @return {boolean}\n */\n static hasDST(zone = Settings.defaultZone) {\n const proto = DateTime.now().setZone(zone).set({ month: 12 });\n\n return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;\n }\n\n /**\n * Return whether the specified zone is a valid IANA specifier.\n * @param {string} zone - Zone to check\n * @return {boolean}\n */\n static isValidIANAZone(zone) {\n return IANAZone.isValidZone(zone);\n }\n\n /**\n * Converts the input into a {@link Zone} instance.\n *\n * * If `input` is already a Zone instance, it is returned unchanged.\n * * If `input` is a string containing a valid time zone name, a Zone instance\n * with that name is returned.\n * * If `input` is a string that doesn't refer to a known time zone, a Zone\n * instance with {@link Zone#isValid} == false is returned.\n * * If `input is a number, a Zone instance with the specified fixed offset\n * in minutes is returned.\n * * If `input` is `null` or `undefined`, the default zone is returned.\n * @param {string|Zone|number} [input] - the value to be converted\n * @return {Zone}\n */\n static normalizeZone(input) {\n return normalizeZone(input, Settings.defaultZone);\n }\n\n /**\n * Get the weekday on which the week starts according to the given locale.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @returns {number} the start of the week, 1 for Monday through 7 for Sunday\n */\n static getStartOfWeek({ locale = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale)).getStartOfWeek();\n }\n\n /**\n * Get the minimum number of days necessary in a week before it is considered part of the next year according\n * to the given locale.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @returns {number}\n */\n static getMinimumDaysInFirstWeek({ locale = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale)).getMinDaysInFirstWeek();\n }\n\n /**\n * Get the weekdays, which are considered the weekend according to the given locale\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday\n */\n static getWeekendWeekdays({ locale = null, locObj = null } = {}) {\n // copy the array, because we cache it internally\n return (locObj || Locale.create(locale)).getWeekendDays().slice();\n }\n\n /**\n * Return an array of standalone month names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @example Info.months()[0] //=> 'January'\n * @example Info.months('short')[0] //=> 'Jan'\n * @example Info.months('numeric')[0] //=> '1'\n * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'\n * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'\n * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'\n * @return {Array}\n */\n static months(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);\n }\n\n /**\n * Return an array of format month names.\n * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that\n * changes the string.\n * See {@link Info#months}\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @return {Array}\n */\n static monthsFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);\n }\n\n /**\n * Return an array of standalone week names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the weekday representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @example Info.weekdays()[0] //=> 'Monday'\n * @example Info.weekdays('short')[0] //=> 'Mon'\n * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'\n * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'\n * @return {Array}\n */\n static weekdays(length = \"long\", { locale = null, numberingSystem = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);\n }\n\n /**\n * Return an array of format week names.\n * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that\n * changes the string.\n * See {@link Info#weekdays}\n * @param {string} [length='long'] - the length of the month representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale=null] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @return {Array}\n */\n static weekdaysFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);\n }\n\n /**\n * Return an array of meridiems.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.meridiems() //=> [ 'AM', 'PM' ]\n * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]\n * @return {Array}\n */\n static meridiems({ locale = null } = {}) {\n return Locale.create(locale).meridiems();\n }\n\n /**\n * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.\n * @param {string} [length='short'] - the length of the era representation, such as \"short\" or \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.eras() //=> [ 'BC', 'AD' ]\n * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]\n * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]\n * @return {Array}\n */\n static eras(length = \"short\", { locale = null } = {}) {\n return Locale.create(locale, null, \"gregory\").eras(length);\n }\n\n /**\n * Return the set of available features in this environment.\n * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.\n * Keys:\n * * `relative`: whether this environment supports relative time formatting\n * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale\n * @example Info.features() //=> { relative: false, localeWeek: true }\n * @return {Object}\n */\n static features() {\n return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() };\n }\n}\n","import Duration from \"../duration.js\";\n\nfunction dayDiff(earlier, later) {\n const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf(\"day\").valueOf(),\n ms = utcDayStart(later) - utcDayStart(earlier);\n return Math.floor(Duration.fromMillis(ms).as(\"days\"));\n}\n\nfunction highOrderDiffs(cursor, later, units) {\n const differs = [\n [\"years\", (a, b) => b.year - a.year],\n [\"quarters\", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4],\n [\"months\", (a, b) => b.month - a.month + (b.year - a.year) * 12],\n [\n \"weeks\",\n (a, b) => {\n const days = dayDiff(a, b);\n return (days - (days % 7)) / 7;\n },\n ],\n [\"days\", dayDiff],\n ];\n\n const results = {};\n const earlier = cursor;\n let lowestOrder, highWater;\n\n /* This loop tries to diff using larger units first.\n If we overshoot, we backtrack and try the next smaller unit.\n \"cursor\" starts out at the earlier timestamp and moves closer and closer to \"later\"\n as we use smaller and smaller units.\n highWater keeps track of where we would be if we added one more of the smallest unit,\n this is used later to potentially convert any difference smaller than the smallest higher order unit\n into a fraction of that smallest higher order unit\n */\n for (const [unit, differ] of differs) {\n if (units.indexOf(unit) >= 0) {\n lowestOrder = unit;\n\n results[unit] = differ(cursor, later);\n highWater = earlier.plus(results);\n\n if (highWater > later) {\n // we overshot the end point, backtrack cursor by 1\n results[unit]--;\n cursor = earlier.plus(results);\n\n // if we are still overshooting now, we need to backtrack again\n // this happens in certain situations when diffing times in different zones,\n // because this calculation ignores time zones\n if (cursor > later) {\n // keep the \"overshot by 1\" around as highWater\n highWater = cursor;\n // backtrack cursor by 1\n results[unit]--;\n cursor = earlier.plus(results);\n }\n } else {\n cursor = highWater;\n }\n }\n }\n\n return [cursor, results, highWater, lowestOrder];\n}\n\nexport default function (earlier, later, units, opts) {\n let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);\n\n const remainingMillis = later - cursor;\n\n const lowerOrderUnits = units.filter(\n (u) => [\"hours\", \"minutes\", \"seconds\", \"milliseconds\"].indexOf(u) >= 0\n );\n\n if (lowerOrderUnits.length === 0) {\n if (highWater < later) {\n highWater = cursor.plus({ [lowestOrder]: 1 });\n }\n\n if (highWater !== cursor) {\n results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);\n }\n }\n\n const duration = Duration.fromObject(results, opts);\n\n if (lowerOrderUnits.length > 0) {\n return Duration.fromMillis(remainingMillis, opts)\n .shiftTo(...lowerOrderUnits)\n .plus(duration);\n } else {\n return duration;\n }\n}\n","const numberingSystems = {\n arab: \"[\\u0660-\\u0669]\",\n arabext: \"[\\u06F0-\\u06F9]\",\n bali: \"[\\u1B50-\\u1B59]\",\n beng: \"[\\u09E6-\\u09EF]\",\n deva: \"[\\u0966-\\u096F]\",\n fullwide: \"[\\uFF10-\\uFF19]\",\n gujr: \"[\\u0AE6-\\u0AEF]\",\n hanidec: \"[〇|一|二|三|四|五|六|七|八|九]\",\n khmr: \"[\\u17E0-\\u17E9]\",\n knda: \"[\\u0CE6-\\u0CEF]\",\n laoo: \"[\\u0ED0-\\u0ED9]\",\n limb: \"[\\u1946-\\u194F]\",\n mlym: \"[\\u0D66-\\u0D6F]\",\n mong: \"[\\u1810-\\u1819]\",\n mymr: \"[\\u1040-\\u1049]\",\n orya: \"[\\u0B66-\\u0B6F]\",\n tamldec: \"[\\u0BE6-\\u0BEF]\",\n telu: \"[\\u0C66-\\u0C6F]\",\n thai: \"[\\u0E50-\\u0E59]\",\n tibt: \"[\\u0F20-\\u0F29]\",\n latn: \"\\\\d\",\n};\n\nconst numberingSystemsUTF16 = {\n arab: [1632, 1641],\n arabext: [1776, 1785],\n bali: [6992, 7001],\n beng: [2534, 2543],\n deva: [2406, 2415],\n fullwide: [65296, 65303],\n gujr: [2790, 2799],\n khmr: [6112, 6121],\n knda: [3302, 3311],\n laoo: [3792, 3801],\n limb: [6470, 6479],\n mlym: [3430, 3439],\n mong: [6160, 6169],\n mymr: [4160, 4169],\n orya: [2918, 2927],\n tamldec: [3046, 3055],\n telu: [3174, 3183],\n thai: [3664, 3673],\n tibt: [3872, 3881],\n};\n\nconst hanidecChars = numberingSystems.hanidec.replace(/[\\[|\\]]/g, \"\").split(\"\");\n\nexport function parseDigits(str) {\n let value = parseInt(str, 10);\n if (isNaN(value)) {\n value = \"\";\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n if (str[i].search(numberingSystems.hanidec) !== -1) {\n value += hanidecChars.indexOf(str[i]);\n } else {\n for (const key in numberingSystemsUTF16) {\n const [min, max] = numberingSystemsUTF16[key];\n if (code >= min && code <= max) {\n value += code - min;\n }\n }\n }\n }\n return parseInt(value, 10);\n } else {\n return value;\n }\n}\n\nexport function digitRegex({ numberingSystem }, append = \"\") {\n return new RegExp(`${numberingSystems[numberingSystem || \"latn\"]}${append}`);\n}\n","import { parseMillis, isUndefined, untruncateYear, signedOffset, hasOwnProperty } from \"./util.js\";\nimport Formatter from \"./formatter.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport DateTime from \"../datetime.js\";\nimport { digitRegex, parseDigits } from \"./digits.js\";\nimport { ConflictingSpecificationError } from \"../errors.js\";\n\nconst MISSING_FTP = \"missing Intl.DateTimeFormat.formatToParts support\";\n\nfunction intUnit(regex, post = (i) => i) {\n return { regex, deser: ([s]) => post(parseDigits(s)) };\n}\n\nconst NBSP = String.fromCharCode(160);\nconst spaceOrNBSP = `[ ${NBSP}]`;\nconst spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, \"g\");\n\nfunction fixListRegex(s) {\n // make dots optional and also make them literal\n // make space and non breakable space characters interchangeable\n return s.replace(/\\./g, \"\\\\.?\").replace(spaceOrNBSPRegExp, spaceOrNBSP);\n}\n\nfunction stripInsensitivities(s) {\n return s\n .replace(/\\./g, \"\") // ignore dots that were made optional\n .replace(spaceOrNBSPRegExp, \" \") // interchange space and nbsp\n .toLowerCase();\n}\n\nfunction oneOf(strings, startIndex) {\n if (strings === null) {\n return null;\n } else {\n return {\n regex: RegExp(strings.map(fixListRegex).join(\"|\")),\n deser: ([s]) =>\n strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex,\n };\n }\n}\n\nfunction offset(regex, groups) {\n return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };\n}\n\nfunction simple(regex) {\n return { regex, deser: ([s]) => s };\n}\n\nfunction escapeToken(value) {\n return value.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, \"\\\\$&\");\n}\n\n/**\n * @param token\n * @param {Locale} loc\n */\nfunction unitForToken(token, loc) {\n const one = digitRegex(loc),\n two = digitRegex(loc, \"{2}\"),\n three = digitRegex(loc, \"{3}\"),\n four = digitRegex(loc, \"{4}\"),\n six = digitRegex(loc, \"{6}\"),\n oneOrTwo = digitRegex(loc, \"{1,2}\"),\n oneToThree = digitRegex(loc, \"{1,3}\"),\n oneToSix = digitRegex(loc, \"{1,6}\"),\n oneToNine = digitRegex(loc, \"{1,9}\"),\n twoToFour = digitRegex(loc, \"{2,4}\"),\n fourToSix = digitRegex(loc, \"{4,6}\"),\n literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }),\n unitate = (t) => {\n if (token.literal) {\n return literal(t);\n }\n switch (t.val) {\n // era\n case \"G\":\n return oneOf(loc.eras(\"short\"), 0);\n case \"GG\":\n return oneOf(loc.eras(\"long\"), 0);\n // years\n case \"y\":\n return intUnit(oneToSix);\n case \"yy\":\n return intUnit(twoToFour, untruncateYear);\n case \"yyyy\":\n return intUnit(four);\n case \"yyyyy\":\n return intUnit(fourToSix);\n case \"yyyyyy\":\n return intUnit(six);\n // months\n case \"M\":\n return intUnit(oneOrTwo);\n case \"MM\":\n return intUnit(two);\n case \"MMM\":\n return oneOf(loc.months(\"short\", true), 1);\n case \"MMMM\":\n return oneOf(loc.months(\"long\", true), 1);\n case \"L\":\n return intUnit(oneOrTwo);\n case \"LL\":\n return intUnit(two);\n case \"LLL\":\n return oneOf(loc.months(\"short\", false), 1);\n case \"LLLL\":\n return oneOf(loc.months(\"long\", false), 1);\n // dates\n case \"d\":\n return intUnit(oneOrTwo);\n case \"dd\":\n return intUnit(two);\n // ordinals\n case \"o\":\n return intUnit(oneToThree);\n case \"ooo\":\n return intUnit(three);\n // time\n case \"HH\":\n return intUnit(two);\n case \"H\":\n return intUnit(oneOrTwo);\n case \"hh\":\n return intUnit(two);\n case \"h\":\n return intUnit(oneOrTwo);\n case \"mm\":\n return intUnit(two);\n case \"m\":\n return intUnit(oneOrTwo);\n case \"q\":\n return intUnit(oneOrTwo);\n case \"qq\":\n return intUnit(two);\n case \"s\":\n return intUnit(oneOrTwo);\n case \"ss\":\n return intUnit(two);\n case \"S\":\n return intUnit(oneToThree);\n case \"SSS\":\n return intUnit(three);\n case \"u\":\n return simple(oneToNine);\n case \"uu\":\n return simple(oneOrTwo);\n case \"uuu\":\n return intUnit(one);\n // meridiem\n case \"a\":\n return oneOf(loc.meridiems(), 0);\n // weekYear (k)\n case \"kkkk\":\n return intUnit(four);\n case \"kk\":\n return intUnit(twoToFour, untruncateYear);\n // weekNumber (W)\n case \"W\":\n return intUnit(oneOrTwo);\n case \"WW\":\n return intUnit(two);\n // weekdays\n case \"E\":\n case \"c\":\n return intUnit(one);\n case \"EEE\":\n return oneOf(loc.weekdays(\"short\", false), 1);\n case \"EEEE\":\n return oneOf(loc.weekdays(\"long\", false), 1);\n case \"ccc\":\n return oneOf(loc.weekdays(\"short\", true), 1);\n case \"cccc\":\n return oneOf(loc.weekdays(\"long\", true), 1);\n // offset/zone\n case \"Z\":\n case \"ZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);\n case \"ZZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);\n // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing\n // because we don't have any way to figure out what they are\n case \"z\":\n return simple(/[a-z_+-/]{1,256}?/i);\n // this special-case \"token\" represents a place where a macro-token expanded into a white-space literal\n // in this case we accept any non-newline white-space\n case \" \":\n return simple(/[^\\S\\n\\r]/);\n default:\n return literal(t);\n }\n };\n\n const unit = unitate(token) || {\n invalidReason: MISSING_FTP,\n };\n\n unit.token = token;\n\n return unit;\n}\n\nconst partTypeStyleToTokenVal = {\n year: {\n \"2-digit\": \"yy\",\n numeric: \"yyyyy\",\n },\n month: {\n numeric: \"M\",\n \"2-digit\": \"MM\",\n short: \"MMM\",\n long: \"MMMM\",\n },\n day: {\n numeric: \"d\",\n \"2-digit\": \"dd\",\n },\n weekday: {\n short: \"EEE\",\n long: \"EEEE\",\n },\n dayperiod: \"a\",\n dayPeriod: \"a\",\n hour12: {\n numeric: \"h\",\n \"2-digit\": \"hh\",\n },\n hour24: {\n numeric: \"H\",\n \"2-digit\": \"HH\",\n },\n minute: {\n numeric: \"m\",\n \"2-digit\": \"mm\",\n },\n second: {\n numeric: \"s\",\n \"2-digit\": \"ss\",\n },\n timeZoneName: {\n long: \"ZZZZZ\",\n short: \"ZZZ\",\n },\n};\n\nfunction tokenForPart(part, formatOpts, resolvedOpts) {\n const { type, value } = part;\n\n if (type === \"literal\") {\n const isSpace = /^\\s+$/.test(value);\n return {\n literal: !isSpace,\n val: isSpace ? \" \" : value,\n };\n }\n\n const style = formatOpts[type];\n\n // The user might have explicitly specified hour12 or hourCycle\n // if so, respect their decision\n // if not, refer back to the resolvedOpts, which are based on the locale\n let actualType = type;\n if (type === \"hour\") {\n if (formatOpts.hour12 != null) {\n actualType = formatOpts.hour12 ? \"hour12\" : \"hour24\";\n } else if (formatOpts.hourCycle != null) {\n if (formatOpts.hourCycle === \"h11\" || formatOpts.hourCycle === \"h12\") {\n actualType = \"hour12\";\n } else {\n actualType = \"hour24\";\n }\n } else {\n // tokens only differentiate between 24 hours or not,\n // so we do not need to check hourCycle here, which is less supported anyways\n actualType = resolvedOpts.hour12 ? \"hour12\" : \"hour24\";\n }\n }\n let val = partTypeStyleToTokenVal[actualType];\n if (typeof val === \"object\") {\n val = val[style];\n }\n\n if (val) {\n return {\n literal: false,\n val,\n };\n }\n\n return undefined;\n}\n\nfunction buildRegex(units) {\n const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, \"\");\n return [`^${re}$`, units];\n}\n\nfunction match(input, regex, handlers) {\n const matches = input.match(regex);\n\n if (matches) {\n const all = {};\n let matchIndex = 1;\n for (const i in handlers) {\n if (hasOwnProperty(handlers, i)) {\n const h = handlers[i],\n groups = h.groups ? h.groups + 1 : 1;\n if (!h.literal && h.token) {\n all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));\n }\n matchIndex += groups;\n }\n }\n return [matches, all];\n } else {\n return [matches, {}];\n }\n}\n\nfunction dateTimeFromMatches(matches) {\n const toField = (token) => {\n switch (token) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n case \"H\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"o\":\n return \"ordinal\";\n case \"L\":\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n case \"E\":\n case \"c\":\n return \"weekday\";\n case \"W\":\n return \"weekNumber\";\n case \"k\":\n return \"weekYear\";\n case \"q\":\n return \"quarter\";\n default:\n return null;\n }\n };\n\n let zone = null;\n let specificOffset;\n if (!isUndefined(matches.z)) {\n zone = IANAZone.create(matches.z);\n }\n\n if (!isUndefined(matches.Z)) {\n if (!zone) {\n zone = new FixedOffsetZone(matches.Z);\n }\n specificOffset = matches.Z;\n }\n\n if (!isUndefined(matches.q)) {\n matches.M = (matches.q - 1) * 3 + 1;\n }\n\n if (!isUndefined(matches.h)) {\n if (matches.h < 12 && matches.a === 1) {\n matches.h += 12;\n } else if (matches.h === 12 && matches.a === 0) {\n matches.h = 0;\n }\n }\n\n if (matches.G === 0 && matches.y) {\n matches.y = -matches.y;\n }\n\n if (!isUndefined(matches.u)) {\n matches.S = parseMillis(matches.u);\n }\n\n const vals = Object.keys(matches).reduce((r, k) => {\n const f = toField(k);\n if (f) {\n r[f] = matches[k];\n }\n\n return r;\n }, {});\n\n return [vals, zone, specificOffset];\n}\n\nlet dummyDateTimeCache = null;\n\nfunction getDummyDateTime() {\n if (!dummyDateTimeCache) {\n dummyDateTimeCache = DateTime.fromMillis(1555555555555);\n }\n\n return dummyDateTimeCache;\n}\n\nfunction maybeExpandMacroToken(token, locale) {\n if (token.literal) {\n return token;\n }\n\n const formatOpts = Formatter.macroTokenToFormatOpts(token.val);\n const tokens = formatOptsToTokens(formatOpts, locale);\n\n if (tokens == null || tokens.includes(undefined)) {\n return token;\n }\n\n return tokens;\n}\n\nexport function expandMacroTokens(tokens, locale) {\n return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));\n}\n\n/**\n * @private\n */\n\nexport function explainFromTokens(locale, input, format) {\n const tokens = expandMacroTokens(Formatter.parseFormat(format), locale),\n units = tokens.map((t) => unitForToken(t, locale)),\n disqualifyingUnit = units.find((t) => t.invalidReason);\n\n if (disqualifyingUnit) {\n return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };\n } else {\n const [regexString, handlers] = buildRegex(units),\n regex = RegExp(regexString, \"i\"),\n [rawMatches, matches] = match(input, regex, handlers),\n [result, zone, specificOffset] = matches\n ? dateTimeFromMatches(matches)\n : [null, null, undefined];\n if (hasOwnProperty(matches, \"a\") && hasOwnProperty(matches, \"H\")) {\n throw new ConflictingSpecificationError(\n \"Can't include meridiem when specifying 24-hour format\"\n );\n }\n return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset };\n }\n}\n\nexport function parseFromTokens(locale, input, format) {\n const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format);\n return [result, zone, specificOffset, invalidReason];\n}\n\nexport function formatOptsToTokens(formatOpts, locale) {\n if (!formatOpts) {\n return null;\n }\n\n const formatter = Formatter.create(locale, formatOpts);\n const df = formatter.dtFormatter(getDummyDateTime());\n const parts = df.formatToParts();\n const resolvedOpts = df.resolvedOptions();\n return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts));\n}\n","import Duration from \"./duration.js\";\nimport Interval from \"./interval.js\";\nimport Settings from \"./settings.js\";\nimport Info from \"./info.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport FixedOffsetZone from \"./zones/fixedOffsetZone.js\";\nimport Locale from \"./impl/locale.js\";\nimport {\n isUndefined,\n maybeArray,\n isDate,\n isNumber,\n bestBy,\n daysInMonth,\n daysInYear,\n isLeapYear,\n weeksInWeekYear,\n normalizeObject,\n roundTo,\n objToLocalTS,\n padStart,\n} from \"./impl/util.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\nimport diff from \"./impl/diff.js\";\nimport { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from \"./impl/regexParser.js\";\nimport {\n parseFromTokens,\n explainFromTokens,\n formatOptsToTokens,\n expandMacroTokens,\n} from \"./impl/tokenParser.js\";\nimport {\n gregorianToWeek,\n weekToGregorian,\n gregorianToOrdinal,\n ordinalToGregorian,\n hasInvalidGregorianData,\n hasInvalidWeekData,\n hasInvalidOrdinalData,\n hasInvalidTimeData,\n usesLocalWeekValues,\n isoWeekdayToLocal,\n} from \"./impl/conversions.js\";\nimport * as Formats from \"./impl/formats.js\";\nimport {\n InvalidArgumentError,\n ConflictingSpecificationError,\n InvalidUnitError,\n InvalidDateTimeError,\n} from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\n\nconst INVALID = \"Invalid DateTime\";\nconst MAX_DATE = 8.64e15;\n\nfunction unsupportedZone(zone) {\n return new Invalid(\"unsupported zone\", `the zone \"${zone.name}\" is not supported`);\n}\n\n// we cache week data on the DT object and this intermediates the cache\n/**\n * @param {DateTime} dt\n */\nfunction possiblyCachedWeekData(dt) {\n if (dt.weekData === null) {\n dt.weekData = gregorianToWeek(dt.c);\n }\n return dt.weekData;\n}\n\n/**\n * @param {DateTime} dt\n */\nfunction possiblyCachedLocalWeekData(dt) {\n if (dt.localWeekData === null) {\n dt.localWeekData = gregorianToWeek(\n dt.c,\n dt.loc.getMinDaysInFirstWeek(),\n dt.loc.getStartOfWeek()\n );\n }\n return dt.localWeekData;\n}\n\n// clone really means, \"make a new object with these modifications\". all \"setters\" really use this\n// to create a new object while only changing some of the properties\nfunction clone(inst, alts) {\n const current = {\n ts: inst.ts,\n zone: inst.zone,\n c: inst.c,\n o: inst.o,\n loc: inst.loc,\n invalid: inst.invalid,\n };\n return new DateTime({ ...current, ...alts, old: current });\n}\n\n// find the right offset a given local time. The o input is our guess, which determines which\n// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)\nfunction fixOffset(localTS, o, tz) {\n // Our UTC time is just a guess because our offset is just a guess\n let utcGuess = localTS - o * 60 * 1000;\n\n // Test whether the zone matches the offset for this ts\n const o2 = tz.offset(utcGuess);\n\n // If so, offset didn't change and we're done\n if (o === o2) {\n return [utcGuess, o];\n }\n\n // If not, change the ts by the difference in the offset\n utcGuess -= (o2 - o) * 60 * 1000;\n\n // If that gives us the local time we want, we're done\n const o3 = tz.offset(utcGuess);\n if (o2 === o3) {\n return [utcGuess, o2];\n }\n\n // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time\n return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];\n}\n\n// convert an epoch timestamp into a calendar object with the given offset\nfunction tsToObj(ts, offset) {\n ts += offset * 60 * 1000;\n\n const d = new Date(ts);\n\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n minute: d.getUTCMinutes(),\n second: d.getUTCSeconds(),\n millisecond: d.getUTCMilliseconds(),\n };\n}\n\n// convert a calendar object to a epoch timestamp\nfunction objToTS(obj, offset, zone) {\n return fixOffset(objToLocalTS(obj), offset, zone);\n}\n\n// create a new DT instance by adding a duration, adjusting for DSTs\nfunction adjustTime(inst, dur) {\n const oPre = inst.o,\n year = inst.c.year + Math.trunc(dur.years),\n month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,\n c = {\n ...inst.c,\n year,\n month,\n day:\n Math.min(inst.c.day, daysInMonth(year, month)) +\n Math.trunc(dur.days) +\n Math.trunc(dur.weeks) * 7,\n },\n millisToAdd = Duration.fromObject({\n years: dur.years - Math.trunc(dur.years),\n quarters: dur.quarters - Math.trunc(dur.quarters),\n months: dur.months - Math.trunc(dur.months),\n weeks: dur.weeks - Math.trunc(dur.weeks),\n days: dur.days - Math.trunc(dur.days),\n hours: dur.hours,\n minutes: dur.minutes,\n seconds: dur.seconds,\n milliseconds: dur.milliseconds,\n }).as(\"milliseconds\"),\n localTS = objToLocalTS(c);\n\n let [ts, o] = fixOffset(localTS, oPre, inst.zone);\n\n if (millisToAdd !== 0) {\n ts += millisToAdd;\n // that could have changed the offset by going over a DST, but we want to keep the ts the same\n o = inst.zone.offset(ts);\n }\n\n return { ts, o };\n}\n\n// helper useful in turning the results of parsing into real dates\n// by handling the zone options\nfunction parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {\n const { setZone, zone } = opts;\n if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) {\n const interpretationZone = parsedZone || zone,\n inst = DateTime.fromObject(parsed, {\n ...opts,\n zone: interpretationZone,\n specificOffset,\n });\n return setZone ? inst : inst.setZone(zone);\n } else {\n return DateTime.invalid(\n new Invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ${format}`)\n );\n }\n}\n\n// if you want to output a technical format (e.g. RFC 2822), this helper\n// helps handle the details\nfunction toTechFormat(dt, format, allowZ = true) {\n return dt.isValid\n ? Formatter.create(Locale.create(\"en-US\"), {\n allowZ,\n forceSimple: true,\n }).formatDateTimeFromString(dt, format)\n : null;\n}\n\nfunction toISODate(o, extended) {\n const longFormat = o.c.year > 9999 || o.c.year < 0;\n let c = \"\";\n if (longFormat && o.c.year >= 0) c += \"+\";\n c += padStart(o.c.year, longFormat ? 6 : 4);\n\n if (extended) {\n c += \"-\";\n c += padStart(o.c.month);\n c += \"-\";\n c += padStart(o.c.day);\n } else {\n c += padStart(o.c.month);\n c += padStart(o.c.day);\n }\n return c;\n}\n\nfunction toISOTime(\n o,\n extended,\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n) {\n let c = padStart(o.c.hour);\n if (extended) {\n c += \":\";\n c += padStart(o.c.minute);\n if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {\n c += \":\";\n }\n } else {\n c += padStart(o.c.minute);\n }\n\n if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {\n c += padStart(o.c.second);\n\n if (o.c.millisecond !== 0 || !suppressMilliseconds) {\n c += \".\";\n c += padStart(o.c.millisecond, 3);\n }\n }\n\n if (includeOffset) {\n if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {\n c += \"Z\";\n } else if (o.o < 0) {\n c += \"-\";\n c += padStart(Math.trunc(-o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(-o.o % 60));\n } else {\n c += \"+\";\n c += padStart(Math.trunc(o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(o.o % 60));\n }\n }\n\n if (extendedZone) {\n c += \"[\" + o.zone.ianaName + \"]\";\n }\n return c;\n}\n\n// defaults for unspecified units in the supported calendars\nconst defaultUnitValues = {\n month: 1,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultWeekUnitValues = {\n weekNumber: 1,\n weekday: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultOrdinalUnitValues = {\n ordinal: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n };\n\n// Units in the supported calendars, sorted by bigness\nconst orderedUnits = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"],\n orderedWeekUnits = [\n \"weekYear\",\n \"weekNumber\",\n \"weekday\",\n \"hour\",\n \"minute\",\n \"second\",\n \"millisecond\",\n ],\n orderedOrdinalUnits = [\"year\", \"ordinal\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n// standardize case and plurality in units\nfunction normalizeUnit(unit) {\n const normalized = {\n year: \"year\",\n years: \"year\",\n month: \"month\",\n months: \"month\",\n day: \"day\",\n days: \"day\",\n hour: \"hour\",\n hours: \"hour\",\n minute: \"minute\",\n minutes: \"minute\",\n quarter: \"quarter\",\n quarters: \"quarter\",\n second: \"second\",\n seconds: \"second\",\n millisecond: \"millisecond\",\n milliseconds: \"millisecond\",\n weekday: \"weekday\",\n weekdays: \"weekday\",\n weeknumber: \"weekNumber\",\n weeksnumber: \"weekNumber\",\n weeknumbers: \"weekNumber\",\n weekyear: \"weekYear\",\n weekyears: \"weekYear\",\n ordinal: \"ordinal\",\n }[unit.toLowerCase()];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n}\n\nfunction normalizeUnitWithLocalWeeks(unit) {\n switch (unit.toLowerCase()) {\n case \"localweekday\":\n case \"localweekdays\":\n return \"localWeekday\";\n case \"localweeknumber\":\n case \"localweeknumbers\":\n return \"localWeekNumber\";\n case \"localweekyear\":\n case \"localweekyears\":\n return \"localWeekYear\";\n default:\n return normalizeUnit(unit);\n }\n}\n\n// this is a dumbed down version of fromObject() that runs about 60% faster\n// but doesn't do any validation, makes a bunch of assumptions about what units\n// are present, and so on.\nfunction quickDT(obj, opts) {\n const zone = normalizeZone(opts.zone, Settings.defaultZone),\n loc = Locale.fromObject(opts),\n tsNow = Settings.now();\n\n let ts, o;\n\n // assume we have the higher-order units\n if (!isUndefined(obj.year)) {\n for (const u of orderedUnits) {\n if (isUndefined(obj[u])) {\n obj[u] = defaultUnitValues[u];\n }\n }\n\n const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n const offsetProvis = zone.offset(tsNow);\n [ts, o] = objToTS(obj, offsetProvis, zone);\n } else {\n ts = tsNow;\n }\n\n return new DateTime({ ts, zone, loc, o });\n}\n\nfunction diffRelative(start, end, opts) {\n const round = isUndefined(opts.round) ? true : opts.round,\n format = (c, unit) => {\n c = roundTo(c, round || opts.calendary ? 0 : 2, true);\n const formatter = end.loc.clone(opts).relFormatter(opts);\n return formatter.format(c, unit);\n },\n differ = (unit) => {\n if (opts.calendary) {\n if (!end.hasSame(start, unit)) {\n return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);\n } else return 0;\n } else {\n return end.diff(start, unit).get(unit);\n }\n };\n\n if (opts.unit) {\n return format(differ(opts.unit), opts.unit);\n }\n\n for (const unit of opts.units) {\n const count = differ(unit);\n if (Math.abs(count) >= 1) {\n return format(count, unit);\n }\n }\n return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);\n}\n\nfunction lastOpts(argList) {\n let opts = {},\n args;\n if (argList.length > 0 && typeof argList[argList.length - 1] === \"object\") {\n opts = argList[argList.length - 1];\n args = Array.from(argList).slice(0, argList.length - 1);\n } else {\n args = Array.from(argList);\n }\n return [opts, args];\n}\n\n/**\n * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.\n *\n * A DateTime comprises of:\n * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.\n * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).\n * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.\n *\n * Here is a brief overview of the most commonly used functionality it provides:\n *\n * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.\n * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},\n * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.\n * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.\n * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.\n * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.\n * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.\n *\n * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.\n */\nexport default class DateTime {\n /**\n * @access private\n */\n constructor(config) {\n const zone = config.zone || Settings.defaultZone;\n\n let invalid =\n config.invalid ||\n (Number.isNaN(config.ts) ? new Invalid(\"invalid input\") : null) ||\n (!zone.isValid ? unsupportedZone(zone) : null);\n /**\n * @access private\n */\n this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;\n\n let c = null,\n o = null;\n if (!invalid) {\n const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);\n\n if (unchanged) {\n [c, o] = [config.old.c, config.old.o];\n } else {\n const ot = zone.offset(this.ts);\n c = tsToObj(this.ts, ot);\n invalid = Number.isNaN(c.year) ? new Invalid(\"invalid input\") : null;\n c = invalid ? null : c;\n o = invalid ? null : ot;\n }\n }\n\n /**\n * @access private\n */\n this._zone = zone;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.invalid = invalid;\n /**\n * @access private\n */\n this.weekData = null;\n /**\n * @access private\n */\n this.localWeekData = null;\n /**\n * @access private\n */\n this.c = c;\n /**\n * @access private\n */\n this.o = o;\n /**\n * @access private\n */\n this.isLuxonDateTime = true;\n }\n\n // CONSTRUCT\n\n /**\n * Create a DateTime for the current instant, in the system's time zone.\n *\n * Use Settings to override these default values if needed.\n * @example DateTime.now().toISO() //~> now in the ISO format\n * @return {DateTime}\n */\n static now() {\n return new DateTime({});\n }\n\n /**\n * Create a local DateTime\n * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month, 1-indexed\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @example DateTime.local() //~> now\n * @example DateTime.local({ zone: \"America/New_York\" }) //~> now, in US east coast time\n * @example DateTime.local(2017) //~> 2017-01-01T00:00:00\n * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00\n * @example DateTime.local(2017, 3, 12, { locale: \"fr\" }) //~> 2017-03-12T00:00:00, with a French locale\n * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00\n * @example DateTime.local(2017, 3, 12, 5, { zone: \"utc\" }) //~> 2017-03-12T05:00:00, in UTC\n * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00\n * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10\n * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765\n * @return {DateTime}\n */\n static local() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime in UTC\n * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @param {Object} options - configuration options for the DateTime\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @example DateTime.utc() //~> now\n * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z\n * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z\n * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: \"fr\" }) //~> 2017-03-12T05:45:00Z with a French locale\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: \"fr\" }) //~> 2017-03-12T05:45:10.765Z with a French locale\n * @return {DateTime}\n */\n static utc() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n\n opts.zone = FixedOffsetZone.utcInstance;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime from a JavaScript Date object. Uses the default zone.\n * @param {Date} date - a JavaScript Date object\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @return {DateTime}\n */\n static fromJSDate(date, options = {}) {\n const ts = isDate(date) ? date.valueOf() : NaN;\n if (Number.isNaN(ts)) {\n return DateTime.invalid(\"invalid input\");\n }\n\n const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n return new DateTime({\n ts: ts,\n zone: zoneToUse,\n loc: Locale.fromObject(options),\n });\n }\n\n /**\n * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} milliseconds - a number of milliseconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromMillis(milliseconds, options = {}) {\n if (!isNumber(milliseconds)) {\n throw new InvalidArgumentError(\n `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`\n );\n } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {\n // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start\n return DateTime.invalid(\"Timestamp out of range\");\n } else {\n return new DateTime({\n ts: milliseconds,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} seconds - a number of seconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromSeconds(seconds, options = {}) {\n if (!isNumber(seconds)) {\n throw new InvalidArgumentError(\"fromSeconds requires a numerical input\");\n } else {\n return new DateTime({\n ts: seconds * 1000,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.year - a year, such as 1987\n * @param {number} obj.month - a month, 1-12\n * @param {number} obj.day - a day of the month, 1-31, depending on the month\n * @param {number} obj.ordinal - day of the year, 1-365 or 366\n * @param {number} obj.weekYear - an ISO week year\n * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year\n * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday\n * @param {number} obj.localWeekYear - a week year, according to the locale\n * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale\n * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale\n * @param {number} obj.hour - hour of the day, 0-23\n * @param {number} obj.minute - minute of the hour, 0-59\n * @param {number} obj.second - second of the minute, 0-59\n * @param {number} obj.millisecond - millisecond of the second, 0-999\n * @param {Object} opts - options for creating this DateTime\n * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()\n * @param {string} [opts.locale='system\\'s locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'\n * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })\n * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'\n * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: \"en-US\" }).toISODate() //=> '2021-12-26'\n * @return {DateTime}\n */\n static fromObject(obj, opts = {}) {\n obj = obj || {};\n const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n const loc = Locale.fromObject(opts);\n const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks);\n const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc);\n\n const tsNow = Settings.now(),\n offsetProvis = !isUndefined(opts.specificOffset)\n ? opts.specificOffset\n : zoneToUse.offset(tsNow),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n // cases:\n // just a weekday -> this week's instance of that weekday, no worries\n // (gregorian data or ordinal) + (weekYear or weekNumber) -> error\n // (gregorian month or day) + ordinal -> error\n // otherwise just use weeks or ordinals or gregorian, depending on what's specified\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);\n\n // configure ourselves to deal with gregorian dates or week stuff\n let units,\n defaultValues,\n objNow = tsToObj(tsNow, offsetProvis);\n if (useWeekData) {\n units = orderedWeekUnits;\n defaultValues = defaultWeekUnitValues;\n objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek);\n } else if (containsOrdinal) {\n units = orderedOrdinalUnits;\n defaultValues = defaultOrdinalUnitValues;\n objNow = gregorianToOrdinal(objNow);\n } else {\n units = orderedUnits;\n defaultValues = defaultUnitValues;\n }\n\n // set default values for missing stuff\n let foundFirst = false;\n for (const u of units) {\n const v = normalized[u];\n if (!isUndefined(v)) {\n foundFirst = true;\n } else if (foundFirst) {\n normalized[u] = defaultValues[u];\n } else {\n normalized[u] = objNow[u];\n }\n }\n\n // make sure the values we have are in range\n const higherOrderInvalid = useWeekData\n ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek)\n : containsOrdinal\n ? hasInvalidOrdinalData(normalized)\n : hasInvalidGregorianData(normalized),\n invalid = higherOrderInvalid || hasInvalidTimeData(normalized);\n\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n // compute the actual time\n const gregorian = useWeekData\n ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek)\n : containsOrdinal\n ? ordinalToGregorian(normalized)\n : normalized,\n [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),\n inst = new DateTime({\n ts: tsFinal,\n zone: zoneToUse,\n o: offsetFinal,\n loc,\n });\n\n // gregorian data + weekday serves only to validate\n if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {\n return DateTime.invalid(\n \"mismatched weekday\",\n `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`\n );\n }\n\n return inst;\n }\n\n /**\n * Create a DateTime from an ISO 8601 string\n * @param {string} text - the ISO string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromISO('2016-05-25T09:08:34.123')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})\n * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})\n * @example DateTime.fromISO('2016-W05-4')\n * @return {DateTime}\n */\n static fromISO(text, opts = {}) {\n const [vals, parsedZone] = parseISODate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"ISO 8601\", text);\n }\n\n /**\n * Create a DateTime from an RFC 2822 string\n * @param {string} text - the RFC 2822 string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')\n * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')\n * @return {DateTime}\n */\n static fromRFC2822(text, opts = {}) {\n const [vals, parsedZone] = parseRFC2822Date(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"RFC 2822\", text);\n }\n\n /**\n * Create a DateTime from an HTTP header date\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @param {string} text - the HTTP header date\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')\n * @return {DateTime}\n */\n static fromHTTP(text, opts = {}) {\n const [vals, parsedZone] = parseHTTPDate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"HTTP\", opts);\n }\n\n /**\n * Create a DateTime from an input string and format string.\n * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromFormat(text, fmt, opts = {}) {\n if (isUndefined(text) || isUndefined(fmt)) {\n throw new InvalidArgumentError(\"fromFormat requires an input string and a format\");\n }\n\n const { locale = null, numberingSystem = null } = opts,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n }),\n [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);\n if (invalid) {\n return DateTime.invalid(invalid);\n } else {\n return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);\n }\n }\n\n /**\n * @deprecated use fromFormat instead\n */\n static fromString(text, fmt, opts = {}) {\n return DateTime.fromFormat(text, fmt, opts);\n }\n\n /**\n * Create a DateTime from a SQL date, time, or datetime\n * Defaults to en-US if no locale has been specified, regardless of the system's locale\n * @param {string} text - the string to parse\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @example DateTime.fromSQL('2017-05-15')\n * @example DateTime.fromSQL('2017-05-15 09:12:34')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })\n * @example DateTime.fromSQL('09:12:34.342')\n * @return {DateTime}\n */\n static fromSQL(text, opts = {}) {\n const [vals, parsedZone] = parseSQL(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"SQL\", text);\n }\n\n /**\n * Create an invalid DateTime.\n * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {DateTime}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the DateTime is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDateTimeError(invalid);\n } else {\n return new DateTime({ invalid });\n }\n }\n\n /**\n * Check if an object is an instance of DateTime. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDateTime(o) {\n return (o && o.isLuxonDateTime) || false;\n }\n\n /**\n * Produce the format string for a set of options\n * @param formatOpts\n * @param localeOpts\n * @returns {string}\n */\n static parseFormatForOpts(formatOpts, localeOpts = {}) {\n const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));\n return !tokenList ? null : tokenList.map((t) => (t ? t.val : null)).join(\"\");\n }\n\n /**\n * Produce the the fully expanded format token for the locale\n * Does NOT quote characters, so quoted tokens will not round trip correctly\n * @param fmt\n * @param localeOpts\n * @returns {string}\n */\n static expandFormat(fmt, localeOpts = {}) {\n const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));\n return expanded.map((t) => t.val).join(\"\");\n }\n\n // INFO\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example DateTime.local(2017, 7, 4).get('month'); //=> 7\n * @example DateTime.local(2017, 7, 4).get('day'); //=> 4\n * @return {number}\n */\n get(unit) {\n return this[unit];\n }\n\n /**\n * Returns whether the DateTime is valid. Invalid DateTimes occur when:\n * * The DateTime was created from invalid calendar information, such as the 13th month or February 30\n * * The DateTime was created by an operation on another invalid date\n * @type {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this DateTime is invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime\n *\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime\n *\n * @type {string}\n */\n get outputCalendar() {\n return this.isValid ? this.loc.outputCalendar : null;\n }\n\n /**\n * Get the time zone associated with this DateTime.\n * @type {Zone}\n */\n get zone() {\n return this._zone;\n }\n\n /**\n * Get the name of the time zone.\n * @type {string}\n */\n get zoneName() {\n return this.isValid ? this.zone.name : null;\n }\n\n /**\n * Get the year\n * @example DateTime.local(2017, 5, 25).year //=> 2017\n * @type {number}\n */\n get year() {\n return this.isValid ? this.c.year : NaN;\n }\n\n /**\n * Get the quarter\n * @example DateTime.local(2017, 5, 25).quarter //=> 2\n * @type {number}\n */\n get quarter() {\n return this.isValid ? Math.ceil(this.c.month / 3) : NaN;\n }\n\n /**\n * Get the month (1-12).\n * @example DateTime.local(2017, 5, 25).month //=> 5\n * @type {number}\n */\n get month() {\n return this.isValid ? this.c.month : NaN;\n }\n\n /**\n * Get the day of the month (1-30ish).\n * @example DateTime.local(2017, 5, 25).day //=> 25\n * @type {number}\n */\n get day() {\n return this.isValid ? this.c.day : NaN;\n }\n\n /**\n * Get the hour of the day (0-23).\n * @example DateTime.local(2017, 5, 25, 9).hour //=> 9\n * @type {number}\n */\n get hour() {\n return this.isValid ? this.c.hour : NaN;\n }\n\n /**\n * Get the minute of the hour (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30\n * @type {number}\n */\n get minute() {\n return this.isValid ? this.c.minute : NaN;\n }\n\n /**\n * Get the second of the minute (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52\n * @type {number}\n */\n get second() {\n return this.isValid ? this.c.second : NaN;\n }\n\n /**\n * Get the millisecond of the second (0-999).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654\n * @type {number}\n */\n get millisecond() {\n return this.isValid ? this.c.millisecond : NaN;\n }\n\n /**\n * Get the week year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 12, 31).weekYear //=> 2015\n * @type {number}\n */\n get weekYear() {\n return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;\n }\n\n /**\n * Get the week number of the week year (1-52ish).\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2017, 5, 25).weekNumber //=> 21\n * @type {number}\n */\n get weekNumber() {\n return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;\n }\n\n /**\n * Get the day of the week.\n * 1 is Monday and 7 is Sunday\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 11, 31).weekday //=> 4\n * @type {number}\n */\n get weekday() {\n return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;\n }\n\n /**\n * Returns true if this date is on a weekend according to the locale, false otherwise\n * @returns {boolean}\n */\n get isWeekend() {\n return this.isValid && this.loc.getWeekendDays().includes(this.weekday);\n }\n\n /**\n * Get the day of the week according to the locale.\n * 1 is the first day of the week and 7 is the last day of the week.\n * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1,\n * @returns {number}\n */\n get localWeekday() {\n return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN;\n }\n\n /**\n * Get the week number of the week year according to the locale. Different locales assign week numbers differently,\n * because the week can start on different days of the week (see localWeekday) and because a different number of days\n * is required for a week to count as the first week of a year.\n * @returns {number}\n */\n get localWeekNumber() {\n return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN;\n }\n\n /**\n * Get the week year according to the locale. Different locales assign week numbers (and therefor week years)\n * differently, see localWeekNumber.\n * @returns {number}\n */\n get localWeekYear() {\n return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN;\n }\n\n /**\n * Get the ordinal (meaning the day of the year)\n * @example DateTime.local(2017, 5, 25).ordinal //=> 145\n * @type {number|DateTime}\n */\n get ordinal() {\n return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;\n }\n\n /**\n * Get the human readable short month name, such as 'Oct'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthShort //=> Oct\n * @type {string}\n */\n get monthShort() {\n return this.isValid ? Info.months(\"short\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable long month name, such as 'October'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthLong //=> October\n * @type {string}\n */\n get monthLong() {\n return this.isValid ? Info.months(\"long\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable short weekday, such as 'Mon'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon\n * @type {string}\n */\n get weekdayShort() {\n return this.isValid ? Info.weekdays(\"short\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the human readable long weekday, such as 'Monday'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday\n * @type {string}\n */\n get weekdayLong() {\n return this.isValid ? Info.weekdays(\"long\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the UTC offset of this DateTime in minutes\n * @example DateTime.now().offset //=> -240\n * @example DateTime.utc().offset //=> 0\n * @type {number}\n */\n get offset() {\n return this.isValid ? +this.o : NaN;\n }\n\n /**\n * Get the short human name for the zone's current offset, for example \"EST\" or \"EDT\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameShort() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"short\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get the long human name for the zone's current offset, for example \"Eastern Standard Time\" or \"Eastern Daylight Time\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameLong() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"long\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get whether this zone's offset ever changes, as in a DST.\n * @type {boolean}\n */\n get isOffsetFixed() {\n return this.isValid ? this.zone.isUniversal : null;\n }\n\n /**\n * Get whether the DateTime is in a DST.\n * @type {boolean}\n */\n get isInDST() {\n if (this.isOffsetFixed) {\n return false;\n } else {\n return (\n this.offset > this.set({ month: 1, day: 1 }).offset ||\n this.offset > this.set({ month: 5 }).offset\n );\n }\n }\n\n /**\n * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC\n * in this DateTime's zone. During DST changes local time can be ambiguous, for example\n * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.\n * This method will return both possible DateTimes if this DateTime's local time is ambiguous.\n * @returns {DateTime[]}\n */\n getPossibleOffsets() {\n if (!this.isValid || this.isOffsetFixed) {\n return [this];\n }\n const dayMs = 86400000;\n const minuteMs = 60000;\n const localTS = objToLocalTS(this.c);\n const oEarlier = this.zone.offset(localTS - dayMs);\n const oLater = this.zone.offset(localTS + dayMs);\n\n const o1 = this.zone.offset(localTS - oEarlier * minuteMs);\n const o2 = this.zone.offset(localTS - oLater * minuteMs);\n if (o1 === o2) {\n return [this];\n }\n const ts1 = localTS - o1 * minuteMs;\n const ts2 = localTS - o2 * minuteMs;\n const c1 = tsToObj(ts1, o1);\n const c2 = tsToObj(ts2, o2);\n if (\n c1.hour === c2.hour &&\n c1.minute === c2.minute &&\n c1.second === c2.second &&\n c1.millisecond === c2.millisecond\n ) {\n return [clone(this, { ts: ts1 }), clone(this, { ts: ts2 })];\n }\n return [this];\n }\n\n /**\n * Returns true if this DateTime is in a leap year, false otherwise\n * @example DateTime.local(2016).isInLeapYear //=> true\n * @example DateTime.local(2013).isInLeapYear //=> false\n * @type {boolean}\n */\n get isInLeapYear() {\n return isLeapYear(this.year);\n }\n\n /**\n * Returns the number of days in this DateTime's month\n * @example DateTime.local(2016, 2).daysInMonth //=> 29\n * @example DateTime.local(2016, 3).daysInMonth //=> 31\n * @type {number}\n */\n get daysInMonth() {\n return daysInMonth(this.year, this.month);\n }\n\n /**\n * Returns the number of days in this DateTime's year\n * @example DateTime.local(2016).daysInYear //=> 366\n * @example DateTime.local(2013).daysInYear //=> 365\n * @type {number}\n */\n get daysInYear() {\n return this.isValid ? daysInYear(this.year) : NaN;\n }\n\n /**\n * Returns the number of weeks in this DateTime's year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2004).weeksInWeekYear //=> 53\n * @example DateTime.local(2013).weeksInWeekYear //=> 52\n * @type {number}\n */\n get weeksInWeekYear() {\n return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;\n }\n\n /**\n * Returns the number of weeks in this DateTime's local week year\n * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52\n * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53\n * @type {number}\n */\n get weeksInLocalWeekYear() {\n return this.isValid\n ? weeksInWeekYear(\n this.localWeekYear,\n this.loc.getMinDaysInFirstWeek(),\n this.loc.getStartOfWeek()\n )\n : NaN;\n }\n\n /**\n * Returns the resolved Intl options for this DateTime.\n * This is useful in understanding the behavior of formatting methods\n * @param {Object} opts - the same options as toLocaleString\n * @return {Object}\n */\n resolvedLocaleOptions(opts = {}) {\n const { locale, numberingSystem, calendar } = Formatter.create(\n this.loc.clone(opts),\n opts\n ).resolvedOptions(this);\n return { locale, numberingSystem, outputCalendar: calendar };\n }\n\n // TRANSFORM\n\n /**\n * \"Set\" the DateTime's zone to UTC. Returns a newly-constructed DateTime.\n *\n * Equivalent to {@link DateTime#setZone}('utc')\n * @param {number} [offset=0] - optionally, an offset from UTC in minutes\n * @param {Object} [opts={}] - options to pass to `setZone()`\n * @return {DateTime}\n */\n toUTC(offset = 0, opts = {}) {\n return this.setZone(FixedOffsetZone.instance(offset), opts);\n }\n\n /**\n * \"Set\" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.\n *\n * Equivalent to `setZone('local')`\n * @return {DateTime}\n */\n toLocal() {\n return this.setZone(Settings.defaultZone);\n }\n\n /**\n * \"Set\" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.\n *\n * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.\n * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.\n * @param {Object} opts - options\n * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.\n * @return {DateTime}\n */\n setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {\n zone = normalizeZone(zone, Settings.defaultZone);\n if (zone.equals(this.zone)) {\n return this;\n } else if (!zone.isValid) {\n return DateTime.invalid(unsupportedZone(zone));\n } else {\n let newTS = this.ts;\n if (keepLocalTime || keepCalendarTime) {\n const offsetGuess = zone.offset(this.ts);\n const asObj = this.toObject();\n [newTS] = objToTS(asObj, offsetGuess, zone);\n }\n return clone(this, { ts: newTS, zone });\n }\n }\n\n /**\n * \"Set\" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.\n * @param {Object} properties - the properties to set\n * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })\n * @return {DateTime}\n */\n reconfigure({ locale, numberingSystem, outputCalendar } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });\n return clone(this, { loc });\n }\n\n /**\n * \"Set\" the locale. Returns a newly-constructed DateTime.\n * Just a convenient alias for reconfigure({ locale })\n * @example DateTime.local(2017, 5, 25).setLocale('en-GB')\n * @return {DateTime}\n */\n setLocale(locale) {\n return this.reconfigure({ locale });\n }\n\n /**\n * \"Set\" the values of specified units. Returns a newly-constructed DateTime.\n * You can only set units with this method; for \"setting\" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.\n *\n * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`.\n * They cannot be mixed with ISO-week units like `weekday`.\n * @param {Object} values - a mapping of units to numbers\n * @example dt.set({ year: 2017 })\n * @example dt.set({ hour: 8, minute: 30 })\n * @example dt.set({ weekday: 5 })\n * @example dt.set({ year: 2005, ordinal: 234 })\n * @return {DateTime}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks);\n const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc);\n\n const settingWeekStuff =\n !isUndefined(normalized.weekYear) ||\n !isUndefined(normalized.weekNumber) ||\n !isUndefined(normalized.weekday),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n let mixed;\n if (settingWeekStuff) {\n mixed = weekToGregorian(\n { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized },\n minDaysInFirstWeek,\n startOfWeek\n );\n } else if (!isUndefined(normalized.ordinal)) {\n mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });\n } else {\n mixed = { ...this.toObject(), ...normalized };\n\n // if we didn't set the day but we ended up on an overflow date,\n // use the last day of the right month\n if (isUndefined(normalized.day)) {\n mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);\n }\n }\n\n const [ts, o] = objToTS(mixed, this.o, this.zone);\n return clone(this, { ts, o });\n }\n\n /**\n * Add a period of time to this DateTime and return the resulting DateTime\n *\n * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @example DateTime.now().plus(123) //~> in 123 milliseconds\n * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes\n * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow\n * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday\n * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min\n * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min\n * @return {DateTime}\n */\n plus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration);\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * Subtract a period of time to this DateTime and return the resulting DateTime\n * See {@link DateTime#plus}\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n @return {DateTime}\n */\n minus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration).negate();\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * \"Set\" this DateTime to the beginning of a unit of time.\n * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week\n * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'\n * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'\n * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'\n * @return {DateTime}\n */\n startOf(unit, { useLocaleWeeks = false } = {}) {\n if (!this.isValid) return this;\n\n const o = {},\n normalizedUnit = Duration.normalizeUnit(unit);\n switch (normalizedUnit) {\n case \"years\":\n o.month = 1;\n // falls through\n case \"quarters\":\n case \"months\":\n o.day = 1;\n // falls through\n case \"weeks\":\n case \"days\":\n o.hour = 0;\n // falls through\n case \"hours\":\n o.minute = 0;\n // falls through\n case \"minutes\":\n o.second = 0;\n // falls through\n case \"seconds\":\n o.millisecond = 0;\n break;\n case \"milliseconds\":\n break;\n // no default, invalid units throw in normalizeUnit()\n }\n\n if (normalizedUnit === \"weeks\") {\n if (useLocaleWeeks) {\n const startOfWeek = this.loc.getStartOfWeek();\n const { weekday } = this;\n if (weekday < startOfWeek) {\n o.weekNumber = this.weekNumber - 1;\n }\n o.weekday = startOfWeek;\n } else {\n o.weekday = 1;\n }\n }\n\n if (normalizedUnit === \"quarters\") {\n const q = Math.ceil(this.month / 3);\n o.month = (q - 1) * 3 + 1;\n }\n\n return this.set(o);\n }\n\n /**\n * \"Set\" this DateTime to the end (meaning the last millisecond) of a unit of time\n * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week\n * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'\n * @return {DateTime}\n */\n endOf(unit, opts) {\n return this.isValid\n ? this.plus({ [unit]: 1 })\n .startOf(unit, opts)\n .minus(1)\n : this;\n }\n\n // OUTPUT\n\n /**\n * Returns a string representation of this DateTime formatted according to the specified format string.\n * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).\n * Defaults to en-US if no locale has been specified, regardless of the system's locale.\n * @param {string} fmt - the format string\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'\n * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'\n * @example DateTime.now().toFormat('yyyy LLL dd', { locale: \"fr\" }) //=> '2017 avr. 22'\n * @example DateTime.now().toFormat(\"HH 'hours and' mm 'minutes'\") //=> '20 hours and 55 minutes'\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.\n * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation\n * of the DateTime in the assigned locale.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toLocaleString(); //=> 4/20/2017\n * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'\n * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'\n * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'\n * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'\n * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'\n * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'\n * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'\n * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'\n * @return {string}\n */\n toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this)\n : INVALID;\n }\n\n /**\n * Returns an array of format \"parts\", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts\n * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.\n * @example DateTime.now().toLocaleParts(); //=> [\n * //=> { type: 'day', value: '25' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'month', value: '05' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'year', value: '1982' }\n * //=> ]\n */\n toLocaleParts(opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)\n : [];\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=false] - add the time zone format extension\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'\n * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'\n * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'\n * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'\n * @return {string}\n */\n toISO({\n format = \"extended\",\n suppressSeconds = false,\n suppressMilliseconds = false,\n includeOffset = true,\n extendedZone = false,\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n const ext = format === \"extended\";\n\n let c = toISODate(this, ext);\n c += \"T\";\n c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);\n return c;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's date component\n * @param {Object} opts - options\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'\n * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'\n * @return {string}\n */\n toISODate({ format = \"extended\" } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return toISODate(this, format === \"extended\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's week date\n * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'\n * @return {string}\n */\n toISOWeekDate() {\n return toTechFormat(this, \"kkkk-'W'WW-c\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's time component\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'\n * @return {string}\n */\n toISOTime({\n suppressMilliseconds = false,\n suppressSeconds = false,\n includeOffset = true,\n includePrefix = false,\n extendedZone = false,\n format = \"extended\",\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n let c = includePrefix ? \"T\" : \"\";\n return (\n c +\n toISOTime(\n this,\n format === \"extended\",\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n )\n );\n }\n\n /**\n * Returns an RFC 2822-compatible string representation of this DateTime\n * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'\n * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'\n * @return {string}\n */\n toRFC2822() {\n return toTechFormat(this, \"EEE, dd LLL yyyy HH:mm:ss ZZZ\", false);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.\n * Specifically, the string conforms to RFC 1123.\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'\n * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'\n * @return {string}\n */\n toHTTP() {\n return toTechFormat(this.toUTC(), \"EEE, dd LLL yyyy HH:mm:ss 'GMT'\");\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Date\n * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'\n * @return {string}\n */\n toSQLDate() {\n if (!this.isValid) {\n return null;\n }\n return toISODate(this, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Time\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc().toSQL() //=> '05:15:16.345'\n * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'\n * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'\n * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'\n * @return {string}\n */\n toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {\n let fmt = \"HH:mm:ss.SSS\";\n\n if (includeZone || includeOffset) {\n if (includeOffsetSpace) {\n fmt += \" \";\n }\n if (includeZone) {\n fmt += \"z\";\n } else if (includeOffset) {\n fmt += \"ZZ\";\n }\n }\n\n return toTechFormat(this, fmt, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'\n * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'\n * @return {string}\n */\n toSQL(opts = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for debugging\n * @return {string}\n */\n toString() {\n return this.isValid ? this.toISO() : INVALID;\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for the REPL.\n * @return {string}\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (this.isValid) {\n return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`;\n } else {\n return `DateTime { Invalid, reason: ${this.invalidReason} }`;\n }\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime.\n * @return {number}\n */\n toMillis() {\n return this.isValid ? this.ts : NaN;\n }\n\n /**\n * Returns the epoch seconds of this DateTime.\n * @return {number}\n */\n toSeconds() {\n return this.isValid ? this.ts / 1000 : NaN;\n }\n\n /**\n * Returns the epoch seconds (as a whole number) of this DateTime.\n * @return {number}\n */\n toUnixInteger() {\n return this.isValid ? Math.floor(this.ts / 1000) : NaN;\n }\n\n /**\n * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns a BSON serializable equivalent to this DateTime.\n * @return {Date}\n */\n toBSON() {\n return this.toJSDate();\n }\n\n /**\n * Returns a JavaScript object with this DateTime's year, month, day, and so on.\n * @param opts - options for generating the object\n * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output\n * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }\n * @return {Object}\n */\n toObject(opts = {}) {\n if (!this.isValid) return {};\n\n const base = { ...this.c };\n\n if (opts.includeConfig) {\n base.outputCalendar = this.outputCalendar;\n base.numberingSystem = this.loc.numberingSystem;\n base.locale = this.loc.locale;\n }\n return base;\n }\n\n /**\n * Returns a JavaScript Date equivalent to this DateTime.\n * @return {Date}\n */\n toJSDate() {\n return new Date(this.isValid ? this.ts : NaN);\n }\n\n // COMPARE\n\n /**\n * Return the difference between two DateTimes as a Duration.\n * @param {DateTime} otherDateTime - the DateTime to compare this one to\n * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example\n * var i1 = DateTime.fromISO('1982-05-25T09:45'),\n * i2 = DateTime.fromISO('1983-10-14T10:30');\n * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\n * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\n * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\n * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n * @return {Duration}\n */\n diff(otherDateTime, unit = \"milliseconds\", opts = {}) {\n if (!this.isValid || !otherDateTime.isValid) {\n return Duration.invalid(\"created by diffing an invalid DateTime\");\n }\n\n const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };\n\n const units = maybeArray(unit).map(Duration.normalizeUnit),\n otherIsLater = otherDateTime.valueOf() > this.valueOf(),\n earlier = otherIsLater ? this : otherDateTime,\n later = otherIsLater ? otherDateTime : this,\n diffed = diff(earlier, later, units, durOpts);\n\n return otherIsLater ? diffed.negate() : diffed;\n }\n\n /**\n * Return the difference between this DateTime and right now.\n * See {@link DateTime#diff}\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n diffNow(unit = \"milliseconds\", opts = {}) {\n return this.diff(DateTime.now(), unit, opts);\n }\n\n /**\n * Return an Interval spanning between this DateTime and another DateTime\n * @param {DateTime} otherDateTime - the other end point of the Interval\n * @return {Interval}\n */\n until(otherDateTime) {\n return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;\n }\n\n /**\n * Return whether this DateTime is in the same unit of time as another DateTime.\n * Higher-order units must also be identical for this function to return `true`.\n * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.\n * @param {DateTime} otherDateTime - the other DateTime\n * @param {string} unit - the unit of time to check sameness on\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used\n * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day\n * @return {boolean}\n */\n hasSame(otherDateTime, unit, opts) {\n if (!this.isValid) return false;\n\n const inputMs = otherDateTime.valueOf();\n const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });\n return (\n adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts)\n );\n }\n\n /**\n * Equality check\n * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.\n * To compare just the millisecond values, use `+dt1 === +dt2`.\n * @param {DateTime} other - the other DateTime\n * @return {boolean}\n */\n equals(other) {\n return (\n this.isValid &&\n other.isValid &&\n this.valueOf() === other.valueOf() &&\n this.zone.equals(other.zone) &&\n this.loc.equals(other.loc)\n );\n }\n\n /**\n * Returns a string representation of a this time relative to now, such as \"in two days\". Can only internationalize if your\n * platform supports Intl.RelativeTimeFormat. Rounds down by default.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} [options.style=\"long\"] - the style of units, must be \"long\", \"short\", or \"narrow\"\n * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of \"years\", \"quarters\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", or \"seconds\"\n * @param {boolean} [options.round=true] - whether to round the numbers in the output.\n * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelative() //=> \"in 1 day\"\n * @example DateTime.now().setLocale(\"es\").toRelative({ days: 1 }) //=> \"dentro de 1 día\"\n * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: \"fr\" }) //=> \"dans 23 heures\"\n * @example DateTime.now().minus({ days: 2 }).toRelative() //=> \"2 days ago\"\n * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: \"hours\" }) //=> \"48 hours ago\"\n * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> \"1.5 days ago\"\n */\n toRelative(options = {}) {\n if (!this.isValid) return null;\n const base = options.base || DateTime.fromObject({}, { zone: this.zone }),\n padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;\n let units = [\"years\", \"months\", \"days\", \"hours\", \"minutes\", \"seconds\"];\n let unit = options.unit;\n if (Array.isArray(options.unit)) {\n units = options.unit;\n unit = undefined;\n }\n return diffRelative(base, this.plus(padding), {\n ...options,\n numeric: \"always\",\n units,\n unit,\n });\n }\n\n /**\n * Returns a string representation of this date relative to today, such as \"yesterday\" or \"next month\".\n * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of \"years\", \"quarters\", \"months\", \"weeks\", or \"days\"\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> \"tomorrow\"\n * @example DateTime.now().setLocale(\"es\").plus({ days: 1 }).toRelative() //=> \"\"mañana\"\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: \"fr\" }) //=> \"demain\"\n * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> \"2 days ago\"\n */\n toRelativeCalendar(options = {}) {\n if (!this.isValid) return null;\n\n return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {\n ...options,\n numeric: \"auto\",\n units: [\"years\", \"months\", \"days\"],\n calendary: true,\n });\n }\n\n /**\n * Return the min of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum\n * @return {DateTime} the min DateTime, or undefined if called with no argument\n */\n static min(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"min requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.min);\n }\n\n /**\n * Return the max of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum\n * @return {DateTime} the max DateTime, or undefined if called with no argument\n */\n static max(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"max requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.max);\n }\n\n // MISC\n\n /**\n * Explain how a string would be parsed by fromFormat()\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see description)\n * @param {Object} options - options taken by fromFormat()\n * @return {Object}\n */\n static fromFormatExplain(text, fmt, options = {}) {\n const { locale = null, numberingSystem = null } = options,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n });\n return explainFromTokens(localeToUse, text, fmt);\n }\n\n /**\n * @deprecated use fromFormatExplain instead\n */\n static fromStringExplain(text, fmt, options = {}) {\n return DateTime.fromFormatExplain(text, fmt, options);\n }\n\n // FORMAT PRESETS\n\n /**\n * {@link DateTime#toLocaleString} format like 10/14/1983\n * @type {Object}\n */\n static get DATE_SHORT() {\n return Formats.DATE_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED() {\n return Formats.DATE_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED_WITH_WEEKDAY() {\n return Formats.DATE_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983'\n * @type {Object}\n */\n static get DATE_FULL() {\n return Formats.DATE_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'\n * @type {Object}\n */\n static get DATE_HUGE() {\n return Formats.DATE_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_SIMPLE() {\n return Formats.TIME_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SECONDS() {\n return Formats.TIME_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SHORT_OFFSET() {\n return Formats.TIME_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_LONG_OFFSET() {\n return Formats.TIME_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_SIMPLE() {\n return Formats.TIME_24_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SECONDS() {\n return Formats.TIME_24_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SHORT_OFFSET() {\n return Formats.TIME_24_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_LONG_OFFSET() {\n return Formats.TIME_24_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT() {\n return Formats.DATETIME_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT_WITH_SECONDS() {\n return Formats.DATETIME_SHORT_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED() {\n return Formats.DATETIME_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_SECONDS() {\n return Formats.DATETIME_MED_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_WEEKDAY() {\n return Formats.DATETIME_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL() {\n return Formats.DATETIME_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL_WITH_SECONDS() {\n return Formats.DATETIME_FULL_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE() {\n return Formats.DATETIME_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE_WITH_SECONDS() {\n return Formats.DATETIME_HUGE_WITH_SECONDS;\n }\n}\n\n/**\n * @private\n */\nexport function friendlyDateTime(dateTimeish) {\n if (DateTime.isDateTime(dateTimeish)) {\n return dateTimeish;\n } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {\n return DateTime.fromJSDate(dateTimeish);\n } else if (dateTimeish && typeof dateTimeish === \"object\") {\n return DateTime.fromObject(dateTimeish);\n } else {\n throw new InvalidArgumentError(\n `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`\n );\n }\n}\n"],"names":["getTransformedScaledValue","value","_a","px","transformedValue","useResolvedStylesApi","classNames","styles","props","stylesCtx","theme","useMantineTheme","resolveClassNames","resolveStyles","version","versionInfo","isPromise","memoize3","fn","cache0","a1","a2","a3","cache1","cache2","fnResult","promiseForObject","object","resolvedValues","resolvedObject","i","key","promiseReduce","values","callbackFn","initialValue","accumulator","resolved","toError","thrownValue","NonErrorThrown","inspect","locatedError","rawOriginalError","nodes","path","_nodes","originalError","isLocatedGraphQLError","GraphQLError","error","collectSubfields","exeContext","returnType","fieldNodes","_collectSubfields","execute","args","devAssert","schema","document","variableValues","rootValue","assertValidExecutionArguments","buildExecutionContext","operation","result","executeOperation","data","buildResponse","executeSync","errors","rawVariableValues","assertValidSchema","isObjectLike","_definition$name","_operation$variableDe","contextValue","operationName","fieldResolver","typeResolver","subscribeFieldResolver","fragments","definition","Kind","variableDefinitions","coercedVariableValues","getVariableValues","defaultFieldResolver","defaultTypeResolver","rootType","rootFields","collectFields","OperationTypeNode","executeFields","executeFieldsSerially","parentType","sourceValue","fields","results","responseName","fieldPath","addPath","executeField","resolvedResult","containsPromise","source","_fieldDef$resolve","fieldDef","getFieldDef","resolveFn","info","buildResolveInfo","getArgumentValues","completed","completeValue","rawError","pathToArray","handleFieldError","isNonNullType","isListType","completeListValue","isLeafType","completeLeafValue","isAbstractType","completeAbstractValue","isObjectType","completeObjectValue","invariant","isIterableObject","itemType","completedResults","item","index","itemPath","completedItem","serializedResult","_returnType$resolveTy","resolveTypeFn","runtimeType","resolvedRuntimeType","ensureValidRuntimeType","runtimeTypeName","subFieldNodes","isTypeOf","resolvedIsTypeOf","invalidReturnTypeError","abstractType","possibleTypes","promisedIsTypeOfResults","type","isTypeOfResult","isTypeOfResults","property","fieldNode","fieldName","SchemaMetaFieldDef","TypeMetaFieldDef","TypeNameMetaFieldDef","graphql","resolve","graphqlImpl","graphqlSync","schemaValidationErrors","validateSchema","parse","syntaxError","validationErrors","validate","isAsyncIterable","maybeAsyncIterable","mapAsyncIterator","iterable","callback","iterator","mapResult","subscribe","resultOrStream","createSourceEventStream","payload","toNormalizedArgs","firstArg","rawArgs","eventStream","executeSubscription","_fieldDef$subscribe","NoSchemaIntrospectionCustomRule","context","node","getNamedType","isIntrospectionType","getOperationAST","documentAST","getOperationRootType","queryType","mutationType","subscriptionType","introspectionFromSchema","options","optionsWithDefaults","getIntrospectionQuery","extendSchema","assertSchema","assertValidSDLExtension","schemaConfig","extendedConfig","extendSchemaImpl","GraphQLSchema","_schemaDef","_schemaDef$descriptio","_schemaDef2","_options$assumeValid","typeDefs","typeExtensionsMap","directiveDefs","schemaDef","schemaExtensions","def","isTypeDefinitionNode","isTypeExtensionNode","extendedTypeName","existingTypeExtensions","typeMap","existingType","extendNamedType","typeNode","_stdTypeMap$name","name","stdTypeMap","buildType","operationTypes","replaceNamedType","getOperationTypes","replaceDirective","buildDirective","replaceType","GraphQLList","GraphQLNonNull","directive","config","GraphQLDirective","mapValue","extendArg","isSpecifiedScalarType","isScalarType","extendScalarType","extendObjectType","isInterfaceType","extendInterfaceType","isUnionType","extendUnionType","isEnumType","extendEnumType","isInputObjectType","extendInputObjectType","_typeExtensionsMap$co","extensions","GraphQLInputObjectType","field","buildInputFieldMap","_typeExtensionsMap$ty","GraphQLEnumType","buildEnumValueMap","_typeExtensionsMap$co2","specifiedByURL","extensionNode","_getSpecifiedByURL","getSpecifiedByURL","GraphQLScalarType","_typeExtensionsMap$co3","GraphQLObjectType","buildInterfaces","extendField","buildFieldMap","_typeExtensionsMap$co4","GraphQLInterfaceType","_typeExtensionsMap$co5","GraphQLUnionType","buildUnionTypes","arg","opTypes","_node$operationTypes","operationTypesNodes","operationType","_stdTypeMap$name2","getWrappedType","_node$description","buildArgumentMap","fieldConfigMap","_node$fields","nodeFields","_field$description","getDeprecationReason","argsNodes","argConfigMap","_arg$description","valueFromAST","inputFieldMap","_node$fields2","fieldsNodes","_field$description2","enumValueMap","_node$values","valuesNodes","_value$description","_node$interfaces$map","_node$interfaces","_node$types$map","_node$types","astNode","_typeExtensionsMap$na","extensionASTNodes","_astNode$description","allNodes","_astNode$description2","_astNode$description3","_astNode$description4","_astNode$description5","_astNode$description6","keyMap","specifiedScalarTypes","introspectionTypes","deprecated","getDirectiveValues","GraphQLDeprecatedDirective","specifiedBy","GraphQLSpecifiedByDirective","buildASTSchema","assertValidSDL","directives","specifiedDirectives","stdDirective","buildSchema","lexicographicSortSchema","keyValMap","sortByName","sortNamedType","sortDirective","replaceMaybeType","maybeType","sortBy","x","sortArgs","sortObjMap","sortFields","fieldsMap","sortInputFields","sortTypes","array","map","sortValueFn","sortedMap","naturalCompare","obj","mapToKey","obj1","obj2","key1","key2","printSchema","printFilteredSchema","n","isSpecifiedDirective","isDefinedType","printIntrospectionSchema","directiveFilter","typeFilter","types","printSchemaDefinition","printDirective","printType","isSchemaOfCommonNames","printDescription","printScalar","printObject","printInterface","printUnion","printEnum","printInputObject","printSpecifiedByURL","printImplementedInterfaces","interfaces","printFields","printDeprecated","printBlock","f","printInputValue","printArgs","items","indentation","defaultAST","astFromValue","argDecl","print","reason","DEFAULT_DEPRECATION_REASON","scalar","firstInBlock","description","blockString","isPrintableAsBlockString","concatAST","documents","definitions","doc","separateOperations","operations","depGraph","definitionNode","collectDependencies","separatedDocumentASTs","dependencies","fragmentName","collectTransitiveDependencies","collected","fromName","immediateDeps","toName","selectionSet","visit","stripIgnoredCharacters","sourceObj","isSource","Source","body","lexer","Lexer","strippedBody","wasLastAddedTokenNonPunctuator","TokenKind","currentToken","tokenKind","isNonPunctuator","isPunctuatorTokenKind","tokenBody","printBlockString","assertValidName","isValidNameError","assertName","BreakingChangeType","DangerousChangeType","findBreakingChanges","oldSchema","newSchema","findSchemaChanges","change","findDangerousChanges","findTypeChanges","findDirectiveChanges","schemaChanges","directivesDiff","diff","oldDirective","newDirective","argsDiff","newArg","isRequiredArgument","oldArg","location","typesDiff","oldType","newType","findEnumTypeChanges","findUnionTypeChanges","findInputObjectTypeChanges","findFieldChanges","findImplementedInterfacesChanges","typeKindName","fieldsDiff","newField","isRequiredInputField","oldField","isChangeSafeForInputObjectFieldOrFieldArg","possibleTypesDiff","newPossibleType","oldPossibleType","valuesDiff","newValue","oldValue","interfacesDiff","newInterface","oldInterface","findArgChanges","isChangeSafeForObjectOrInterfaceField","oldValueStr","stringifyValue","newValueStr","isNamedType","ast","sortValueNode","oldArray","newArray","added","removed","persisted","oldMap","newMap","oldItem","newItem","shouldInclude","variables","getInclusionDirectives","ifArgument","evaledValue","hasDirectives","names","root","all","nameSet","uniqueCount","BREAK","hasClientExports","isInclusionDirective","directiveArguments","directiveName","ifValue","defaultMakeData","forEach","slice","hasOwnProperty","Trie$1","Trie","weakness","makeData","len","head","child","create","isObjRef","currentContext","MISSING_VALUE","idCounter","makeSlotClass","thisArg","slots","parent","saved","maybe","globalKey","host","globalHost","Slot","parentEntrySlot","arrayFromSet","set","maybeUnsubscribe","entryOrDep","unsubscribe","emptySetPool","POOL_TARGET_SIZE","assert","condition","optionalMessage","valueIs","a","b","valueGet","valueCopy","Entry","mightBeDirty","rememberParent","reallyRecompute","reportDirty","forgetChildren","eachParent","forgetChild","dep","reportDirtyChild","reportCleanChild","entry","recomputeNewValue","maybeSubscribe","setClean","normalizeResult","oldValueCopy","e","reportClean","parentCount","parents","parentWasClean","childValue","removeDirtyChild","dc","_value","EntryMethods","depsByKey","depend","entryMethodName","m","defaultKeyTrie","defaultMakeCacheKey","caches","wrap","originalFunction","max","keyArgs","makeCacheKey","cacheOption","StrongCache","cache","optimistic","dirtyKey","peekKey","forgetKey","identity","DocumentTransform","transform","canUseWeakSet","predicate","left","right","documentTransform","_this","stableCacheKeys_1","canUseWeakMap","cacheKeys","cacheSizes","WeakCache","checkDocument","transformedDocument","otherTransform","printCache","origPrint","AutoCleanedWeakCache","registerGlobalCache","isArray","isNonEmptyArray","TYPENAME_FIELD","isEmpty","op","fragmentMap","selection","nullIfDocIsEmpty","getOperationDefinition","getFragmentDefinition","createFragmentMap","getFragmentDefinitions","getDirectiveMatcher","configs","tests","testConfig","test","makeInUseGetterFunction","defaultKey","inUse","removeDirectivesFromDocument","getInUseByOperationName","getInUseByFragmentName","getInUse","ancestors","p","ancestor","operationCount","directiveMatcher","shouldRemoveField","nodeDirectives","originalFragmentDefsByPath","firstVisitMadeChanges","fieldOrInlineFragmentVisitor","docWithoutDirectiveSubtrees","_key","_parent","_path","originalNode","populateTransitiveVars","childFragmentName","varName","allFragmentNamesUsed","fragmentWillBeRemoved","enterVisitor","usedVariableNames_1","__assign","varDef","addTypenameToDocument","selections","skip","isField","d","__spreadArray","buildQueryFromSelectionSet","getMainDefinition","definitionOperation","modifiedDoc","removeClientSetsFromDocument","mergeDeep","sources","_i","mergeDeepArray","target","count","merger","DeepMerger","defaultReconciler","reconciler","isNonNullObject","sourceKey","targetValue","relayStylePagination","existing","canRead","readField","edges","firstEdgeCursor","lastEdgeCursor","edge","_b","startCursor","endCursor","getExtras","incoming","isReference","makeEmptyData","incomingEdges","pageInfo_1","firstEdge","lastEdge","firstCursor","lastCursor","prefix","suffix","pageInfo","hasPreviousPage","hasNextPage","extras","__rest_1","__rest","notExtras","toString","cloneDeep","cloneDeepHelper","val","seen","copy_1","copy_2","deepFreeze","workSet","shallowFreeze","maybeDeepFreeze","iterateObserversSafely","observers","method","argument","observersWithMethod","obs","asyncMap","observable","mapFn","catchFn","Observable","observer","promiseQueue","makeCallback","examiner","both","handler","sub","fixObservableSubclass","subclass","canUseSymbol","isPromiseLike","Concast","_super","__extends","reject","_","nextOrError","nextResultListeners","listener","called","isExecutionPatchIncrementalResult","isExecutionPatchInitialResult","isExecutionPatchResult","isApolloPayloadResult","mergeIncrementalData","prevResult","mergedData","isNumericKey","parent_1","graphQLResultHasError","getGraphQLErrorsFromResult","graphQLErrors","incrementalResult","compact","objects","mergeOptions","defaults","fromError","errorValue","toPromise","fromPromise","promise","throwServerError","response","message","filterOperationVariables","query","unusedNames","empty","ApolloLink","from","split","concat","asyncIterator","nodeStreamIterator","stream","cleanup","done","waiting","onData","chunk","shiftedArr","onError","err","pair","onEnd","getNext","canUseAsyncIteratorSymbol","promiseIterator","readerIterator","reader","isNodeResponse","isReadableStream","isAsyncIterableIterator","isStreamableBlob","isBlob","isNodeReadableStream","responseIterator","PROTOCOL_ERRORS_SYMBOL","graphQLResultHasProtocolErrors","isApolloError","generateErrorMessage","ApolloError","protocolErrors","clientErrors","networkError","errorMessage","extraInfo","readMultipartBody","nextValue","__awaiter","decoder","contentType","delimiter","boundaryVal","boundary","buffer","running","searchFrom","bi","headers","contentType_1","next","_c","_d","__generator","_e","parseHeaders","parseJsonBody","headerText","headersInit","line","name_1","bodyText","getResult","parseError","handleError","parseAndCheckHttpResponse","serializeFetchParameter","label","serialized","newInvariantError","defaultHttpOptions","defaultHeaders","defaultOptions","fallbackHttpConfig","defaultPrinter","printer","selectHttpOptionsAndBody","fallbackConfig","selectHttpOptionsAndBodyInternal","http","removeDuplicateHeaders","preserveHeaderCase","normalizedHeaders_1","headerData","normalizedHeaders","checkFetcher","fetcher","createSignalIfSupported","controller","signal","selectURI","fallbackURI","contextURI","rewriteURIForGET","chosenURI","queryParams","addQueryParam","serializedVariables","serializedExtensions","fragment","preFragment","fragmentStart","queryParamsPrefix","newURI","backupFetch","createHttpLink","linkOptions","uri","preferredFetch","includeExtensions","useGETForQueries","includeUnusedVariables","requestOptions","linkConfig","clientAwarenessHeaders","contextHeaders","contextConfig","transformedQuery","definitionIsMutation","definitionIsSubscription","isSubscription","hasDefer","acceptHeader","currentFetch","observerNext","ctype","HttpLink","fnToStr","previousComparisons","equal","check","aTag","bTag","previouslyCompared","aKeys","definedKeys","bKeys","keyCount","k","aIterator","isMap","aKey","aValue","aCode","endsWith","nativeCodeSuffix","isDefinedKey","full","fromIndex","bSet","ApolloCache","getFragmentQueryDocument","optimisticId","updateResult","transaction","id","update","getApolloCacheMemoryInternals","Cache","MissingFieldError","hasOwn","isNullish","defaultDataIdFromObject","__typename","_id","defaultConfig","normalizeConfig","shouldCanonizeResults","getTypenameFromStoreObject","store","objectOrReference","TypeOrFieldNameRegExp","fieldNameFromStoreName","storeFieldName","match","selectionSetMatchesResult","resultKeyNameFromField","storeValueIsStoreObject","makeProcessedFieldsMerger","extractFragmentContext","DELETE","delModifier","INVALIDATE","EntityStore","policies","group","objOrRef","objOrIdOrRef","mergeIntoStore","makeReference","ref","dataId","storeObject","Layer","dependOnExistence","older","newer","merged","storeObjectReconciler","fieldsToDirty_1","changedFields_1","needToMerge_1","allDeleted_1","sharedDetails_1","fieldNameOrOptions","fieldValue","modify","checkReference","seenReference","someNonReference","newValue_1","typename","limit","evicted","extraRootIds","newData","__META","rest_1","rootId","ids","snapshot","idsToRemove","root_1","found_1","workSet_1","CacheGroup","caching","makeDepKey","maybeDependOnExistenceOfEntity","entityId","supportsResultCaching","Root","resultCaching","seed","Stump","layerId","replay","ownStoreObject","parentStoreObject","fromParent","existingObject","incomingObject","existingValue","incomingValue","shallowCopy","isObjectOrArray","ObjectCanon","copy","original","proto","proto_1","array_1","keys","firstValueIndex_1","obj_1","json","execSelectionSetKeyArgs","StoreReader","canonizeResults","peekArgs","other","returnPartialData","getDefaultValues","getQueryDefinition","rootRef","execResult","canonicalStringify","missing","firstMissing","latest","enclosingRef","objectsToMerge","missingMerger","handleMissing","resultName","getFragmentFromSelection","finalResult","frozen","childResult","assertSelectionSetForIdValue","tree","cacheSlot","cacheInfoMap","getCacheInfo","forgetCache","rv","recallCache","makeVar","listeners","broadcast","oldListeners","attach","specifierInfoCache","lookupSpecifierInfo","spec","cacheKey","keyFieldsFnFromSpecifier","specifier","extract","keyObject","collectSpecifierPaths","schemaKeyPath","extracted","extractKeyPath","extractKey","keyArgsFnFromSpecifier","keyPath","firstKey","firstChar","directiveName_1","directiveArgs","argumentsObjectFromField","variableName","varKeyPath","extractor","getSpecifierPaths","toMerge","paths_1","currentPath_1","s","normalize","reducer","argsFromFieldSpecifier","nullKeyFieldsFn","simpleKeyArgsFn","_args","mergeTrueFn","mergeObjects","mergeFalseFn","Policies","partialContext","normalizeReadFieldOptions","policy","keyFn","specifierOrId","typePolicies","keyFields","setMerge","merge","read","which","old","supertype","subtype","policy_1","supertypes_1","regExp","fuzzy","fuzzySupertypes","rest","inbox","createIfMissing","fieldPolicies","supertypeSet","typenameSupertypeSet","workQueue_1","maybeEnqueue_1","needToCheckFuzzySubtypes","checkingFuzzySubtypes","fuzzyString","fieldSpec","specifierOrString","storeKeyNameFromField","getStoreKeyName","nameOrField","readOptions","makeFieldFunctionOptions","parentTypename","childTypename","storage","makeMergeObjectsFunction","toReference","readFieldArgs","argc","stringifyForDisplay","eType","iType","typesDiffer","getContextFlavor","clientOnly","deferred","flavored","StoreWriter","overwrite","operationDefinition","mergeTree","fieldNodeSet","entityRef","applied","fieldsWithSelectionSets_1","hasSelectionSet_1","hasMergeFunction_1","childTree","warnAboutDataLoss","getTypenameFromResult","result_1","resultFieldKey","getChildMergeTree","maybeRecycleChildMergeTree","dataRef","sets","previous_1","mergeMergeTrees","mergeTreeIsEmpty","fieldMap","limitingTrie","flatten","inheritedContext","visitedNode","dir","getStorageArgs","e_1","i_1","getValue_1","eVal","iVal","aVal","emptyMergeTreePool","needToMergeMaps","remainingRightKeys_1","leftTree","warnings","existingRef","incomingObj","getChild","typeDotName","childTypenames","InMemoryCache","rootStore","resetResultIdentities","previousReader","c","watch","idToRemove","newOptimisticData","removeOptimistic","onWatchUpdated","perform","layer","optimisticData","alreadyDirty","lastDiff","getInMemoryCacheMemoryInternals","NetworkStatus","isNetworkRequestInFlight","networkStatus","isNetworkRequestSettled","equalByQuery","aData","aRest","bData","bRest","equalBySelectionSet","aResult","bResult","seenSelections","selectionHasNonreactiveDirective","resultKey","aResultChild","bResultChild","childSelectionSet","aChildIsArray","bChildIsArray","length_1","directiveIsNonreactive","assign","ObservableQuery","queryManager","queryInfo","subObserver","defaultSubscriptionObserverErrorCallback","first","last","skipCacheDataFor","defaultFetchPolicy","fetchPolicy","_f","initialFetchPolicy","opDef","subscription","saveAsLastResult","lastResult","logMissingFieldErrors","newResult","resultIsDifferent","variablesMustMatch","reobserveOptions","queryDef","vars","v","fetchMoreOptions","combinedOptions","qid","originalNetworkStatus","updatedQuerySet","fetchMoreResult","updateQuery","previous","reobserveCacheFirst","subscriptionData","newOptions","mergedOptions","pollInterval","newNetworkStatus","pollingInfo","maybeFetch","poll","useDisposableConcast","oldVariables","oldFetchPolicy","finishWaitingForOwnResult","concast","fromLink","lastError","isDifferent","errorResult","obsQuery","nextFetchPolicy","currentFetchPolicy","LocalState","client","resolvers","fragmentMatcher","resolverGroup","remoteResult","onlyRunForcedResolvers","localResult","document_1","forceResolvers","rootValue_1","mainDefinition","selectionsToResolve","defaultOperationType","execContext","isClientFieldDescendant","resultsToMerge","typeCondition","fieldResult","isInlineFragment","fragmentResult","aliasedFieldName","aliasUsed","defaultResult","resultPromise","resolverType","resolverMap","isClientField","isSingleASTNode","selectionsToResolveCache","collectByDefinition","matches_1","__","___","isSelectionNode","spread","fragmentSelections","destructiveMethodCounts","wrapDestructiveCacheMethod","methodName","cancelNotifyTimeout","QueryInfo","queryId","oq","oldDiff","watchOptions","lastWrite","cacheWriteBehavior","shouldWriteResult","diffOptions","errorPolicy","ignoreErrors","writeWithErrors","IGNORE","QueryManager","link","queryDeduplication","onBroadcast","ssrMode","clientAwareness","localState","assumeImmutableResults","defaultContext","defaultDocumentTransform","_info","cancel","mutationId","mutationStoreValue","isOptimistic","self","mutation","optimisticResponse","updateQueries","refetchQueries","awaitRefetchQueries","updateWithProxyFn","onQueryUpdated","_g","_h","keepRootFields","_j","storeResult","cacheWrites","skipCache","updateQueries_1","observableQuery","queryName","updater","currentQueryResult","complete","nextQueryResult","getOperationName","results_1","write","isFinalResult","transformCache","cacheEntry","include","queries","queryNamesAndDocs","legacyQueryOptions","desc","isDocumentNode","makeUniqueId","included","nameOrDoc","includeStandby","observableQueryPromises","makeObservable","hasErrors","hasProtocolErrors","observablePromise_1","deduplication","serverQuery","clientQuery","inFlightLinkObservables_1","printedServerQuery_1","varJson_1","requestId","linkDocument","aqr","notifyOnNetworkStatusChange","normalized","fromVariables","sourcesWithInfo","cleanupCancelFn","containsDataFromLink","updateCache","includedQueriesById","refetchWritePolicy","oldNetworkStatus","readCache","resultsFromCache","fromData","resultsFromLink","shouldNotify","newContext","hasSuggestedDevtools","ApolloClient","credentials","ssrForceFetchDelay","connectToDevTools","clientAwarenessName","clientAwarenessVersion","windowWithDevTools","devtoolsSymbol","nav","ua","url","cb","serializedState","newLink","getApolloClientMemoryInternals","docCache","fragmentSourceMap","printFragmentWarnings","experimentalFragmentVariables","string","cacheKeyFromLoc","loc","processFragments","seenKeys","fragmentDefinition","sourceKeySet","stripLoc","parseDocument","parsed","gql","literals","resetCaches","disableFragmentWarnings","enableExperimentalFragmentVariables","disableExperimentalFragmentVariables","gql_1","setVerbosity","introspection","setContext","setter","forward","request","handle","closed","req","ActionCableLink_1","core_1","require$$0","graphql_1","require$$1","ActionCableLink","_next","channelId","actionName","connectionParams","channel","_default","adapters","logger","messages","now","secondsSince","time","ConnectionMonitor","connection","staleThreshold","reconnectionBackoffRate","backoff","jitter","INTERNAL","message_types","protocols","supportedProtocols","indexOf","Connection","consumer","socketProtocols","allowReconnect","states","state","eventName","event","identifier","reconnect","extend","properties","Subscription","params","mixin","action","SubscriptionGuarantor","subscriptions","Subscriptions","channelName","callbackName","command","Consumer","createWebSocketURL","subprotocol","createConsumer","getConfig","element","getCable","createClientLink","initialCSRFToken","createCSRFLink","createTerminatingLink","httpLink","createSubscriptionsLink","requireMeta","cableLink","initialToken","getMeta","createApolloLink","NavbarContext","createContext","useNavbar","useContext","NAVBAR_VISIBILITY_BREAKPOINT","LuxonError","InvalidDateTimeError","InvalidIntervalError","InvalidDurationError","ConflictingSpecificationError","InvalidUnitError","unit","InvalidArgumentError","ZoneIsAbstractError","l","DATE_SHORT","DATE_MED","DATE_MED_WITH_WEEKDAY","DATE_FULL","DATE_HUGE","TIME_SIMPLE","TIME_WITH_SECONDS","TIME_WITH_SHORT_OFFSET","TIME_WITH_LONG_OFFSET","TIME_24_SIMPLE","TIME_24_WITH_SECONDS","TIME_24_WITH_SHORT_OFFSET","TIME_24_WITH_LONG_OFFSET","DATETIME_SHORT","DATETIME_SHORT_WITH_SECONDS","DATETIME_MED","DATETIME_MED_WITH_SECONDS","DATETIME_MED_WITH_WEEKDAY","DATETIME_FULL","DATETIME_FULL_WITH_SECONDS","DATETIME_HUGE","DATETIME_HUGE_WITH_SECONDS","Zone","ts","opts","format","otherZone","singleton","SystemZone","locale","parseZoneInfo","formatOffset","dtfCache","makeDTF","zone","typeToPos","hackyOffset","dtf","date","formatted","fMonth","fDay","fYear","fadOrBc","fHour","fMinute","fSecond","partsOffset","filled","pos","isUndefined","ianaZoneCache","IANAZone","year","month","day","adOrBc","hour","minute","second","asUTC","objToLocalTS","asTS","over","intlLFCache","getCachedLF","locString","intlDTCache","getCachedDTF","intlNumCache","getCachedINF","inf","intlRelCache","getCachedRTF","base","cacheKeyOpts","sysLocaleCache","systemLocale","weekInfoCache","getCachedWeekInfo","parseLocaleString","localeStr","xIndex","uIndex","selectedStr","smaller","numberingSystem","calendar","intlConfigString","outputCalendar","mapMonths","ms","dt","DateTime","mapWeekdays","listStuff","length","englishFn","intlFn","mode","supportsFastNumbers","PolyNumberFormatter","intl","forceSimple","padTo","floor","otherOpts","intlOpts","fixed","roundTo","padStart","PolyDateFormatter","z","gmtOffset","offsetZ","parts","part","offsetName","PolyRelFormatter","isEnglish","hasRelative","English.formatRelativeTime","fallbackWeekSettings","Locale","weekSettings","defaultToEN","specifiedLocale","Settings","localeR","numberingSystemR","outputCalendarR","weekSettingsR","validateWeekSettings","numbering","parsedLocale","parsedNumberingSystem","parsedOutputCalendar","isActuallyEn","hasNoWeirdness","alts","English.months","formatStr","English.weekdays","English.meridiems","English.eras","df","matching","hasLocaleWeekInfo","FixedOffsetZone","offset","signedOffset","InvalidZone","zoneName","normalizeZone","input","defaultZone","isString","lowered","isNumber","defaultLocale","defaultNumberingSystem","defaultOutputCalendar","twoDigitCutoffYear","throwOnInvalid","defaultWeekSettings","cutoffYear","t","Invalid","explanation","nonLeapLadder","leapLadder","unitOutOfRange","dayOfWeek","js","computeOrdinal","isLeapYear","uncomputeOrdinal","ordinal","table","month0","isoWeekdayToLocal","isoWeekday","startOfWeek","gregorianToWeek","gregObj","minDaysInFirstWeek","weekday","weekNumber","weekYear","weeksInWeekYear","timeObject","weekToGregorian","weekData","weekdayOfJan4","yearInDays","daysInYear","gregorianToOrdinal","gregData","ordinalToGregorian","ordinalData","usesLocalWeekValues","hasInvalidWeekData","validYear","isInteger","validWeek","integerBetween","validWeekday","hasInvalidOrdinalData","validOrdinal","hasInvalidGregorianData","validMonth","validDay","daysInMonth","hasInvalidTimeData","millisecond","validHour","validMinute","validSecond","validMillisecond","o","isDate","maybeArray","thing","bestBy","arr","by","compare","best","pick","prop","settings","bottom","top","floorMod","isNeg","padded","parseInteger","parseFloating","parseMillis","fraction","number","digits","towardZero","factor","modMonth","modYear","firstWeekOffset","weekOffset","weekOffsetNext","untruncateYear","offsetFormat","timeZone","modified","offHourStr","offMinuteStr","offHour","offMin","offMinSigned","asNumber","numericValue","normalizeObject","normalizer","u","hours","minutes","sign","monthsLong","monthsShort","monthsNarrow","months","weekdaysLong","weekdaysShort","weekdaysNarrow","weekdays","meridiems","erasLong","erasShort","erasNarrow","eras","meridiemForDateTime","weekdayForDateTime","monthForDateTime","eraForDateTime","formatRelativeTime","numeric","narrow","units","lastable","isDay","isInPast","fmtValue","singular","lilUnits","fmtUnit","stringifyTokens","splits","tokenToString","token","macroTokenToFormatOpts","Formats.DATE_SHORT","Formats.DATE_MED","Formats.DATE_FULL","Formats.DATE_HUGE","Formats.TIME_SIMPLE","Formats.TIME_WITH_SECONDS","Formats.TIME_WITH_SHORT_OFFSET","Formats.TIME_WITH_LONG_OFFSET","Formats.TIME_24_SIMPLE","Formats.TIME_24_WITH_SECONDS","Formats.TIME_24_WITH_SHORT_OFFSET","Formats.TIME_24_WITH_LONG_OFFSET","Formats.DATETIME_SHORT","Formats.DATETIME_MED","Formats.DATETIME_FULL","Formats.DATETIME_HUGE","Formats.DATETIME_SHORT_WITH_SECONDS","Formats.DATETIME_MED_WITH_SECONDS","Formats.DATETIME_FULL_WITH_SECONDS","Formats.DATETIME_HUGE_WITH_SECONDS","Formatter","fmt","current","currentFull","bracketed","formatOpts","interval","knownEnglish","useDateTimeFormatter","meridiem","English.meridiemForDateTime","standalone","English.monthForDateTime","English.weekdayForDateTime","maybeMacro","era","English.eraForDateTime","dur","tokenToField","lildur","mapped","tokens","realTokens","found","literal","collapsed","ianaRegex","combineRegexes","regexes","r","combineExtractors","extractors","mergedVals","mergedZone","cursor","ex","patterns","regex","simpleParse","ret","offsetRegex","isoExtendedZone","isoTimeBaseRegex","isoTimeRegex","isoTimeExtensionRegex","isoYmdRegex","isoWeekRegex","isoOrdinalRegex","extractISOWeekData","extractISOOrdinalData","sqlYmdRegex","sqlTimeRegex","sqlTimeExtensionRegex","int","fallback","extractISOYmd","extractISOTime","extractISOOffset","local","fullOffset","extractIANAZone","isoTimeOnly","isoDuration","extractISODuration","yearStr","monthStr","weekStr","dayStr","hourStr","minuteStr","secondStr","millisecondsStr","hasNegativePrefix","negativeSeconds","maybeNegate","num","force","obsOffsets","fromStrings","weekdayStr","English.monthsShort","English.weekdaysLong","English.weekdaysShort","rfc2822","extractRFC2822","obsOffset","milOffset","preprocessRFC2822","rfc1123","rfc850","ascii","extractRFC1123Or850","extractASCII","isoYmdWithTimeExtensionRegex","isoWeekWithTimeExtensionRegex","isoOrdinalWithTimeExtensionRegex","isoTimeCombinedRegex","extractISOYmdTimeAndOffset","extractISOWeekTimeAndOffset","extractISOOrdinalDateAndTime","extractISOTimeAndOffset","parseISODate","parseRFC2822Date","parseHTTPDate","parseISODuration","extractISOTimeOnly","parseISOTimeOnly","sqlYmdWithTimeExtensionRegex","sqlTimeCombinedRegex","extractISOTimeOffsetAndIANAZone","parseSQL","INVALID","lowOrderMatrix","casualMatrix","daysInYearAccurate","daysInMonthAccurate","accurateMatrix","orderedUnits","reverseUnits","clone","clear","conf","Duration","durationToMillis","matrix","vals","sum","normalizeValues","previousVal","conv","rollUp","removeZeroes","newVals","accurate","durationLike","text","invalid","fmtOpts","millis","duration","mixed","conversionAccuracy","built","accumulated","lastUnit","own","ak","negated","eq","v1","v2","validateStartEnd","start","end","Interval","builtStart","friendlyDateTime","builtEnd","validateError","startIsValid","endIsValid","dateTime","dateTimes","sorted","idx","numberOfParts","intervals","final","sofar","currentCount","ends","flattened","dateFormat","separator","Info","locObj","dayDiff","earlier","later","utcDayStart","highOrderDiffs","differs","days","lowestOrder","highWater","differ","remainingMillis","lowerOrderUnits","numberingSystems","numberingSystemsUTF16","hanidecChars","parseDigits","str","code","min","digitRegex","append","MISSING_FTP","intUnit","post","NBSP","spaceOrNBSP","spaceOrNBSPRegExp","fixListRegex","stripInsensitivities","oneOf","strings","startIndex","groups","h","simple","escapeToken","unitForToken","one","two","three","four","six","oneOrTwo","oneToThree","oneToSix","oneToNine","twoToFour","fourToSix","partTypeStyleToTokenVal","tokenForPart","resolvedOpts","isSpace","style","actualType","buildRegex","handlers","matches","matchIndex","dateTimeFromMatches","toField","specificOffset","dummyDateTimeCache","getDummyDateTime","maybeExpandMacroToken","formatOptsToTokens","expandMacroTokens","explainFromTokens","disqualifyingUnit","regexString","rawMatches","parseFromTokens","invalidReason","MAX_DATE","unsupportedZone","possiblyCachedWeekData","possiblyCachedLocalWeekData","inst","fixOffset","localTS","tz","utcGuess","o2","o3","tsToObj","objToTS","adjustTime","oPre","millisToAdd","parseDataToDateTime","parsedZone","setZone","interpretationZone","toTechFormat","allowZ","toISODate","extended","longFormat","toISOTime","suppressSeconds","suppressMilliseconds","includeOffset","extendedZone","defaultUnitValues","defaultWeekUnitValues","defaultOrdinalUnitValues","orderedWeekUnits","orderedOrdinalUnits","normalizeUnit","normalizeUnitWithLocalWeeks","quickDT","tsNow","offsetProvis","diffRelative","round","lastOpts","argList","ot","zoneToUse","milliseconds","seconds","containsOrdinal","containsGregorYear","containsGregorMD","containsGregor","definiteWeekDef","useWeekData","defaultValues","objNow","foundFirst","higherOrderInvalid","gregorian","tsFinal","offsetFinal","localeToUse","localeOpts","tokenList","dayMs","minuteMs","oEarlier","oLater","o1","ts1","ts2","c1","c2","keepLocalTime","keepCalendarTime","newTS","offsetGuess","asObj","settingWeekStuff","useLocaleWeeks","normalizedUnit","q","ext","includePrefix","includeZone","includeOffsetSpace","otherDateTime","durOpts","otherIsLater","diffed","inputMs","adjustedToZone","padding","Formats.DATE_MED_WITH_WEEKDAY","Formats.DATETIME_MED_WITH_WEEKDAY","dateTimeish"],"mappings":"8yEAAA,SAASA,GAA0BC,EAAO,OACxC,OAAI,OAAOA,GAAU,UAAY,CAACA,EAAM,SAAS,sBAAsB,EAC9DA,GAEFC,EAAAD,EAAM,MAAM,iBAAiB,IAA7B,YAAAC,EAAiC,GAAG,MAAM,KAAK,GAAG,MAC3D,CACA,SAASC,GAAGF,EAAO,CACjB,MAAMG,EAAmBJ,GAA0BC,CAAK,EACxD,OAAI,OAAOG,GAAqB,SACvBA,EAEL,OAAOA,GAAqB,SAC1BA,EAAiB,SAAS,MAAM,GAAKA,EAAiB,SAAS,KAAK,EAC/DA,EAELA,EAAiB,SAAS,IAAI,EACzB,OAAOA,EAAiB,QAAQ,KAAM,EAAE,CAAC,EAE9CA,EAAiB,SAAS,KAAK,EAC1B,OAAOA,EAAiB,QAAQ,MAAO,EAAE,CAAC,EAAI,GAEnDA,EAAiB,SAAS,IAAI,EACzB,OAAOA,EAAiB,QAAQ,KAAM,EAAE,CAAC,EAAI,GAE/C,OAAOA,CAAgB,EAEzB,GACT,CChBA,SAASC,GAAqB,CAC5B,WAAAC,EACA,OAAAC,EACA,MAAAC,EACA,UAAAC,CACF,EAAG,CACD,MAAMC,EAAQC,KACd,MAAO,CACL,mBAAoBC,GAAkB,CACpC,MAAAF,EACA,WAAAJ,EACA,MAAAE,EACA,UAAWC,GAAa,MAC9B,CAAK,EACD,eAAgBI,GAAc,CAC5B,MAAAH,EACA,OAAAH,EACA,MAAAC,EACA,UAAWC,GAAa,MAC9B,CAAK,CACL,CACA,CC1BO,MAAMK,GAAU,SAKVC,GAAc,OAAO,OAAO,CACvC,MAAO,GACP,MAAO,EACP,MAAO,EAC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B,EAEaU,GAAiB,CAC5B,KAAMntC,EACN,OAAQA,EACR,UAAW,KACb,EAEaotC,GAAuB,CAClC,KAAMptC,EACN,OAAQA,EACR,OAAQA,EACR,UAAW,KACb,EAEaqtC,GAA4B,CACvC,KAAMrtC,EACN,OAAQA,EACR,OAAQA,EACR,UAAW,MACX,aAAcuvB,EAChB,EAEa+d,GAA2B,CACtC,KAAMttC,EACN,OAAQA,EACR,OAAQA,EACR,UAAW,MACX,aAAcysC,EAChB,EAEac,GAAiB,CAC5B,KAAMvtC,EACN,MAAOA,EACP,IAAKA,EACL,KAAMA,EACN,OAAQA,CACV,EAEawtC,GAA8B,CACzC,KAAMxtC,EACN,MAAOA,EACP,IAAKA,EACL,KAAMA,EACN,OAAQA,EACR,OAAQA,CACV,EAEaytC,GAAe,CAC1B,KAAMztC,EACN,MAAOuvB,GACP,IAAKvvB,EACL,KAAMA,EACN,OAAQA,CACV,EAEa0tC,GAA4B,CACvC,KAAM1tC,EACN,MAAOuvB,GACP,IAAKvvB,EACL,KAAMA,EACN,OAAQA,EACR,OAAQA,CACV,EAEa2tC,GAA4B,CACvC,KAAM3tC,EACN,MAAOuvB,GACP,IAAKvvB,EACL,QAASuvB,GACT,KAAMvvB,EACN,OAAQA,CACV,EAEa4tC,GAAgB,CAC3B,KAAM5tC,EACN,MAAOysC,GACP,IAAKzsC,EACL,KAAMA,EACN,OAAQA,EACR,aAAcuvB,EAChB,EAEase,GAA6B,CACxC,KAAM7tC,EACN,MAAOysC,GACP,IAAKzsC,EACL,KAAMA,EACN,OAAQA,EACR,OAAQA,EACR,aAAcuvB,EAChB,EAEaue,GAAgB,CAC3B,KAAM9tC,EACN,MAAOysC,GACP,IAAKzsC,EACL,QAASysC,GACT,KAAMzsC,EACN,OAAQA,EACR,aAAcysC,EAChB,EAEasB,GAA6B,CACxC,KAAM/tC,EACN,MAAOysC,GACP,IAAKzsC,EACL,QAASysC,GACT,KAAMzsC,EACN,OAAQA,EACR,OAAQA,EACR,aAAcys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google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,101,102,103,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130]}