@sanity/sdk 3.12.0 → 3.13.0-next.20261106104949

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version-DRnj2zr5.js","names":["\"_createdAt\"","\"_updatedAt\"","\"publishAt\"","\"intendedPublishAt\""],"sources":["../src/auth/projectAccessError.ts","../src/document/patchOperations.ts","../src/document/processMutations.ts","../src/document/processActions/shared.ts","../src/favorites/favorites.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 {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","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 {\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 * 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 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","// 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 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 params?: 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/** @beta */\nexport function getQueryState<TData>(\n instance: SanityInstance,\n queryOptions: QueryOptions,\n): StateSource<TData | undefined>\n\n/** @beta */\nexport function getQueryState(\n instance: SanityInstance,\n queryOptions: QueryOptions,\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/** @beta */\nexport function resolveQuery<TData>(\n instance: SanityInstance,\n queryOptions: ResolveQueryOptions,\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,SAAS,6BACP,SACA,UACQ;CACR,IAAM,SAAS,qBAAqB,QAAQ;CAK5C,OACE,GALc,SAAS,uCAAuC,OAAO,KAAK,sBAK/D,qBAJG,QAAQ,Y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U,GAOtC,iBAAiB,SAAS,EAAE;CAClC,MAAM,IAAI,iBAAiB,cAAc,KAAK,cAAc,CAAC;CAE7D,IAAM,WAAW,SACb,IAAI,YAAkB,aAAa;EACjC,IAAM,gBAAgB;GACpB,OAAO,oBAAoB,SAAS,QAAQ;EAC9C,GAEM,iBAAiB;GAGrB,AAFA,SAAS,MAAM,IAAI,aAAa,8BAA8B,YAAY,CAAC,GAC3E,SAAS,SAAS,GAClB,QAAQ;EACV;EAGA,OAFA,OAAO,iBAAiB,SAAS,QAAQ,GAElC;CACT,CAAC,CAAC,CAAC,KACD,YAAY,UAAU;EAQpB,MAPI,iBAAiB,SAAS,MAAM,SAAS,gBAK3C,MAAM,IAAI,oBAAoB,iBAAiB,KAAK,cAAc,CAAC,GAE/D;CACR,CAAC,CACH,IACA,OAEE,YAAY,MAAM,WAAW,KACjC,IAAI,UAAU,GACd,OAAO,MAAM,MAAM,KAAA,CAAS,CAC9B,GAEM,UAAU,eAAe,KAAK,CAAC,WAAW,QAAQ,CAAC,CAAC,GACpD,0BAA0B;EAC9B,wBAAwB;GACtB,MAAM,IAAI,oBAAoB,iBAAiB,KAAK,cAAc,CAAC;EACrE,GAAG,uBAAuB;CAC5B;CAEA,OADA,QAAQ,KAAK,mBAAmB,iBAAiB,GAC1C;AACT,CACF,GExZa,mBAAmB,OAAO,aAAa,KAAK"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/sdk",
3
- "version": "3.12.0",
3
+ "version": "3.13.0-next.20261106104949",
4
4
  "private": false,
5
5
  "description": "Sanity SDK",
6
6
  "keywords": [
@@ -57,6 +57,7 @@
57
57
  "@sanity/mutate": "^0.18.2",
58
58
  "@sanity/telemetry": "^1.1.0",
59
59
  "@sanity/types": "^6.21.0",
60
+ "@sentry/browser": "^11.8.0",
60
61
  "groq": "^6.21.0",
61
62
  "groq-js": "^2.0.1",
62
63
  "reselect": "^5.3.0",
@@ -77,7 +78,7 @@
77
78
  "oxlint": "^1.90.0",
78
79
  "rolldown": "^1.2.12",
79
80
  "typescript": "^7.0.2",
80
- "vite": "^8.3.5",
81
+ "vite": "^8.3.6",
81
82
  "vitest": "^5.0.5"
82
83
  },
83
84
  "browserslist": "extends @sanity/browserslist-config",
@@ -30,6 +30,7 @@ export {
30
30
  export type {ApplicationStatus, ApplicationStatusUpdate} from '../dashboard/messageBus/topics'
31
31
  export {getTopicState, resolveTopic} from '../dashboard/messageBus/topicStore'
32
32
  export {getWorkerClient, type WorkerConnection} from '../dashboard/messageBus/workerStore'
33
+ export {reportError} from '../errorReporting/errorReporter'
33
34
  export {getBusFavoriteState, resolveBusFavorite, setBusFavorite} from '../favorites/busFavorites'
34
35
  export {PREVIEW_PROJECTION} from '../preview/previewConstants'
35
36
  export {transformProjectionToPreview} from '../preview/previewProjectionUtils'
@@ -0,0 +1,207 @@
1
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
2
+
3
+ import {ActionError} from '../document/processActions/shared'
4
+ import {createErrorReporter} from './errorReporter'
5
+
6
+ type SentPayload = {
7
+ release?: string
8
+ tags?: Record<string, string>
9
+ extra?: Record<string, unknown>
10
+ breadcrumbs?: unknown[]
11
+ user?: {ip_address?: string}
12
+ }
13
+
14
+ const SDK_FRAME = 'https://sanity-cdn.com/v1/modules/@sanity__sdk-react/default/%5E1.0.0/index.js'
15
+ const APP_FRAME = 'https://myapp.example.com/assets/main.js'
16
+ const BUILTIN_FRAME = '<anonymous>'
17
+
18
+ function errorWithStack(message: string, frames: string[]): Error {
19
+ const error = new TypeError(message)
20
+ const lines = frames.map((f) =>
21
+ f === BUILTIN_FRAME ? ' at JSON.parse (<anonymous>)' : ` at fn (${f}:10:5)`,
22
+ )
23
+ error.stack = `TypeError: ${message}\n${lines.join('\n')}`
24
+ return error
25
+ }
26
+
27
+ function setup() {
28
+ const sent: SentPayload[] = []
29
+ const transport = (() => ({
30
+ send: async (envelope: unknown[]) => {
31
+ for (const [, payload] of envelope[1] as [unknown, SentPayload][]) sent.push(payload)
32
+ return {statusCode: 200}
33
+ },
34
+ flush: async () => true,
35
+ })) as never
36
+ const {reportError} = createErrorReporter({transport})
37
+ // `reportError` loads Sentry lazily and sends in the background
38
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 100))
39
+ return {sent, reportError, settle}
40
+ }
41
+
42
+ describe('createErrorReporter', () => {
43
+ beforeEach(() => {
44
+ vi.stubGlobal('window', {location: {hostname: 'myapp.example.com'}})
45
+ vi.stubGlobal('document', {
46
+ querySelectorAll: () => [{textContent: JSON.stringify({imports: {'@sanity/sdk': 'x'}})}],
47
+ })
48
+ vi.stubGlobal('localStorage', {getItem: () => null})
49
+ })
50
+
51
+ afterEach(() => {
52
+ vi.unstubAllGlobals()
53
+ })
54
+
55
+ it('sends nothing when error reporting is disabled', async () => {
56
+ vi.stubGlobal('document', {querySelectorAll: () => []})
57
+ const {sent, reportError, settle} = setup()
58
+ reportError(errorWithStack('boom', [SDK_FRAME]))
59
+ await settle()
60
+ expect(sent).toHaveLength(0)
61
+ })
62
+
63
+ it('sends nothing for a known error', async () => {
64
+ const {sent, reportError, settle} = setup()
65
+ const error = new ActionError({message: 'm', documentId: 'd', transactionId: 't'})
66
+ error.stack = `Error: m\n at fn (${SDK_FRAME}:1:1)`
67
+ reportError(error)
68
+ await settle()
69
+ expect(sent).toHaveLength(0)
70
+ })
71
+
72
+ it('sends nothing for a value that is not an Error', async () => {
73
+ const {sent, reportError, settle} = setup()
74
+ reportError('just a string')
75
+ await settle()
76
+ expect(sent).toHaveLength(0)
77
+ })
78
+
79
+ it('sends a scrubbed event with tags for an SDK error', async () => {
80
+ const {sent, reportError, settle} = setup()
81
+ reportError(errorWithStack('boom', [SDK_FRAME, APP_FRAME]), {errorBoundary: 'AuthBoundary'})
82
+ await settle()
83
+ expect(sent).toHaveLength(1)
84
+ expect(sent[0]?.tags).toMatchObject({handled: 'no', errorBoundary: 'AuthBoundary'})
85
+ expect(sent[0]?.user).toEqual({ip_address: '0.0.0.0'})
86
+ expect(sent[0]?.release).toEqual(expect.any(String))
87
+ })
88
+
89
+ it('drops errors thrown by app code', async () => {
90
+ const {sent, reportError, settle} = setup()
91
+ reportError(errorWithStack('app only', [APP_FRAME]))
92
+ reportError(errorWithStack('sdk called app', [APP_FRAME, SDK_FRAME]))
93
+ await settle()
94
+ expect(sent).toHaveLength(0)
95
+ })
96
+
97
+ it('reports the same message once', async () => {
98
+ const {sent, reportError, settle} = setup()
99
+ reportError(errorWithStack('repeat', [SDK_FRAME]))
100
+ reportError(errorWithStack('repeat', [SDK_FRAME]))
101
+ await settle()
102
+ expect(sent).toHaveLength(1)
103
+ })
104
+
105
+ it('attributes an error thrown by a builtin to the code that called it', async () => {
106
+ const {sent, reportError, settle} = setup()
107
+ reportError(errorWithStack('sdk parse', [BUILTIN_FRAME, SDK_FRAME]))
108
+ reportError(errorWithStack('app parse', [BUILTIN_FRAME, APP_FRAME]))
109
+ await settle()
110
+ expect(sent).toHaveLength(1)
111
+ })
112
+
113
+ it('matches a percent-encoded module server URL', async () => {
114
+ const {sent, reportError, settle} = setup()
115
+ reportError(
116
+ errorWithStack('encoded', [
117
+ 'https://sanity-cdn.com/v1/modules/%40sanity__sdk/default/1/a.mjs',
118
+ ]),
119
+ )
120
+ await settle()
121
+ expect(sent).toHaveLength(1)
122
+ })
123
+
124
+ it('does not match a similar package name or an app path that looks like this repo', async () => {
125
+ const {sent, reportError, settle} = setup()
126
+ reportError(errorWithStack('other package', ['https://cdn.example.com/@sanity/sdk-other/a.js']))
127
+ reportError(
128
+ errorWithStack('app monorepo', ['https://myapp.example.com/packages/core/src/a.ts']),
129
+ )
130
+ await settle()
131
+ expect(sent).toHaveLength(0)
132
+ })
133
+
134
+ it('matches this repo sources only when the debug flag is set', async () => {
135
+ vi.stubGlobal('localStorage', {getItem: () => '1'})
136
+ const {sent, reportError, settle} = setup()
137
+ reportError(
138
+ errorWithStack('dev source', ['http://localhost:3333/@fs/repo/packages/react/src/a.ts']),
139
+ )
140
+ await settle()
141
+ expect(sent).toHaveLength(1)
142
+ })
143
+
144
+ it('reports distinct errors that wrap the same cause', async () => {
145
+ const {sent, reportError, settle} = setup()
146
+ const cause = errorWithStack('shared cause', [SDK_FRAME])
147
+ for (const message of ['first', 'second']) {
148
+ const error = errorWithStack(message, [SDK_FRAME])
149
+ error.cause = cause
150
+ reportError(error)
151
+ }
152
+ await settle()
153
+ expect(sent).toHaveLength(2)
154
+ })
155
+
156
+ it('leaves the error it was given unmarked, so a host Sentry can still capture it', async () => {
157
+ const {sent, reportError, settle} = setup()
158
+ const appError = errorWithStack('app error', [APP_FRAME])
159
+ const sdkError = errorWithStack('sdk error', [SDK_FRAME])
160
+ reportError(appError)
161
+ reportError(sdkError)
162
+ await settle()
163
+ expect(sent).toHaveLength(1)
164
+ expect(Object.hasOwn(appError, '__sentry_captured__')).toBe(false)
165
+ expect(Object.hasOwn(sdkError, '__sentry_captured__')).toBe(false)
166
+ })
167
+
168
+ it('does not send state from a Sentry instance the host page runs', async () => {
169
+ const hostSentry = await import('@sentry/browser')
170
+ hostSentry.setTag('customer_tag', 'secret-tenant')
171
+ hostSentry.setExtra('cart', 'items')
172
+ hostSentry.addBreadcrumb({message: 'clicked buy for customer X'})
173
+ try {
174
+ const {sent, reportError, settle} = setup()
175
+ reportError(errorWithStack('sdk bug', [SDK_FRAME]), {errorBoundary: 'AuthBoundary'})
176
+ await settle()
177
+
178
+ expect(sent).toHaveLength(1)
179
+ expect(sent[0]?.tags).toEqual({handled: 'no', errorBoundary: 'AuthBoundary'})
180
+ expect(sent[0]?.extra).toBeUndefined()
181
+ expect(sent[0]?.breadcrumbs).toBeUndefined()
182
+ } finally {
183
+ const hostScope = hostSentry.getIsolationScope()
184
+ hostScope.setTag('customer_tag', undefined)
185
+ hostScope.setExtra('cart', undefined)
186
+ hostScope.clearBreadcrumbs()
187
+ }
188
+ })
189
+
190
+ it('does not throw when inspecting the error throws', () => {
191
+ const {reportError} = setup()
192
+ const error = new Error('hostile')
193
+ Object.defineProperty(error, 'cause', {
194
+ get() {
195
+ throw new Error('cause getter')
196
+ },
197
+ })
198
+ expect(() => reportError(error)).not.toThrow()
199
+ })
200
+
201
+ it('stops after 10 events from one reporter', async () => {
202
+ const {sent, reportError, settle} = setup()
203
+ for (let i = 0; i < 20; i++) reportError(errorWithStack(`distinct ${i}`, [SDK_FRAME]))
204
+ await settle()
205
+ expect(sent).toHaveLength(10)
206
+ })
207
+ })