@sanity/sdk 3.18.0-next.20261201154713 → 3.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"version-ClZD8IhJ.js","names":["\"_createdAt\"","\"_updatedAt\"","\"state\"","\"publishAt\"","\"intendedPublishAt\""],"sources":["../src/auth/projectAccessError.ts","../src/document/processActions/releaseUtil.ts","../src/document/patchOperations.ts","../src/document/processMutations.ts","../src/utils/MultiKeyWeakMap.ts","../src/document/processActions/shared.ts","../src/document/permissions.ts","../src/document/processActions/create.ts","../src/document/processActions/delete.ts","../src/document/processActions/discard.ts","../src/document/processActions/edit.ts","../src/document/processActions/publish.ts","../src/document/processActions/releaseArchive.ts","../src/document/processActions/releaseCreate.ts","../src/document/processActions/releaseDelete.ts","../src/document/processActions/releaseEdit.ts","../src/document/processActions/releasePublish.ts","../src/document/processActions/releaseSchedule.ts","../src/document/processActions/unpublish.ts","../src/document/processActions/processActions.ts","../src/document/reducers.ts","../src/favorites/favorites.ts","../src/preferences/preferenceError.ts","../src/users/usersConstants.ts","../src/users/reducers.ts","../src/client/liveEvents.ts","../src/releases/observeReleases.ts","../src/releases/utils/sortReleases.ts","../src/releases/releasesStore.ts","../src/releases/getPerspectiveState.ts","../src/query/queryStoreConstants.ts","../src/query/reducers.ts","../src/query/queryStore.ts","../package.json","../src/version.ts"],"sourcesContent":["import {ClientError} from '@sanity/client'\n\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {getCurrentUserState} from './authStore'\nimport {getClientErrorApiBody, getClientErrorApiProjectId, getClientErrorApiType} from './utils'\n\n/**\n * Identifiers from a `projectUserNotFoundError` response. Each field is\n * optional because older API responses only carry a description.\n *\n * @internal\n */\nexport interface ProjectAccessErrorDetails {\n /** The project the failed request was made against. */\n projectId?: string\n /** The global ID of the signed-in user, which has no membership in the project. */\n userId?: string\n /** The trace ID of the failed request. Support uses it to find the request in logs. */\n traceId?: string\n}\n\nfunction findClientError(error: unknown): ClientError | null {\n if (error instanceof ClientError) return error\n if (error instanceof Error && error.cause instanceof ClientError) return error.cause\n return null\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' && value ? value : undefined\n}\n\n/**\n * Reads the identifiers from the 401 `projectUserNotFoundError` that the\n * Content Lake returns when the signed-in user is not a member of the project.\n * Accepts the `ClientError` itself or an error that wraps it as its `cause`,\n * such as the React package's `AuthError`.\n *\n * @returns The identifiers, or `null` when the error is not a\n * `projectUserNotFoundError`.\n * @internal\n */\nexport function getProjectAccessErrorDetails(error: unknown): ProjectAccessErrorDetails | null {\n const clientError = findClientError(error)\n if (\n !clientError ||\n clientError.statusCode !== 401 ||\n getClientErrorApiType(clientError) !== 'projectUserNotFoundError'\n ) {\n return null\n }\n\n const body = getClientErrorApiBody(clientError)?.error\n return {\n projectId: getClientErrorApiProjectId(clientError),\n userId: stringOrUndefined(body?.userID),\n traceId: stringOrUndefined(clientError.traceId),\n }\n}\n\n/**\n * Returns the ID of the project that rejected a request because the signed-in\n * user isn't a member of it. The Content Lake reports this as a 401\n * `projectUserNotFoundError`. It usually means the user signed in with a\n * different account than the one that has access, for example Google instead\n * of SSO with the same email address.\n *\n * When this error reaches the SDK's `AuthBoundary`, the boundary replaces the\n * whole app with a screen that explains the problem. An app-level error\n * boundary inside `AuthBoundary` catches the error first, so it decides where\n * the error goes. Rethrow it when the app can't work without the rejected\n * project. Handle it in place when only part of the app reads from that\n * project, so a user who can access the app's other projects can keep using\n * them.\n *\n * @param error - The value to inspect. A `ClientError`, or an error that wraps\n * one as its `cause`.\n * @returns The rejected project's ID, or `null` when the error isn't a\n * `projectUserNotFoundError` or the response doesn't name the project.\n *\n * @example Rethrowing only for the project the whole app needs\n * ```tsx\n * const MAIN_PROJECT_ID = 'abc123'\n *\n * function Fallback({error}: FallbackProps) {\n * const projectId = getProjectAccessErrorProjectId(error)\n * // The app can't work without its main project, so let AuthBoundary\n * // replace it with the project access screen.\n * if (projectId === MAIN_PROJECT_ID) throw error\n * if (projectId) return <p>You don't have access to project {projectId}.</p>\n * return <p>Something went wrong.</p>\n * }\n * ```\n *\n * @category Authentication\n * @public\n */\nexport function getProjectAccessErrorProjectId(error: unknown): string | null {\n return getProjectAccessErrorDetails(error)?.projectId ?? null\n}\n\n// Provider IDs come from the `provider` field of `/users/me`. SAML providers\n// are org-configured and arrive as `saml-<providerId>`.\nconst SIGN_IN_METHOD_LABELS: Record<string, string> = {\n google: 'Google',\n github: 'GitHub',\n sanity: 'email and password',\n vercel: 'Vercel',\n}\n\n/**\n * Returns a user-facing name for a `/users/me` `provider` value, such as\n * `Google` for `google` or `SSO` for any `saml-*` provider.\n *\n * @returns The label, or `undefined` for an unknown or missing provider.\n * @internal\n */\nexport function getSignInMethodLabel(provider: string | undefined): string | undefined {\n if (!provider) return undefined\n if (provider.startsWith('saml-')) return 'SSO'\n return SIGN_IN_METHOD_LABELS[provider]\n}\n\n// Names the sign-in method but never the email address, because error\n// messages end up in logs and error trackers.\nfunction getProjectAccessErrorMessage(\n details: ProjectAccessErrorDetails,\n provider: string | undefined,\n): string {\n const method = getSignInMethodLabel(provider)\n const account = method ? `Your Sanity account (signed in with ${method})` : 'Your Sanity account'\n const project = details.projectId ? `project ${details.projectId}` : 'this project'\n // Matches the trace ID suffix @sanity/client adds to ClientError messages.\n const traceId = details.traceId ? ` (traceId: ${details.traceId})` : ''\n return (\n `${account} isn't a member of ${project}. ` +\n 'Each sign-in method, such as Google or SSO, is a separate account. ' +\n `Sign out and sign in with the account that has access.${traceId}`\n )\n}\n\n// Keeps everything the original ClientError carries (status code, response\n// body, trace ID) so `instanceof ClientError` checks and\n// `getProjectAccessErrorDetails` keep working on it.\nclass ProjectAccessClientError extends ClientError {\n constructor(error: ClientError, message: string) {\n super(error.response)\n this.message = message\n }\n}\n\n/**\n * Replaces the API's `projectUserNotFoundError` message with one that tells\n * the user what to do. Hooks throw store errors to the nearest error boundary,\n * and most boundaries, including routers' default error screens, render\n * `error.message`. Any other error is returned unchanged.\n *\n * @internal\n */\nexport function withProjectAccessMessage(instance: SanityInstance, error: unknown): unknown {\n if (!(error instanceof ClientError) || error instanceof ProjectAccessClientError) return error\n const details = getProjectAccessErrorDetails(error)\n if (!details) return error\n\n const provider = getCurrentUserState(instance).getCurrent()?.provider\n return new ProjectAccessClientError(error, getProjectAccessErrorMessage(details, provider))\n}\n","import {type Action, type ReleaseAction} from '../actions'\n\n/**\n * Path prefix shared by every release document. Matches studio's\n * `RELEASE_DOCUMENTS_PATH` constant.\n */\nconst RELEASE_DOCUMENTS_PATH = '_.releases'\n\n/**\n * Returns the full release document ID for the given release name.\n * e.g. `getReleaseDocumentId('my-release') === '_.releases.my-release'`\n * @beta\n */\nexport function getReleaseDocumentId(releaseId: string): string {\n return `${RELEASE_DOCUMENTS_PATH}.${releaseId}`\n}\n\nconst RELEASE_ACTION_TYPES = new Set([\n 'release.create',\n 'release.edit',\n 'release.publish',\n 'release.schedule',\n 'release.unschedule',\n 'release.archive',\n 'release.unarchive',\n 'release.delete',\n])\n\nexport function isReleaseAction(action: Action): action is ReleaseAction {\n return RELEASE_ACTION_TYPES.has(action.type)\n}\n","import {applyPatches, parsePatch} from '@sanity/diff-match-patch'\nimport {getIndexForKey, jsonMatch, slicePath, stringifyPath} from '@sanity/json-match'\nimport {\n type IndexTuple,\n type InsertPatch,\n isKeyedObject,\n isKeySegment,\n type PathSegment,\n} from '@sanity/types'\n\ntype SingleValuePath = Exclude<PathSegment, IndexTuple>[]\n\ntype ToNumber<TInput extends string> = TInput extends `${infer TNumber extends number}`\n ? TNumber\n : TInput\n\n/**\n * Parse a single \"segment\" that may include bracket parts.\n *\n * For example, the literal\n *\n * ```\n * \"friends[0][1]\"\n * ```\n *\n * is parsed as:\n *\n * ```\n * [\"friends\", 0, 1]\n * ```\n */\ntype ParseSegment<TInput extends string> = TInput extends `${infer TProp}[${infer TRest}`\n ? TProp extends ''\n ? [...ParseBracket<`[${TRest}`>] // no property name before '['\n : [TProp, ...ParseBracket<`[${TRest}`>]\n : TInput extends ''\n ? []\n : [TInput]\n\n/**\n * Parse one or more bracketed parts from a segment.\n *\n * It recursively \"peels off\" a bracketed part and then continues.\n *\n * For example, given the string:\n *\n * ```\n * \"[0][foo]\"\n * ```\n *\n * it produces:\n *\n * ```\n * [ToNumber<\"0\">, \"foo\"]\n * ```\n */\ntype ParseBracket<TInput extends string> = TInput extends `[${infer TPart}]${infer TRest}`\n ? [ToNumber<TPart>, ...ParseSegment<TRest>]\n : [] // no leading bracket → end of this segment\n\n/**\n * Split the entire path string on dots \"outside\" of any brackets.\n *\n * For example:\n * ```\n * \"friends[0].name\"\n * ```\n *\n * becomes:\n *\n * ```\n * [...ParseSegment<\"friends[0]\">, ...ParseSegment<\"name\">]\n * ```\n *\n * (We use a simple recursion that splits on the first dot.)\n */\ntype PathParts<TPath extends string> = TPath extends `${infer Head}.${infer Tail}`\n ? [Head, ...PathParts<Tail>]\n : TPath extends ''\n ? []\n : [TPath]\n\n/**\n * Given a type T and an array of \"access keys\" Parts, recursively index into T.\n *\n * If a part is a key, it looks up that property.\n * If T is an array and the part is a number, it \"indexes\" into the element type.\n */\ntype DeepGet<TValue, TPath extends readonly (string | number)[]> = TPath extends []\n ? TValue\n : TPath extends readonly [infer THead, ...infer TTail]\n ? // Handle traversing into optional properties\n DeepGet<\n TValue extends undefined | null\n ? undefined // Stop traversal if current value is null/undefined\n : THead extends keyof TValue // Access property if key exists\n ? TValue[THead]\n : // Handle array indexing\n THead extends number\n ? TValue extends readonly (infer TElement)[]\n ? TElement | undefined // Array element or undefined if out of bounds\n : undefined // Cannot index non-array with number\n : undefined, // Key/index doesn't exist\n TTail extends readonly (string | number)[] ? TTail : [] // Continue with the rest of the path\n >\n : never // Should be unreachable\n\n/**\n * Given a document type TDocument and a JSON Match path string TPath,\n * compute the type found at that path.\n * @beta\n */\nexport type JsonMatch<TDocument, TPath extends string> = DeepGet<TDocument, PathParts<TPath>>\n\n// this is a similar array key to the studio:\n// https://github.com/sanity-io/sanity/blob/v3.74.1/packages/sanity/src/core/form/inputs/arrays/ArrayOfObjectsInput/createProtoArrayValue.ts\nfunction generateArrayKey(length: number = 12): string {\n // Each byte gives two hex characters, so generate enough bytes.\n const numBytes = Math.ceil(length / 2)\n const bytes = crypto.getRandomValues(new Uint8Array(numBytes))\n // Convert each byte to a 2-digit hex string and join them.\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n .slice(0, length)\n}\n\nfunction memoize<TFunction extends (input: unknown) => unknown>(fn: TFunction): TFunction {\n const cache = new WeakMap<object, unknown>()\n return ((input) => {\n if (!input || typeof input !== 'object') return fn(input)\n\n const cached = cache.get(input)\n if (cached) return cached\n\n const result = fn(input)\n cache.set(input, result)\n return result\n }) as TFunction\n}\n\n/**\n * Recursively traverse a value. When an array is encountered, ensure that\n * each object item has a _key property. Memoized such that sub-objects that\n * have not changed aren't re-computed.\n */\nexport const ensureArrayKeysDeep = memoize(<R>(input: R): R => {\n if (!input || typeof input !== 'object') return input\n\n if (Array.isArray(input)) {\n // if the array is empty then just return the input\n if (!input.length) return input\n const first = input[0]\n // if the first input in the array isn't an object (null is allowed) then\n // assume that this is an array of primitives, just return the input\n if (typeof first !== 'object') return input\n\n // if all the items already have a key, then return the input\n if (input.every(isKeyedObject)) return input\n\n // otherwise return a new object item with a new key\n return input.map((item: unknown) => {\n if (!item || typeof item !== 'object') return item\n if (isKeyedObject(item)) return ensureArrayKeysDeep(item)\n const next = ensureArrayKeysDeep(item)\n return {...next, _key: generateArrayKey()}\n }) as R\n }\n\n const entries = Object.entries(input).map(([key, value]) => [key, ensureArrayKeysDeep(value)])\n\n if (entries.every(([key, value]) => input[key as keyof typeof input] === value)) {\n return input\n }\n\n return Object.fromEntries(entries) as R\n})\n\n/**\n * Whether every array-addressing segment (keyed `[_key==\"…\"]` or numeric\n * index) in the given match path resolves to an existing array item.\n *\n * This mirrors Content Lake, which auto-creates missing *object* properties\n * when setting but never creates *array items*:\n *\n * ```js\n * // object properties are created, even nested ones:\n * set({}, {'meta.author.name': 'Ada'})\n * // -> {meta: {author: {name: 'Ada'}}} (applies)\n *\n * // array items are not:\n * set({items: [{_key: 'a'}]}, {'items[_key==\"b\"].title': 'x'})\n * // -> {items: [{_key: 'a'}]} (no-op)\n * ```\n *\n * Without this filter, the second example fabricated a degenerate item\n * (`{title: 'x'}`, no `_key`) that would never exist on the server, which\n * is how concurrent Portable Text edits grew phantom span-less children.\n */\nfunction resolvesArraySegments(input: unknown, path: SingleValuePath): boolean {\n let current: unknown = input\n for (const segment of path) {\n if (typeof segment === 'string') {\n // missing object properties (nested ones included) are created\n // server-side, so a string segment may descend into undefined\n current =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)[segment]\n : undefined\n continue\n }\n // keyed and numeric segments address array items, which are never created\n if (!Array.isArray(current)) return false\n if (isKeySegment(segment)) {\n const index = getIndexForKey(current, segment._key)\n if (index === undefined) return false\n current = current[index]\n } else {\n const index = segment < 0 ? current.length + segment : segment\n if (!(index in current)) return false\n current = current[index]\n }\n }\n return true\n}\n\n/**\n * Given an input object and a record of path expressions to values, this\n * function will set each match with the given value.\n *\n * ```js\n * const output = set(\n * {name: {first: 'initial', last: 'initial'}},\n * {'name.first': 'changed'}\n * );\n *\n * // { name: { first: 'changed', last: 'initial' } }\n * console.log(output);\n * ```\n */\nexport function set<R>(input: unknown, pathExpressionValues: Record<string, unknown>): R\nexport function set(input: unknown, pathExpressionValues: Record<string, unknown>): unknown {\n const result = Object.entries(pathExpressionValues)\n .flatMap(([pathExpression, replacementValue]) =>\n Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({\n ...matchEntry,\n replacementValue,\n })),\n )\n .filter(({path}) => resolvesArraySegments(input, path))\n .reduce((acc, {path, replacementValue}) => setDeep(acc, path, replacementValue), input)\n\n return ensureArrayKeysDeep(result)\n}\n\n/**\n * Given an input object and a record of path expressions to values, this\n * function will set each match with the given value **if the value at the current\n * path is missing** (i.e. `null` or `undefined`).\n *\n * ```js\n * const output = setIfMissing(\n * {items: [null, 'initial']},\n * {'items[:]': 'changed'}\n * );\n *\n * // { items: ['changed', 'initial'] }\n * console.log(output);\n * ```\n */\nexport function setIfMissing<R>(input: unknown, pathExpressionValues: Record<string, unknown>): R\nexport function setIfMissing(\n input: unknown,\n pathExpressionValues: Record<string, unknown>,\n): unknown {\n const result = Object.entries(pathExpressionValues)\n .flatMap(([pathExpression, replacementValue]) => {\n return Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({\n ...matchEntry,\n replacementValue,\n }))\n })\n .filter((matchEntry) => matchEntry.value === null || matchEntry.value === undefined)\n .filter(({path}) => resolvesArraySegments(input, path))\n .reduce((acc, {path, replacementValue}) => setDeep(acc, path, replacementValue), input)\n\n return ensureArrayKeysDeep(result)\n}\n\n/**\n * Given an input object and an array of path expressions, this function will\n * remove each match from the input object.\n *\n * ```js\n * const output = unset(\n * {name: {first: 'one', last: 'two'}},\n * ['name.last']\n * );\n *\n * // { name: { first: 'one' } }\n * console.log(output);\n * ```\n */\nexport function unset<R>(input: unknown, pathExpressions: string[]): R\nexport function unset(input: unknown, pathExpressions: string[]): unknown {\n const result = pathExpressions\n .flatMap((pathExpression) => Array.from(jsonMatch(input, pathExpression)))\n // ensure that we remove in the reverse order the paths were found in\n // this is necessary for array unsets so the indexes don't change as we unset\n .reverse()\n .reduce((acc, {path}) => unsetDeep(acc, path), input)\n\n return ensureArrayKeysDeep(result)\n}\n\n/**\n * Given an input object, a path expression (inside the insert patch object), and an array of items,\n * this function will insert or replace the matched items.\n *\n * **Insert before:**\n *\n * ```js\n * const input = {some: {array: ['a', 'b', 'c']}}\n * const output = insert(\n * input,\n * {\n * before: 'some.array[1]',\n * items: ['!']\n * }\n * );\n * // { some: { array: ['a', '!', 'b', 'c'] } }\n * console.log(output);\n * ```\n *\n * **Insert before with negative index (append):**\n *\n * ```js\n * const input = {some: {array: ['a', 'b', 'c']}}\n * const output = insert(\n * input,\n * {\n * before: 'some.array[-1]',\n * items: ['!']\n * }\n * );\n * // { some: { array: ['a', 'b', 'c', '!'] } }\n * console.log(output);\n * ```\n *\n * **Insert after:**\n *\n * ```js\n * const input = {some: {array: ['a', 'b', 'c']}}\n * const output = insert(\n * input,\n * {\n * after: 'some.array[1]',\n * items: ['!']\n * }\n * );\n * // { some: { array: ['a', 'b', '!', 'c'] } }\n * console.log(output);\n * ```\n *\n * **Replace:**\n *\n * ```js\n * const output = insert(\n * { some: { array: ['a', 'b', 'c'] } },\n * {\n * replace: 'some.array[1]',\n * items: ['!']\n * }\n * );\n * // { some: { array: ['a', '!', 'c'] } }\n * console.log(output);\n * ```\n *\n * **Replace many:**\n *\n * ```js\n * const input = {some: {array: ['a', 'b', 'c', 'd']}}\n * const output = insert(\n * input,\n * {\n * replace: 'some.array[1:3]',\n * items: ['!', '?']\n * }\n * );\n * // { some: { array: ['a', '!', '?', 'd'] } }\n * console.log(output);\n * ```\n */\nexport function insert<R>(input: unknown, insertPatch: InsertPatch): R\nexport function insert(input: unknown, {items, ...insertPatch}: InsertPatch): unknown {\n let operation\n let pathExpression\n\n // behavior observed from content-lake when inserting:\n // 1. if the operation is before, out of all the matches, it will use the\n // insert the items before the first match that appears in the array\n // 2. if the operation is after, it will insert the items after the first\n // match that appears in the array\n // 3. if the operation is replace, then insert the items before the first\n // match and then delete the rest\n if ('before' in insertPatch) {\n operation = 'before' as const\n pathExpression = insertPatch.before\n } else if ('after' in insertPatch) {\n operation = 'after' as const\n pathExpression = insertPatch.after\n } else if ('replace' in insertPatch) {\n operation = 'replace' as const\n pathExpression = insertPatch.replace\n }\n if (!operation) return input\n if (typeof pathExpression !== 'string') return input\n\n // in order to do an insert patch, you need to provide at least one path segment\n if (!pathExpression.length) return input\n\n const arrayPath = slicePath(pathExpression, 0, -1)\n const positionPath = slicePath(pathExpression, -1)\n\n let result = input\n\n for (const {path, value} of jsonMatch(input, arrayPath)) {\n if (!Array.isArray(value)) continue\n let arr = value\n\n switch (operation) {\n case 'replace': {\n const indexesToRemove = new Set<number>()\n let position = Infinity\n\n for (const itemMatch of jsonMatch(arr, positionPath)) {\n // there should only be one path segment for an insert patch, invalid otherwise\n if (itemMatch.path.length !== 1) continue\n const [segment] = itemMatch.path\n if (typeof segment === 'string') continue\n\n let index\n\n if (typeof segment === 'number') index = segment\n if (typeof index === 'number' && index < 0) index = arr.length + index\n if (isKeySegment(segment)) index = getIndexForKey(arr, segment._key)\n if (typeof index !== 'number') continue\n if (index < 0) index = arr.length + index\n\n indexesToRemove.add(index)\n if (index < position) position = index\n }\n\n if (position === Infinity) continue\n\n // remove all other indexes\n arr = arr\n .map((item, index) => ({item, index}))\n .filter(({index}) => !indexesToRemove.has(index))\n .map(({item}) => item)\n\n // insert at the min index\n arr = [...arr.slice(0, position), ...items, ...arr.slice(position, arr.length)]\n\n break\n }\n case 'before': {\n let position = Infinity\n\n for (const itemMatch of jsonMatch(arr, positionPath)) {\n if (itemMatch.path.length !== 1) continue\n const [segment] = itemMatch.path\n\n if (typeof segment === 'string') continue\n\n let index\n\n if (typeof segment === 'number') index = segment\n if (typeof index === 'number' && index < 0) index = arr.length + index\n if (isKeySegment(segment)) index = getIndexForKey(arr, segment._key)\n if (typeof index !== 'number') continue\n if (index < 0) index = arr.length - index\n if (index < position) position = index\n }\n\n if (position === Infinity) continue\n\n arr = [...arr.slice(0, position), ...items, ...arr.slice(position, arr.length)]\n\n break\n }\n case 'after': {\n let position = -Infinity\n\n for (const itemMatch of jsonMatch(arr, positionPath)) {\n if (itemMatch.path.length !== 1) continue\n const [segment] = itemMatch.path\n\n if (typeof segment === 'string') continue\n\n let index\n\n if (typeof segment === 'number') index = segment\n if (typeof index === 'number' && index < 0) index = arr.length + index\n if (isKeySegment(segment)) index = getIndexForKey(arr, segment._key)\n if (typeof index !== 'number') continue\n if (index > position) position = index\n }\n\n if (position === -Infinity) continue\n\n arr = [...arr.slice(0, position + 1), ...items, ...arr.slice(position + 1, arr.length)]\n\n break\n }\n\n default: {\n continue\n }\n }\n\n result = setDeep(result, path, arr)\n }\n\n return ensureArrayKeysDeep(result)\n}\n\n/**\n * Given an input object and a record of path expressions to numeric values,\n * this function will increment each match with the given value.\n *\n * ```js\n * const output = inc(\n * {foo: {first: 3, second: 4.5}},\n * {'foo.first': 3, 'foo.second': 4}\n * );\n *\n * // { foo: { first: 6, second: 8.5 } }\n * console.log(output);\n * ```\n */\nexport function inc<R>(input: unknown, pathExpressionValues: Record<string, number>): R\nexport function inc(input: unknown, pathExpressionValues: Record<string, number>): unknown {\n const result = Object.entries(pathExpressionValues)\n .flatMap(([pathExpression, valueToAdd]) =>\n Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({\n ...matchEntry,\n valueToAdd,\n })),\n )\n .filter(\n <T extends {value: unknown}>(matchEntry: T): matchEntry is T & {value: number} =>\n typeof matchEntry.value === 'number',\n )\n .reduce((acc, {path, value, valueToAdd}) => setDeep(acc, path, value + valueToAdd), input)\n\n return ensureArrayKeysDeep(result)\n}\n\n/**\n * Given an input object and a record of path expressions to numeric values,\n * this function will decrement each match with the given value.\n *\n * ```js\n * const output = dec(\n * {foo: {first: 3, second: 4.5}},\n * {'foo.first': 3, 'foo.second': 4}\n * );\n *\n * // { foo: { first: 0, second: 0.5 } }\n * console.log(output);\n * ```\n */\nexport function dec<R>(input: unknown, pathExpressionValues: Record<string, number>): R\nexport function dec(input: unknown, pathExpressionValues: Record<string, number>): unknown {\n const result = inc(\n input,\n Object.fromEntries(\n Object.entries(pathExpressionValues)\n .filter(([, value]) => typeof value === 'number')\n .map(([key, value]) => [key, -value]),\n ),\n )\n\n return ensureArrayKeysDeep(result)\n}\n\n/**\n * Given an input object and a record of paths to [diff match patches][0], this\n * function will apply the diff match patch for the string at each match.\n *\n * [0]: https://www.sanity.io/docs/http-patches#aTbJhlAJ\n *\n * ```js\n * const output = diffMatchPatch(\n * {foo: 'the quick brown fox'},\n * {'foo': '@@ -13,7 +13,7 @@\\n own \\n-fox\\n+cat\\n'}\n * );\n *\n * // { foo: 'the quick brown cat' }\n * console.log(output);\n * ```\n */\nexport function diffMatchPatch<R>(input: unknown, pathExpressionValues: Record<string, string>): R\nexport function diffMatchPatch(\n input: unknown,\n pathExpressionValues: Record<string, string>,\n): unknown {\n const result = Object.entries(pathExpressionValues)\n .flatMap(([pathExpression, dmp]) =>\n Array.from(jsonMatch(input, pathExpression)).map((m) => ({...m, dmp})),\n )\n .filter((i) => i.value !== undefined)\n .map(({path, value, dmp}) => {\n if (typeof value !== 'string') {\n throw new Error(\n `Can't diff-match-patch \\`${JSON.stringify(value)}\\` at path \\`${stringifyPath(path)}\\`, because it is not a string`,\n )\n }\n\n // Offsets arrive as UTF-8 byte positions and can overshoot when they\n // land inside a multi-byte character, which happens once the string a\n // patch was computed against has diverged. The default is to throw, and\n // that throw escapes the rebase loop in `reducers.ts`, kills the\n // outgoing-actions pipeline, and leaves the instance silently dropping\n // every write. Clamping to the nearest index applies the patch instead,\n // which is what the Studio and the Portable Text editor already do.\n const [nextValue] = applyPatches(parsePatch(dmp), value, {\n allowExceedingIndices: true,\n })\n return {path, value: nextValue}\n })\n .reduce((acc, {path, value}) => setDeep(acc, path, value), input)\n\n return ensureArrayKeysDeep(result)\n}\n\n/**\n * Simply checks if the given document input has a `_rev` that matches the given\n * `revisionId` and throws otherwise.\n *\n * (No code example provided.)\n */\nexport function ifRevisionID<R>(input: unknown, revisionId: string): R\nexport function ifRevisionID(input: unknown, revisionId: string): unknown {\n const inputRev =\n typeof input === 'object' && !!input && '_rev' in input && typeof input._rev === 'string'\n ? input._rev\n : undefined\n\n if (typeof inputRev !== 'string') {\n throw new Error(`Patch specified \\`ifRevisionID\\` but could not find document's revision ID.`)\n }\n\n if (revisionId !== inputRev) {\n throw new Error(\n `Patch's \\`ifRevisionID\\` \\`${revisionId}\\` does not match document's revision ID \\`${inputRev}\\``,\n )\n }\n\n return input\n}\n\n/**\n * Gets a value deep inside of an object given a path. If the path does not\n * exist in the object, `undefined` will be returned.\n */\nexport function getDeep<R>(input: unknown, path: SingleValuePath): R\nexport function getDeep(input: unknown, path: SingleValuePath): unknown {\n const [currentSegment, ...restOfPath] = path\n if (currentSegment === undefined) return input\n if (typeof input !== 'object' || input === null) return undefined\n\n let key\n if (isKeySegment(currentSegment)) {\n key = getIndexForKey(input, currentSegment._key)\n } else if (typeof currentSegment === 'string') {\n key = currentSegment\n } else if (typeof currentSegment === 'number') {\n key = currentSegment\n }\n\n if (key === undefined) return undefined\n\n // Use .at() to support negative indexes on arrays.\n const nestedInput =\n typeof key === 'number' && Array.isArray(input)\n ? input.at(key)\n : (input as Record<string, unknown>)[key]\n\n return getDeep(nestedInput, restOfPath)\n}\n\n/**\n * Sets a value deep inside of an object given a path. If the path does not\n * exist in the object, it will be created.\n */\nexport function setDeep<R>(input: unknown, path: SingleValuePath, value: unknown): R\nexport function setDeep(input: unknown, path: SingleValuePath, value: unknown): unknown {\n const [currentSegment, ...restOfPath] = path\n if (currentSegment === undefined) return value\n\n // If the current input is not an object, create a new container.\n if (typeof input !== 'object' || input === null) {\n if (typeof currentSegment === 'string') {\n return {[currentSegment]: setDeep(null, restOfPath, value)}\n }\n\n let index: number | undefined\n if (isKeySegment(currentSegment)) {\n // When creating a new array via a keyed segment, use index 0.\n index = 0\n } else if (typeof currentSegment === 'number' && currentSegment >= 0) {\n index = currentSegment\n } else {\n // For negative numbers in a non‐object we simply return input.\n return input\n }\n\n return [\n // fill until index\n ...Array.from({length: index}).fill(null),\n // then set deep here\n setDeep(null, restOfPath, value),\n ]\n }\n\n // When input is an array…\n if (Array.isArray(input)) {\n let index: number | undefined\n if (isKeySegment(currentSegment)) {\n index = getIndexForKey(input, currentSegment._key) ?? input.length\n } else if (typeof currentSegment === 'number') {\n // Support negative indexes by computing the proper positive index.\n index = currentSegment < 0 ? input.length + currentSegment : currentSegment\n }\n if (index === undefined) return input\n\n if (index in input) {\n // Update the element at the resolved index.\n return input.map((nestedInput, i) =>\n i === index ? setDeep(nestedInput, restOfPath, value) : nestedInput,\n )\n }\n\n // Expand the array if needed.\n return [\n ...input,\n ...Array.from({length: index - input.length}).fill(null),\n setDeep(null, restOfPath, value),\n ]\n }\n\n // For keyed segments that aren't arrays, do nothing.\n if (typeof currentSegment === 'object') return input\n\n // For plain objects, update an existing property if it exists…\n if (currentSegment in input) {\n return Object.fromEntries(\n Object.entries(input).map(([key, nestedInput]) =>\n key === currentSegment\n ? [key, setDeep(nestedInput, restOfPath, value)]\n : [key, nestedInput],\n ),\n )\n }\n\n // ...otherwise create the new nested path.\n return {...input, [currentSegment]: setDeep(null, restOfPath, value)}\n}\n\n/**\n * Given an object and an exact path as an array, this unsets the value at the\n * given path.\n */\nexport function unsetDeep<R>(input: unknown, path: SingleValuePath): R\nexport function unsetDeep(input: unknown, path: SingleValuePath): unknown {\n const [currentSegment, ...restOfPath] = path\n if (currentSegment === undefined) return input\n if (typeof input !== 'object' || input === null) return input\n\n let _segment: string | number | undefined\n if (isKeySegment(currentSegment)) {\n _segment = getIndexForKey(input, currentSegment._key)\n } else if (typeof currentSegment === 'string' || typeof currentSegment === 'number') {\n _segment = currentSegment\n }\n if (_segment === undefined) return input\n\n // For numeric segments in arrays, compute the positive index.\n let segment: string | number = _segment\n if (typeof segment === 'number' && Array.isArray(input)) {\n segment = segment < 0 ? input.length + segment : segment\n }\n if (!(segment in input)) return input\n\n // If we're at the final segment, remove the property/element.\n if (!restOfPath.length) {\n if (Array.isArray(input)) {\n return input.filter((_nestedInput, index) => index !== segment)\n }\n return Object.fromEntries(Object.entries(input).filter(([key]) => key !== segment.toString()))\n }\n\n // Otherwise, recurse into the nested value.\n if (Array.isArray(input)) {\n return input.map((nestedInput, index) =>\n index === segment ? unsetDeep(nestedInput, restOfPath) : nestedInput,\n )\n }\n\n return Object.fromEntries(\n Object.entries(input).map(([key, value]) =>\n key === segment ? [key, unsetDeep(value, restOfPath)] : [key, value],\n ),\n )\n}\n","import {\n type Mutation,\n type MutationSelection,\n type PatchOperations,\n type SanityDocument,\n} from '@sanity/types'\n\nimport {randomUuid} from '../utils/ids'\nimport {\n dec,\n diffMatchPatch,\n ifRevisionID,\n inc,\n insert,\n set,\n setIfMissing,\n unset,\n} from './patchOperations'\n\n/**\n * Maps document IDs to documents, using `null` for documents that do not exist.\n *\n * @beta\n */\nexport type DocumentSet<TDocument extends SanityDocument = SanityDocument> = {\n [TDocumentId in string]?: TDocument | null\n}\n\ntype SupportedPatchOperation = Exclude<keyof PatchOperations, 'merge'>\n\n/**\n * Exposes the patch operations used by {@link processMutations}.\n *\n * @remarks\n * Property order determines execution order in {@link processMutations}:\n * `ifRevisionID`, `set`, `setIfMissing`, `unset`, `inc`, `dec`, `insert`,\n * then `diffMatchPatch`. Reordering the properties changes mutation results.\n * Freezes the collection to prevent callers from replacing the functions\n * used by the SDK's mutation evaluator.\n *\n * @see https://www.sanity.io/docs/http-mutations#5b4db1396e56\n *\n * @example\n * ```ts\n * const document = {items: [{_key: 'a', title: 'Before'}]}\n * const updated = patchOperations.set<typeof document>(document, {\n * 'items[_key==\"a\"].title': 'After',\n * })\n * ```\n *\n * @internal\n */\nexport const patchOperations = Object.freeze({\n ifRevisionID,\n set,\n setIfMissing,\n unset,\n inc,\n dec,\n insert,\n diffMatchPatch,\n} satisfies {\n [K in SupportedPatchOperation]: (\n input: unknown,\n pathExpressions: NonNullable<PatchOperations[K]>,\n ) => unknown\n})\n\n/**\n * Implements ID generation:\n *\n * A create mutation creates a new document. It takes the literal document\n * content as its argument. The rules for the new document's identifier are as\n * follows:\n *\n * - If the `_id` attribute is missing, then a new, random, unique ID is\n * generated.\n * - If the `_id` attribute is present but ends with `.`, then it is used as a\n * prefix for a new, random, unique ID.\n * - If the _id attribute is present, it is used as-is.\n *\n * [- source](https://www.sanity.io/docs/http-mutations#c732f27330a4)\n */\nexport function getId(id?: string): string {\n if (!id || typeof id !== 'string') return randomUuid()\n if (id.endsWith('.')) return `${id}${randomUuid()}`\n return id\n}\n\n/**\n * Configures {@link processMutations}.\n *\n * @internal\n */\nexport interface ProcessMutationsOptions {\n /**\n * The transaction ID that will become the next `_rev` for documents mutated\n * by the given mutations.\n */\n transactionId: string\n /**\n * The input document set that the mutations will be applied to.\n */\n documents: DocumentSet\n /**\n * A list of mutations to apply to the given document set.\n */\n mutations: Mutation[]\n /**\n * Supplies the default `_createdAt` and `_updatedAt` timestamps.\n * Uses the current time when omitted or empty.\n */\n timestamp?: string\n}\n\nexport function getDocumentIds(selection: MutationSelection): string[] {\n if ('id' in selection) {\n // NOTE: the `MutationSelection` type within `@sanity/client` (instead of\n // `@sanity/types`) allows for the ID field to be an array of strings so we\n // support that as well\n const array = Array.isArray(selection.id) ? selection.id : [selection.id]\n const ids = array.filter((id): id is string => typeof id === 'string')\n return Array.from(new Set(ids))\n }\n\n if ('query' in selection) {\n throw new Error(`'query' in mutations is not supported.`)\n }\n\n return []\n}\n\n/**\n * Applies mutations to an in-memory set of Sanity documents.\n * Deleted documents remain in the returned set with a value of `null`.\n *\n * Include every document affected by `mutations` in `documents`, using `null`\n * for documents that do not exist.\n *\n * Returns `documents` itself when `mutations` is empty. Otherwise, returns a\n * shallow copy of that object. The result can reuse document objects and\n * nested objects from `documents`. Mutating a reused object through the\n * result also changes the input.\n *\n * Sets `_rev` to `transactionId` on created, replaced, and patched documents.\n * Uses `timestamp` for timestamps unless the mutation preserves them.\n * Ignores `merge` patches; `inc` and `dec` skip values that are not numbers.\n * Generates document IDs when omitted or ending in `.`.\n * Patch operations can generate missing array keys.\n *\n * Does not persist documents or run Content Lake's server validation.\n *\n * @throws If a selection uses a query, a `create` targets an existing document,\n * or a `patch` targets a document that does not exist.\n * @throws If a patch operation fails, including a revision check failure or\n * `diffMatchPatch` applied to a value other than a string or `undefined`.\n *\n * @internal\n */\nexport function processMutations({\n documents,\n mutations,\n transactionId,\n timestamp,\n}: ProcessMutationsOptions): DocumentSet {\n // early return if there are no mutations given\n if (!mutations.length) return documents\n\n const dataset = {...documents}\n const now = timestamp || new Date().toISOString()\n\n for (const mutation of mutations) {\n if ('create' in mutation) {\n const id = getId(mutation.create._id)\n\n if (dataset[id]) {\n throw new Error(\n `Cannot create document with \\`_id\\` \\`${id}\\` because another document with the same ID already exists.`,\n )\n }\n\n const document: SanityDocument = {\n // > `_createdAt` and `_updatedAt` may be submitted and will override\n // > the default which is of course the current time. This can be used\n // > to reconstruct a data-set with its timestamp structure intact.\n // >\n // > [- source](https://www.sanity.io/docs/http-mutations#c732f27330a4)\n _createdAt: now,\n _updatedAt: now,\n ...mutation.create, // prefer the user's `_createdAt` and `_updatedAt`\n _rev: transactionId,\n _id: id,\n }\n\n dataset[id] = document\n\n continue\n }\n\n if ('createOrReplace' in mutation) {\n const id = getId(mutation.createOrReplace._id)\n const prev = dataset[id]\n\n const document: SanityDocument = {\n ...mutation.createOrReplace,\n // otherwise, if the mutation provided, a `_createdAt` time, use it,\n // otherwise default to now\n _createdAt:\n // if there was an existing document, use the previous `_createdAt`\n // since we're replacing the current document\n prev?._createdAt ||\n // if there was no previous document, then we're creating this\n // document for the first time so we should use the `_createdAt` from\n // the mutation if the user included it\n (typeof mutation.createOrReplace['_createdAt'] === 'string' &&\n mutation.createOrReplace['_createdAt']) ||\n // otherwise, default to now\n now,\n\n _updatedAt:\n // if there was an existing document, then set the `_updatedAt` to now\n // since we're replacing the current document\n prev\n ? now\n : // otherwise, we're creating this document for the first time,\n // in that case, use the user's `_updatedAt` if included in the\n // mutation\n (typeof mutation.createOrReplace['_updatedAt'] === 'string' &&\n mutation.createOrReplace['_updatedAt']) ||\n // otherwise default to now\n now,\n _rev: transactionId,\n _id: id,\n }\n\n dataset[id] = document\n\n continue\n }\n\n if ('createIfNotExists' in mutation) {\n const id = getId(mutation.createIfNotExists._id)\n const prev = dataset[id]\n if (prev) continue\n\n const document: SanityDocument = {\n // same logic as `create`:\n // prefer the user's `_createdAt` and `_updatedAt`\n _createdAt: now,\n _updatedAt: now,\n ...mutation.createIfNotExists,\n _rev: transactionId,\n _id: id,\n }\n\n dataset[id] = document\n\n continue\n }\n\n if ('delete' in mutation) {\n for (const id of getDocumentIds(mutation.delete)) {\n dataset[id] = null\n }\n\n continue\n }\n\n if ('patch' in mutation) {\n const {patch} = mutation\n const ids = getDocumentIds(patch)\n\n const patched = ids.map((id) => {\n if (!dataset[id]) {\n throw new Error(`Cannot patch document with ID \\`${id}\\` because it was not found.`)\n }\n\n type Entries<T> = {[K in keyof T]: [K, T[K]]}[keyof T][]\n const entries = Object.entries(patchOperations) as Entries<typeof patchOperations>\n\n return entries.reduce((acc, [type, operation]) => {\n if (patch[type]) {\n return operation(\n acc,\n // @ts-expect-error TS doesn't handle this union very well\n patch[type],\n )\n }\n return acc\n }, dataset[id])\n })\n\n for (const result of patched) {\n dataset[result._id] = {\n ...result,\n _rev: transactionId,\n _updatedAt: now,\n }\n }\n\n continue\n }\n }\n\n return dataset\n}\n","interface MultiKeyWeakMapNode {\n value: unknown\n next: WeakMap<object, MultiKeyWeakMapNode>\n}\n\nexport class MultiKeyWeakMap<T = unknown> {\n // The root of our nested WeakMap structure.\n #rootMap = new WeakMap<object, MultiKeyWeakMapNode>()\n\n // Instead of random IDs, we use a counter for deterministic IDs.\n static #globalIdCounter = 0\n // Each instance keeps a cache mapping a key to its assigned ID.\n #idCache = new WeakMap<object, number>()\n\n /**\n * Assigns a numeric ID to the key.\n */\n #assignId(key: object): number {\n const cachedId = this.#idCache.get(key)\n if (cachedId !== undefined) return cachedId\n\n const id = MultiKeyWeakMap.#globalIdCounter\n this.#idCache.set(key, id)\n MultiKeyWeakMap.#globalIdCounter++\n return id\n }\n\n /**\n * Remove duplicate keys and arrange them in a consistent order\n * by sorting according to their assigned IDs.\n */\n #arrangeKeys(keys: object[]): object[] {\n const uniqueKeys = Array.from(new Set(keys))\n const keyed = uniqueKeys.map((key) => [this.#assignId(key), key] as const)\n keyed.sort((a, b) => a[0] - b[0])\n return keyed.map(([, key]) => key)\n }\n\n /**\n * Recursively search the nested WeakMap structure for the value.\n */\n #getDeep(keys: object[], map: WeakMap<object, MultiKeyWeakMapNode>): unknown {\n if (keys.length === 0) return undefined\n\n const [firstKey, ...restKeys] = keys\n const node = map.get(firstKey)\n if (!node) return undefined\n if (restKeys.length === 0) return node.value\n return this.#getDeep(restKeys, node.next)\n }\n\n /**\n * Recursively create nodes along the key chain until the final key\n * is reached, then assign the value.\n */\n #setDeep(keys: object[], map: WeakMap<object, MultiKeyWeakMapNode>, value: unknown): void {\n if (keys.length === 0) return\n\n const [firstKey, ...restKeys] = keys\n let node = map.get(firstKey)\n if (!node) {\n node = {\n value: undefined,\n next: new WeakMap(),\n }\n map.set(firstKey, node)\n }\n\n if (restKeys.length === 0) {\n node.value = value\n } else {\n this.#setDeep(restKeys, node.next, value)\n }\n }\n\n /**\n * Retrieves the value associated with the array of keys.\n * The keys are de-duplicated and sorted so that the order does not matter.\n */\n get(keys: object[]): T | undefined {\n const arrangedKeys = this.#arrangeKeys(keys)\n return this.#getDeep(arrangedKeys, this.#rootMap) as T | undefined\n }\n\n /**\n * Associates the value with the given array of keys.\n */\n set(keys: object[], value: T): void {\n const arrangedKeys = this.#arrangeKeys(keys)\n this.#setDeep(arrangedKeys, this.#rootMap, value)\n }\n}\n","import {diffValue} from '@sanity/diff-patch'\nimport {jsonMatch, stringifyPath} from '@sanity/json-match'\nimport {type Mutation, type PatchOperations, type SanityDocument} from '@sanity/types'\nimport {evaluateSync, type ExprNode} from 'groq-js'\n\nimport {type Grant} from '../permissions'\nimport {type DocumentSet, processMutations} from '../processMutations'\nimport {type HttpAction} from '../reducers'\n\nexport interface ActionHandlerContext {\n base: DocumentSet\n working: DocumentSet\n transactionId: string\n timestamp: string\n grants: Record<Grant, ExprNode>\n /**\n * The current user's ID, used by GROQ's `identity()` when evaluating ACL\n * filters. May be `undefined` before the user has loaded; in that case\n * `identity()` evaluates to null.\n */\n identity: string | undefined\n outgoingActions: HttpAction[]\n outgoingMutations: Mutation[]\n}\n\nexport interface ActionHandlerResult {\n base: DocumentSet\n working: DocumentSet\n}\n\nexport function checkGrant(\n grantExpr: ExprNode,\n document: SanityDocument,\n identity: string | undefined,\n): boolean {\n const value = evaluateSync(grantExpr, {params: {document}, identity})\n return value.type === 'boolean' && value.data\n}\n\ninterface ActionErrorOptions {\n message: string\n documentId: string\n transactionId: string\n}\n\n/**\n * Thrown when a precondition for an action failed.\n */\nexport class ActionError extends Error implements ActionErrorOptions {\n documentId!: string\n transactionId!: string\n\n constructor(options: ActionErrorOptions) {\n super(options.message)\n Object.assign(this, options)\n }\n}\n\nexport class PermissionActionError extends ActionError {}\n\n/**\n * Creates a `processMutations` wrapper that surfaces application failures as\n * `ActionError`s when the caller asked to preserve their patch operations.\n * With preserved operations, patches can legitimately fail to apply (e.g.\n * re-applied onto a diverged document during a rebase), so wrapping lets a\n * rebase skip the transaction instead of failing the store. Without\n * `preserveOperations`, errors are rethrown untouched.\n */\nexport function createMutationApplier(options: {\n documentId: string\n transactionId: string\n timestamp: string\n preserveOperations: boolean | undefined\n}): (\n documents: DocumentSet,\n mutations: Mutation[],\n documentSetName: 'base' | 'working',\n) => DocumentSet {\n const {documentId, transactionId, timestamp, preserveOperations} = options\n return (documents, mutations, documentSetName) => {\n try {\n return processMutations({documents, transactionId, mutations, timestamp})\n } catch (error) {\n if (!preserveOperations) throw error\n throw new ActionError({\n documentId,\n transactionId,\n message: `Failed to apply patches to the ${documentSetName} document: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n })\n }\n }\n}\n\n/**\n * Re-applies the operational intent of user-supplied `inc`/`dec` patches to a\n * set of snapshot-diffed patches.\n *\n * The outgoing patches sent to Content Lake are re-derived by diffing the\n * base document before and after the user's patches were applied. That diff\n * collapses an `inc` into a `set` of the resulting number, which turns\n * concurrent increments from different clients into last-write-wins. This\n * helper finds diffed `set` operations that are exactly explained by the\n * user's `inc`/`dec` operations and swaps them back, so the server applies\n * the increment against whatever value is current at commit time.\n *\n * A `set` is only swapped when its value equals the base value plus the\n * accumulated user deltas for that exact path; anything else (e.g. an `inc`\n * combined with a `set` of the same field) keeps the diffed `set`.\n *\n * Content Lake fails the whole transaction when `inc`/`dec` targets a missing\n * path (unlike `set`, which always succeeds). To avoid turning a concurrent\n * field removal into a transaction revert, the emitted patch seeds the target\n * with a `setIfMissing` of the base value; the server executes `setIfMissing`\n * before `inc`/`dec` within a single patch, so a concurrently removed field\n * degrades to the same result the diffed `set` would have produced. A path\n * into a concurrently removed keyed array item can still fail the\n * transaction (`setIfMissing` cannot create array items); the transaction is\n * then reverted and reported, which is preferable to silently resurrecting\n * the item.\n */\nexport function preserveNumericOperations(\n baseBefore: SanityDocument | null | undefined,\n userPatches: PatchOperations[] | undefined,\n diffedPatches: PatchOperations[],\n): PatchOperations[] {\n if (!baseBefore || !userPatches?.length) return diffedPatches\n\n // accumulate the user's inc/dec deltas per concrete (stringified) path,\n // tracking the expected final value by replaying the additions in order\n const targets = new Map<string, {baseValue: number; expectedValue: number; delta: number}>()\n for (const patch of userPatches) {\n for (const [op, sign] of [\n ['inc', 1],\n ['dec', -1],\n ] as const) {\n const record = patch[op]\n if (!record) continue\n for (const [pathExpression, amount] of Object.entries(record)) {\n if (typeof amount !== 'number') continue\n for (const match of jsonMatch(baseBefore, pathExpression)) {\n const path = stringifyPath(match.path)\n const existing = targets.get(path)\n if (existing) {\n existing.expectedValue += sign * amount\n existing.delta += sign * amount\n } else if (typeof match.value === 'number') {\n targets.set(path, {\n baseValue: match.value,\n expectedValue: match.value + sign * amount,\n delta: sign * amount,\n })\n }\n }\n }\n }\n }\n if (!targets.size) return diffedPatches\n\n const preserved = new Map<string, {delta: number; baseValue: number}>()\n const next = diffedPatches.flatMap((patch) => {\n if (!patch.set) return [patch]\n\n const keptSet: Record<string, unknown> = {}\n for (const [path, value] of Object.entries(patch.set)) {\n const target = targets.get(path)\n if (target && typeof value === 'number' && value === target.expectedValue) {\n preserved.set(path, {delta: target.delta, baseValue: target.baseValue})\n } else {\n keptSet[path] = value\n }\n }\n\n if (Object.keys(keptSet).length === Object.keys(patch.set).length) return [patch]\n const {set: _set, ...rest} = patch\n const withKept = Object.keys(keptSet).length ? {...rest, set: keptSet} : rest\n return Object.keys(withKept).length ? [withKept] : []\n })\n\n if (!preserved.size) return next\n\n const setIfMissing: Record<string, unknown> = {}\n const inc: Record<string, number> = {}\n const dec: Record<string, number> = {}\n for (const [path, {delta, baseValue}] of preserved) {\n setIfMissing[path] = baseValue\n if (delta >= 0) inc[path] = delta\n else dec[path] = -delta\n }\n return [\n ...next,\n {\n setIfMissing,\n ...(Object.keys(inc).length && {inc}),\n ...(Object.keys(dec).length && {dec}),\n },\n ]\n}\n\ninterface ApplySingleDocPatchOptions {\n base: DocumentSet\n working: DocumentSet\n documentId: string\n patches: PatchOperations[] | undefined\n transactionId: string\n timestamp: string\n grants: Record<Grant, ExprNode>\n identity: string | undefined\n /**\n * Error message thrown when the target document does not exist in either\n * the base or working set.\n */\n notFoundMessage?: string\n /**\n * Error message thrown when the working document fails the `update` grant.\n */\n permissionMessage?: string\n /**\n * When `true`, the given patches are used verbatim instead of being\n * re-derived by diffing the base document before and after application.\n * Patch application failures are surfaced as `ActionError`s so a rebase\n * can skip the transaction instead of failing the store.\n */\n preserveOperations?: boolean\n}\n\ninterface ApplySingleDocPatchResult {\n base: DocumentSet\n working: DocumentSet\n /**\n * Patch operations representing the minimal diff between base before and\n * after the user's patches were applied. These are the patches that should\n * be sent to the server (or applied to the working set as mutations).\n */\n diffedPatches: PatchOperations[]\n /**\n * Mutation envelopes for `diffedPatches` already keyed to `documentId`.\n * Useful for callers that want to push them to `outgoingMutations`.\n */\n workingMutations: Mutation[]\n}\n\n/**\n * Shared logic for applying user-provided patches to a single document that\n * is identified by an exact ID (no draft/published wrapping). Used by the\n * liveEdit branch of `document.edit` and by `release.edit`.\n *\n * Returns the updated base + working sets, plus the diffed patches in both\n * raw and mutation form so the caller can decide what to send to the server.\n */\nexport function applySingleDocPatch({\n base: initialBase,\n working: initialWorking,\n documentId,\n patches,\n transactionId,\n timestamp,\n grants,\n identity,\n notFoundMessage = 'Cannot edit document because it does not exist.',\n permissionMessage = `You do not have permission to edit document \"${documentId}\".`,\n preserveOperations,\n}: ApplySingleDocPatchOptions): ApplySingleDocPatchResult {\n let base = initialBase\n let working = initialWorking\n\n const userPatches = patches?.map((patch) => ({patch: {id: documentId, ...patch}}))\n\n if (!userPatches?.length) {\n return {base, working, diffedPatches: [], workingMutations: []}\n }\n\n if (!working[documentId] || !base[documentId]) {\n throw new ActionError({documentId, transactionId, message: notFoundMessage})\n }\n\n const applyMutations = createMutationApplier({\n documentId,\n transactionId,\n timestamp,\n preserveOperations,\n })\n\n const baseBefore = base[documentId]\n base = applyMutations(base, userPatches, 'base')\n const baseAfter = base[documentId]\n const diffedPatches = preserveOperations\n ? (patches as PatchOperations[])\n : preserveNumericOperations(\n baseBefore,\n patches,\n diffValue(baseBefore, baseAfter) as PatchOperations[],\n )\n\n const workingBefore = working[documentId] as SanityDocument\n if (!checkGrant(grants.update, workingBefore, identity)) {\n throw new PermissionActionError({documentId, transactionId, message: permissionMessage})\n }\n\n const workingMutations: Mutation[] = diffedPatches.map((patch) => ({\n patch: {id: documentId, ...patch},\n }))\n\n working = applyMutations(working, workingMutations, 'working')\n\n return {base, working, diffedPatches, workingMutations}\n}\n","import {DocumentId, getDraftId, getPublishedId, getVersionId} from '@sanity/id-utils'\nimport {type SanityDocument} from '@sanity/types'\nimport {type ExprNode, parse} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {isReleasePerspective} from '../releases/utils/isReleasePerspective'\nimport {type SelectorContext} from '../store/createStateSourceAction'\nimport {randomId} from '../utils/ids'\nimport {MultiKeyWeakMap} from '../utils/MultiKeyWeakMap'\nimport {type DocumentAction} from './actions'\nimport {ActionError, PermissionActionError, processActions} from './processActions/processActions'\nimport {checkGrant} from './processActions/shared'\nimport {type DocumentSet} from './processMutations'\nimport {type SyncTransactionState, throwDocumentError} from './reducers'\n\nexport type Grant = 'read' | 'update' | 'create' | 'history'\n\nexport type DatasetAcl = {\n filter: string\n permissions: Grant[]\n}[]\n\nexport function createGrantsLookup(datasetAcl: DatasetAcl): Record<Grant, ExprNode> {\n const filtersByGrant: Record<Grant, Set<string>> = {\n create: new Set(),\n history: new Set(),\n read: new Set(),\n update: new Set(),\n }\n\n for (const entry of datasetAcl) {\n for (const grant of entry.permissions) {\n const set = filtersByGrant[grant]\n // Ignore permissions we don't model (e.g. \"manage\")\n if (!set) continue\n set.add(entry.filter)\n filtersByGrant[grant] = set\n }\n }\n\n return Object.fromEntries(\n Object.entries(filtersByGrant).map(([grant, filters]) => {\n const combinedFilter = Array.from(filters)\n .map((i) => `(${i})`)\n .join('||')\n\n if (!combinedFilter) return [grant, parse('false')]\n return [grant, parse(`$document {\"_\": ${combinedFilter}}._`)]\n }),\n ) as Record<Grant, ExprNode>\n}\n\n// Cache for documents based on an array of document objects.\nconst documentsCache = new MultiKeyWeakMap<DocumentSet>()\n// Use a WeakMap so that when a computed DocumentSet is no longer in use,\n// its nested cache for actions can be garbage-collected.\nconst actionsCache = new WeakMap<DocumentSet, Map<string, DocumentAction[]>>()\n\nconst nullReplacer: object = {}\n\n// Compute documents from state and actions.\n// (If the same documents are computed, the MultiKeyWeakMap will return the same instance.)\nconst documentsSelector = createSelector(\n [\n ({state: {documentStates}}: SelectorContext<SyncTransactionState>) => documentStates,\n (_context: SelectorContext<SyncTransactionState>, {actions}: {actions: DocumentAction[]}) =>\n actions,\n ],\n (documentStates, actions) => {\n // Collect all document IDs needed for permission checks.\n // Important: liveEdit documents don't have drafts, so we only fetch the single document to avoid waiting for non-existent draft documents.\n const documentIds = new Set(\n actions\n .map((action) => {\n if (typeof action.documentId !== 'string') return []\n // For liveEdit documents, only fetch the single document\n if (action.liveEdit) return [action.documentId]\n // For standard documents, fetch both draft and published\n const ids: string[] = [\n getPublishedId(DocumentId(action.documentId)),\n getDraftId(DocumentId(action.documentId)),\n ]\n if (isReleasePerspective(action.perspective)) {\n ids.push(getVersionId(DocumentId(action.documentId), action.perspective.releaseName))\n }\n return ids\n })\n .flat(),\n )\n\n throwDocumentError(documentStates, documentIds)\n const documents: DocumentSet = {}\n\n for (const documentId of documentIds) {\n const local = documentStates[documentId]?.local\n\n // early exit if we don't have all the documents yet\n if (local === undefined) return undefined\n documents[documentId] = local\n }\n\n // Create a key from the documents values (using a nullReplacer when needed).\n const keys = Object.values(\n // value in this record will be `undefined` because\n // of the early return if undefined is found above\n documents as Record<string, SanityDocument | null>,\n ).map((doc) => (doc === null ? nullReplacer : doc))\n const cached = documentsCache.get(keys)\n if (cached) return cached\n\n documentsCache.set(keys, documents)\n return documents\n },\n)\n\n// Cache the actions array based on a serialized version, but “attach” the cache\n// to the computed documents. That way if the computed documents object is no longer in use,\n// the cache is eligible for GC.\nconst memoizedActionsSelector = createSelector(\n [\n documentsSelector,\n (_state: SelectorContext<SyncTransactionState>, {actions}: {actions: DocumentAction[]}) =>\n actions,\n ],\n (documents, actions) => {\n if (!documents) return undefined\n\n // Get (or create) the nested Map for this computed documents.\n let nestedCache = actionsCache.get(documents)\n if (!nestedCache) {\n nestedCache = new Map<string, DocumentAction[]>()\n actionsCache.set(documents, nestedCache)\n }\n\n const normalizedActions = Array.isArray(actions) ? actions : [actions]\n\n // Use JSON.stringify to get a serialized key for the actions.\n // TODO: considering swapping thisfor a more efficient or stable hash\n const actionsKey = JSON.stringify(normalizedActions)\n const cached = nestedCache.get(actionsKey)\n if (cached) return cached\n\n nestedCache.set(actionsKey, normalizedActions)\n return normalizedActions\n },\n)\n\n/** @beta */\nexport interface PermissionDeniedReason {\n type: 'precondition' | 'access'\n message: string\n documentId?: string\n}\n\n/** @beta */\nexport type DocumentPermissionsResult =\n | {\n allowed: false\n message: string\n reasons: PermissionDeniedReason[]\n }\n | {allowed: true; message?: undefined; reasons?: undefined}\n\nconst enNarrowConjunction = new Intl.ListFormat('en', {style: 'narrow', type: 'conjunction'})\n\nexport function calculatePermissions(\n ...args: Parameters<typeof _calculatePermissions>\n): ReturnType<typeof _calculatePermissions> {\n return _calculatePermissions(...args)\n}\n\nconst _calculatePermissions = createSelector(\n [\n ({state: {grants}}: SelectorContext<SyncTransactionState>) => grants,\n ({state: {identity}}: SelectorContext<SyncTransactionState>) => identity,\n documentsSelector,\n memoizedActionsSelector,\n ],\n (\n grants: Record<Grant, ExprNode> | undefined,\n identity: string | undefined,\n documents: DocumentSet | undefined,\n actions: DocumentAction[] | undefined,\n ): DocumentPermissionsResult | undefined => {\n if (!documents) return undefined\n if (!grants) return undefined\n if (!actions) return undefined\n\n const timestamp = new Date().toISOString()\n const reasons: PermissionDeniedReason[] = []\n\n try {\n processActions({\n actions,\n transactionId: randomId(16),\n working: documents,\n base: documents,\n timestamp,\n grants,\n identity,\n })\n } catch (error) {\n if (error instanceof PermissionActionError) {\n reasons.push({\n message: error.message,\n documentId: error.documentId,\n type: 'access',\n })\n } else if (error instanceof ActionError) {\n reasons.push({\n message: error.message,\n documentId: error.documentId,\n type: 'precondition',\n })\n } else {\n throw error\n }\n }\n\n for (const action of actions) {\n // Check edit actions with no patches\n if (action.type === 'document.edit' && !action.patches?.length) {\n const docId = action.documentId\n let doc: SanityDocument | null | undefined\n if (action.liveEdit) {\n doc = documents[docId]\n }\n // don't allow users to edit version documents that don't exist\n // they should be explicitly created first, as in studio\n else if (isReleasePerspective(action.perspective)) {\n doc = documents[getVersionId(DocumentId(docId), action.perspective.releaseName)]\n } else {\n doc =\n documents[getDraftId(DocumentId(docId))] ?? documents[getPublishedId(DocumentId(docId))]\n }\n if (!doc) {\n if (isReleasePerspective(action.perspective)) {\n reasons.push({\n type: 'precondition',\n message: `The version document with ID \"${docId}\" could not be found. Please create it or add it to the release first.`,\n documentId: docId,\n })\n } else {\n reasons.push({\n type: 'precondition',\n message: `The document with ID \"${docId}\" could not be found. Please check that it exists before editing.`,\n documentId: docId,\n })\n }\n } else if (!checkGrant(grants.update, doc, identity)) {\n reasons.push({\n type: 'access',\n message: `You are not allowed to edit the document with ID \"${docId}\".`,\n documentId: docId,\n })\n }\n }\n }\n\n const allowed = reasons.length === 0\n if (allowed) return {allowed}\n\n const sortedReasons = reasons\n .map((reason, index) => ({...reason, index}))\n .sort((a, b) => {\n if (a.type !== b.type) return a.type === 'access' ? -1 : 1\n return a.message.localeCompare(b.message, 'en-US')\n })\n .map(({index: _index, ...reason}) => reason)\n\n return {\n allowed,\n reasons: sortedReasons,\n message: enNarrowConjunction.format(sortedReasons.map((i) => i.message)),\n }\n },\n)\n","import {DocumentId, getDraftId, getPublishedId, getVersionId} from '@sanity/id-utils'\nimport {type Mutation, type SanityDocument} from '@sanity/types'\n\nimport {isReleasePerspective} from '../../releases/utils/isReleasePerspective'\nimport {type CreateDocumentAction} from '../actions'\nimport {getId, processMutations} from '../processMutations'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleCreate(\n action: CreateDocumentAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations} = ctx\n let {base, working} = ctx\n\n const documentId = getId(action.documentId)\n\n if (action.liveEdit) {\n if (working[documentId]) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `This document already exists.`,\n })\n }\n\n const newDocBase = {_type: action.documentType, _id: documentId, ...action.initialValue}\n const newDocWorking = {\n _type: action.documentType,\n _id: documentId,\n ...action.initialValue,\n }\n const mutations: Mutation[] = [{create: newDocWorking}]\n\n base = processMutations({\n documents: base,\n transactionId,\n mutations: [{create: newDocBase}],\n timestamp,\n })\n working = processMutations({\n documents: working,\n transactionId,\n mutations,\n timestamp,\n })\n\n if (!checkGrant(grants.create, working[documentId] as SanityDocument, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to create document \"${documentId}\".`,\n })\n }\n\n // liveEdit documents use the mutation endpoint directly -- we don't send actions\n outgoingMutations.push(...mutations)\n return {base, working}\n }\n\n // Standard draft/published/version logic\n const versionId = isReleasePerspective(action.perspective)\n ? getVersionId(DocumentId(documentId), action.perspective.releaseName)\n : undefined\n const draftId = getDraftId(DocumentId(documentId))\n const publishedId = getPublishedId(DocumentId(documentId))\n\n const alreadyHasVersion = versionId ? working[versionId] : working[draftId]\n\n if (alreadyHasVersion) {\n const errorDocType = versionId ? 'release version' : 'draft'\n throw new ActionError({\n documentId,\n transactionId,\n message: `A ${errorDocType} of this document already exists. Please use or discard the existing ${errorDocType} before creating a new one.`,\n })\n }\n\n // Spread the (possibly undefined) draft or published version directly.\n // (studio uses the draft version as a base if you are in a release perspective)\n const newDocBase = {\n ...(base[draftId] ?? base[publishedId]),\n _type: action.documentType,\n _id: versionId ?? draftId,\n ...action.initialValue,\n }\n const newDocWorking = {\n ...(working[draftId] ?? working[publishedId]),\n _type: action.documentType,\n _id: versionId ?? draftId,\n ...action.initialValue,\n }\n const mutations: Mutation[] = [{create: newDocWorking}]\n\n base = processMutations({\n documents: base,\n transactionId,\n mutations: [{create: newDocBase}],\n timestamp,\n })\n working = processMutations({\n documents: working,\n transactionId,\n mutations,\n timestamp,\n })\n\n if (versionId && !checkGrant(grants.create, working[versionId] as SanityDocument, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to create a release version for document \"${documentId}\".`,\n })\n } else if (\n !versionId &&\n !checkGrant(grants.create, working[draftId] as SanityDocument, identity)\n ) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to create a draft for document \"${documentId}\".`,\n })\n }\n\n outgoingMutations.push(...mutations)\n outgoingActions.push({\n actionType: 'sanity.action.document.version.create',\n publishedId,\n attributes: newDocWorking,\n })\n return {base, working}\n}\n","import {DocumentId, getDraftId, getPublishedId} from '@sanity/id-utils'\nimport {type Mutation} from '@sanity/types'\n\nimport {isReleasePerspective} from '../../releases/utils/isReleasePerspective'\nimport {type DeleteDocumentAction} from '../actions'\nimport {processMutations} from '../processMutations'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleDelete(\n action: DeleteDocumentAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations} = ctx\n let {base, working} = ctx\n\n const documentId = action.documentId\n\n if (isReleasePerspective(action.perspective)) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Cannot delete a version document. You may want to use the \"unpublish\" or \"discard\" actions instead.`,\n })\n }\n\n if (action.liveEdit) {\n if (!working[documentId]) {\n throw new ActionError({\n documentId,\n transactionId,\n message: 'The document you are trying to delete does not exist.',\n })\n }\n\n if (!checkGrant(grants.update, working[documentId], identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to delete this document.`,\n })\n }\n\n const mutations: Mutation[] = [{delete: {id: documentId}}]\n\n base = processMutations({documents: base, transactionId, mutations, timestamp})\n working = processMutations({documents: working, transactionId, mutations, timestamp})\n\n // although liveEdit documents can use the actions API for deletion,\n // having this be an action while other operations are mutations creates an inconsistency\n // (and a possible race condition in document store where mutations might get skipped)\n outgoingMutations.push(...mutations)\n return {base, working}\n }\n\n // Standard draft/published logic\n const draftId = getDraftId(DocumentId(documentId))\n const publishedId = getPublishedId(DocumentId(documentId))\n\n if (!working[publishedId]) {\n throw new ActionError({\n documentId,\n transactionId,\n message: working[draftId]\n ? 'Cannot delete a document without a published version.'\n : 'The document you are trying to delete does not exist.',\n })\n }\n\n const cantDeleteDraft = working[draftId] && !checkGrant(grants.update, working[draftId], identity)\n const cantDeletePublished =\n working[publishedId] && !checkGrant(grants.update, working[publishedId], identity)\n\n if (cantDeleteDraft || cantDeletePublished) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to delete this document.`,\n })\n }\n\n const mutations: Mutation[] = [{delete: {id: publishedId}}, {delete: {id: draftId}}]\n const includeDrafts = working[draftId] ? [draftId] : undefined\n\n base = processMutations({documents: base, transactionId, mutations, timestamp})\n working = processMutations({documents: working, transactionId, mutations, timestamp})\n\n outgoingMutations.push(...mutations)\n outgoingActions.push({\n actionType: 'sanity.action.document.delete',\n publishedId,\n ...(includeDrafts ? {includeDrafts} : {}),\n })\n return {base, working}\n}\n","import {DocumentId, getDraftId, getVersionId} from '@sanity/id-utils'\nimport {type Mutation} from '@sanity/types'\n\nimport {isReleasePerspective} from '../../releases/utils/isReleasePerspective'\nimport {type DiscardDocumentAction} from '../actions'\nimport {getId, processMutations} from '../processMutations'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleDiscard(\n action: DiscardDocumentAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations} = ctx\n let {base, working} = ctx\n\n const documentId = getId(action.documentId)\n\n if (action.liveEdit) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Cannot discard changes for liveEdit document \"${documentId}\". LiveEdit documents do not support drafts.`,\n })\n }\n\n // draft/published or version logic\n const versionId = isReleasePerspective(action.perspective)\n ? getVersionId(DocumentId(documentId), action.perspective.releaseName)\n : getDraftId(DocumentId(documentId))\n const mutations: Mutation[] = [{delete: {id: versionId}}]\n\n if (!working[versionId]) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `There is no draft or version available to discard for document \"${documentId}\".`,\n })\n }\n\n if (!checkGrant(grants.update, working[versionId], identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to discard changes for document \"${documentId}\".`,\n })\n }\n\n base = processMutations({documents: base, transactionId, mutations, timestamp})\n working = processMutations({documents: working, transactionId, mutations, timestamp})\n\n outgoingMutations.push(...mutations)\n outgoingActions.push({\n actionType: 'sanity.action.document.version.discard',\n versionId,\n })\n return {base, working}\n}\n","import {diffValue} from '@sanity/diff-patch'\nimport {DocumentId, getDraftId, getPublishedId, getVersionId} from '@sanity/id-utils'\nimport {type Mutation, type PatchOperations, type SanityDocument} from '@sanity/types'\n\nimport {isReleasePerspective} from '../../releases/utils/isReleasePerspective'\nimport {type EditDocumentAction} from '../actions'\nimport {getId} from '../processMutations'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n applySingleDocPatch,\n checkGrant,\n createMutationApplier,\n PermissionActionError,\n preserveNumericOperations,\n} from './shared'\n\nexport function handleEdit(\n action: EditDocumentAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations} = ctx\n let {base, working} = ctx\n\n const documentId = getId(action.documentId)\n\n if (action.liveEdit) {\n const result = applySingleDocPatch({\n base,\n working,\n documentId,\n patches: action.patches,\n transactionId,\n timestamp,\n grants,\n identity,\n preserveOperations: action.preserveOperations,\n })\n // liveEdit documents use the mutation endpoint directly -- we don't send actions\n outgoingMutations.push(...result.workingMutations)\n return {base: result.base, working: result.working}\n }\n\n const versionId = isReleasePerspective(action.perspective)\n ? getVersionId(DocumentId(documentId), action.perspective.releaseName)\n : undefined\n const draftId = getDraftId(DocumentId(documentId))\n const publishedId = getPublishedId(DocumentId(documentId))\n const patchDocumentId = isReleasePerspective(action.perspective) ? versionId! : draftId\n const userPatches = action.patches?.map((patch) => ({\n patch: {id: patchDocumentId, ...patch},\n }))\n\n // skip this action if there are no associated patches\n if (!userPatches?.length) return {base, working}\n\n if (isReleasePerspective(action.perspective)) {\n if (!working[versionId!] && !base[versionId!]) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `This document does not exist in the release. Please create it or add it to the release first.`,\n })\n }\n } else if (\n (!working[draftId] && !working[publishedId]) ||\n (!base[draftId] && !base[publishedId])\n ) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Cannot edit document because it does not exist in draft or published form.`,\n })\n }\n\n const applyMutations = createMutationApplier({\n documentId,\n transactionId,\n timestamp,\n preserveOperations: action.preserveOperations,\n })\n\n const baseMutations: Mutation[] = []\n // don't create a draft from the published version in a release perspective\n if (!isReleasePerspective(action.perspective) && !base[draftId] && base[publishedId]) {\n // otherwise make a draft from the published version\n baseMutations.push({create: {...base[publishedId], _id: draftId}})\n }\n\n // the above statement and guards should make this never be null or undefined\n const baseBefore = base[patchDocumentId] ?? base[publishedId]\n if (userPatches) {\n baseMutations.push(...userPatches)\n }\n\n base = applyMutations(base, baseMutations, 'base')\n // this one will always be defined because a patch mutation will never\n // delete an input document\n const baseAfter = base[patchDocumentId] as SanityDocument\n // when the caller asked us to preserve their operations, forward their\n // patches verbatim instead of re-deriving them from a snapshot diff. this\n // keeps keyed array operations addressable so concurrent edits from other\n // clients interleave instead of being overwritten. otherwise, diff the\n // snapshots but swap back any `inc`/`dec` the diff collapsed into a `set`,\n // so concurrent increments accumulate instead of last-write-winning\n const patches = action.preserveOperations\n ? (action.patches ?? [])\n : preserveNumericOperations(\n baseBefore,\n action.patches,\n diffValue(baseBefore, baseAfter) as PatchOperations[],\n )\n\n const workingMutations: Mutation[] = []\n if (!isReleasePerspective(action.perspective) && !working[draftId] && working[publishedId]) {\n const newDraftFromPublished = {...working[publishedId], _id: draftId}\n\n if (!checkGrant(grants.create, newDraftFromPublished, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to create a draft for editing this document.`,\n })\n }\n\n workingMutations.push({create: newDraftFromPublished})\n }\n\n // the first if statement should make this never be null or undefined\n const workingBefore = working[patchDocumentId] ?? working[publishedId]\n if (!checkGrant(grants.update, workingBefore!, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to edit document \"${documentId}\".`,\n })\n }\n workingMutations.push(...patches.map((patch) => ({patch: {id: patchDocumentId, ...patch}})))\n\n working = applyMutations(working, workingMutations, 'working')\n\n outgoingMutations.push(...workingMutations)\n outgoingActions.push(\n ...patches.map((patch) => ({\n actionType: 'sanity.action.document.edit' as const,\n draftId: patchDocumentId,\n publishedId,\n patch: patch as PatchOperations,\n })),\n )\n\n return {base, working}\n}\n","import {DocumentId, getDraftId, getPublishedId} from '@sanity/id-utils'\nimport {type Mutation, type Reference, type SanityDocument} from '@sanity/types'\n\nimport {isReleasePerspective} from '../../releases/utils/isReleasePerspective'\nimport {isDeepEqual} from '../../utils/object'\nimport {type PublishDocumentAction} from '../actions'\nimport {getId, processMutations} from '../processMutations'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handlePublish(\n action: PublishDocumentAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations} = ctx\n let {base, working} = ctx\n\n const documentId = getId(action.documentId)\n\n if (action.liveEdit || isReleasePerspective(action.perspective)) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Cannot publish this document. Publishing is not supported for liveEdit or version (release) documents.`,\n })\n }\n\n // Standard draft/published logic\n const draftId = getDraftId(DocumentId(documentId))\n const publishedId = getPublishedId(DocumentId(documentId))\n\n const workingDraft = working[draftId]\n const baseDraft = base[draftId]\n if (!workingDraft || !baseDraft) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Cannot publish because no draft version was found for document \"${documentId}\".`,\n })\n }\n\n // Before proceeding, verify that the working draft is identical to the base draft.\n // TODO: is it enough just to check for the _rev or nah?\n if (!isDeepEqual(workingDraft, baseDraft)) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Publish aborted: The document has changed elsewhere. Please try again.`,\n })\n }\n\n const newPublishedFromDraft = {...strengthenOnPublish(workingDraft), _id: publishedId}\n\n const mutations: Mutation[] = [{delete: {id: draftId}}, {createOrReplace: newPublishedFromDraft}]\n\n if (working[draftId] && !checkGrant(grants.update, working[draftId], identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `Publish failed: You do not have permission to update the draft for \"${documentId}\".`,\n })\n }\n\n if (working[publishedId] && !checkGrant(grants.update, newPublishedFromDraft, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `Publish failed: You do not have permission to update the published version of \"${documentId}\".`,\n })\n } else if (!working[publishedId] && !checkGrant(grants.create, newPublishedFromDraft, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `Publish failed: You do not have permission to publish a new version of \"${documentId}\".`,\n })\n }\n\n base = processMutations({documents: base, transactionId, mutations, timestamp})\n working = processMutations({documents: working, transactionId, mutations, timestamp})\n\n outgoingMutations.push(...mutations)\n outgoingActions.push({\n actionType: 'sanity.action.document.publish',\n draftId,\n publishedId,\n })\n return {base, working}\n}\n\nfunction strengthenOnPublish(draft: SanityDocument): SanityDocument {\n const isStrengthenReference = (\n value: object,\n ): value is Reference & Required<Pick<Reference, '_strengthenOnPublish'>> =>\n '_strengthenOnPublish' in value\n\n function strengthen(value: unknown): unknown {\n if (typeof value !== 'object' || !value) return value\n\n if (isStrengthenReference(value)) {\n const {_strengthenOnPublish, _weak, ...rest} = value\n return {\n ...rest,\n ...(_strengthenOnPublish.weak && {_weak: true}),\n }\n }\n\n if (Array.isArray(value)) {\n return value.map(strengthen)\n }\n\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, strengthen(v)]))\n }\n\n return strengthen(draft) as SanityDocument\n}\n","import {type ArchiveReleaseAction, type UnarchiveReleaseAction} from '../actions'\nimport {getReleaseDocumentId} from './releaseUtil'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleReleaseArchive(\n action: ArchiveReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {base, working, grants, outgoingActions, transactionId, identity} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n const existing = working[releaseDocumentId] ?? base[releaseDocumentId]\n if (!existing) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot archive release \"${action.releaseId}\" because it does not exist.`,\n })\n }\n\n if (!checkGrant(grants.update, existing, identity)) {\n throw new PermissionActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `You do not have permission to archive release \"${action.releaseId}\".`,\n })\n }\n\n // Archiving deletes every version document in the release server-side.\n // Although technically we could search through the document store for all related\n // version documents, for now it's simpler to just let the server handle it.\n // (Those local documents will be eventually updated by the listener.)\n outgoingActions.push({\n actionType: 'sanity.action.release.archive',\n releaseId: action.releaseId,\n })\n\n return {base, working}\n}\n\nexport function handleReleaseUnarchive(\n action: UnarchiveReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {base, working, grants, outgoingActions, transactionId, identity} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n const existing = working[releaseDocumentId] ?? base[releaseDocumentId]\n if (!existing) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot unarchive release \"${action.releaseId}\" because it does not exist.`,\n })\n }\n\n if (!checkGrant(grants.update, existing, identity)) {\n throw new PermissionActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `You do not have permission to unarchive release \"${action.releaseId}\".`,\n })\n }\n\n outgoingActions.push({\n actionType: 'sanity.action.release.unarchive',\n releaseId: action.releaseId,\n })\n\n return {base, working}\n}\n","import {type Mutation, type SanityDocument} from '@sanity/types'\n\nimport {type CreateReleaseAction} from '../actions'\nimport {processMutations} from '../processMutations'\nimport {getReleaseDocumentId} from './releaseUtil'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleReleaseCreate(\n action: CreateReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity} = ctx\n let {base, working} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n\n if (working[releaseDocumentId] || base[releaseDocumentId]) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `A release with id \"${action.releaseId}\" already exists.`,\n })\n }\n // Optimistic local release doc\n const releaseDoc = {\n _id: releaseDocumentId,\n _type: 'system.release',\n name: action.releaseId,\n state: 'active',\n metadata: action.metadata,\n }\n const mutations: Mutation[] = [{create: releaseDoc}]\n\n base = processMutations({documents: base, transactionId, mutations, timestamp})\n working = processMutations({documents: working, transactionId, mutations, timestamp})\n\n if (!checkGrant(grants.create, working[releaseDocumentId] as SanityDocument, identity)) {\n throw new PermissionActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `You do not have permission to create release \"${action.releaseId}\".`,\n })\n }\n\n outgoingMutations.push(...mutations)\n outgoingActions.push({\n actionType: 'sanity.action.release.create',\n releaseId: action.releaseId,\n metadata: action.metadata,\n })\n\n return {base, working}\n}\n","import {type Mutation} from '@sanity/types'\n\nimport {type DeleteReleaseAction} from '../actions'\nimport {processMutations} from '../processMutations'\nimport {getReleaseDocumentId} from './releaseUtil'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\n// you can only delete archived or published releases\n// https://www.sanity.io/docs/content-lake/dispatch-actions#k22ab37420f3c\nconst DELETABLE_STATES = new Set(['archived', 'published'])\n\nexport function handleReleaseDelete(\n action: DeleteReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity} = ctx\n let {base, working} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n const existing = working[releaseDocumentId] ?? base[releaseDocumentId]\n\n if (!existing) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot delete release \"${action.releaseId}\" because it does not exist.`,\n })\n }\n\n const state = existing['state']\n if (state && typeof state === 'string' && !DELETABLE_STATES.has(state)) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot delete release \"${action.releaseId}\" while it is \"${state}\". Archive it first.`,\n })\n }\n\n if (!checkGrant(grants.update, existing, identity)) {\n throw new PermissionActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `You do not have permission to delete release \"${action.releaseId}\".`,\n })\n }\n\n const mutations: Mutation[] = [{delete: {id: releaseDocumentId}}]\n\n base = processMutations({documents: base, transactionId, mutations, timestamp})\n working = processMutations({documents: working, transactionId, mutations, timestamp})\n\n outgoingMutations.push(...mutations)\n outgoingActions.push({\n actionType: 'sanity.action.release.delete',\n releaseId: action.releaseId,\n })\n\n return {base, working}\n}\n","import {type EditReleaseAction} from '../actions'\nimport {getReleaseDocumentId} from './releaseUtil'\nimport {type ActionHandlerContext, type ActionHandlerResult, applySingleDocPatch} from './shared'\n\nexport function handleReleaseEdit(\n action: EditReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity} = ctx\n const {base, working} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n\n const result = applySingleDocPatch({\n base,\n working,\n documentId: releaseDocumentId,\n patches: [action.patch],\n transactionId,\n timestamp,\n grants,\n identity,\n notFoundMessage: `Cannot edit release \"${action.releaseId}\" because it does not exist.`,\n permissionMessage: `You do not have permission to edit release \"${action.releaseId}\".`,\n })\n\n outgoingMutations.push(...result.workingMutations)\n outgoingActions.push(\n ...result.diffedPatches.map((patch) => ({\n actionType: 'sanity.action.release.edit' as const,\n releaseId: action.releaseId,\n patch,\n })),\n )\n\n return {base: result.base, working: result.working}\n}\n","import {type PublishReleaseAction} from '../actions'\nimport {getReleaseDocumentId} from './releaseUtil'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleReleasePublish(\n action: PublishReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {base, working, grants, outgoingActions, transactionId, identity} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n const existing = working[releaseDocumentId] ?? base[releaseDocumentId]\n if (!existing) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot publish release \"${action.releaseId}\" because it does not exist.`,\n })\n }\n\n if (!checkGrant(grants.update, existing, identity)) {\n throw new PermissionActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `You do not have permission to publish release \"${action.releaseId}\".`,\n })\n }\n\n // a release publish cascades to every version document in the release\n // although technically we could search through the document store for all related\n // version documents, for now it's simpler to just let the server handle it.\n // (Those local documents will be eventually updated by the listener.)\n outgoingActions.push({\n actionType: 'sanity.action.release.publish',\n releaseId: action.releaseId,\n })\n\n return {base, working}\n}\n","import {type ScheduleReleaseAction, type UnscheduleReleaseAction} from '../actions'\nimport {getReleaseDocumentId} from './releaseUtil'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleReleaseSchedule(\n action: ScheduleReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {base, working, grants, outgoingActions, transactionId, identity} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n\n if (Number.isNaN(Date.parse(action.publishAt))) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot schedule release \"${action.releaseId}\": \"publishAt\" must be a valid ISO 8601 timestamp (received \"${action.publishAt}\").`,\n })\n }\n\n const existing = working[releaseDocumentId] ?? base[releaseDocumentId]\n if (!existing) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot schedule release \"${action.releaseId}\" because it does not exist.`,\n })\n }\n\n if (!checkGrant(grants.update, existing, identity)) {\n throw new PermissionActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `You do not have permission to schedule release \"${action.releaseId}\".`,\n })\n }\n\n // Scheduling flips `state` to 'scheduled' and locks version documents\n // server-side. We don't model the lock locally yet — local edits to those\n // version docs will be rejected at submit time. The listener will sync the\n // updated release state.\n outgoingActions.push({\n actionType: 'sanity.action.release.schedule',\n releaseId: action.releaseId,\n publishAt: action.publishAt,\n })\n\n return {base, working}\n}\n\nexport function handleReleaseUnschedule(\n action: UnscheduleReleaseAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {base, working, grants, outgoingActions, transactionId, identity} = ctx\n\n const releaseDocumentId = getReleaseDocumentId(action.releaseId)\n const existing = working[releaseDocumentId] ?? base[releaseDocumentId]\n if (!existing) {\n throw new ActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `Cannot unschedule release \"${action.releaseId}\" because it does not exist.`,\n })\n }\n\n if (!checkGrant(grants.update, existing, identity)) {\n throw new PermissionActionError({\n documentId: releaseDocumentId,\n transactionId,\n message: `You do not have permission to unschedule release \"${action.releaseId}\".`,\n })\n }\n\n outgoingActions.push({\n actionType: 'sanity.action.release.unschedule',\n releaseId: action.releaseId,\n })\n\n return {base, working}\n}\n","import {DocumentId, getDraftId, getPublishedId} from '@sanity/id-utils'\nimport {type Mutation, type SanityDocument} from '@sanity/types'\n\nimport {isReleasePerspective} from '../../releases/utils/isReleasePerspective'\nimport {type UnpublishDocumentAction} from '../actions'\nimport {getId, processMutations} from '../processMutations'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n checkGrant,\n PermissionActionError,\n} from './shared'\n\nexport function handleUnpublish(\n action: UnpublishDocumentAction,\n ctx: ActionHandlerContext,\n): ActionHandlerResult {\n const {transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations} = ctx\n let {base, working} = ctx\n\n const documentId = getId(action.documentId)\n\n if (action.liveEdit || isReleasePerspective(action.perspective)) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Cannot unpublish this document. Unpublishing is not supported for liveEdit or version (release) documents.`,\n })\n }\n\n // Standard draft/published or version logic\n const draftId = getDraftId(DocumentId(documentId))\n const publishedId = getPublishedId(DocumentId(documentId))\n\n if (!working[publishedId] && !base[publishedId]) {\n throw new ActionError({\n documentId,\n transactionId,\n message: `Cannot unpublish because the document \"${documentId}\" is not currently published.`,\n })\n }\n\n const sourceDoc = working[publishedId] ?? (base[publishedId] as SanityDocument)\n const newDraftFromPublished = {...sourceDoc, _id: draftId}\n const mutations: Mutation[] = [\n {delete: {id: publishedId}},\n {createIfNotExists: newDraftFromPublished},\n ]\n\n if (!checkGrant(grants.update, sourceDoc, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to unpublish the document \"${documentId}\".`,\n })\n }\n\n if (!working[draftId] && !checkGrant(grants.create, newDraftFromPublished, identity)) {\n throw new PermissionActionError({\n documentId,\n transactionId,\n message: `You do not have permission to create a draft from the published version of \"${documentId}\".`,\n })\n }\n\n base = processMutations({\n documents: base,\n transactionId,\n mutations: [\n {delete: {id: publishedId}},\n {createIfNotExists: {...(base[publishedId] ?? sourceDoc), _id: draftId}},\n ],\n timestamp,\n })\n working = processMutations({documents: working, transactionId, mutations, timestamp})\n\n outgoingMutations.push(...mutations)\n outgoingActions.push({\n actionType: 'sanity.action.document.unpublish',\n draftId,\n publishedId,\n })\n return {base, working}\n}\n","import {type Mutation} from '@sanity/types'\nimport {type ExprNode} from 'groq-js'\n\nimport {type Action, type DocumentAction} from '../actions'\nimport {type Grant} from '../permissions'\nimport {type DocumentSet} from '../processMutations'\nimport {type HttpAction} from '../reducers'\nimport {handleCreate} from './create'\nimport {handleDelete} from './delete'\nimport {handleDiscard} from './discard'\nimport {handleEdit} from './edit'\nimport {handlePublish} from './publish'\nimport {handleReleaseArchive, handleReleaseUnarchive} from './releaseArchive'\nimport {handleReleaseCreate} from './releaseCreate'\nimport {handleReleaseDelete} from './releaseDelete'\nimport {handleReleaseEdit} from './releaseEdit'\nimport {handleReleasePublish} from './releasePublish'\nimport {handleReleaseSchedule, handleReleaseUnschedule} from './releaseSchedule'\nimport {isReleaseAction} from './releaseUtil'\nimport {\n ActionError,\n type ActionHandlerContext,\n type ActionHandlerResult,\n PermissionActionError,\n} from './shared'\nimport {handleUnpublish} from './unpublish'\n\nexport {ActionError, PermissionActionError}\n\ninterface ProcessActionsOptions {\n /**\n * The ID of this transaction. This will become the resulting `_rev` for all\n * documents affected by changes derived from the current set of actions.\n */\n transactionId: string\n\n /**\n * The actions to apply to the given documents\n */\n actions: Action[]\n\n /**\n * The set of documents these actions were intended to be applied to. These\n * set of documents should be captured right before a queued action is\n * applied.\n */\n base: DocumentSet\n\n /**\n * The current \"working\" set of documents. A patch will be created by applying\n * the actions to the base. This patch will then be applied to the working\n * set for conflict resolution. Initially, this value should match the base\n * set.\n */\n working: DocumentSet\n\n /**\n * The timestamp to use for `_updateAt` and other similar timestamps for this\n * transaction\n */\n timestamp: string\n\n /**\n * the lookup with pre-parsed GROQ expressions\n */\n grants: Record<Grant, ExprNode>\n\n /**\n * The current user's ID, passed to GROQ as the value of `identity()` when\n * evaluating ACL filters. Optional because the user may not have loaded yet;\n * filters that reference `identity()` will evaluate to null in that case.\n */\n identity?: string\n\n // // TODO: implement initial values from the schema?\n // initialValues?: {[TDocumentType in string]?: {_type: string}}\n}\n\ninterface ProcessActionsResult {\n /**\n * The resulting document set after the actions have been applied. This is\n * derived from the working documents.\n */\n working: DocumentSet\n /**\n * The document set before the actions have been applied. This is simply the\n * input of the `working` document set.\n */\n previous: DocumentSet\n /**\n * The outgoing action that were collected when applying the actions. These\n * are sent to the Actions HTTP API\n */\n outgoingActions: HttpAction[]\n /**\n * The outgoing mutations that were collected when applying the actions. These\n * are here for debugging purposes.\n */\n outgoingMutations: Mutation[]\n /**\n * The previous revisions of the given documents before the actions were applied.\n */\n previousRevs: {[TDocumentId in string]?: string}\n}\n\n/**\n * Applies the given set of actions to the working set of documents and converts\n * high-level actions into lower-level outgoing mutations/actions that respect\n * the current state of the working documents.\n *\n * Supports a \"base\" and \"working\" set of documents to allow actions to be\n * applied on top of a different working set of documents in a 3-way merge\n *\n * Actions are applied to the base set of documents first. The difference\n * between the base before and after is used to create a patch. This patch is\n * then applied to the working set of documents and is set as the outgoing patch\n * sent to the server.\n */\nexport function processActions({\n actions,\n transactionId,\n working: initialWorking,\n base: initialBase,\n timestamp,\n grants,\n identity,\n}: ProcessActionsOptions): ProcessActionsResult {\n let base: DocumentSet = {...initialBase}\n let working: DocumentSet = {...initialWorking}\n\n const outgoingActions: HttpAction[] = []\n const outgoingMutations: Mutation[] = []\n\n // liveEdit document actions go to the mutations API, since the actions API\n // requires a draft+published pair. Mixing them with anything else in the same\n // transaction would silently lose atomicity for the non-liveEdit operations,\n // so require users to split the transaction.\n // (Note that the reducers already does this for us -- you'd have to try hard to mix them.)\n const liveEditAction = actions.find((action) => !isReleaseAction(action) && action.liveEdit) as\n | DocumentAction\n | undefined\n const otherAction = actions.find((action) => isReleaseAction(action) || !action.liveEdit)\n if (liveEditAction && otherAction) {\n throw new ActionError({\n documentId: liveEditAction.documentId!,\n transactionId,\n message:\n 'Cannot combine liveEdit document actions with other actions in the same transaction. Submit them as separate transactions.',\n })\n }\n\n for (const action of actions) {\n const result = dispatch(action, {\n base,\n working,\n transactionId,\n timestamp,\n grants,\n identity,\n outgoingActions,\n outgoingMutations,\n })\n base = result.base\n working = result.working\n }\n\n const previousRevs = Object.fromEntries(\n Object.entries(initialWorking).map(([id, doc]) => [id, doc?._rev]),\n )\n\n return {\n working,\n outgoingActions,\n outgoingMutations,\n previous: initialWorking,\n previousRevs,\n }\n}\n\nfunction dispatch(action: Action, ctx: ActionHandlerContext): ActionHandlerResult {\n switch (action.type) {\n case 'document.create':\n return handleCreate(action, ctx)\n case 'document.delete':\n return handleDelete(action, ctx)\n case 'document.discard':\n return handleDiscard(action, ctx)\n case 'document.edit':\n return handleEdit(action, ctx)\n case 'document.publish':\n return handlePublish(action, ctx)\n case 'document.unpublish':\n return handleUnpublish(action, ctx)\n case 'release.create':\n return handleReleaseCreate(action, ctx)\n case 'release.edit':\n return handleReleaseEdit(action, ctx)\n case 'release.publish':\n return handleReleasePublish(action, ctx)\n case 'release.schedule':\n return handleReleaseSchedule(action, ctx)\n case 'release.unschedule':\n return handleReleaseUnschedule(action, ctx)\n case 'release.archive':\n return handleReleaseArchive(action, ctx)\n case 'release.unarchive':\n return handleReleaseUnarchive(action, ctx)\n case 'release.delete':\n return handleReleaseDelete(action, ctx)\n default:\n throw new Error(\n `Unknown action type: \"${\n // @ts-expect-error invalid input\n action.type\n }\". Please contact support if this issue persists.`,\n )\n }\n}\n","import {DocumentId, getDraftId, getPublishedId, getVersionId} from '@sanity/id-utils'\nimport {type Mutation, type PatchOperations, type SanityDocumentLike} from '@sanity/types'\n\nimport {type DocumentHandle} from '../config/sanityConfig'\nimport {isReleasePerspective} from '../releases/utils/isReleasePerspective'\nimport {type StoreContext} from '../store/defineStore'\nimport {randomId} from '../utils/ids'\nimport {isDeepEqual, omitProperty} from '../utils/object'\nimport {setCleanupTimeout} from '../utils/setCleanupTimeout'\nimport {type Action, type EditDocumentAction} from './actions'\nimport {DOCUMENT_STATE_CLEAR_DELAY, UNVERIFIED_REVISION_RETENTION_TIME} from './documentConstants'\nimport {type DocumentState, type DocumentStoreState} from './documentStore'\nimport {type RemoteDocument} from './listen'\nimport {ActionError, processActions} from './processActions/processActions'\nimport {getReleaseDocumentId, isReleaseAction} from './processActions/releaseUtil'\nimport {type DocumentSet} from './processMutations'\n\nconst EMPTY_REVISIONS: NonNullable<Required<DocumentState['unverifiedRevisions']>> = {}\n\n/**\n * How many of this client's own transaction IDs to remember per document for\n * `remote-patches` origin labeling. Sized to comfortably outlast the window\n * between submitting a transaction and observing its listener echo.\n */\nconst MAX_RECENT_OWN_TRANSACTION_IDS = 50\n\nexport type SyncTransactionState = Pick<\n DocumentStoreState,\n 'queued' | 'applied' | 'documentStates' | 'outgoing' | 'grants' | 'identity'\n>\n\ntype DocumentHandleLike = Pick<DocumentHandle, 'perspective'> & {\n documentId?: string\n liveEdit?: boolean\n}\n\ntype ActionMap = {\n create: 'sanity.action.document.version.create'\n discard: 'sanity.action.document.version.discard'\n unpublish: 'sanity.action.document.unpublish'\n delete: 'sanity.action.document.delete'\n edit: 'sanity.action.document.edit'\n publish: 'sanity.action.document.publish'\n releaseCreate: 'sanity.action.release.create'\n releaseEdit: 'sanity.action.release.edit'\n releasePublish: 'sanity.action.release.publish'\n releaseSchedule: 'sanity.action.release.schedule'\n releaseUnschedule: 'sanity.action.release.unschedule'\n releaseArchive: 'sanity.action.release.archive'\n releaseUnarchive: 'sanity.action.release.unarchive'\n releaseDelete: 'sanity.action.release.delete'\n}\n\ntype OptimisticLock = {\n ifDraftRevisionId?: string\n ifPublishedRevisionId?: string\n}\n\ninterface ReleaseMetadataPayload {\n title?: string\n description?: string\n intendedPublishAt?: string\n releaseType?: 'asap' | 'scheduled' | 'undecided'\n cardinality?: 'one' | 'many'\n}\n\nexport type HttpAction =\n | {actionType: ActionMap['create']; publishedId: string; attributes: SanityDocumentLike}\n | {actionType: ActionMap['discard']; versionId: string; purge?: boolean}\n | {actionType: ActionMap['unpublish']; draftId: string; publishedId: string}\n | {actionType: ActionMap['delete']; publishedId: string; includeDrafts?: string[]}\n | {actionType: ActionMap['edit']; draftId: string; publishedId: string; patch: PatchOperations}\n | ({actionType: ActionMap['publish']; draftId: string; publishedId: string} & OptimisticLock)\n | {\n actionType: ActionMap['releaseCreate']\n releaseId: string\n metadata?: ReleaseMetadataPayload\n }\n | {actionType: ActionMap['releaseEdit']; releaseId: string; patch: PatchOperations}\n | {actionType: ActionMap['releasePublish']; releaseId: string}\n | {actionType: ActionMap['releaseSchedule']; releaseId: string; publishAt: string}\n | {actionType: ActionMap['releaseUnschedule']; releaseId: string}\n | {actionType: ActionMap['releaseArchive']; releaseId: string}\n | {actionType: ActionMap['releaseUnarchive']; releaseId: string}\n | {actionType: ActionMap['releaseDelete']; releaseId: string}\n\n/**\n * Represents a transaction that is queued to be applied but has not yet been\n * applied. A transaction will remain in a queued state until all required\n * documents for the transactions are available locally.\n */\nexport interface QueuedTransaction {\n /**\n * the ID of this transaction. this is generated client-side.\n */\n transactionId: string\n /**\n * the high-level actions associated with this transaction. note that these\n * actions don't mention draft IDs and is meant to abstract away the draft\n * model from users.\n */\n actions: Action[]\n /**\n * An optional flag set to disable this transaction from being batched with\n * other transactions.\n */\n disableBatching?: boolean\n}\n\n/**\n * Represents a transaction that has been applied locally but has not been\n * committed/transitioned-to-outgoing. These transactions are visible to the\n * user but may be rebased upon a new working document set. Applied transactions\n * also contain the resulting `outgoingActions` that will be submitted to\n * Content Lake. These `outgoingActions` depend on the state of the working\n * documents so they are recomputed on rebase and are only relevant to applied\n * actions (we cannot compute `outgoingActions` for queued transactions because\n * we haven't resolved the set of documents the actions are dependent on yet).\n *\n * In order to support better conflict resolution, the original `previous` set\n * is saved as the `base` set.\n */\nexport interface AppliedTransaction extends QueuedTransaction {\n /**\n * the resulting set of documents after the actions have been applied\n */\n working: DocumentSet\n\n /**\n * the previous set of documents before the action was applied\n */\n previous: DocumentSet\n\n /**\n * the original `previous` document set captured when this action was\n * originally applied. this is used as a reference point to do a 3-way merge\n * if this applied transaction ever needs to be reapplied on a different\n * set of documents.\n */\n base: DocumentSet\n\n /**\n * the `_rev`s from `previous` document set\n */\n previousRevs: {[TDocumentId in string]?: string}\n\n /**\n * a timestamp for when this transaction was applied locally\n */\n timestamp: string\n\n /**\n * the resulting HTTP actions derived from the state of the `working` document\n * set. these are sent to Content Lake as-is when this transaction is batched\n * and transitioned into an outgoing transaction.\n */\n outgoingActions: HttpAction[]\n\n /**\n * similar to `outgoingActions` but comprised of mutations instead of actions.\n * Useful for debugging, and is also used by liveEdit documents to send mutations,\n * since they can't use the Actions API which is pretty dependent on the draft model.\n */\n outgoingMutations: Mutation[]\n}\n\n/**\n * Represents a set of applied transactions batched into a single outgoing\n * transaction. An outgoing transaction is the result of batching many applied\n * actions. An outgoing transaction may be reverted locally if the server\n * does not accept it.\n */\nexport interface OutgoingTransaction extends AppliedTransaction {\n disableBatching: boolean\n batchedTransactionIds: string[]\n}\n\nexport interface UnverifiedDocumentRevision {\n transactionId: string\n documentId: string\n previousRev: string | undefined\n timestamp: string\n}\n\nexport function queueTransaction(\n prev: SyncTransactionState,\n transaction: QueuedTransaction,\n): SyncTransactionState {\n const {transactionId, actions} = transaction\n const prevWithSubscriptionIds = getDocumentIdsFromHandleLikes(actions).reduce(\n (acc, id) => addSubscriptionIdToDocument(acc, id, transactionId),\n prev,\n )\n\n return {\n ...prevWithSubscriptionIds,\n queued: [...prev.queued, transaction],\n }\n}\n\nexport function removeQueuedTransaction(\n prev: SyncTransactionState,\n transactionId: string,\n): SyncTransactionState {\n const transaction = prev.queued.find((t) => t.transactionId === transactionId)\n if (!transaction) return prev\n\n const prevWithSubscriptionIds = getDocumentIdsFromHandleLikes(transaction.actions).reduce(\n (acc, id) => removeSubscriptionIdFromDocument(acc, id, transactionId),\n prev,\n )\n\n return {\n ...prevWithSubscriptionIds,\n queued: prev.queued.filter((t) => transactionId !== t.transactionId),\n }\n}\n\nexport function applyFirstQueuedTransaction(prev: SyncTransactionState): SyncTransactionState {\n const queued = prev.queued.at(0)\n if (!queued) return prev\n if (!prev.grants) return prev\n\n const ids = getDocumentIdsFromHandleLikes(queued.actions)\n // the local value is only ever `undefined` if it has not been loaded yet\n // we can't get the next applied state unless all relevant documents are ready\n if (ids.some((id) => prev.documentStates[id]?.local === undefined)) return prev\n\n const working = ids.reduce<DocumentSet>((acc, id) => {\n acc[id] = prev.documentStates[id]?.local\n return acc\n }, {})\n\n const timestamp = new Date().toISOString()\n\n const result = processActions({\n ...queued,\n working,\n base: working,\n timestamp,\n grants: prev.grants,\n identity: prev.identity,\n })\n const applied: AppliedTransaction = {\n ...queued,\n ...result,\n base: result.previous,\n timestamp,\n }\n\n return {\n ...prev,\n applied: [...prev.applied, applied],\n queued: prev.queued.filter((t) => t.transactionId !== queued.transactionId),\n documentStates: Object.entries(result.working).reduce(\n (acc, [id, next]) => {\n const prevDoc = acc[id]\n if (!prevDoc) return acc\n acc[id] = {...prevDoc, local: next}\n return acc\n },\n {...prev.documentStates},\n ),\n }\n}\n\n/** Whether a transaction can be combined with adjacent edits in the submission queue. */\nexport function isBatchableTransaction<TTransaction extends QueuedTransaction>(\n transaction: TTransaction,\n): transaction is TTransaction & {actions: [EditDocumentAction]} {\n return (\n !transaction.disableBatching &&\n transaction.actions.length === 1 &&\n transaction.actions[0].type === 'document.edit'\n )\n}\n\nexport function batchAppliedTransactions([curr, ...rest]: AppliedTransaction[]):\n | OutgoingTransaction\n | undefined {\n // No transactions? Nothing to batch.\n if (!curr) return undefined\n\n // Skip transactions with no actions.\n if (!curr.actions.length) return batchAppliedTransactions(rest)\n\n // Explicitly unbatched transactions, non-edit actions, and multi-action\n // transactions must retain their transaction boundary.\n if (!isBatchableTransaction(curr)) {\n return {\n ...curr,\n disableBatching: true,\n batchedTransactionIds: [curr.transactionId],\n }\n }\n\n const [action] = curr.actions\n\n // Create an outgoing transaction for the single edit action.\n // At this point, batching is allowed.\n const editAction: OutgoingTransaction = {\n ...curr,\n actions: [action],\n disableBatching: false,\n batchedTransactionIds: [curr.transactionId],\n }\n if (!rest.length) return editAction\n\n // The rest may hold only transactions without actions; submit this edit on its own.\n const next = batchAppliedTransactions(rest)\n if (!next) return editAction\n if (next.disableBatching) return editAction\n\n // Don't batch a liveEdit edit with a non-liveEdit edit — they route to different APIs\n const nextFirst = next.actions[0]\n const nextLiveEdit = nextFirst && 'liveEdit' in nextFirst ? nextFirst.liveEdit : false\n if (!!action.liveEdit !== !!nextLiveEdit) return editAction\n\n return {\n disableBatching: false,\n // Use the transactionId from the later (next) transaction.\n transactionId: next.transactionId,\n // Accumulate actions: current action first, then later ones.\n actions: [action, ...next.actions],\n // Merge outgoingActions in order.\n outgoingActions: [...curr.outgoingActions, ...next.outgoingActions],\n // Batched transaction IDs: preserve order by placing curr first.\n batchedTransactionIds: [curr.transactionId, ...next.batchedTransactionIds],\n // Merge outgoingMutations in order.\n outgoingMutations: [...curr.outgoingMutations, ...next.outgoingMutations],\n // Working state reflects the latest optimistic changes: later transactions override earlier.\n working: {...curr.working, ...next.working},\n // Base state (base, previous, previousRevs) must reflect the original state.\n // Use curr values (the earliest transaction) to override later ones.\n previousRevs: {...next.previousRevs, ...curr.previousRevs},\n previous: {...next.previous, ...curr.previous},\n base: {...next.base, ...curr.base},\n // Use the earliest timestamp from curr.\n timestamp: curr.timestamp ?? next.timestamp,\n }\n}\n\nexport function transitionAppliedTransactionsToOutgoing(\n prev: SyncTransactionState,\n): SyncTransactionState {\n if (prev.outgoing) return prev\n\n const transaction = batchAppliedTransactions(prev.applied)\n if (!transaction) return prev\n\n const {\n transactionId,\n previousRevs,\n working,\n batchedTransactionIds: consumedTransactions,\n } = transaction\n const timestamp = new Date().toISOString()\n\n return {\n ...prev,\n outgoing: transaction,\n applied: prev.applied.filter((i) => !consumedTransactions.includes(i.transactionId)),\n documentStates: Object.entries(previousRevs).reduce(\n (acc, [documentId, previousRev]) => {\n if (working[documentId]?._rev === previousRev) return acc\n\n const documentState = prev.documentStates[documentId]\n if (!documentState) return acc\n\n acc[documentId] = {\n ...documentState,\n unverifiedRevisions: {\n ...documentState.unverifiedRevisions,\n // add unverified revision\n [transactionId]: {documentId, previousRev, transactionId, timestamp},\n },\n // also track the transaction ID durably (unverified revisions can be\n // pruned by sync events before the listener echo arrives) so\n // `remote-patches` events label our own transactions correctly\n recentOwnTransactionIds: [\n ...(documentState.recentOwnTransactionIds ?? []).slice(\n -(MAX_RECENT_OWN_TRANSACTION_IDS - 1),\n ),\n transactionId,\n ],\n }\n\n return acc\n },\n {...prev.documentStates},\n ),\n }\n}\n\nexport function cleanupOutgoingTransaction(prev: SyncTransactionState): SyncTransactionState {\n const {outgoing} = prev\n if (!outgoing) return prev\n\n let next = prev\n const ids = getDocumentIdsFromHandleLikes(outgoing.actions)\n for (const transactionId of outgoing.batchedTransactionIds) {\n for (const documentId of ids) {\n next = removeSubscriptionIdFromDocument(next, documentId, transactionId)\n }\n }\n\n // every ack is also when a previously retained document's echo may have\n // stopped being expected, so re-make that eviction decision here\n return {\n ...next,\n outgoing: undefined,\n documentStates: evictOrphanedDocumentStates(next.documentStates),\n }\n}\n\nexport function revertOutgoingTransaction(prev: SyncTransactionState): SyncTransactionState {\n if (!prev.grants) return prev\n\n // unregister the reverted batch's transaction-held subscriptions, symmetric\n // with `cleanupOutgoingTransaction` on ack and `removeQueuedTransaction` on\n // apply failure. without this, a reverted document's subscription IDs are\n // never released and it can never be evicted\n let base = prev\n if (prev.outgoing) {\n const ids = getDocumentIdsFromHandleLikes(prev.outgoing.actions)\n for (const transactionId of prev.outgoing.batchedTransactionIds) {\n for (const documentId of ids) {\n base = removeSubscriptionIdFromDocument(base, documentId, transactionId)\n }\n }\n }\n\n let working = Object.fromEntries(\n Object.entries(base.documentStates).map(([documentId, documentState]) => [\n documentId,\n documentState?.remote,\n ]),\n )\n const nextApplied: AppliedTransaction[] = []\n\n for (const t of prev.applied) {\n try {\n const next = processActions({...t, working, grants: prev.grants, identity: prev.identity})\n working = next.working\n nextApplied.push({...t, ...next})\n } catch (error) {\n // if we're already reverting a transaction, skip any applied actions if\n // they throw while we rebuild the state\n if (error instanceof ActionError) continue\n throw error\n }\n }\n\n return {\n ...base,\n applied: nextApplied,\n outgoing: undefined,\n // discarding the outgoing transaction drops its echo-recognition memory,\n // which can leave a document that was only being kept alive for that echo\n // with nothing left to wait for, so sweep afterwards\n documentStates: evictOrphanedDocumentStates(\n Object.fromEntries(\n Object.entries(base.documentStates)\n .filter((e): e is [string, DocumentState] => !!e[1])\n .map(([documentId, documentState]) => {\n const {unverifiedRevisions = {}} = documentState\n const next: DocumentState = {\n ...documentState,\n unverifiedRevisions:\n prev.outgoing && prev.outgoing.transactionId in unverifiedRevisions\n ? omitProperty(unverifiedRevisions, prev.outgoing.transactionId)\n : unverifiedRevisions,\n }\n\n // a document with no subscribers that is still waiting on the echo\n // of a different, already acked transaction of its own is not\n // represented in `working` (only `applied` transactions are\n // re-applied above), so rebuilding its `local` from `remote` would\n // drop that transaction's effect. leave it for the echo to resolve\n if (!next.subscriptions.length && isAwaitingOwnEcho(next)) {\n return [documentId, next] as const\n }\n\n return [\n documentId,\n {...next, local: documentId in working ? working[documentId] : next.local},\n ] as const\n }),\n ),\n ),\n }\n}\n\n/**\n * Extracts the patch operations addressed to the given document from a set of\n * raw listener mutations, stripping the mutation-level `id` addressing so the\n * patches are rooted at the document. A transaction can carry mutations for\n * other documents, so anything not explicitly id-addressed to this document\n * (including query-addressed patches) is dropped.\n */\nfunction extractPatchOperations(\n mutations: Mutation[] | undefined,\n documentId: string,\n): PatchOperations[] {\n if (!mutations) return []\n return mutations.flatMap((mutation) => {\n if (!('patch' in mutation) || !mutation.patch) return []\n const {id, ...operations} = mutation.patch as PatchOperations & {id?: string}\n if (id !== documentId) return []\n return [operations]\n })\n}\n\nexport function applyRemoteDocument(\n prev: SyncTransactionState,\n {document, documentId, previousRev, revision, timestamp, type, mutations}: RemoteDocument,\n events: DocumentStoreState['events'],\n): SyncTransactionState {\n if (!prev.grants) return prev\n const prevDocState = prev.documentStates[documentId]\n\n // document state is deleted when there are no more subscribers so we can\n // simply skip if there is no state\n if (!prevDocState) return prev\n\n // we send out transactions with IDs generated client-side to identify them\n // when they are observed through the listener. here we can check if this\n // incoming remote document is the result of one of our transactions\n const prevUnverifiedRevisions = prevDocState.unverifiedRevisions\n const revisionToVerify = revision ? prevUnverifiedRevisions?.[revision] : undefined\n let unverifiedRevisions = prevUnverifiedRevisions ?? EMPTY_REVISIONS\n if (revision && revisionToVerify) {\n unverifiedRevisions = omitProperty(prevUnverifiedRevisions, revision)\n }\n\n // surface the operational patches from this transaction before they are\n // collapsed into the whole-document snapshot below. consumers that keep\n // their own state (e.g. collaborative text editors) rely on these to apply\n // remote changes without re-diffing document snapshots\n if (type === 'mutation' && revision) {\n const patches = extractPatchOperations(mutations, documentId)\n if (patches.length) {\n // `unverifiedRevisions` alone isn't a reliable origin marker: a sync\n // event can prune an in-flight transaction's entry before its listener\n // echo arrives. `recentOwnTransactionIds` survives that race\n const isOwnTransaction =\n Boolean(revisionToVerify) ||\n (prevDocState.recentOwnTransactionIds?.includes(revision) ?? false)\n events.next({\n type: 'remote-patches',\n documentId,\n transactionId: revision,\n previousRev,\n timestamp,\n patches,\n origin: isOwnTransaction ? 'local' : 'remote',\n })\n }\n }\n\n // if this remote document is from a `'sync'` event (meaning that the whole\n // thing was just fetched and not re-created from mutations)\n if (type === 'sync') {\n // then remove unverified revisions that are older than our sync time. we\n // don't need to verify them for a rebase any more because we synced and\n // grabbed the latest document\n unverifiedRevisions = Object.fromEntries(\n Object.entries(unverifiedRevisions).filter(([, unverifiedRevision]) => {\n if (!unverifiedRevision) return false\n return new Date(timestamp).getTime() <= new Date(unverifiedRevision.timestamp).getTime()\n }),\n )\n }\n\n // if there is a revision to verify and the previous revision from remote\n // matches the previous revision we expected, we can \"fast-forward\" and skip\n // rebasing local changes on top of this new base\n if (revisionToVerify && revisionToVerify.previousRev === previousRev) {\n // even on a clean fast-forward, the server's result can differ from our\n // optimistic prediction: a publish derives the published content from the\n // server's copy of the draft, which may carry concurrent edits our\n // prediction never saw. once nothing else is pending locally for this\n // document (no applied transaction and no in-flight transaction, other\n // than the one this event just confirmed, modifies it), converge `local`\n // to the server's document. while local work that modifies this document\n // is pending, keep the optimistic `local` so those changes stay visible;\n // that work's own echo (or rebase) recomputes `local` later.\n //\n // \"modifies\" matters: pending work on other documents must not block\n // convergence here (nothing would ever revisit this document's `local`),\n // and a pending draft edit carries the published document in its working\n // set without changing it, so a presence check would block published-doc\n // convergence whenever a draft edit is pending. this is the same\n // modified-test `transitionAppliedTransactionsToOutgoing` uses\n const modifiesDocument = (transaction: AppliedTransaction) =>\n transaction.working[documentId]?._rev !== transaction.previousRevs[documentId]\n const nothingElsePending =\n !prev.applied.some(modifiesDocument) &&\n (!prev.outgoing ||\n prev.outgoing.transactionId === revision ||\n !modifiesDocument(prev.outgoing))\n const local =\n nothingElsePending && !isDeepEqual(prevDocState.local, document)\n ? document\n : prevDocState.local\n\n return {\n ...prev,\n documentStates: evictOrphanedDocumentStates({\n ...prev.documentStates,\n [documentId]: {\n ...prevDocState,\n remote: document,\n remoteRev: revision,\n local,\n unverifiedRevisions,\n },\n }),\n }\n }\n\n // if we got this far, this means that we could not fast-forward this revision\n // for this document. now we can rebase our local changes (if any) on top of\n // this new base from remote. in order to do that we grab the set of documents\n // captured before the earliest local transaction\n const previous = prev.applied.at(0)?.previous\n // our initial working set now is the state of the documents before any of our\n // local transactions plus the newly updated document from remote\n let working = {...previous, [documentId]: document}\n const nextApplied: AppliedTransaction[] = []\n\n // now we can iterate through our applied (but not yet committed) transactions\n // starting with the updated working set and re-apply each transaction in\n // order creating a new set of applied transactions as we go.\n //\n // NOTE: we don't want to rebase over the outgoing transaction because that\n // transaction is already on its way to the server. if an outgoing transaction\n // needs to be rebased, then it eventually will be when we see that\n // transaction again through the listener and this same flow will run then\n for (const curr of prev.applied) {\n try {\n const next = processActions({...curr, working, grants: prev.grants, identity: prev.identity})\n working = next.working\n // next includes an updated `previous` set and `working` set and updates\n // the `outgoingAction` and `outgoingMutations`. the `base` set from the\n // original applied transaction gets put back into the updated transaction\n // as-is to preserve the intended base for a 3-way merge\n nextApplied.push({...curr, ...next})\n } catch (error) {\n // if processing the action ever throws a related error, we can skip this\n // local transaction and report the error to the user\n if (error instanceof ActionError) {\n events.next({\n type: 'rebase-error',\n transactionId: error.transactionId,\n documentId: error.documentId,\n message: error.message,\n error,\n })\n continue\n }\n throw error\n }\n }\n\n // when the recompute lands on a value deep-equal to the current local\n // (the common case for echoes of our own transactions), keep the previous\n // reference so subscribers don't re-render for an identical value\n const nextLocal = working[documentId]\n const local = isDeepEqual(prevDocState.local, nextLocal) ? prevDocState.local : nextLocal\n\n return {\n ...prev,\n applied: nextApplied,\n documentStates: evictOrphanedDocumentStates({\n ...prev.documentStates,\n [documentId]: {\n ...prevDocState,\n remote: document,\n remoteRev: revision,\n local,\n unverifiedRevisions,\n },\n }),\n }\n}\n\nexport function addSubscriptionIdToDocument(\n prev: SyncTransactionState,\n documentId: string,\n subscriptionId: string,\n): SyncTransactionState {\n const prevDocState = prev.documentStates?.[documentId]\n const prevSubscriptions = prevDocState?.subscriptions ?? []\n\n return {\n ...prev,\n documentStates: {\n ...prev.documentStates,\n [documentId]: {\n ...prevDocState,\n id: documentId,\n subscriptions: [...prevSubscriptions, subscriptionId],\n },\n },\n }\n}\n\nexport function removeSubscriptionIdFromDocument(\n prev: SyncTransactionState,\n documentId: string,\n subscriptionId: string,\n): SyncTransactionState {\n const prevDocState = prev.documentStates?.[documentId]\n if (!prevDocState) return prev\n\n const subscriptions = prevDocState.subscriptions.filter((id) => id !== subscriptionId)\n\n // a document with no subscribers left is normally evicted below, but if a\n // transaction was just submitted for it, its echo-recognition memory\n // (`unverifiedRevisions`) is still waiting on the listener echo.\n // `cleanupOutgoingTransaction` removes the outgoing transaction's own\n // subscription right at HTTP ack, before the echo arrives, so deleting the\n // state here would lose that memory and make the echo mislabel as\n // `origin: 'remote'` (or, worse, get skipped outright). keep the state\n // alive, unsubscribed, until the echo verifies or the wait expires\n if (!subscriptions.length && !isAwaitingOwnEcho(prevDocState)) {\n return {...prev, documentStates: omitProperty(prev.documentStates, documentId)}\n }\n\n return {\n ...prev,\n documentStates: {\n ...prev.documentStates,\n [documentId]: {...prevDocState, subscriptions},\n },\n }\n}\n\n/**\n * Whether this document still expects the listener echo of one of its own\n * submitted transactions. That expectation is the only reason a document state\n * with no subscribers is kept around.\n *\n * Revisions stop counting after `UNVERIFIED_REVISION_RETENTION_TIME` because an\n * echo is not guaranteed to arrive at all: Content Lake records no transaction\n * when every operation resolves to a no-op (e.g. a keyed path that no longer\n * exists), while the client bumps `_rev` regardless and so tracks a revision\n * for it. Without the expiry, such a document (and the listener keyed off its\n * state) would be pinned for the lifetime of the store.\n *\n * `recentOwnTransactionIds` deliberately does not extend the wait: it is capped\n * rather than drained, so honoring it would keep every edited document alive.\n */\nfunction isAwaitingOwnEcho(documentState: DocumentState): boolean {\n const expiresAfter = Date.now() - UNVERIFIED_REVISION_RETENTION_TIME\n return Object.values(documentState.unverifiedRevisions ?? {}).some(\n (revision) => !!revision && new Date(revision.timestamp).getTime() > expiresAfter,\n )\n}\n\n/**\n * Removes every document state that has no subscribers left and no own\n * transaction still awaiting its echo.\n *\n * This is a sweep rather than a decision made where the last subscriber leaves\n * because `removeSubscriptionIdFromDocument` defers that eviction while an echo\n * is in flight, and both halves of the condition can change without a\n * subscriber going anywhere: the echo can verify, be dropped by a sync, be\n * discarded by a revert, or simply never arrive. Every reducer that can settle\n * an in-flight transaction sweeps, so the deferred decision is always re-made.\n *\n * Note this can evict the very document whose remote event is being processed,\n * which synchronously unsubscribes that document's listener from inside its own\n * emission (see `subscribeToSubscriptionsAndListenToDocuments`).\n */\nfunction evictOrphanedDocumentStates(\n documentStates: SyncTransactionState['documentStates'],\n): SyncTransactionState['documentStates'] {\n let next = documentStates\n for (const [documentId, documentState] of Object.entries(documentStates)) {\n if (!documentState) continue\n if (documentState.subscriptions.length) continue\n if (isAwaitingOwnEcho(documentState)) continue\n next = omitProperty(next, documentId)\n }\n return next\n}\n\nexport function manageSubscriberIds(\n {state}: StoreContext<SyncTransactionState>,\n handles: DocumentHandleLike[],\n): () => void {\n const documentIds = getDocumentIdsFromHandleLikes(handles)\n\n const subscriptionId = randomId(16)\n state.set('addSubscribers', (prev) =>\n documentIds.reduce(\n (acc, id) => addSubscriptionIdToDocument(acc, id, subscriptionId),\n prev as SyncTransactionState,\n ),\n )\n\n return () => {\n setCleanupTimeout(() => {\n state.set('removeSubscribers', (prev) =>\n documentIds.reduce(\n (acc, id) => removeSubscriptionIdFromDocument(acc, id, subscriptionId),\n prev as SyncTransactionState,\n ),\n )\n }, DOCUMENT_STATE_CLEAR_DELAY)\n }\n}\n\nexport function throwDocumentError(\n documentStates: DocumentStoreState['documentStates'],\n documentIds: Iterable<string>,\n): void {\n for (const documentId of documentIds) {\n const documentError = documentStates[documentId]?.error\n if (documentError) throw documentError\n }\n}\n\n// document handles are passed in via the public facing API, but we also need to\n// pull the correct document ids from action bodies, which have similar but not\n// identical shapes to the document handles. release actions also flow through\n// here, and resolve to the underlying release document id.\nexport function getDocumentIdsFromHandleLikes(handles: (DocumentHandleLike | Action)[]): string[] {\n return handles.flatMap((handle) => {\n if ('type' in handle && isReleaseAction(handle)) {\n return [getReleaseDocumentId(handle.releaseId)]\n }\n const idsForDocument = []\n if (!handle.documentId) return []\n if (handle.liveEdit) {\n return [handle.documentId]\n }\n if (isReleasePerspective(handle.perspective)) {\n idsForDocument.push(\n getVersionId(DocumentId(handle.documentId), handle.perspective.releaseName),\n )\n }\n idsForDocument.push(getDraftId(DocumentId(handle.documentId)))\n idsForDocument.push(getPublishedId(DocumentId(handle.documentId)))\n return idsForDocument\n })\n}\n","import {\n type CanvasResource,\n type Events,\n type FrameMessages,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n type WindowMessages,\n} from '@sanity/message-protocol'\nimport {catchError, first, from, map, type Observable, of, switchMap} from 'rxjs'\n\nimport {getNodeState} from '../comlink/node/getNodeState'\nimport {type DocumentHandle} from '../config/sanityConfig'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {defineFetcher, defineMutation} from '../store/fetcherStore'\n\n/**\n * @public\n */\nexport interface FavoriteStatusResponse {\n isFavorited: boolean\n}\n\n/**\n * @public\n */\nexport interface FavoriteDocumentContext extends DocumentHandle {\n resourceId: string\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n schemaName?: string\n}\n\n/**\n * The `document` a favorite write addresses over Comlink.\n *\n * @internal\n */\nexport function toFavoriteDocument(context: FavoriteDocumentContext): {\n id: string\n type: string\n resource: {id: string; type: FavoriteDocumentContext['resourceType']; schemaName?: string}\n} {\n return {\n id: context.documentId,\n type: context.documentType,\n resource: {\n id: context.resourceId,\n type: context.resourceType,\n ...(context.schemaName ? {schemaName: context.schemaName} : {}),\n },\n }\n}\n\n// Helper to create a stable key for the store\nfunction createFavoriteKey(context: FavoriteDocumentContext): string {\n return `${context.documentId}:${context.documentType}:${context.resourceId}:${context.resourceType}${\n context.schemaName ? `:${context.schemaName}` : ''\n }`\n}\n\n/**\n * The mutation scope for a document's favorite state, so its changes are sent one at a time and the\n * server keeps the last one made.\n *\n * @internal\n */\nexport function favoriteScope(context: FavoriteDocumentContext): string {\n return `favorite:${createFavoriteKey(context)}`\n}\n\n/**\n * Fetcher for a document's favorite status, read from the dashboard over\n * comlink, on the shared fetcher cache.\n *\n * @internal\n */\nexport const favorites = defineFetcher<[context: FavoriteDocumentContext], FavoriteStatusResponse>({\n name: 'favorites',\n getKey: (_instance: SanityInstance, context: FavoriteDocumentContext) =>\n createFavoriteKey(context),\n // Tag each entry with its key so `setFavorite` can invalidate exactly it.\n tags: (_data, context) => [{type: 'favorite', id: createFavoriteKey(context)}],\n fetch: (instance) => {\n return (context: FavoriteDocumentContext): Observable<FavoriteStatusResponse> => {\n const nodeStateSource = getNodeState<FrameMessages, WindowMessages>(instance, {\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n const payload = {document: toFavoriteDocument(context)}\n\n return nodeStateSource.observable.pipe(\n // Wait until connected, then complete after the single fetch settles.\n first((nodeState) => !!nodeState),\n switchMap((nodeState) => {\n const node = nodeState!.node\n return from(node.fetch('dashboard/v1/events/favorite/query', payload)).pipe(\n map((response) => ({isFavorited: response.isFavorited})),\n catchError((err) => {\n // eslint-disable-next-line no-console\n console.error('Favorites service connection error', err)\n return of({isFavorited: false})\n }),\n )\n }),\n )\n }\n },\n})\n\n/**\n * Input for {@link setFavorite}: the document context plus the desired state.\n *\n * @public\n */\nexport type SetFavoriteInput = FavoriteDocumentContext & {\n /** The favorite state to move to: `true` to favorite, `false` to unfavorite. */\n isFavorited: boolean\n}\n\n/**\n * Sets a document's favorite state over comlink. Writes the new state into the\n * cached {@link favorites} status before the request (rolled back on failure),\n * then invalidates it so active readers reconverge on server truth. The\n * write-side counterpart to {@link favorites}.\n *\n * @internal\n */\nexport const setFavorite = defineMutation<SetFavoriteInput, FavoriteStatusResponse>({\n name: 'setFavorite',\n scope: favoriteScope,\n mutationFn: (instance) => {\n return ({isFavorited, ...context}: SetFavoriteInput): Observable<FavoriteStatusResponse> => {\n const nodeStateSource = getNodeState<FrameMessages, WindowMessages>(instance, {\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n const payload: Events.FavoriteMutateMessage['data'] = {\n eventType: isFavorited ? 'added' : 'removed',\n document: toFavoriteDocument(context),\n }\n\n return nodeStateSource.observable.pipe(\n // Wait until connected, then complete after the single mutation settles.\n first((nodeState) => !!nodeState),\n switchMap((nodeState) => {\n const node = nodeState!.node\n return from(node.fetch('dashboard/v1/events/favorite/mutate', payload)).pipe(\n map((response) => {\n if (!response.success) throw new Error('Failed to update favorite status')\n return {isFavorited}\n }),\n )\n }),\n )\n }\n },\n onMutate: (write, {isFavorited, ...context}) => write(favorites, [context], {isFavorited}),\n invalidates: (_result, input) => [{type: 'favorite', id: createFavoriteKey(input)}],\n})\n","import {ClientError, ConnectionFailedError, isTimeoutError, ServerError} from '@sanity/client'\n\nimport {getClientErrorApiBody} from '../auth/utils'\nimport {isNetworkFailure} from '../errorReporting/isNetworkFailure'\n\nconst API_ERROR_CODES = [\n 'requestInvalid',\n 'levelNotAllowed',\n 'valueInvalid',\n 'unauthorized',\n 'accessDenied',\n 'sessionScopeDenied',\n 'keyNotDeclared',\n 'versionNotDeclared',\n 'quotaExceeded',\n 'backwardsNotAllowed',\n 'preconditionFailed',\n 'valueTooLarge',\n 'accessCheckFailed',\n] as const\n\n/**\n * The preferences API's error codes, plus `networkError` when the API couldn't be reached and\n * `requestFailed` when it answered with an error but no code, like a gateway timeout.\n * @internal\n */\nexport type PreferenceErrorCode =\n | (typeof API_ERROR_CODES)[number]\n | 'networkError'\n | 'requestFailed'\n\n/**\n * Every failed preference read or write is one of these. Branch on `code`: `message` is for\n * people and can change.\n * @internal\n */\nexport class PreferenceError extends Error {\n /** What went wrong, for code to branch on. */\n readonly code: PreferenceErrorCode\n /** The API's HTTP status, when it answered. */\n readonly statusCode: number | undefined\n\n /** Creates an error with a code, a message for people, and optionally the API's status. */\n constructor(\n code: PreferenceErrorCode,\n message: string,\n details: {statusCode?: number; cause?: unknown} = {},\n ) {\n super(message, {cause: details.cause})\n this.name = 'PreferenceError'\n this.code = code\n this.statusCode = details.statusCode\n }\n}\n\nfunction isApiErrorCode(code: unknown): code is (typeof API_ERROR_CODES)[number] {\n return API_ERROR_CODES.some((known) => known === code)\n}\n\n/**\n * Turns a failed preferences request into a {@link PreferenceError}. Anything else, like a bug,\n * is returned as it is, so error reporting still sees it.\n * @internal\n */\nexport function toPreferenceError(error: unknown): unknown {\n if (isNetworkFailure(error) || isTimeoutError(error) || error instanceof ConnectionFailedError) {\n return new PreferenceError(\n 'networkError',\n \"Couldn't reach the preferences API. Check your connection and try again.\",\n {cause: error},\n )\n }\n if (!(error instanceof ClientError || error instanceof ServerError)) return error\n\n const {statusCode} = error\n // A `ServerError` carries its response the same way\n const {code, message} = getClientErrorApiBody(error as ClientError) ?? {}\n if (!isApiErrorCode(code)) {\n return new PreferenceError(\n 'requestFailed',\n `The preferences API answered with status ${statusCode}. Try again later.`,\n {statusCode, cause: error},\n )\n }\n return new PreferenceError(code, String(message), {statusCode, cause: error})\n}\n","// NOTE: currently this API is only available on vX\nexport const API_VERSION = 'vX'\nexport const PROJECT_API_VERSION = '2025-07-18'\nexport const USERS_STATE_CLEAR_DELAY = 5000\nexport const DEFAULT_USERS_BATCH_SIZE = 100\n","import {type SanityInstance} from '../store/createSanityInstance'\nimport {omitProperty} from '../utils/object'\nimport {type GetUsersOptions, type SanityUserResponse, type UsersStoreState} from './types'\nimport {DEFAULT_USERS_BATCH_SIZE} from './usersConstants'\n\n/** @internal */\nexport const getUsersKey = (\n instance: SanityInstance,\n {\n resourceType,\n organizationId,\n batchSize = DEFAULT_USERS_BATCH_SIZE,\n projectId = instance.config.projectId,\n userId,\n }: GetUsersOptions = {},\n): string =>\n JSON.stringify({\n resourceType,\n organizationId,\n batchSize,\n projectId,\n userId,\n } satisfies ReturnType<typeof parseUsersKey>)\n\n/** @internal */\nexport const parseUsersKey = (\n key: string,\n): {\n batchSize: number\n resourceType?: 'organization' | 'project'\n projectId?: string\n organizationId?: string\n userId?: string\n} => JSON.parse(key)\n\nexport const addSubscription =\n (subscriptionId: string, key: string) =>\n (prev: UsersStoreState): UsersStoreState => {\n const group = prev.users[key]\n const subscriptions = [...(group?.subscriptions ?? []), subscriptionId]\n return {...prev, users: {...prev.users, [key]: {...group, subscriptions}}}\n }\n\nexport const removeSubscription =\n (subscriptionId: string, key: string) =>\n (prev: UsersStoreState): UsersStoreState => {\n const group = prev.users[key]\n if (!group) return prev\n const subscriptions = group.subscriptions.filter((id) => id !== subscriptionId)\n if (!subscriptions.length) return {...prev, users: omitProperty(prev.users, key)}\n return {...prev, users: {...prev.users, [key]: {...group, subscriptions}}}\n }\n\nexport const setUsersData =\n (key: string, {data, nextCursor, totalCount}: SanityUserResponse) =>\n (prev: UsersStoreState): UsersStoreState => {\n const group = prev.users[key]\n if (!group) return prev\n const users = [...(group.users ?? []), ...data]\n return {...prev, users: {...prev.users, [key]: {...group, users, totalCount, nextCursor}}}\n }\n\nexport const updateLastLoadMoreRequest =\n (timestamp: string, key: string) =>\n (prev: UsersStoreState): UsersStoreState => {\n const group = prev.users[key]\n if (!group) return prev\n return {...prev, users: {...prev.users, [key]: {...group, lastLoadMoreRequest: timestamp}}}\n }\n\nexport const setUsersError =\n (key: string, error: unknown) =>\n (prev: UsersStoreState): UsersStoreState => {\n const group = prev.users[key]\n if (!group) return prev\n return {...prev, users: {...prev.users, [key]: {...group, error}}}\n }\n\nexport const cancelRequest =\n (key: string) =>\n (prev: UsersStoreState): UsersStoreState => {\n const group = prev.users[key]\n if (!group) return prev\n if (group.subscriptions.length) return prev\n return {...prev, users: omitProperty(prev.users, key)}\n }\n\nexport const initializeRequest =\n (key: string) =>\n (prev: UsersStoreState): UsersStoreState => {\n if (prev.users[key]) return prev\n return {...prev, users: {...prev.users, [key]: {subscriptions: []}}}\n }\n","import {\n ConnectionFailedError,\n CorsOriginError,\n DisconnectError,\n type LiveEventMessage,\n} from '@sanity/client'\nimport {\n defer,\n distinctUntilChanged,\n EMPTY,\n filter,\n map,\n type Observable,\n of,\n switchMap,\n timer,\n} from 'rxjs'\n\nimport {getClientAuthState, getTokenState} from '../auth/authStore'\nimport {type DocumentResource} from '../config/sanityConfig'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {getClientState} from './clientStore'\nimport {retryWithCredential} from './retry'\n\n/**\n * All live-events subscriptions must use identical connection options\n * (API version, request tag, `includeDrafts`): `@sanity/client` caches the\n * underlying EventSource per URL + options, so divergent options would\n * silently split what should be a single shared connection.\n */\nconst LIVE_EVENTS_API_VERSION = 'v2025-05-06'\n\n/**\n * Delay before re-establishing the live events connection after a\n * server-initiated error (e.g. ChannelError, MessageError). Live errors are\n * retried rather than surfaced because an errored live connection would\n * otherwise poison the consuming store. Plain connection drops never reach\n * this — they are reconnected inside `@sanity/client`.\n *\n * @internal\n */\nexport const LIVE_EVENTS_RETRY_DELAY = 1000\n\n/**\n * Options for {@link observeLiveEvents}.\n * @internal\n */\nexport interface ObserveLiveEventsOptions {\n /** Resource to scope the underlying client and live connection to. */\n resource?: DocumentResource\n /**\n * Called when the connection fails due to a CORS misconfiguration. The\n * error is swallowed (the stream never errors; it idles) so consumers can\n * surface it as store state instead of a stream error.\n */\n onCorsError: (error: unknown) => void\n}\n\n/**\n * Emits Live Content API messages for a dataset so consumers can invalidate\n * fetched data via sync tags.\n *\n * All consumers observe the same underlying EventSource connection:\n * `@sanity/client` caches the live-events stream per URL and connection\n * options, and every subscription made through this function uses the same\n * API version and request tag.\n *\n * @internal\n */\nexport function observeLiveEvents(\n instance: SanityInstance,\n {resource, onCorsError}: ObserveLiveEventsOptions,\n): Observable<LiveEventMessage> {\n // Drafts need a token. Other clients are rebuilt when their token changes,\n // but an OAuth app's client follows its token through `auth`, so reconnect it\n // only when a token appears or disappears, not on every refresh.\n const hasToken$ = getTokenState(instance).observable.pipe(map(Boolean), distinctUntilChanged())\n const connection$ = getClientState(instance, {\n apiVersion: LIVE_EVENTS_API_VERSION,\n resource,\n }).observable.pipe(\n switchMap((client) =>\n (client.config().auth ? hasToken$ : of(Boolean(client.config().token))).pipe(\n map((includeDrafts) => [client, includeDrafts] as const),\n ),\n ),\n )\n\n return connection$.pipe(\n switchMap(([client, includeDrafts]) =>\n retryWithCredential(\n defer(() => client.live.events({includeDrafts, tag: 'live-events'})),\n getClientAuthState(instance),\n (error, _, credentialChanged) => {\n if (error instanceof CorsOriginError) {\n // Swallow CORS errors without bubbling up so that they can be\n // handled by the consumer (e.g. shown via the Cors Error component)\n onCorsError(error)\n return EMPTY\n }\n if (error instanceof DisconnectError) {\n // The server explicitly told this client to stop reconnecting —\n // end live updates without erroring (consumers keep serving data,\n // they just stop receiving live invalidation)\n return EMPTY\n }\n if (\n error instanceof ConnectionFailedError &&\n typeof error.status === 'number' &&\n error.status >= 400 &&\n error.status < 500\n ) {\n // The server rejected the connection with a 4xx (e.g. a 401 from\n // an expired token) — it will keep rejecting the same credential,\n // so retrying on a timer would reconnect once per second forever.\n // Reconnect once the credential changes instead. A\n // ConnectionFailedError without a status stays retryable: it may\n // be a transient network failure.\n return credentialChanged\n }\n // Server-initiated live errors (e.g. ChannelError, MessageError) are\n // retried, not surfaced. Dropped connections are already reconnected\n // inside @sanity/client.\n return timer(LIVE_EVENTS_RETRY_DELAY)\n },\n ),\n ),\n filter((e): e is LiveEventMessage => e.type === 'message'),\n )\n}\n","import {type ReleaseDocument, type SyncTag} from '@sanity/client'\nimport {\n BehaviorSubject,\n combineLatest,\n distinctUntilChanged,\n filter,\n map,\n type Observable,\n startWith,\n switchMap,\n tap,\n} from 'rxjs'\n\nimport {getClientAuthState} from '../auth/authStore'\nimport {getClientState} from '../client/clientStore'\nimport {observeLiveEvents} from '../client/liveEvents'\nimport {retryRead} from '../client/retry'\nimport {type DocumentResource} from '../config/sanityConfig'\nimport {type SanityInstance} from '../store/createSanityInstance'\n\nconst RELEASES_QUERY = 'releases::all()'\nconst RELEASES_API_VERSION = 'v2025-05-06'\n\n/**\n * Options for {@link observeReleases}.\n * @internal\n */\nexport interface ObserveReleasesOptions {\n /** Resource to scope the underlying client and live connection to. */\n resource?: DocumentResource\n /**\n * Called when the live events connection fails due to a CORS\n * misconfiguration. See `observeLiveEvents`.\n */\n onCorsError: (error: unknown) => void\n /** Receives a failed fetch, and `undefined` once fetching recovers. */\n onError: (error: unknown) => void\n}\n\n/**\n * Emits every release document (including archived and published), refetching\n * whenever a Live Content API event matches the query's sync tags.\n *\n * This fetches directly through the client store — deliberately not via the\n * query store — because release data is itself an input to query perspective\n * resolution (`getPerspectiveState`); fetching through the query store would\n * make the two stores mutually dependent.\n *\n * @internal\n */\nexport function observeReleases(\n instance: SanityInstance,\n {resource, onCorsError, onError}: ObserveReleasesOptions,\n): Observable<ReleaseDocument[] | undefined> {\n const client$ = getClientState(instance, {\n apiVersion: RELEASES_API_VERSION,\n resource,\n }).observable\n\n return client$.pipe(\n switchMap((client) => {\n const syncTags$ = new BehaviorSubject<SyncTag[] | undefined>(undefined)\n\n // Pair the latest live message with the latest known sync tags so that\n // a message arriving while a fetch is still in flight is re-evaluated\n // (and refetched if it matches) once that fetch's tags land — instead\n // of being dropped and leaving the store stale until the next event.\n const refetchEventId$ = combineLatest([\n observeLiveEvents(instance, {resource, onCorsError}).pipe(startWith(undefined)),\n syncTags$,\n ]).pipe(\n filter(\n ([message, syncTags]) =>\n message === undefined || message.tags.some((tag) => syncTags?.includes(tag)),\n ),\n map(([message]) => message?.id),\n distinctUntilChanged(),\n )\n\n return refetchEventId$.pipe(\n switchMap((lastLiveEventId) =>\n client.observable.fetch<ReleaseDocument[]>(\n RELEASES_QUERY,\n {},\n {\n perspective: 'raw',\n filterResponse: false,\n returnQuery: false,\n lastLiveEventId,\n tag: 'releases',\n },\n ),\n ),\n tap((response) => {\n syncTags$.next(response.syncTags)\n }),\n map((response) => response.result),\n )\n }),\n retryRead(getClientAuthState(instance), onError),\n )\n}\n","import {type ReleaseDocument} from '@sanity/client'\n\n// mirrors the order of the releases in the releases list in Studio\n// https://github.com/sanity-io/sanity/blob/main/packages/sanity/src/core/releases/hooks/utils.ts\nexport function sortReleases(releases: ReleaseDocument[] = []): ReleaseDocument[] {\n // The order should always be:\n // [undecided (sortByCreatedAt), scheduled(sortBy publishAt || metadata.intendedPublishAt), asap(sortByCreatedAt)]\n return [...releases].sort((a, b) => {\n // metadata is optional on a release document; guard against releases that\n // have no metadata at all so sorting can't throw and wipe out the list.\n const aType = a.metadata?.releaseType\n const bType = b.metadata?.releaseType\n\n // undecided are always first, then by createdAt descending\n if (aType === 'undecided' && bType !== 'undecided') {\n return -1\n }\n if (aType !== 'undecided' && bType === 'undecided') {\n return 1\n }\n if (aType === 'undecided' && bType === 'undecided') {\n // Sort by createdAt\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n\n // Scheduled are always at the middle, then by publishAt descending\n if (aType === 'scheduled' && bType === 'scheduled') {\n const aPublishAt = a['publishAt'] || a.metadata?.['intendedPublishAt']\n if (!aPublishAt) {\n return 1\n }\n const bPublishAt = b['publishAt'] || b.metadata?.['intendedPublishAt']\n if (!bPublishAt) {\n return -1\n }\n return new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime()\n }\n\n // ASAP are always last, then by createdAt descending\n if (aType === 'asap' && bType !== 'asap') {\n return 1\n }\n if (aType !== 'asap' && bType === 'asap') {\n return -1\n }\n if (aType === 'asap' && bType === 'asap') {\n // Sort by createdAt\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n\n return 0\n })\n}\n","import {type ReleaseDocument} from '@sanity/client'\nimport {map} from 'rxjs'\n\nimport {type DocumentResource} from '../config/sanityConfig'\nimport {bindActionByResource, type BoundResourceKey} from '../store/createActionBinder'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {createStateSourceAction, type StateSource} from '../store/createStateSourceAction'\nimport {defineStore, type StoreContext} from '../store/defineStore'\nimport {observeReleases} from './observeReleases'\nimport {sortReleases} from './utils/sortReleases'\n\nconst ARCHIVED_RELEASE_STATES = ['archived', 'published']\nconst STABLE_EMPTY_RELEASES: ReleaseDocument[] = []\n\n/**\n * Lifecycle states a release document can be in. Mirrors the server's\n * `ReleaseState`.\n * @beta\n */\nexport type ReleaseState =\n | 'active'\n | 'archiving'\n | 'unarchiving'\n | 'archived'\n | 'published'\n | 'publishing'\n | 'scheduled'\n | 'scheduling'\n\nexport interface ReleasesStoreState {\n activeReleases?: ReleaseDocument[]\n allReleases?: ReleaseDocument[]\n error?: unknown\n fetchError?: unknown\n}\n\nexport const releasesStore = defineStore<ReleasesStoreState, BoundResourceKey>({\n name: 'Releases',\n // Empty rather than undefined, so the React hooks do not suspend on first load. A\n // reconnect keeps whatever was last known until the fetch returns.\n getInitialState: (): ReleasesStoreState => ({\n activeReleases: STABLE_EMPTY_RELEASES,\n allReleases: STABLE_EMPTY_RELEASES,\n }),\n upstream: (context) => subscribeToReleases(context),\n})\n\n/**\n * Get the active releases from the store.\n * @internal\n */\nconst _getActiveReleasesState = bindActionByResource(\n releasesStore,\n createStateSourceAction({\n selector: ({state}) => {\n if (state.error ?? state.fetchError) throw state.error ?? state.fetchError\n return state.activeReleases\n },\n }),\n)\n\n/**\n * Get the active releases from the store.\n * @internal\n */\nexport const getActiveReleasesState = (\n instance: SanityInstance,\n options?: {resource?: DocumentResource},\n): StateSource<ReleaseDocument[] | undefined> =>\n // bindActionByResource keyFn destructures { resource } from the first param, so pass {} when no options\n _getActiveReleasesState(instance, options ?? {})\n\n/**\n * Get every release in the store, including archived and published.\n * @internal\n */\nconst _getAllReleasesState = bindActionByResource(\n releasesStore,\n createStateSourceAction({\n selector: ({state}) => {\n if (state.error ?? state.fetchError) throw state.error ?? state.fetchError\n return state.allReleases\n },\n }),\n)\n\n/**\n * Get every release in the store, including archived and published.\n * @internal\n */\nexport const getAllReleasesState = (\n instance: SanityInstance,\n options?: {resource?: DocumentResource},\n): StateSource<ReleaseDocument[] | undefined> => _getAllReleasesState(instance, options ?? {})\n\nconst subscribeToReleases = ({\n instance,\n state,\n key: {resource},\n}: StoreContext<ReleasesStoreState, BoundResourceKey>) => {\n const releases$ = observeReleases(instance, {\n resource,\n // Surface CORS errors as store state instead of erroring the stream so\n // they can be handled by the Cors Error component\n onCorsError: (error) => state.set('setError', {error}),\n onError: (fetchError) => state.set('setFetchError', {fetchError}),\n })\n return releases$\n .pipe(\n map((releases) => {\n // logic here mirrors that of studio:\n // https://github.com/sanity-io/sanity/blob/156e8fa482703d99219f08da7bacb384517f1513/packages/sanity/src/core/releases/store/useActiveReleases.ts#L29\n const sorted = sortReleases(releases ?? STABLE_EMPTY_RELEASES).reverse()\n state.set('setReleases', {\n allReleases: sorted,\n activeReleases: sorted.filter(\n (release) => !ARCHIVED_RELEASE_STATES.includes(release.state),\n ),\n fetchError: undefined,\n })\n }),\n )\n .subscribe({error: (error) => state.set('setError', {error})})\n}\n","import {createSelector} from 'reselect'\n\nimport {type DocumentResource, type PerspectiveHandle} from '../config/sanityConfig'\nimport {bindActionByResource, type BoundStoreAction} from '../store/createActionBinder'\nimport {createStateSourceAction, type SelectorContext} from '../store/createStateSourceAction'\nimport {releasesStore, type ReleasesStoreState} from './releasesStore'\nimport {isReleasePerspective} from './utils/isReleasePerspective'\nimport {sortReleases} from './utils/sortReleases'\n\nconst DEFAULT_PERSPECTIVE = 'drafts'\n\n// Cache for options\nconst optionsCache = new Map<string, Map<string, PerspectiveHandle>>()\n\nconst selectInstancePerspective = (context: SelectorContext<ReleasesStoreState>, _?: unknown) =>\n context.instance.config.perspective\nconst selectActiveReleases = (context: SelectorContext<ReleasesStoreState>) =>\n context.state.activeReleases\nconst selectOptions = (\n _context: SelectorContext<ReleasesStoreState>,\n options: PerspectiveHandle & {projectId?: string; dataset?: string; resource?: DocumentResource},\n) => options\n\nconst memoizedOptionsSelector = createSelector(\n [selectActiveReleases, selectOptions],\n (activeReleases, options) => {\n if (!options || !activeReleases) return options\n\n // Use release document IDs as the cache key\n const releaseIds = activeReleases.map((release) => release._id).join(',')\n let nestedCache = optionsCache.get(releaseIds)\n if (!nestedCache) {\n nestedCache = new Map<string, PerspectiveHandle>()\n optionsCache.set(releaseIds, nestedCache)\n }\n\n const optionsKey = JSON.stringify(options)\n let cachedOptions = nestedCache.get(optionsKey)\n\n if (!cachedOptions) {\n cachedOptions = options\n nestedCache.set(optionsKey, cachedOptions)\n }\n return cachedOptions\n },\n)\n\nconst _getPerspectiveStateSelector = createStateSourceAction({\n selector: createSelector(\n [selectInstancePerspective, selectActiveReleases, memoizedOptionsSelector],\n (instancePerspective, activeReleases, memoizedOptions) => {\n const perspective = memoizedOptions?.perspective ?? instancePerspective ?? DEFAULT_PERSPECTIVE\n\n if (!isReleasePerspective(perspective)) return perspective\n\n // if there are no active releases we can't compute the release perspective\n if (!activeReleases || activeReleases.length === 0) return undefined\n\n const releaseNames = sortReleases(activeReleases).map((release) => release.name)\n const index = releaseNames.findIndex((name) => name === perspective.releaseName)\n\n if (index < 0) {\n throw new Error(`Release \"${perspective.releaseName}\" not found in active releases`)\n }\n\n const filteredReleases = releaseNames.slice(0, index + 1) // Include the release itself\n\n return ['drafts', ...filteredReleases]\n .filter((name) => !perspective.excludedPerspectives?.includes(name))\n .reverse()\n },\n ),\n})\n\ntype OmitFirst<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never\ntype SelectorParams = OmitFirst<Parameters<typeof _getPerspectiveStateSelector>>\ntype BoundGetPerspectiveState = BoundStoreAction<\n ReleasesStoreState,\n SelectorParams,\n ReturnType<typeof _getPerspectiveStateSelector>\n>\n\nconst _boundGetPerspectiveState = bindActionByResource(\n releasesStore,\n _getPerspectiveStateSelector,\n) as BoundGetPerspectiveState\n\n/**\n * Provides a subscribable state source for a \"perspective\" for the Sanity client,\n * which is used to fetch documents as though certain Content Releases are active.\n *\n * @param instance - The Sanity instance to get the perspective for\n * @param options - The options for the perspective -- usually a release name\n *\n * @returns A subscribable perspective value, usually a list of applicable release names,\n * or a single release name / default perspective (such as 'drafts').\n *\n * @public\n */\nexport const getPerspectiveState: BoundGetPerspectiveState = (instance, ...rest) =>\n // bindActionByResource keyFn destructures { resource } from the first param, so pass {} when no options\n _boundGetPerspectiveState(instance, ...(rest.length ? rest : [{}]))\n","import {UPSTREAM_CLOSE_DELAY_MS} from '../store/createStoreInstance'\n\n/**\n * When a query has no more subscribers, its state is cleaned up and removed\n * from the store. A delay used to prevent re-creating resources when the last\n * subscriber is removed quickly before another one is added. This is helpful\n * when used in a frontend where components may suspend or transition to\n * different views quickly.\n *\n * Must not exceed the live connection's close delay: nothing refetches when the\n * connection reopens, so a result kept past the close would miss live events.\n */\nexport const QUERY_STATE_CLEAR_DELAY = UPSTREAM_CLOSE_DELAY_MS\nexport const QUERY_STORE_API_VERSION = 'v2025-05-06'\nexport const QUERY_STORE_DEFAULT_PERSPECTIVE = 'drafts'\n","import {omitProperty} from '../utils/object'\n\ninterface QueryState {\n syncTags?: string[]\n result?: unknown\n error?: unknown\n lastLiveEventId?: string\n subscribers: string[]\n}\n\nexport interface QueryStoreState {\n queries: {[key: string]: QueryState | undefined}\n error?: unknown\n}\n\nexport const setQueryError =\n (key: string, error: unknown) =>\n (prev: QueryStoreState): QueryStoreState => {\n const prevQuery = prev.queries[key]\n if (!prevQuery) return prev\n return {...prev, queries: {...prev.queries, [key]: {...prevQuery, error}}}\n }\n\nexport const setQueryData =\n (key: string, result: unknown, syncTags?: string[]) =>\n (prev: QueryStoreState): QueryStoreState => {\n const prevQuery = prev.queries[key]\n if (!prevQuery) return prev\n return {\n ...prev,\n queries: {...prev.queries, [key]: {...prevQuery, result: result ?? null, syncTags}},\n }\n }\n\nexport const setLastLiveEventId =\n (key: string, lastLiveEventId: string) =>\n (prev: QueryStoreState): QueryStoreState => {\n const prevQuery = prev.queries[key]\n if (!prevQuery) return prev\n return {...prev, queries: {...prev.queries, [key]: {...prevQuery, lastLiveEventId}}}\n }\n\nexport const addSubscriber =\n (key: string, subscriptionId: string) =>\n (prev: QueryStoreState): QueryStoreState => {\n const prevQuery = prev.queries[key]\n const subscribers = [...(prevQuery?.subscribers ?? []), subscriptionId]\n return {...prev, queries: {...prev.queries, [key]: {...prevQuery, subscribers}}}\n }\n\nexport const removeSubscriber =\n (key: string, subscriptionId: string) =>\n (prev: QueryStoreState): QueryStoreState => {\n const prevQuery = prev.queries[key]\n if (!prevQuery) return prev\n const subscribers = prevQuery.subscribers.filter((id) => id !== subscriptionId)\n if (!subscribers.length) return {...prev, queries: omitProperty(prev.queries, key)}\n return {...prev, queries: {...prev.queries, [key]: {...prevQuery, subscribers}}}\n }\n","import {type ClientParams, type ResponseQueryOptions} from '@sanity/client'\nimport {\n catchError,\n combineLatest,\n distinctUntilChanged,\n EMPTY,\n filter,\n first,\n firstValueFrom,\n groupBy,\n map,\n mergeMap,\n NEVER,\n Observable,\n of,\n pairwise,\n race,\n share,\n startWith,\n switchMap,\n tap,\n} from 'rxjs'\n\nimport {getClientAuthState} from '../auth/authStore'\nimport {withProjectAccessMessage} from '../auth/projectAccessError'\nimport {getClientState} from '../client/clientStore'\nimport {observeLiveEvents} from '../client/liveEvents'\nimport {retryRead} from '../client/retry'\nimport {type DatasetHandle} from '../config/sanityConfig'\nimport {getPerspectiveState} from '../releases/getPerspectiveState'\nimport {isReleasePerspective} from '../releases/utils/isReleasePerspective'\nimport {bindActionByResource, type BoundResourceKey} from '../store/createActionBinder'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {\n createStateSourceAction,\n type SelectorContext,\n type StateSource,\n} from '../store/createStateSourceAction'\nimport {type StoreState} from '../store/createStoreState'\nimport {defineStore, type StoreContext} from '../store/defineStore'\nimport {type ResolveQueryResult} from '../typegen/resolve'\nimport {randomId} from '../utils/ids'\nimport {setCleanupTimeout} from '../utils/setCleanupTimeout'\nimport {\n QUERY_STATE_CLEAR_DELAY,\n QUERY_STORE_API_VERSION,\n QUERY_STORE_DEFAULT_PERSPECTIVE,\n} from './queryStoreConstants'\nimport {\n addSubscriber,\n type QueryStoreState,\n removeSubscriber,\n setLastLiveEventId,\n setQueryData,\n setQueryError,\n} from './reducers'\n\n/**\n * @beta\n */\nexport interface QueryOptions<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>\n extends\n Pick<ResponseQueryOptions, 'useCdn' | 'cache' | 'next' | 'cacheMode' | 'tag'>,\n DatasetHandle<TDataset, TProjectId> {\n query: TQuery\n /**\n * The query's parameters. For a query carrying a `__groqParams` brand, such as the default\n * export of a `.groq` file imported through `@sanity-labs/groq-content-mapper`, these are\n * checked against the branded params type (experimental).\n *\n * `any` satisfies that brand check and would type `params` as `any`. It keeps the open\n * record, which is what an untyped query accepted before. See {@link ResolveQueryResult}\n * for why the check is written this way.\n */\n params?: boolean extends (TQuery extends never ? true : false)\n ? Record<string, unknown>\n : ClientParams<TQuery, Record<string, unknown>>\n}\n\n/**\n * @beta\n */\nexport interface ResolveQueryOptions<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends QueryOptions<TQuery, TDataset, TProjectId> {\n signal?: AbortSignal\n}\n\nconst EMPTY_ARRAY: never[] = []\n\n/** @internal */\nexport const getQueryKey = (instance: SanityInstance, options: QueryOptions): string =>\n JSON.stringify(normalizeOptionsWithPerspective(instance, options))\n/** @internal */\nexport const parseQueryKey = (key: string): QueryOptions => JSON.parse(key)\n\n/**\n * Ensures the query key includes an effective perspective so that\n * implicit differences (e.g. different instance.config.perspective)\n * don't collide in the dataset-scoped store.\n *\n * Since perspectives are unique, we can depend on the release stacks\n * to be correct when we retrieve the results.\n *\n */\nfunction normalizeOptionsWithPerspective(\n instance: SanityInstance,\n options: QueryOptions,\n): QueryOptions {\n if (options.perspective !== undefined) return options\n const instancePerspective = instance.config.perspective\n return {\n ...options,\n perspective:\n instancePerspective !== undefined ? instancePerspective : QUERY_STORE_DEFAULT_PERSPECTIVE,\n }\n}\n\nconst queryStore = defineStore<QueryStoreState, BoundResourceKey>({\n name: 'QueryStore',\n getInitialState: () => ({queries: {}}),\n initialize(context) {\n const subscription = listenForNewSubscribersAndFetch(context)\n return () => subscription.unsubscribe()\n },\n upstream: (context) => listenToLiveClientAndSetLastLiveEventIds(context),\n})\n\nconst errorHandler = (state: StoreState<{error?: unknown}>) => {\n return (error: unknown): void => state.set('setError', {error})\n}\n\nconst listenForNewSubscribersAndFetch = ({state, instance}: StoreContext<QueryStoreState>) => {\n return state.observable\n .pipe(\n map((s) => new Set(Object.keys(s.queries))),\n distinctUntilChanged((curr, next) => {\n if (curr.size !== next.size) return false\n return Array.from(next).every((i) => curr.has(i))\n }),\n startWith(new Set<string>()),\n pairwise(),\n mergeMap(([curr, next]) => {\n const added = Array.from(next).filter((i) => !curr.has(i))\n const removed = Array.from(curr).filter((i) => !next.has(i))\n\n return [\n ...added.map((key) => ({key, added: true})),\n ...removed.map((key) => ({key, added: false})),\n ]\n }),\n groupBy((i) => i.key),\n mergeMap((group$) =>\n group$.pipe(\n switchMap((e) => {\n if (!e.added) return EMPTY\n\n const lastLiveEventId$ = state.observable.pipe(\n map((s) => s.queries[group$.key]?.lastLiveEventId),\n distinctUntilChanged(),\n )\n const {\n query,\n params,\n projectId,\n dataset,\n tag,\n resource,\n perspective: perspectiveFromOptions,\n ...restOptions\n } = parseQueryKey(group$.key)\n\n // Short-circuit perspective resolution for non-release perspectives to avoid\n // touching the releases store (and its initialization) unnecessarily.\n const perspective$ = isReleasePerspective(perspectiveFromOptions)\n ? getPerspectiveState(instance, {\n perspective: perspectiveFromOptions,\n resource,\n }).observable.pipe(filter(Boolean))\n : of(perspectiveFromOptions ?? QUERY_STORE_DEFAULT_PERSPECTIVE)\n\n const client$ = getClientState(instance, {\n apiVersion: QUERY_STORE_API_VERSION,\n projectId,\n dataset,\n resource,\n }).observable\n\n return combineLatest({\n lastLiveEventId: lastLiveEventId$,\n client: client$,\n perspective: perspective$,\n }).pipe(\n switchMap(({lastLiveEventId, client, perspective}) =>\n client.observable.fetch(query, params, {\n ...restOptions,\n perspective,\n filterResponse: false,\n returnQuery: false,\n lastLiveEventId,\n tag,\n }),\n ),\n tap(({result, syncTags}) => {\n state.set('setQueryData', setQueryData(group$.key, result, syncTags))\n }),\n // Retry inside the per-event stream: erroring the group pipe would\n // complete the group's subscription, and since `groupBy` above never\n // removes its group subjects, re-adding the key would emit into a\n // subject with no subscribers — the key could never be fetched again.\n retryRead(getClientAuthState(instance), (error) =>\n state.set(\n 'setQueryError',\n setQueryError(group$.key, withProjectAccessMessage(instance, error)),\n ),\n ),\n )\n }),\n ),\n ),\n )\n .subscribe({error: errorHandler(state)})\n}\n\nconst listenToLiveClientAndSetLastLiveEventIds = ({\n state,\n instance,\n key: {resource},\n}: StoreContext<QueryStoreState, BoundResourceKey>) => {\n const liveMessages$ = observeLiveEvents(instance, {\n resource,\n // Surface CORS errors as store state (handled by the Cors Error\n // component) instead of erroring the stream: a stream error here would\n // reach the outer subscription's errorHandler, set the store-wide\n // `state.error`, and permanently brick every query selector.\n onCorsError: (error) => state.set('setError', {error}),\n }).pipe(share())\n\n return state.observable\n .pipe(\n mergeMap((s) => Object.entries(s.queries)),\n groupBy(([key]) => key),\n mergeMap((group$) => {\n const syncTags$ = group$.pipe(\n map(([, queryState]) => queryState),\n map((i) => i?.syncTags ?? EMPTY_ARRAY),\n distinctUntilChanged(),\n )\n\n return combineLatest([liveMessages$, syncTags$]).pipe(\n filter(([message, syncTags]) => message.tags.some((tag) => syncTags.includes(tag))),\n tap(([message]) => {\n state.set('setLastLiveEventId', setLastLiveEventId(group$.key, message.id))\n }),\n )\n }),\n )\n .subscribe({error: errorHandler(state)})\n}\n\n/**\n * Returns the state source for a query.\n *\n * This function returns a state source that represents the current result of a GROQ query.\n * Subscribing to the state source will instruct the SDK to fetch the query (if not already fetched)\n * and will keep the query live using the Live content API (considering sync tags) to provide up-to-date results.\n * When the last subscriber is removed, the query state is automatically cleaned up from the store.\n *\n * Note: This functionality is for advanced users who want to build their own framework integrations.\n * Our SDK also provides a React integration (useQuery hook) for convenient usage.\n *\n * Note: Automatic cleanup can interfere with React Suspense because if a component suspends while being the only subscriber,\n * cleanup might occur unexpectedly. In such cases, consider using `resolveQuery` instead.\n *\n * @beta\n */\nexport function getQueryState<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n instance: SanityInstance,\n queryOptions: QueryOptions<TQuery, TDataset, TProjectId>,\n): StateSource<ResolveQueryResult<TQuery, `${TProjectId}.${TDataset}`> | undefined>\n\n/**\n * `TQuery` is never written at a call site. With `TData` given it stays `string`, so params are\n * the open record; without it, it is inferred, so a branded query's params are still checked.\n *\n * @beta\n */\nexport function getQueryState<TData, TQuery extends string = string>(\n instance: SanityInstance,\n queryOptions: QueryOptions<TQuery>,\n): StateSource<TData | undefined>\n\n/** @beta */\nexport function getQueryState<TQuery extends string = string>(\n instance: SanityInstance,\n queryOptions: QueryOptions<TQuery>,\n): StateSource<unknown>\n\n/** @beta */\nexport function getQueryState(\n ...args: Parameters<typeof _getQueryState>\n): ReturnType<typeof _getQueryState> {\n return _getQueryState(...args)\n}\nconst _getQueryState = bindActionByResource(\n queryStore,\n createStateSourceAction({\n selector: ({state, instance}: SelectorContext<QueryStoreState>, options: QueryOptions) => {\n if (state.error) throw state.error\n const key = getQueryKey(instance, options)\n const queryState = state.queries[key]\n if (queryState?.error) throw queryState.error\n return queryState?.result\n },\n onSubscribe: ({state, instance}, options: QueryOptions) => {\n const subscriptionId = randomId(16)\n const key = getQueryKey(instance, options)\n\n state.set('addSubscriber', addSubscriber(key, subscriptionId))\n\n return () => {\n // this runs on unsubscribe\n setCleanupTimeout(\n () => state.set('removeSubscriber', removeSubscriber(key, subscriptionId)),\n QUERY_STATE_CLEAR_DELAY,\n )\n }\n },\n }),\n)\n\n/**\n * Resolves the result of a query without registering a lasting subscriber.\n *\n * This function fetches the result of a GROQ query and returns a promise that resolves with the query result.\n * It registers a temporary subscriber for the lifetime of the resolution (released shortly after the promise\n * settles), so the query state participates in normal cleanup even when no lasting subscriber ever attaches —\n * e.g. when a suspended component errors before committing. This makes it ideal for use with React Suspense,\n * where the returned promise is thrown to delay rendering until the query result becomes available.\n * Once the promise resolves, it is expected that a real subscriber will be added via `getQueryState` to manage ongoing updates.\n *\n * Additionally, an optional AbortSignal can be provided to cancel the query and immediately clear the associated state\n * if there are no other active subscribers.\n *\n * @beta\n */\nexport function resolveQuery<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n instance: SanityInstance,\n queryOptions: ResolveQueryOptions<TQuery, TDataset, TProjectId>,\n): Promise<ResolveQueryResult<TQuery, `${TProjectId}.${TDataset}`>>\n\n/**\n * `TQuery` is never written at a call site; see the matching {@link getQueryState} overload.\n *\n * @beta\n */\nexport function resolveQuery<TData, TQuery extends string = string>(\n instance: SanityInstance,\n queryOptions: ResolveQueryOptions<TQuery>,\n): Promise<TData>\n/** @beta */\nexport function resolveQuery(...args: Parameters<typeof _resolveQuery>): Promise<unknown> {\n return _resolveQuery(...args)\n}\nconst _resolveQuery = bindActionByResource(\n queryStore,\n ({state, instance}, {signal, ...options}: ResolveQueryOptions) => {\n const normalized = normalizeOptionsWithPerspective(instance, options)\n const {getCurrent} = getQueryState(instance, normalized)\n const key = getQueryKey(instance, normalized)\n\n // Hold a temporary subscription for the lifetime of this resolution so the\n // key participates in normal cleanup. Without one, a fetch that errors\n // while a component is suspended leaves a subscriber-less key behind — the\n // component never commits, so no other subscriber exists — and its stored\n // error would be rethrown on every future mount without ever refetching.\n const subscriptionId = randomId(16)\n state.set('addSubscriber', addSubscriber(key, subscriptionId))\n\n const aborted$ = signal\n ? new Observable<void>((observer) => {\n const cleanup = () => {\n signal.removeEventListener('abort', listener)\n }\n\n const listener = () => {\n observer.error(new DOMException('The operation was aborted.', 'AbortError'))\n observer.complete()\n cleanup()\n }\n signal.addEventListener('abort', listener)\n\n return cleanup\n }).pipe(\n catchError((error) => {\n if (error instanceof Error && error.name === 'AbortError') {\n // Release immediately (not after the clear delay) so that when\n // this was the only subscriber, the key removal tears down the\n // in-flight request right away — e.g. when useQuery switches\n // to a different query\n state.set('removeSubscriber', removeSubscriber(key, subscriptionId))\n }\n throw error\n }),\n )\n : NEVER\n\n const resolved$ = state.observable.pipe(\n map(getCurrent),\n first((i) => i !== undefined),\n )\n\n const promise = firstValueFrom(race([resolved$, aborted$]))\n const releaseSubscriber = () => {\n setCleanupTimeout(() => {\n state.set('removeSubscriber', removeSubscriber(key, subscriptionId))\n }, QUERY_STATE_CLEAR_DELAY)\n }\n promise.then(releaseSubscriber, releaseSubscriber)\n return promise\n },\n)\n","","import {version} from '../package.json'\nimport {getEnv} from './utils/getEnv'\n\n/**\n * This version is provided by pkg-utils at build time\n * @internal\n */\nexport const CORE_SDK_VERSION = getEnv('PKG_VERSION') || `${version}-development`\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,SAAS,gBAAgB,OAAoC;CAG3D,OAFI,iBAAiB,cAAoB,QACrC,iBAAiB,SAAS,MAAM,iBAAiB,cAAoB,MAAM,QACxE;AACT;AAEA,SAAS,kBAAkB,OAAoC;CAC7D,OAAO,OAAO,SAAU,YAAY,QAAQ,QAAQ,KAAA;AACtD;;;;;;;;;;;AAYA,SAAgB,6BAA6B,OAAkD;CAC7F,IAAM,cAAc,gBAAgB,KAAK;CACzC,IACE,CAAC,eACD,YAAY,eAAe,OAC3B,sBAAsB,WAAW,MAAM,4BAEvC,OAAO;CAGT,IAAM,OAAO,sBAAsB,WAAW,CAAC,EAAE;CACjD,OAAO;EACL,WAAW,2BAA2B,WAAW;EACjD,QAAQ,kBAAkB,MAAM,MAAM;EACtC,SAAS,kBAAkB,YAAY,OAAO;CAChD;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,+BAA+B,OAA+B;CAC5E,OAAO,6BAA6B,KAAK,CAAC,EAAE,aAAa;AAC3D;AAIA,MAAM,wBAAgD;CACpD,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV;;;;;;;;AASA,SAAgB,qBAAqB,UAAkD;CACrF,IAAK,UAEL,OADI,SAAS,WAAW,OAAO,IAAU,QAClC,sBAAsB;AAC/B;AAIA,SA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