@sanity/client 6.29.1 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks-cjs/resolveEditInfo.cjs.map +1 -1
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
- package/dist/_chunks-es/resolveEditInfo.js.map +1 -1
- package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
- package/src/csm/draftUtils.ts +1 -1
- package/src/util/shareReplayLatest.ts +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/http/errors.ts","../src/http/request.ts","../src/data/eventsource.ts","../src/util/getSelection.ts","../src/data/patch.ts","../src/data/transaction.ts","../src/http/requestOptions.ts","../src/data/encodeQueryString.ts","../src/data/dataMethods.ts","../src/assets/AssetsClient.ts","../src/util/defaults.ts","../src/util/pick.ts","../src/data/eventsourcePolyfill.ts","../src/data/reconnectOnConnectionFailure.ts","../src/data/listen.ts","../src/util/shareReplayLatest.ts","../src/data/live.ts","../src/datasets/DatasetsClient.ts","../src/projects/ProjectsClient.ts","../src/users/UsersClient.ts","../src/SanityClient.ts","../src/defineCreateClient.ts","../src/defineDeprecatedCreateClient.ts","../src/http/nodeMiddleware.ts","../src/index.ts"],"sourcesContent":["import type {ActionError, Any, ErrorProps, MutationError} from '../types'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\n\n/** @public */\nexport class ClientError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 400\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\n/** @public */\nexport class ServerError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 500\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\nfunction extractErrorProps(res: Any): ErrorProps {\n const body = res.body\n const props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n message: '',\n details: undefined as Any,\n }\n\n // API/Boom style errors ({statusCode, error, message})\n if (body.error && body.message) {\n props.message = `${body.error} - ${body.message}`\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(body) || isActionError(body)) {\n const allItems = body.error.items || []\n const items = allItems\n .slice(0, MAX_ITEMS_IN_ERROR_MESSAGE)\n .map((item) => item.error?.description)\n .filter(Boolean)\n let itemsStr = items.length ? `:\\n- ${items.join('\\n- ')}` : ''\n if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {\n itemsStr += `\\n...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`\n }\n props.message = `${body.error.description}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query/database errors ({error: {description, other, arb, props}})\n if (body.error && body.error.description) {\n props.message = body.error.description\n props.details = body.error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = body.error || body.message || httpErrorMessage(res)\n return props\n}\n\nfunction isMutationError(body: Any): body is MutationError {\n return (\n isPlainObject(body) &&\n isPlainObject(body.error) &&\n body.error.type === 'mutationError' &&\n typeof body.error.description === 'string'\n )\n}\n\nfunction isActionError(body: Any): body is ActionError {\n return (\n isPlainObject(body) &&\n isPlainObject(body.error) &&\n body.error.type === 'actionError' &&\n typeof body.error.description === 'string'\n )\n}\n\nfunction isPlainObject(obj: Any): obj is Record<string, unknown> {\n return typeof obj === 'object' && obj !== null && !Array.isArray(obj)\n}\n\nfunction httpErrorMessage(res: Any) {\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`\n}\n\nfunction stringifyBody(body: Any, res: Any) {\n const contentType = (res.headers['content-type'] || '').toLowerCase()\n const isJson = contentType.indexOf('application/json') !== -1\n return isJson ? JSON.stringify(body, null, 2) : body\n}\n\n/** @public */\nexport class CorsOriginError extends Error {\n projectId: string\n addOriginUrl?: URL\n\n constructor({projectId}: {projectId: string}) {\n super('CorsOriginError')\n this.name = 'CorsOriginError'\n this.projectId = projectId\n\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n if (typeof location !== 'undefined') {\n const {origin} = location\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n this.addOriginUrl = url\n this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`\n } else {\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`\n }\n }\n}\n","import {getIt, type Middlewares, type Requester} from 'get-it'\nimport {jsonRequest, jsonResponse, observable, progress, retry} from 'get-it/middleware'\nimport {Observable} from 'rxjs'\n\nimport type {Any} from '../types'\nimport {ClientError, ServerError} from './errors'\n\nconst httpError = {\n onResponse: (res: Any) => {\n if (res.statusCode >= 500) {\n throw new ServerError(res)\n } else if (res.statusCode >= 400) {\n throw new ClientError(res)\n }\n\n return res\n },\n}\n\nfunction printWarnings() {\n const seen: Record<string, boolean> = {}\n return {\n onResponse: (res: Any) => {\n const warn = res.headers['x-sanity-warning']\n const warnings = Array.isArray(warn) ? warn : [warn]\n for (const msg of warnings) {\n if (!msg || seen[msg]) continue\n seen[msg] = true\n console.warn(msg) // eslint-disable-line no-console\n }\n return res\n },\n }\n}\n\n/** @internal */\nexport function defineHttpRequest(envMiddleware: Middlewares): Requester {\n return getIt([\n retry({shouldRetry}),\n ...envMiddleware,\n printWarnings(),\n jsonRequest(),\n jsonResponse(),\n progress(),\n httpError,\n observable({implementation: Observable}),\n ])\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction shouldRetry(err: any, attempt: number, options: any) {\n // Allow opting out of retries\n if (options.maxRetries === 0) return false\n\n // By default `retry.shouldRetry` doesn't retry on server errors so we add our own logic.\n\n const isSafe = options.method === 'GET' || options.method === 'HEAD'\n const uri = options.uri || options.url\n const isQuery = uri.startsWith('/data/query')\n const isRetriableResponse =\n err.response &&\n (err.response.statusCode === 429 ||\n err.response.statusCode === 502 ||\n err.response.statusCode === 503)\n\n // We retry the following errors:\n // - 429 means that the request was rate limited. It's a bit difficult\n // to know exactly how long it makes sense to wait and/or how many\n // attempts we should retry, but the backoff should alleviate the\n // additional load.\n // - 502/503 can occur when certain components struggle to talk to their\n // upstream dependencies. This is most likely a temporary problem\n // and retrying makes sense.\n\n if ((isSafe || isQuery) && isRetriableResponse) return true\n\n return retry.shouldRetry(err, attempt, options)\n}\n","import {defer, isObservable, mergeMap, Observable, of} from 'rxjs'\n\nimport {type Any} from '../types'\n\n/**\n * @public\n * Thrown if the EventSource connection could not be established.\n * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.\n */\nexport class ConnectionFailedError extends Error {\n readonly name = 'ConnectionFailedError'\n}\n\n/**\n * The listener has been told to explicitly disconnect.\n * This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n * eg in the case of a deleted dataset, a blocked project or similar events.\n * @public\n */\nexport class DisconnectError extends Error {\n readonly name = 'DisconnectError'\n readonly reason?: string\n constructor(message: string, reason?: string, options: ErrorOptions = {}) {\n super(message, options)\n this.reason = reason\n }\n}\n\n/**\n * @public\n * The server sent a `channelError` message. Usually indicative of a bad or malformed request\n */\nexport class ChannelError extends Error {\n readonly name = 'ChannelError'\n readonly data?: unknown\n constructor(message: string, data: unknown) {\n super(message)\n this.data = data\n }\n}\n\n/**\n * @public\n * The server sent an `error`-event to tell the client that an unexpected error has happened.\n */\nexport class MessageError extends Error {\n readonly name = 'MessageError'\n readonly data?: unknown\n constructor(message: string, data: unknown, options: ErrorOptions = {}) {\n super(message, options)\n this.data = data\n }\n}\n\n/**\n * @public\n * An error occurred while parsing the message sent by the server as JSON. Should normally not happen.\n */\nexport class MessageParseError extends Error {\n readonly name = 'MessageParseError'\n}\n\n/**\n * @public\n */\nexport interface ServerSentEvent<Name extends string> {\n type: Name\n id?: string\n data?: unknown\n}\n\n// Always listen for these events, no matter what\nconst REQUIRED_EVENTS = ['channelError', 'disconnect']\n\n/**\n * @internal\n */\nexport type EventSourceEvent<Name extends string> = ServerSentEvent<Name>\n\n/**\n * @internal\n */\nexport type EventSourceInstance = InstanceType<typeof globalThis.EventSource>\n\n/**\n * Sanity API specific EventSource handler shared between the listen and live APIs\n *\n * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance\n * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers)\n * via the passed `initEventSource` function which must return an EventSource instance.\n *\n * Possible errors to be thrown on the returned observable are:\n * - {@link MessageError}\n * - {@link MessageParseError}\n * - {@link ChannelError}\n * - {@link DisconnectError}\n * - {@link ConnectionFailedError}\n *\n * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance\n * @param events - an array of named events from the API to listen for.\n *\n * @internal\n */\nexport function connectEventSource<EventName extends string>(\n initEventSource: () => EventSourceInstance | Observable<EventSourceInstance>,\n events: EventName[],\n) {\n return defer(() => {\n const es = initEventSource()\n return isObservable(es) ? es : of(es)\n }).pipe(mergeMap((es) => connectWithESInstance(es, events))) as Observable<\n ServerSentEvent<EventName>\n >\n}\n\n/**\n * Provides an observable from the passed EventSource instance, subscribing to the passed list of names of events types to listen for\n * Handles connection logic, adding/removing event listeners, payload parsing, error propagation, etc.\n *\n * @param es - The EventSource instance\n * @param events - List of event names to listen for\n */\nfunction connectWithESInstance<EventTypeName extends string>(\n es: EventSourceInstance,\n events: EventTypeName[],\n) {\n return new Observable<EventSourceEvent<EventTypeName>>((observer) => {\n const emitOpen = (events as string[]).includes('open')\n const emitReconnect = (events as string[]).includes('reconnect')\n\n // EventSource will emit a regular Event if it fails to connect, however the API may also emit an `error` MessageEvent\n // So we need to handle both cases\n function onError(evt: MessageEvent | Event) {\n // If the event has a `data` property, then it`s a MessageEvent emitted by the API and we should forward the error\n if ('data' in evt) {\n const [parseError, event] = parseEvent(evt as MessageEvent)\n observer.error(\n parseError\n ? new MessageParseError('Unable to parse EventSource error message', {cause: event})\n : new MessageError((event?.data as {message: string}).message, event),\n )\n return\n }\n\n // We should never be in a disconnected state. By default, EventSource will reconnect\n // automatically, but in some cases (like when a laptop lid is closed), it will trigger onError\n // if it can't reconnect.\n // see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model\n if (es.readyState === es.CLOSED) {\n // In these cases we'll signal to consumers (via the error path) that a retry/reconnect is needed.\n observer.error(new ConnectionFailedError('EventSource connection failed'))\n } else if (emitReconnect) {\n observer.next({type: 'reconnect' as EventTypeName})\n }\n }\n\n function onOpen() {\n // The open event of the EventSource API is fired when a connection with an event source is opened.\n observer.next({type: 'open' as EventTypeName})\n }\n\n function onMessage(message: MessageEvent) {\n const [parseError, event] = parseEvent(message)\n if (parseError) {\n observer.error(\n new MessageParseError('Unable to parse EventSource message', {cause: parseError}),\n )\n return\n }\n if (message.type === 'channelError') {\n // An error occurred. This is different from a network-level error (which will be emitted as 'error').\n // Possible causes are things such as malformed filters, non-existant datasets or similar.\n observer.error(new ChannelError(extractErrorMessage(event?.data), event.data))\n return\n }\n if (message.type === 'disconnect') {\n // The listener has been told to explicitly disconnect and not reconnect.\n // This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n // eg in the case of a deleted dataset, a blocked project or similar events.\n observer.error(\n new DisconnectError(\n `Server disconnected client: ${\n (event.data as {reason?: string})?.reason || 'unknown error'\n }`,\n ),\n )\n return\n }\n observer.next({\n type: message.type as EventTypeName,\n id: message.lastEventId,\n ...(event.data ? {data: event.data} : {}),\n })\n }\n\n es.addEventListener('error', onError)\n\n if (emitOpen) {\n es.addEventListener('open', onOpen)\n }\n\n // Make sure we have a unique list of events types to avoid listening multiple times,\n const cleanedEvents = [...new Set([...REQUIRED_EVENTS, ...events])]\n // filter out events that are handled separately\n .filter((type) => type !== 'error' && type !== 'open' && type !== 'reconnect')\n\n cleanedEvents.forEach((type: string) => es.addEventListener(type, onMessage))\n\n return () => {\n es.removeEventListener('error', onError)\n if (emitOpen) {\n es.removeEventListener('open', onOpen)\n }\n cleanedEvents.forEach((type: string) => es.removeEventListener(type, onMessage))\n es.close()\n }\n })\n}\n\nfunction parseEvent(\n message: MessageEvent,\n): [null, {type: string; id: string; data?: unknown}] | [Error, null] {\n try {\n const data = typeof message.data === 'string' && JSON.parse(message.data)\n return [\n null,\n {\n type: message.type,\n id: message.lastEventId,\n ...(isEmptyObject(data) ? {} : {data}),\n },\n ]\n } catch (err) {\n return [err as Error, null]\n }\n}\n\nfunction extractErrorMessage(err: Any) {\n if (!err.error) {\n return err.message || 'Unknown listener error'\n }\n\n if (err.error.description) {\n return err.error.description\n }\n\n return typeof err.error === 'string' ? err.error : JSON.stringify(err.error, null, 2)\n}\n\nfunction isEmptyObject(data: object) {\n for (const _ in data) {\n return false\n }\n return true\n}\n","import type {MutationSelection} from '../types'\n\nexport function getSelection(sel: unknown): MutationSelection {\n if (typeof sel === 'string') {\n return {id: sel}\n }\n\n if (Array.isArray(sel)) {\n return {query: '*[_id in $ids]', params: {ids: sel}}\n }\n\n if (typeof sel === 'object' && sel !== null && 'query' in sel && typeof sel.query === 'string') {\n return 'params' in sel && typeof sel.params === 'object' && sel.params !== null\n ? {query: sel.query, params: sel.params}\n : {query: sel.query}\n }\n\n const selectionOpts = [\n '* Document ID (<docId>)',\n '* Array of document IDs',\n '* Object containing `query`',\n ].join('\\n')\n\n throw new Error(`Unknown selection - must be one of:\\n\\n${selectionOpts}`)\n}\n","import {type Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n AttributeSet,\n BaseMutationOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n MultipleMutationResult,\n PatchMutationOperation,\n PatchOperations,\n PatchSelection,\n SanityDocument,\n SingleMutationResult,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport {validateInsert, validateObject} from '../validators'\n\n/** @internal */\nexport class BasePatch {\n protected selection: PatchSelection\n protected operations: PatchOperations\n constructor(selection: PatchSelection, operations: PatchOperations = {}) {\n this.selection = selection\n this.operations = operations\n }\n\n /**\n * Sets the given attributes to the document. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n set(attrs: AttributeSet): this {\n return this._assign('set', attrs)\n }\n\n /**\n * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n setIfMissing(attrs: AttributeSet): this {\n return this._assign('setIfMissing', attrs)\n }\n\n /**\n * Performs a \"diff-match-patch\" operation on the string attributes provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"dmp\"\\}\n */\n diffMatchPatch(attrs: AttributeSet): this {\n validateObject('diffMatchPatch', attrs)\n return this._assign('diffMatchPatch', attrs)\n }\n\n /**\n * Unsets the attribute paths provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attribute paths to unset.\n */\n unset(attrs: string[]): this {\n if (!Array.isArray(attrs)) {\n throw new Error('unset(attrs) takes an array of attributes to unset, non-array given')\n }\n\n this.operations = Object.assign({}, this.operations, {unset: attrs})\n return this\n }\n\n /**\n * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to increment, values representing the number to increment by.\n */\n inc(attrs: {[key: string]: number}): this {\n return this._assign('inc', attrs)\n }\n\n /**\n * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.\n */\n dec(attrs: {[key: string]: number}): this {\n return this._assign('dec', attrs)\n }\n\n /**\n * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.\n *\n * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path\n * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key==\"abc123\"]`\n * @param items - Array of items to insert/replace\n */\n insert(at: 'before' | 'after' | 'replace', selector: string, items: Any[]): this {\n validateInsert(at, selector, items)\n return this._assign('insert', {[at]: selector, items})\n }\n\n /**\n * Append the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`\n * @param items - Array of items to append to the array\n */\n append(selector: string, items: Any[]): this {\n return this.insert('after', `${selector}[-1]`, items)\n }\n\n /**\n * Prepend the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`\n * @param items - Array of items to prepend to the array\n */\n prepend(selector: string, items: Any[]): this {\n return this.insert('before', `${selector}[0]`, items)\n }\n\n /**\n * Change the contents of an array by removing existing elements and/or adding new elements.\n *\n * @param selector - Attribute or JSONPath expression for array\n * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x\n * @param deleteCount - An integer indicating the number of old array elements to remove.\n * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.\n */\n splice(selector: string, start: number, deleteCount?: number, items?: Any[]): this {\n // Negative indexes doesn't mean the same in Sanity as they do in JS;\n // -1 means \"actually at the end of the array\", which allows inserting\n // at the end of the array without knowing its length. We therefore have\n // to substract negative indexes by one to match JS. If you want Sanity-\n // behaviour, just use `insert('replace', selector, items)` directly\n const delAll = typeof deleteCount === 'undefined' || deleteCount === -1\n const startIndex = start < 0 ? start - 1 : start\n const delCount = delAll ? -1 : Math.max(0, start + deleteCount)\n const delRange = startIndex < 0 && delCount >= 0 ? '' : delCount\n const rangeSelector = `${selector}[${startIndex}:${delRange}]`\n return this.insert('replace', rangeSelector, items || [])\n }\n\n /**\n * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value\n *\n * @param rev - Revision to lock the patch to\n */\n ifRevisionId(rev: string): this {\n this.operations.ifRevisionID = rev\n return this\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n serialize(): PatchMutationOperation {\n return {...getSelection(this.selection), ...this.operations}\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n toJSON(): PatchMutationOperation {\n return this.serialize()\n }\n\n /**\n * Clears the patch of all operations\n */\n reset(): this {\n this.operations = {}\n return this\n }\n\n protected _assign(op: keyof PatchOperations, props: Any, merge = true): this {\n validateObject(op, props)\n this.operations = Object.assign({}, this.operations, {\n [op]: Object.assign({}, (merge && this.operations[op]) || {}, props),\n })\n return this\n }\n\n protected _set(op: keyof PatchOperations, props: Any): this {\n return this._assign(op, props, false)\n }\n}\n\n/** @public */\nexport class ObservablePatch extends BasePatch {\n #client?: ObservableSanityClient\n\n constructor(\n selection: PatchSelection,\n operations?: PatchOperations,\n client?: ObservableSanityClient,\n ) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): ObservablePatch {\n return new ObservablePatch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the patch, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n\n/** @public */\nexport class Patch extends BasePatch {\n #client?: SanityClient\n constructor(selection: PatchSelection, operations?: PatchOperations, client?: SanityClient) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): Patch {\n return new Patch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the patch, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n","import type {Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n BaseMutationOptions,\n IdentifiedSanityDocumentStub,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n SanityDocument,\n SanityDocumentStub,\n SingleMutationResult,\n TransactionAllDocumentIdsMutationOptions,\n TransactionAllDocumentsMutationOptions,\n TransactionFirstDocumentIdMutationOptions,\n TransactionFirstDocumentMutationOptions,\n} from '../types'\nimport * as validators from '../validators'\nimport {ObservablePatch, Patch} from './patch'\n\n/** @public */\nexport type PatchBuilder = (patch: Patch) => Patch\n/** @public */\nexport type ObservablePatchBuilder = (patch: ObservablePatch) => ObservablePatch\n\nconst defaultMutateOptions = {returnDocuments: false}\n\n/** @internal */\nexport class BaseTransaction {\n protected operations: Mutation[]\n protected trxId?: string\n constructor(operations: Mutation[] = [], transactionId?: string) {\n this.operations = operations\n this.trxId = transactionId\n }\n /**\n * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create. Requires a `_type` property.\n */\n create<R extends Record<string, Any> = Record<string, Any>>(doc: SanityDocumentStub<R>): this {\n validators.validateObject('create', doc)\n return this._add({create: doc})\n }\n\n /**\n * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createIfNotExists'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create or replace. Requires `_id` and `_type` properties.\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createOrReplace'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Deletes the document with the given document ID\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to delete\n */\n delete(documentId: string): this {\n validators.validateDocumentId('delete', documentId)\n return this._add({delete: {id: documentId}})\n }\n\n /**\n * Gets the current transaction ID, if any\n */\n transactionId(): string | undefined\n /**\n * Set the ID of this transaction.\n *\n * @param id - Transaction ID\n */\n transactionId(id: string): this\n transactionId(id?: string): this | string | undefined {\n if (!id) {\n return this.trxId\n }\n\n this.trxId = id\n return this\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n serialize(): Mutation[] {\n return [...this.operations]\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n toJSON(): Mutation[] {\n return this.serialize()\n }\n\n /**\n * Clears the transaction of all operations\n */\n reset(): this {\n this.operations = []\n return this\n }\n\n protected _add(mut: Mutation): this {\n this.operations.push(mut)\n return this\n }\n}\n\n/** @public */\nexport class Transaction extends BaseTransaction {\n #client?: SanityClient\n constructor(operations?: Mutation[], client?: SanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): Transaction {\n return new Transaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning a promise that resolves to the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the transaction, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Promise<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Performs a patch on the given selection. Can either be a builder function or an object of patch operations.\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(patch: MutationSelection, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - Patch to execute\n */\n patch(patch: Patch): this\n patch(\n patchOrDocumentId: Patch | MutationSelection | string,\n patchOps?: PatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch = typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof Patch\n const isMutationSelection =\n typeof patchOrDocumentId === 'object' &&\n ('query' in patchOrDocumentId || 'id' in patchOrDocumentId)\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof Patch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n /**\n * transaction.patch(\n * {query: \"*[_type == 'person' && points >= $threshold]\", params: { threshold: 100 }},\n * {dec: { points: 100 }, inc: { bonuses: 1 }}\n * )\n */\n if (isMutationSelection) {\n const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client)\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n\n/** @public */\nexport class ObservableTransaction extends BaseTransaction {\n #client?: ObservableSanityClient\n constructor(operations?: Mutation[], client?: ObservableSanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): ObservableTransaction {\n return new ObservableTransaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning an observable that produces the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the transaction, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Observable<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: ObservablePatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - ObservablePatch to execute\n */\n patch(patch: ObservablePatch): this\n patch(\n patchOrDocumentId: ObservablePatch | string,\n patchOps?: ObservablePatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch =\n typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof ObservablePatch\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof ObservablePatch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n","import type {RequestOptions} from 'get-it'\n\nimport type {Any} from '../types'\n\nconst projectHeader = 'X-Sanity-Project-ID'\n\nexport function requestOptions(config: Any, overrides: Any = {}): Omit<RequestOptions, 'url'> {\n const headers: Any = {}\n\n const token = overrides.token || config.token\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n\n if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {\n headers[projectHeader] = config.projectId\n }\n\n const withCredentials = Boolean(\n typeof overrides.withCredentials === 'undefined'\n ? config.withCredentials\n : overrides.withCredentials,\n )\n\n const timeout = typeof overrides.timeout === 'undefined' ? config.timeout : overrides.timeout\n return Object.assign({}, overrides, {\n headers: Object.assign({}, headers, overrides.headers || {}),\n timeout: typeof timeout === 'undefined' ? 5 * 60 * 1000 : timeout,\n proxy: overrides.proxy || config.proxy,\n json: true,\n withCredentials,\n fetch:\n typeof overrides.fetch === 'object' && typeof config.fetch === 'object'\n ? {...config.fetch, ...overrides.fetch}\n : overrides.fetch || config.fetch,\n })\n}\n","import type {Any, ListenParams, QueryParams} from '../types'\n\nexport const encodeQueryString = ({\n query,\n params = {},\n options = {},\n}: {\n query: string\n params?: ListenParams | QueryParams\n options?: Any\n}) => {\n const searchParams = new URLSearchParams()\n // We generally want tag at the start of the query string\n const {tag, includeMutations, returnQuery, ...opts} = options\n // We're using `append` instead of `set` to support React Native: https://github.com/facebook/react-native/blob/1982c4722fcc51aa87e34cf562672ee4aff540f1/packages/react-native/Libraries/Blob/URL.js#L86-L88\n if (tag) searchParams.append('tag', tag)\n searchParams.append('query', query)\n\n // Iterate params, the keys are prefixed with `$` and their values JSON stringified\n for (const [key, value] of Object.entries(params)) {\n searchParams.append(`$${key}`, JSON.stringify(value))\n }\n // Options are passed as-is\n for (const [key, value] of Object.entries(opts)) {\n // Skip falsy values\n if (value) searchParams.append(key, `${value}`)\n }\n\n // `returnQuery` is default `true`, so needs an explicit `false` handling\n if (returnQuery === false) searchParams.append('returnQuery', 'false')\n\n // `includeMutations` is default `true`, so needs an explicit `false` handling\n if (includeMutations === false) searchParams.append('includeMutations', 'false')\n\n return `?${searchParams}`\n}\n","import {from, type MonoTypeOperatorFunction, Observable} from 'rxjs'\nimport {combineLatestWith, filter, map} from 'rxjs/operators'\n\nimport {validateApiPerspective} from '../config'\nimport {requestOptions} from '../http/requestOptions'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {stegaClean} from '../stega/stegaClean'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n HttpRequestEvent,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n InitializedStegaConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n QueryOptions,\n RawQueryResponse,\n RequestObservableOptions,\n RequestOptions,\n SanityDocument,\n SingleActionResult,\n SingleMutationResult,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport * as validate from '../validators'\nimport * as validators from '../validators'\nimport {printCdnPreviewDraftsWarning, printPreviewDraftsDeprecationWarning} from '../warnings'\nimport {encodeQueryString} from './encodeQueryString'\nimport {ObservablePatch, Patch} from './patch'\nimport {ObservableTransaction, Transaction} from './transaction'\n\ntype Client = SanityClient | ObservableSanityClient\n\nconst excludeFalsey = (param: Any, defValue: Any) => {\n const value = typeof param === 'undefined' ? defValue : param\n return param === false ? undefined : value\n}\n\nconst getMutationQuery = (options: BaseMutationOptions = {}) => {\n return {\n dryRun: options.dryRun,\n returnIds: true,\n returnDocuments: excludeFalsey(options.returnDocuments, true),\n visibility: options.visibility || 'sync',\n autoGenerateArrayKeys: options.autoGenerateArrayKeys,\n skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation,\n }\n}\n\nconst isResponse = (event: Any) => event.type === 'response'\nconst getBody = (event: Any) => event.body\n\nconst indexBy = (docs: Any[], attr: Any) =>\n docs.reduce((indexed, doc) => {\n indexed[attr(doc)] = doc\n return indexed\n }, Object.create(null))\n\nconst getQuerySizeLimit = 11264\n\n/** @internal */\nexport function _fetch<R, Q>(\n client: Client,\n httpRequest: HttpRequest,\n _stega: InitializedStegaConfig,\n query: string,\n _params: Q = {} as Q,\n options: QueryOptions = {},\n): Observable<RawQueryResponse<R> | R> {\n const stega =\n 'stega' in options\n ? {\n ...(_stega || {}),\n ...(typeof options.stega === 'boolean' ? {enabled: options.stega} : options.stega || {}),\n }\n : _stega\n const params = stega.enabled ? stegaClean(_params) : _params\n const mapResponse =\n options.filterResponse === false ? (res: Any) => res : (res: Any) => res.result\n\n const {cache, next, ...opts} = {\n // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.\n // This is necessary in React Server Components to avoid opting out of Request Memoization.\n useAbortSignal: typeof options.signal !== 'undefined',\n // Set `resultSourceMap' when stega is enabled, as it's required for encoding.\n resultSourceMap: stega.enabled ? 'withKeyArraySelector' : options.resultSourceMap,\n ...options,\n // Default to not returning the query, unless `filterResponse` is `false`,\n // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy\n returnQuery: options.filterResponse === false && options.returnQuery !== false,\n }\n const reqOpts =\n typeof cache !== 'undefined' || typeof next !== 'undefined'\n ? {...opts, fetch: {cache, next}}\n : opts\n\n const $request = _dataRequest(client, httpRequest, 'query', {query, params}, reqOpts)\n return stega.enabled\n ? $request.pipe(\n combineLatestWith(\n from(\n import('../stega/stegaEncodeSourceMap').then(\n ({stegaEncodeSourceMap}) => stegaEncodeSourceMap,\n ),\n ),\n ),\n map(\n ([res, stegaEncodeSourceMap]: [\n Any,\n (typeof import('../stega/stegaEncodeSourceMap'))['stegaEncodeSourceMap'],\n ]) => {\n const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega)\n return mapResponse({...res, result})\n },\n ),\n )\n : $request.pipe(map(mapResponse))\n}\n\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<SanityDocument<R> | undefined> {\n const options = {\n uri: _getDataUrl(client, 'doc', id),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<SanityDocument<R> | undefined>(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => event.body.documents && event.body.documents[0]),\n )\n}\n\n/** @internal */\nexport function _getDocuments<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n ids: string[],\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<(SanityDocument<R> | null)[]> {\n const options = {\n uri: _getDataUrl(client, 'doc', ids.join(',')),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<(SanityDocument<R> | null)[]>(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event: Any) => {\n const indexed = indexBy(event.body.documents || [], (doc: Any) => doc._id)\n return ids.map((id) => indexed[id] || null)\n }),\n )\n}\n\n/** @internal */\nexport function _createIfNotExists<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createIfNotExists', doc)\n return _create<R>(client, httpRequest, doc, 'createIfNotExists', options)\n}\n\n/** @internal */\nexport function _createOrReplace<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createOrReplace', doc)\n return _create<R>(client, httpRequest, doc, 'createOrReplace', options)\n}\n\n/** @internal */\nexport function _delete<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n return _dataRequest(\n client,\n httpRequest,\n 'mutate',\n {mutations: [{delete: getSelection(selection)}]},\n options,\n )\n}\n\n/** @internal */\nexport function _mutate<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n mutations: Mutation<R>[] | Patch | ObservablePatch | Transaction | ObservableTransaction,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n let mut: Mutation | Mutation[]\n if (mutations instanceof Patch || mutations instanceof ObservablePatch) {\n mut = {patch: mutations.serialize()}\n } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {\n mut = mutations.serialize()\n } else {\n mut = mutations\n }\n\n const muts = Array.isArray(mut) ? mut : [mut]\n const transactionId = (options && options.transactionId) || undefined\n return _dataRequest(client, httpRequest, 'mutate', {mutations: muts, transactionId}, options)\n}\n\n/**\n * @internal\n */\nexport function _action(\n client: Client,\n httpRequest: HttpRequest,\n actions: Action | Action[],\n options?: BaseActionOptions,\n): Observable<SingleActionResult | MultipleActionResult> {\n const acts = Array.isArray(actions) ? actions : [actions]\n const transactionId = (options && options.transactionId) || undefined\n const skipCrossDatasetReferenceValidation =\n (options && options.skipCrossDatasetReferenceValidation) || undefined\n const dryRun = (options && options.dryRun) || undefined\n\n return _dataRequest(\n client,\n httpRequest,\n 'actions',\n {actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun},\n options,\n )\n}\n\n/**\n * @internal\n */\nexport function _dataRequest(\n client: Client,\n httpRequest: HttpRequest,\n endpoint: string,\n body: Any,\n options: Any = {},\n): Any {\n const isMutation = endpoint === 'mutate'\n const isAction = endpoint === 'actions'\n const isQuery = endpoint === 'query'\n\n // Check if the query string is within a configured threshold,\n // in which case we can use GET. Otherwise, use POST.\n const strQuery = isMutation || isAction ? '' : encodeQueryString(body)\n const useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit\n const stringQuery = useGet ? strQuery : ''\n const returnFirst = options.returnFirst\n const {timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode} = options\n\n const uri = _getDataUrl(client, endpoint, stringQuery)\n\n const reqOptions = {\n method: useGet ? 'GET' : 'POST',\n uri: uri,\n json: true,\n body: useGet ? undefined : body,\n query: isMutation && getMutationQuery(options),\n timeout,\n headers,\n token,\n tag,\n returnQuery,\n perspective: options.perspective,\n resultSourceMap: options.resultSourceMap,\n lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,\n cacheMode: cacheMode,\n canUseCdn: isQuery,\n signal: options.signal,\n fetch: options.fetch,\n useAbortSignal: options.useAbortSignal,\n useCdn: options.useCdn,\n }\n\n return _requestObservable(client, httpRequest, reqOptions).pipe(\n filter(isResponse),\n map(getBody),\n map((res) => {\n if (!isMutation) {\n return res\n }\n\n // Should we return documents?\n const results = res.results || []\n if (options.returnDocuments) {\n return returnFirst\n ? results[0] && results[0].document\n : results.map((mut: Any) => mut.document)\n }\n\n // Return a reduced subset\n const key = returnFirst ? 'documentId' : 'documentIds'\n const ids = returnFirst ? results[0] && results[0].id : results.map((mut: Any) => mut.id)\n return {\n transactionId: res.transactionId,\n results: results,\n [key]: ids,\n }\n }),\n )\n}\n\n/**\n * @internal\n */\nexport function _create<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: Any,\n op: Any,\n options: Any = {},\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n const mutation = {[op]: doc}\n const opts = Object.assign({returnFirst: true, returnDocuments: true}, options)\n return _dataRequest(client, httpRequest, 'mutate', {mutations: [mutation]}, opts)\n}\n\nconst hasDataConfig = (client: Client) =>\n (client.config().dataset !== undefined && client.config().projectId !== undefined) ||\n client.config()['~experimental_resource'] !== undefined\n\nconst isQuery = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'query'))\n\nconst isMutate = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'mutate'))\n\nconst isDoc = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'doc', ''))\n\nconst isListener = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'listen'))\n\nconst isHistory = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'history', ''))\n\nconst isData = (client: Client, uri: string) =>\n uri.startsWith('/data/') ||\n isQuery(client, uri) ||\n isMutate(client, uri) ||\n isDoc(client, uri) ||\n isListener(client, uri) ||\n isHistory(client, uri)\n\n/**\n * @internal\n */\nexport function _requestObservable<R>(\n client: Client,\n httpRequest: HttpRequest,\n options: RequestObservableOptions,\n): Observable<HttpRequestEvent<R>> {\n const uri = options.url || (options.uri as string)\n const config = client.config()\n\n // If the `canUseCdn`-option is not set we detect it automatically based on the method + URL.\n // Only the /data endpoint is currently available through API-CDN.\n const canUseCdn =\n typeof options.canUseCdn === 'undefined'\n ? ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && isData(client, uri)\n : options.canUseCdn\n\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn\n\n const tag =\n options.tag && config.requestTagPrefix\n ? [config.requestTagPrefix, options.tag].join('.')\n : options.tag || config.requestTagPrefix\n\n if (tag && options.tag !== null) {\n options.query = {tag: validate.requestTag(tag), ...options.query}\n }\n\n // GROQ query-only parameters\n if (['GET', 'HEAD', 'POST'].indexOf(options.method || 'GET') >= 0 && isQuery(client, uri)) {\n const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap\n if (resultSourceMap !== undefined && resultSourceMap !== false) {\n options.query = {resultSourceMap, ...options.query}\n }\n const perspectiveOption = options.perspective || config.perspective\n if (typeof perspectiveOption !== 'undefined') {\n if (perspectiveOption === 'previewDrafts') {\n printPreviewDraftsDeprecationWarning()\n }\n validateApiPerspective(perspectiveOption)\n options.query = {\n perspective: Array.isArray(perspectiveOption)\n ? perspectiveOption.join(',')\n : perspectiveOption,\n ...options.query,\n }\n // If the perspective is set to `drafts` or multiple perspectives we can't use the CDN, the API will throw\n if (\n ((Array.isArray(perspectiveOption) && perspectiveOption.length > 0) ||\n // previewDrafts was renamed to drafts, but keep for backwards compat\n perspectiveOption === 'previewDrafts' ||\n perspectiveOption === 'drafts') &&\n useCdn\n ) {\n useCdn = false\n printCdnPreviewDraftsWarning()\n }\n }\n\n if (options.lastLiveEventId) {\n options.query = {...options.query, lastLiveEventId: options.lastLiveEventId}\n }\n\n if (options.returnQuery === false) {\n options.query = {returnQuery: 'false', ...options.query}\n }\n\n if (useCdn && options.cacheMode == 'noStale') {\n options.query = {cacheMode: 'noStale', ...options.query}\n }\n }\n\n const reqOptions = requestOptions(\n config,\n Object.assign({}, options, {\n url: _getUrl(client, uri, useCdn),\n }),\n ) as RequestOptions\n\n const request = new Observable<HttpRequestEvent<R>>((subscriber) =>\n httpRequest(reqOptions, config.requester!).subscribe(subscriber),\n )\n\n return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request\n}\n\n/**\n * @internal\n */\nexport function _request<R>(client: Client, httpRequest: HttpRequest, options: Any): Observable<R> {\n const observable = _requestObservable<R>(client, httpRequest, options).pipe(\n filter((event: Any) => event.type === 'response'),\n map((event: Any) => event.body),\n )\n\n return observable\n}\n\n/**\n * @internal\n */\nexport function _getDataUrl(client: Client, operation: string, path?: string): string {\n const config = client.config()\n if (config['~experimental_resource']) {\n validators.resourceConfig(config)\n const resourceBase = resourceDataBase(config)\n const uri = path !== undefined ? `${operation}/${path}` : operation\n return `${resourceBase}/${uri}`.replace(/\\/($|\\?)/, '$1')\n }\n const catalog = validators.hasDataset(config)\n const baseUri = `/${operation}/${catalog}`\n const uri = path !== undefined ? `${baseUri}/${path}` : baseUri\n return `/data${uri}`.replace(/\\/($|\\?)/, '$1')\n}\n\n/**\n * @internal\n */\nexport function _getUrl(client: Client, uri: string, canUseCdn = false): string {\n const {url, cdnUrl} = client.config()\n const base = canUseCdn ? cdnUrl : url\n return `${base}/${uri.replace(/^\\//, '')}`\n}\n\n/**\n * @internal\n */\nfunction _withAbortSignal<T>(signal: AbortSignal): MonoTypeOperatorFunction<T> {\n return (input) => {\n return new Observable((observer) => {\n const abort = () => observer.error(_createAbortError(signal))\n\n if (signal && signal.aborted) {\n abort()\n return\n }\n const subscription = input.subscribe(observer)\n signal.addEventListener('abort', abort)\n return () => {\n signal.removeEventListener('abort', abort)\n subscription.unsubscribe()\n }\n })\n }\n}\n// DOMException is supported on most modern browsers and Node.js 18+.\n// @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException#browser_compatibility\nconst isDomExceptionSupported = Boolean(globalThis.DOMException)\n\n/**\n * @internal\n * @param signal\n * Original source copied from https://github.com/sindresorhus/ky/blob/740732c78aad97e9aec199e9871bdbf0ae29b805/source/errors/DOMException.ts\n * TODO: When targeting Node.js 18, use `signal.throwIfAborted()` (https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted)\n */\nfunction _createAbortError(signal?: AbortSignal) {\n /*\n NOTE: Use DomException with AbortError name as specified in MDN docs (https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)\n > When abort() is called, the fetch() promise rejects with an Error of type DOMException, with name AbortError.\n */\n if (isDomExceptionSupported) {\n return new DOMException(signal?.reason ?? 'The operation was aborted.', 'AbortError')\n }\n\n // DOMException not supported. Fall back to use of error and override name.\n const error = new Error(signal?.reason ?? 'The operation was aborted.')\n error.name = 'AbortError'\n\n return error\n}\n\nconst resourceDataBase = (config: InitializedClientConfig): string => {\n if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_resource']\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset ID must be in the format \"project.dataset\"')\n }\n return `/projects/${segments[0]}/datasets/${segments[1]}`\n }\n case 'canvas': {\n return `/canvases/${id}`\n }\n case 'media-library': {\n return `/media-libraries/${id}`\n }\n case 'dashboard': {\n return `/dashboards/${id}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport {_requestObservable} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n HttpRequest,\n HttpRequestEvent,\n InitializedClientConfig,\n ResponseEvent,\n SanityAssetDocument,\n SanityImageAssetDocument,\n UploadBody,\n UploadClientConfig,\n} from '../types'\nimport * as validators from '../validators'\n\n/** @internal */\nexport class ObservableAssetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument}>>\n\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityImageAssetDocument}>>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n return _upload(this.#client, this.#httpRequest, assetType, body, options)\n }\n}\n\n/** @internal */\nexport class AssetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument>\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityImageAssetDocument>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument> {\n const observable = _upload(this.#client, this.#httpRequest, assetType, body, options)\n return lastValueFrom(\n observable.pipe(\n filter((event: Any) => event.type === 'response'),\n map(\n (event) =>\n (event as ResponseEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>)\n .body.document,\n ),\n ),\n )\n }\n}\n\nfunction _upload(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n assetType: 'image' | 'file',\n body: UploadBody,\n opts: UploadClientConfig = {},\n): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n validators.validateAssetType(assetType)\n\n // If an empty array is given, explicitly set `none` to override API defaults\n let meta = opts.extract || undefined\n if (meta && !meta.length) {\n meta = ['none']\n }\n\n const config = client.config()\n const options = optionsFromFile(opts, body)\n const {tag, label, title, description, creditLine, filename, source} = options\n const query: Any = {\n label,\n title,\n description,\n filename,\n meta,\n creditLine,\n }\n if (source) {\n query.sourceId = source.id\n query.sourceName = source.name\n query.sourceUrl = source.url\n }\n\n return _requestObservable(client, httpRequest, {\n tag,\n method: 'POST',\n timeout: options.timeout || 0,\n uri: buildAssetUploadUrl(config, assetType),\n headers: options.contentType ? {'Content-Type': options.contentType} : {},\n query,\n body,\n })\n}\n\nfunction buildAssetUploadUrl(config: InitializedClientConfig, assetType: 'image' | 'file'): string {\n const assetTypeEndpoint = assetType === 'image' ? 'images' : 'files'\n\n if (config['~experimental_resource']) {\n const {type, id} = config['~experimental_resource']\n switch (type) {\n case 'dataset': {\n throw new Error(\n 'Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.',\n )\n }\n case 'canvas': {\n return `/canvases/${id}/assets/${assetTypeEndpoint}`\n }\n case 'media-library': {\n return `/media-libraries/${id}/upload`\n }\n case 'dashboard': {\n return `/dashboards/${id}/assets/${assetTypeEndpoint}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n }\n\n const dataset = validators.hasDataset(config)\n return `assets/${assetTypeEndpoint}/${dataset}`\n}\n\nfunction optionsFromFile(opts: Record<string, Any>, file: Any) {\n if (typeof File === 'undefined' || !(file instanceof File)) {\n return opts\n }\n\n return Object.assign(\n {\n filename: opts.preserveFilename === false ? undefined : file.name,\n contentType: file.type,\n },\n opts,\n )\n}\n","import type {Any} from '../types'\n\nexport default (obj: Any, defaults: Any) =>\n Object.keys(defaults)\n .concat(Object.keys(obj))\n .reduce((target, prop) => {\n target[prop] = typeof obj[prop] === 'undefined' ? defaults[prop] : obj[prop]\n\n return target\n }, {} as Any)\n","import {type Any} from '../types'\n\nexport const pick = (obj: Any, props: Any) =>\n props.reduce((selection: Any, prop: Any) => {\n if (typeof obj[prop] === 'undefined') {\n return selection\n }\n\n selection[prop] = obj[prop]\n return selection\n }, {})\n","import {defer, shareReplay} from 'rxjs'\nimport {map} from 'rxjs/operators'\n\nexport const eventSourcePolyfill = defer(() => import('@sanity/eventsource')).pipe(\n map(({default: EventSource}) => EventSource as unknown as typeof globalThis.EventSource),\n shareReplay(1),\n)\n","import {\n catchError,\n concat,\n mergeMap,\n Observable,\n of,\n type OperatorFunction,\n throwError,\n timer,\n} from 'rxjs'\n\nimport {ConnectionFailedError} from './eventsource'\n\n/**\n * Note: connection failure is not the same as network disconnect which may happen more frequent.\n * The EventSource instance will automatically reconnect in case of a network disconnect, however,\n * in some rare cases a ConnectionFailed Error will be thrown and this operator explicitly retries these\n */\nexport function reconnectOnConnectionFailure<T>(): OperatorFunction<T, T | {type: 'reconnect'}> {\n return function (source: Observable<T>) {\n return source.pipe(\n catchError((err, caught) => {\n if (err instanceof ConnectionFailedError) {\n return concat(of({type: 'reconnect' as const}), timer(1000).pipe(mergeMap(() => caught)))\n }\n return throwError(() => err)\n }),\n )\n }\n}\n","import {Observable, of, throwError} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {\n type Any,\n type ListenEvent,\n type ListenOptions,\n type ListenParams,\n type MutationEvent,\n} from '../types'\nimport defaults from '../util/defaults'\nimport {pick} from '../util/pick'\nimport {_getDataUrl} from './dataMethods'\nimport {encodeQueryString} from './encodeQueryString'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\n// Limit is 16K for a _request_, eg including headers. Have to account for an\n// unknown range of headers, but an average EventSource request from Chrome seems\n// to have around 700 bytes of cruft, so let us account for 1.2K to be \"safe\"\nconst MAX_URL_LENGTH = 16000 - 1200\n\nconst possibleOptions = [\n 'includePreviousRevision',\n 'includeResult',\n 'includeMutations',\n 'includeAllVersions',\n 'visibility',\n 'effectFormat',\n 'tag',\n]\n\nconst defaultOptions = {\n includeResult: true,\n}\n\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n): Observable<MutationEvent<R>>\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n options?: ListenOptions,\n): Observable<ListenEvent<R>>\n/** @public */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n opts: ListenOptions = {},\n): Observable<MutationEvent<R> | ListenEvent<R>> {\n const {url, token, withCredentials, requestTagPrefix} = this.config()\n const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join('.') : opts.tag\n const options = {...defaults(opts, defaultOptions), tag}\n const listenOpts = pick(options, possibleOptions)\n const qs = encodeQueryString({query, params, options: {tag, ...listenOpts}})\n\n const uri = `${url}${_getDataUrl(this, 'listen', qs)}`\n if (uri.length > MAX_URL_LENGTH) {\n return throwError(() => new Error('Query too large for listener'))\n }\n\n const listenFor = options.events ? options.events : ['mutation']\n\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (withCredentials) {\n esOptions.withCredentials = true\n }\n\n if (token) {\n esOptions.headers = {\n Authorization: `Bearer ${token}`,\n }\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(uri, esOptions)))\n\n return connectEventSource(initEventSource, listenFor).pipe(\n reconnectOnConnectionFailure(),\n filter((event) => listenFor.includes(event.type)),\n map(\n (event) =>\n ({\n type: event.type,\n ...('data' in event ? (event.data as object) : {}),\n }) as MutationEvent<R> | ListenEvent<R>,\n ),\n )\n}\n","import {\n finalize,\n merge,\n type MonoTypeOperatorFunction,\n Observable,\n share,\n type ShareConfig,\n tap,\n} from 'rxjs'\n\nexport type ShareReplayLatestConfig<T> = ShareConfig<T> & {predicate: (value: T) => boolean}\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param predicate - Predicate function to determine which value to replay\n */\nexport function shareReplayLatest<T>(predicate: (value: T) => boolean): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param config - ShareConfig with additional predicate function\n */\nexport function shareReplayLatest<T>(\n config: ShareReplayLatestConfig<T>,\n): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param configOrPredicate - Predicate function to determine which value to replay\n * @param config - Optional ShareConfig\n */\nexport function shareReplayLatest<T>(\n configOrPredicate: ShareReplayLatestConfig<T> | ShareReplayLatestConfig<T>['predicate'],\n config?: ShareConfig<T>,\n) {\n return _shareReplayLatest(\n typeof configOrPredicate === 'function'\n ? {predicate: configOrPredicate, ...config}\n : configOrPredicate,\n )\n}\nfunction _shareReplayLatest<T>(config: ShareReplayLatestConfig<T>): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => {\n let latest: T | undefined\n let emitted = false\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const {predicate, ...shareConfig} = config\n\n const wrapped = source.pipe(\n tap((value) => {\n if (config.predicate(value)) {\n emitted = true\n latest = value\n }\n }),\n finalize(() => {\n emitted = false\n latest = undefined\n }),\n share(shareConfig),\n )\n const emitLatest = new Observable<T>((subscriber) => {\n if (emitted) {\n subscriber.next(\n // this cast is safe because of the emitted check which asserts that we got T from the source\n latest as T,\n )\n }\n subscriber.complete()\n })\n return merge(wrapped, emitLatest)\n }\n}\n","import {catchError, concat, EMPTY, mergeMap, Observable, of} from 'rxjs'\nimport {finalize, map} from 'rxjs/operators'\n\nimport {CorsOriginError} from '../http/errors'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n LiveEvent,\n LiveEventGoAway,\n LiveEventMessage,\n LiveEventReconnect,\n LiveEventRestart,\n LiveEventWelcome,\n SyncTag,\n} from '../types'\nimport {shareReplayLatest} from '../util/shareReplayLatest'\nimport * as validate from '../validators'\nimport {_getDataUrl} from './dataMethods'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\nconst requiredApiVersion = '2021-03-25'\n\n/**\n * @public\n */\nexport class LiveClient {\n #client: SanityClient | ObservableSanityClient\n constructor(client: SanityClient | ObservableSanityClient) {\n this.#client = client\n }\n\n /**\n * Requires `apiVersion` to be `2021-03-25` or later.\n */\n events({\n includeDrafts = false,\n tag: _tag,\n }: {\n includeDrafts?: boolean\n /**\n * Optional request tag for the listener. Use to identify the request in logs.\n *\n * @defaultValue `undefined`\n */\n tag?: string\n } = {}): Observable<LiveEvent> {\n validate.resourceGuard('live', this.#client.config())\n const {\n projectId,\n apiVersion: _apiVersion,\n token,\n withCredentials,\n requestTagPrefix,\n } = this.#client.config()\n const apiVersion = _apiVersion.replace(/^v/, '')\n if (apiVersion !== 'X' && apiVersion < requiredApiVersion) {\n throw new Error(\n `The live events API requires API version ${requiredApiVersion} or later. ` +\n `The current API version is ${apiVersion}. ` +\n `Please update your API version to use this feature.`,\n )\n }\n if (includeDrafts && !token && !withCredentials) {\n throw new Error(\n `The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.`,\n )\n }\n const path = _getDataUrl(this.#client, 'live/events')\n const url = new URL(this.#client.getUrl(path, false))\n const tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join('.') : _tag\n if (tag) {\n url.searchParams.set('tag', tag)\n }\n if (includeDrafts) {\n url.searchParams.set('includeDrafts', 'true')\n }\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (includeDrafts && token) {\n esOptions.headers = {\n Authorization: `Bearer ${token}`,\n }\n }\n if (includeDrafts && withCredentials) {\n esOptions.withCredentials = true\n }\n\n const key = `${url.href}::${JSON.stringify(esOptions)}`\n const existing = eventsCache.get(key)\n\n if (existing) {\n return existing\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(url.href, esOptions)))\n\n const events = connectEventSource(initEventSource, [\n 'message',\n 'restart',\n 'welcome',\n 'reconnect',\n 'goaway',\n ]).pipe(\n reconnectOnConnectionFailure(),\n map((event) => {\n if (event.type === 'message') {\n const {data, ...rest} = event\n // Splat data properties from the eventsource message onto the returned event\n return {...rest, tags: (data as {tags: SyncTag[]}).tags} as LiveEventMessage\n }\n return event as LiveEventRestart | LiveEventReconnect | LiveEventWelcome | LiveEventGoAway\n }),\n )\n\n // Detect if CORS is allowed, the way the CORS is checked supports preflight caching, so when the EventSource boots up it knows it sees the preflight was already made and we're good to go\n const checkCors = fetchObservable(url, {\n method: 'OPTIONS',\n mode: 'cors',\n credentials: esOptions.withCredentials ? 'include' : 'omit',\n headers: esOptions.headers,\n }).pipe(\n mergeMap(() => EMPTY),\n catchError(() => {\n // If the request fails, then we assume it was due to CORS, and we rethrow a special error that allows special handling in userland\n throw new CorsOriginError({projectId: projectId!})\n }),\n )\n const observable = concat(checkCors, events).pipe(\n finalize(() => eventsCache.delete(key)),\n shareReplayLatest({\n predicate: (event) => event.type === 'welcome',\n }),\n )\n eventsCache.set(key, observable)\n return observable\n }\n}\n\nfunction fetchObservable(url: URL, init: RequestInit) {\n return new Observable((observer) => {\n const controller = new AbortController()\n const signal = controller.signal\n fetch(url, {...init, signal: controller.signal}).then(\n (response) => {\n observer.next(response)\n observer.complete()\n },\n (err) => {\n if (!signal.aborted) {\n observer.error(err)\n }\n },\n )\n return () => controller.abort()\n })\n}\n\nconst eventsCache = new Map<string, Observable<LiveEvent>>()\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {DatasetAclMode, DatasetResponse, DatasetsResponse, HttpRequest} from '../types'\nimport * as validate from '../validators'\n\n/** @internal */\nexport class ObservableDatasetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options)\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options)\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Observable<{deleted: true}> {\n return _modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name)\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Observable<DatasetsResponse> {\n return _request<DatasetsResponse>(this.#client, this.#httpRequest, {\n uri: '/datasets',\n tag: null,\n })\n }\n}\n\n/** @internal */\nexport class DatasetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options),\n )\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options),\n )\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Promise<{deleted: true}> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(_modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name))\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Promise<DatasetsResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _request<DatasetsResponse>(this.#client, this.#httpRequest, {uri: '/datasets', tag: null}),\n )\n }\n}\n\nfunction _modify<R = unknown>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n method: 'DELETE' | 'PATCH' | 'PUT',\n name: string,\n options?: {aclMode?: DatasetAclMode},\n) {\n validate.resourceGuard('dataset', client.config())\n validate.dataset(name)\n return _request<R>(client, httpRequest, {\n method,\n uri: `/datasets/${name}`,\n body: options,\n tag: null,\n })\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {HttpRequest, SanityProject} from '../types'\nimport * as validate from '../validators'\n\n/** @internal */\nexport class ObservableProjectsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * @param options.includeMembers - Whether to include members in the response (default: true)\n */\n list(options?: {includeMembers?: true}): Observable<SanityProject[]>\n list(options?: {includeMembers?: false}): Observable<Omit<SanityProject, 'members'>[]>\n list(options?: {\n includeMembers?: boolean\n }): Observable<SanityProject[] | Omit<SanityProject, 'members'>[]> {\n validate.resourceGuard('projects', this.#client.config())\n const uri = options?.includeMembers === false ? '/projects?includeMembers=false' : '/projects'\n return _request<SanityProject[]>(this.#client, this.#httpRequest, {uri})\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Observable<SanityProject> {\n validate.resourceGuard('projects', this.#client.config())\n return _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`})\n }\n}\n\n/** @internal */\nexport class ProjectsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * @param options.includeMembers - Whether to include members in the response (default: true)\n */\n list(options?: {includeMembers?: true}): Promise<SanityProject[]>\n list(options?: {includeMembers?: false}): Promise<Omit<SanityProject, 'members'>[]>\n list(options?: {includeMembers?: boolean}): Promise<SanityProject[]> {\n validate.resourceGuard('projects', this.#client.config())\n const uri = options?.includeMembers === false ? '/projects?includeMembers=false' : '/projects'\n return lastValueFrom(_request<SanityProject[]>(this.#client, this.#httpRequest, {uri}))\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Promise<SanityProject> {\n validate.resourceGuard('projects', this.#client.config())\n return lastValueFrom(\n _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`}),\n )\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {CurrentSanityUser, HttpRequest, SanityUser} from '../types'\n\n/** @public */\nexport class ObservableUsersClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return _request<T extends 'me' ? CurrentSanityUser : SanityUser>(\n this.#client,\n this.#httpRequest,\n {uri: `/users/${id}`},\n )\n }\n}\n\n/** @public */\nexport class UsersClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Promise<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return lastValueFrom(\n _request<T extends 'me' ? CurrentSanityUser : SanityUser>(this.#client, this.#httpRequest, {\n uri: `/users/${id}`,\n }),\n )\n }\n}\n","import {lastValueFrom, Observable} from 'rxjs'\n\nimport {AssetsClient, ObservableAssetsClient} from './assets/AssetsClient'\nimport {defaultConfig, initConfig} from './config'\nimport * as dataMethods from './data/dataMethods'\nimport {_listen} from './data/listen'\nimport {LiveClient} from './data/live'\nimport {ObservablePatch, Patch} from './data/patch'\nimport {ObservableTransaction, Transaction} from './data/transaction'\nimport {DatasetsClient, ObservableDatasetsClient} from './datasets/DatasetsClient'\nimport {ObservableProjectsClient, ProjectsClient} from './projects/ProjectsClient'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n ClientConfig,\n ClientReturn,\n FilteredResponseQueryOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n PatchSelection,\n QueryOptions,\n QueryParams,\n QueryWithoutParams,\n RawQuerylessQueryResponse,\n RawQueryResponse,\n RawRequestOptions,\n SanityDocument,\n SanityDocumentStub,\n SingleActionResult,\n SingleMutationResult,\n UnfilteredResponseQueryOptions,\n UnfilteredResponseWithoutQuery,\n} from './types'\nimport {ObservableUsersClient, UsersClient} from './users/UsersClient'\n\nexport type {\n _listen,\n AssetsClient,\n DatasetsClient,\n LiveClient,\n ObservableAssetsClient,\n ObservableDatasetsClient,\n ObservableProjectsClient,\n ObservableUsersClient,\n ProjectsClient,\n UsersClient,\n}\n\n/** @public */\nexport class ObservableSanityClient {\n assets: ObservableAssetsClient\n datasets: ObservableDatasetsClient\n live: LiveClient\n projects: ObservableProjectsClient\n users: ObservableUsersClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new ObservableAssetsClient(this, this.#httpRequest)\n this.datasets = new ObservableDatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.projects = new ObservableProjectsClient(this, this.#httpRequest)\n this.users = new ObservableUsersClient(this, this.#httpRequest)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): ObservableSanityClient {\n return new ObservableSanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): ObservableSanityClient {\n const thisConfig = this.config()\n return new ObservableSanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: string,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Observable<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Observable<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Observable<RawQueryResponse<R> | R> {\n return dataMethods._fetch<R, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {tag?: string},\n ): Observable<SanityDocument<R> | undefined> {\n return dataMethods._getDocument<R>(this, this.#httpRequest, id, options)\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {tag?: string},\n ): Observable<(SanityDocument<R> | null)[]> {\n return dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options)\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._create<R>(this, this.#httpRequest, document, 'create', options)\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._delete<R>(this, this.#httpRequest, selection, options)\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns an observable that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._mutate<R>(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: PatchSelection, operations?: PatchOperations): ObservablePatch {\n return new ObservablePatch(selection, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): ObservableTransaction {\n return new ObservableTransaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n return dataMethods._action(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Perform an HTTP request against the Sanity API\n *\n * @param options - Request options\n */\n request<R = Any>(options: RawRequestOptions): Observable<R> {\n return dataMethods._request(this, this.#httpRequest, options)\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n\n/** @public */\nexport class SanityClient {\n assets: AssetsClient\n datasets: DatasetsClient\n live: LiveClient\n projects: ProjectsClient\n users: UsersClient\n\n /**\n * Observable version of the Sanity client, with the same configuration as the promise-based one\n */\n observable: ObservableSanityClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new AssetsClient(this, this.#httpRequest)\n this.datasets = new DatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.projects = new ProjectsClient(this, this.#httpRequest)\n this.users = new UsersClient(this, this.#httpRequest)\n\n this.observable = new ObservableSanityClient(httpRequest, config)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): SanityClient {\n return new SanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n if (this.observable) {\n this.observable.config(newConfig)\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): SanityClient {\n const thisConfig = this.config()\n return new SanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Promise<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>> | ClientReturn<G, R>> {\n return lastValueFrom(\n dataMethods._fetch<ClientReturn<G, R>, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n ),\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<SanityDocument<R> | undefined> {\n return lastValueFrom(dataMethods._getDocument<R>(this, this.#httpRequest, id, options))\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<(SanityDocument<R> | null)[]> {\n return lastValueFrom(dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options))\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._create<R>(this, this.#httpRequest, document, 'create', options),\n )\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._delete<R>(this, this.#httpRequest, selection, options))\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns a promise that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._mutate<R>(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: PatchSelection, operations?: PatchOperations): Patch {\n return new Patch(documentId, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): Transaction {\n return new Transaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n * Returns a promise that resolves to the transaction result\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n return lastValueFrom(dataMethods._action(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Perform a request against the Sanity API\n * NOTE: Only use this for Sanity API endpoints, not for your own APIs!\n *\n * @param options - Request options\n * @returns Promise resolving to the response body\n */\n request<R = Any>(options: RawRequestOptions): Promise<R> {\n return lastValueFrom(dataMethods._request<R>(this, this.#httpRequest, options))\n }\n\n /**\n * Perform an HTTP request a `/data` sub-endpoint\n * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.\n *\n * @deprecated - Use `request()` or your own HTTP library instead\n * @param endpoint - Endpoint to hit (mutate, query etc)\n * @param body - Request body\n * @param options - Request options\n * @internal\n */\n dataRequest(endpoint: string, body: unknown, options?: BaseMutationOptions): Promise<Any> {\n return lastValueFrom(dataMethods._dataRequest(this, this.#httpRequest, endpoint, body, options))\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n","import type {Middlewares} from 'get-it'\n\nimport {defineHttpRequest} from './http/request'\nimport type {Any, ClientConfig, HttpRequest} from './types'\n\nexport {validateApiPerspective} from './config'\nexport {\n ChannelError,\n connectEventSource,\n ConnectionFailedError,\n DisconnectError,\n type EventSourceEvent,\n type EventSourceInstance,\n MessageError,\n MessageParseError,\n type ServerSentEvent,\n} from './data/eventsource'\nexport * from './data/patch'\nexport * from './data/transaction'\nexport {ClientError, CorsOriginError, ServerError} from './http/errors'\nexport * from './SanityClient'\nexport * from './types'\n\n/** @alpha */\nexport {adapter as unstable__adapter, environment as unstable__environment} from 'get-it'\n\n/**\n * Create the `requester` and `createClient` exports, that have environment specific middleware for node and browsers\n * @internal\n */\nexport default function defineCreateClientExports<\n SanityClientType,\n ClientConfigType extends ClientConfig,\n>(\n envMiddleware: Middlewares,\n ClassConstructor: new (httpRequest: HttpRequest, config: ClientConfigType) => SanityClientType,\n) {\n // Set the http client to use for requests, and its environment specific middleware\n const defaultRequester = defineHttpRequest(envMiddleware)\n\n const createClient = (config: ClientConfigType) => {\n const clientRequester = defineHttpRequest(envMiddleware)\n return new ClassConstructor(\n (options, requester) =>\n (requester || clientRequester)({\n maxRedirects: 0,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n ...options,\n } as Any),\n config,\n )\n }\n\n return {requester: defaultRequester, createClient}\n}\n","import {printNoDefaultExport} from './warnings'\n\n/* @internal */\nexport function defineDeprecatedCreateClient<SanityClientType, ClientConfigType>(\n createClient: (config: ClientConfigType) => SanityClientType,\n) {\n return function deprecatedCreateClient(config: ClientConfigType) {\n printNoDefaultExport()\n return createClient(config)\n }\n}\n","import {agent, debug, headers} from 'get-it/middleware'\n\nimport {name, version} from '../../package.json'\n\nconst middleware = [\n debug({verbose: true, namespace: 'sanity:client'}),\n headers({'User-Agent': `${name} ${version}`}),\n\n // Enable keep-alive, and in addition limit the number of sockets that can be opened.\n // This avoids opening too many connections to the server if someone tries to execute\n // a bunch of requests in parallel. It's recommended to have a concurrency limit\n // at a \"higher limit\" (i.e. you shouldn't actually execute hundreds of requests in parallel),\n // and this is mainly to minimize the impact for the network and server.\n //\n // We're currently matching the same defaults as browsers:\n // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op\n agent({\n keepAlive: true,\n maxSockets: 30,\n maxTotalSockets: 256,\n }),\n]\n\nexport default middleware\n","import defineCreateClientExports, {type ClientConfig, SanityClient} from './defineCreateClient'\nimport {defineDeprecatedCreateClient} from './defineDeprecatedCreateClient'\nimport envMiddleware from './http/nodeMiddleware'\n\nexport * from './defineCreateClient'\n\nconst exp = defineCreateClientExports<SanityClient, ClientConfig>(envMiddleware, SanityClient)\n\n/** @public */\nexport const requester = exp.requester\n\n/**\n * @remarks\n * As of API version `v2025-02-19`, the default perspective used by the client has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}\n * @public\n */\nexport const createClient = exp.createClient\n\n/**\n * @public\n * @deprecated Use the named export `createClient` instead of the `default` export\n */\nconst deprecatedCreateClient = defineDeprecatedCreateClient(createClient)\nexport default deprecatedCreateClient\n"],"names":["isQuery","merge","validators.validateObject","validators.requireDocumentId","validators.validateDocumentId","headers","validate.requestTag","validators.resourceConfig","uri","validators.hasDataset","observable","validators.validateAssetType","dataset","defaults","EventSource","validate.resourceGuard","finalize","name","validate.dataset","dataMethods._fetch","dataMethods._getDocument","dataMethods._getDocuments","dataMethods._create","dataMethods._createIfNotExists","dataMethods._createOrReplace","dataMethods._delete","dataMethods._mutate","dataMethods._action","dataMethods._request","dataMethods._getUrl","dataMethods._getDataUrl","dataMethods._dataRequest","requester","createClient","envMiddleware"],"mappings":";;;;;;;AAKO,MAAM,oBAAoB,MAAM;AAAA,EACrC;AAAA,EACA,aAAuC;AAAA,EACvC;AAAA,EACA;AAAA,EAEA,YAAY,KAAU;AACd,UAAA,QAAQ,kBAAkB,GAAG;AACnC,UAAM,MAAM,OAAO,GACnB,OAAO,OAAO,MAAM,KAAK;AAAA,EAAA;AAE7B;AAGO,MAAM,oBAAoB,MAAM;AAAA,EACrC;AAAA,EACA,aAAuC;AAAA,EACvC;AAAA,EACA;AAAA,EAEA,YAAY,KAAU;AACd,UAAA,QAAQ,kBAAkB,GAAG;AACnC,UAAM,MAAM,OAAO,GACnB,OAAO,OAAO,MAAM,KAAK;AAAA,EAAA;AAE7B;AAE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kBAAkB,kBAAkB,aAAa;AACvD,WAAO,IAAI;AAAA,MACT,CAAC,SAASE,gBACPA,cAAa,iBAAiB;AAAA,QAC7B,cAAc;AAAA,QACd,YAAY,OAAO;AAAA,QACnB,YAAY,OAAO;AAAA,QACnB,GAAG;AAAA,MAAA,CACG;AAAA,MACV;AAAA,IACF;AAAA,EAAA,EAG+C;AACnD;ACpDO,SAAS,6BACdC,eACA;AACA,SAAO,SAAgC,QAA0B;AAC1C,WAAA,qBAAA,GACdA,cAAa,MAAM;AAAA,EAC5B;AACF;;ACNA,MAAM,aAAa;AAAA,EACjB,MAAM,EAAC,SAAS,IAAM,WAAW,iBAAgB;AAAA,EACjD,QAAQ,EAAC,cAAc,GAAG,IAAI,IAAI,OAAO,IAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU5C,MAAM;AAAA,IACJ,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,iBAAiB;AAAA,EAClB,CAAA;AACH,GCfM,MAAM,0BAAsDC,YAAe,YAAY,GAGhF,YAAY,IAAI,WAOhB,eAAe,IAAI,cAM1B,yBAAyB,6BAA6B,YAAY;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/http/errors.ts","../src/http/request.ts","../src/data/eventsource.ts","../src/util/getSelection.ts","../src/data/patch.ts","../src/data/transaction.ts","../src/http/requestOptions.ts","../src/data/encodeQueryString.ts","../src/data/dataMethods.ts","../src/assets/AssetsClient.ts","../src/util/defaults.ts","../src/util/pick.ts","../src/data/eventsourcePolyfill.ts","../src/data/reconnectOnConnectionFailure.ts","../src/data/listen.ts","../src/util/shareReplayLatest.ts","../src/data/live.ts","../src/datasets/DatasetsClient.ts","../src/projects/ProjectsClient.ts","../src/users/UsersClient.ts","../src/SanityClient.ts","../src/defineCreateClient.ts","../src/defineDeprecatedCreateClient.ts","../src/http/nodeMiddleware.ts","../src/index.ts"],"sourcesContent":["import type {ActionError, Any, ErrorProps, MutationError} from '../types'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\n\n/** @public */\nexport class ClientError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 400\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\n/** @public */\nexport class ServerError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 500\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\nfunction extractErrorProps(res: Any): ErrorProps {\n const body = res.body\n const props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n message: '',\n details: undefined as Any,\n }\n\n // API/Boom style errors ({statusCode, error, message})\n if (body.error && body.message) {\n props.message = `${body.error} - ${body.message}`\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(body) || isActionError(body)) {\n const allItems = body.error.items || []\n const items = allItems\n .slice(0, MAX_ITEMS_IN_ERROR_MESSAGE)\n .map((item) => item.error?.description)\n .filter(Boolean)\n let itemsStr = items.length ? `:\\n- ${items.join('\\n- ')}` : ''\n if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {\n itemsStr += `\\n...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`\n }\n props.message = `${body.error.description}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query/database errors ({error: {description, other, arb, props}})\n if (body.error && body.error.description) {\n props.message = body.error.description\n props.details = body.error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = body.error || body.message || httpErrorMessage(res)\n return props\n}\n\nfunction isMutationError(body: Any): body is MutationError {\n return (\n isPlainObject(body) &&\n isPlainObject(body.error) &&\n body.error.type === 'mutationError' &&\n typeof body.error.description === 'string'\n )\n}\n\nfunction isActionError(body: Any): body is ActionError {\n return (\n isPlainObject(body) &&\n isPlainObject(body.error) &&\n body.error.type === 'actionError' &&\n typeof body.error.description === 'string'\n )\n}\n\nfunction isPlainObject(obj: Any): obj is Record<string, unknown> {\n return typeof obj === 'object' && obj !== null && !Array.isArray(obj)\n}\n\nfunction httpErrorMessage(res: Any) {\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`\n}\n\nfunction stringifyBody(body: Any, res: Any) {\n const contentType = (res.headers['content-type'] || '').toLowerCase()\n const isJson = contentType.indexOf('application/json') !== -1\n return isJson ? JSON.stringify(body, null, 2) : body\n}\n\n/** @public */\nexport class CorsOriginError extends Error {\n projectId: string\n addOriginUrl?: URL\n\n constructor({projectId}: {projectId: string}) {\n super('CorsOriginError')\n this.name = 'CorsOriginError'\n this.projectId = projectId\n\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n if (typeof location !== 'undefined') {\n const {origin} = location\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n this.addOriginUrl = url\n this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`\n } else {\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`\n }\n }\n}\n","import {getIt, type Middlewares, type Requester} from 'get-it'\nimport {jsonRequest, jsonResponse, observable, progress, retry} from 'get-it/middleware'\nimport {Observable} from 'rxjs'\n\nimport type {Any} from '../types'\nimport {ClientError, ServerError} from './errors'\n\nconst httpError = {\n onResponse: (res: Any) => {\n if (res.statusCode >= 500) {\n throw new ServerError(res)\n } else if (res.statusCode >= 400) {\n throw new ClientError(res)\n }\n\n return res\n },\n}\n\nfunction printWarnings() {\n const seen: Record<string, boolean> = {}\n return {\n onResponse: (res: Any) => {\n const warn = res.headers['x-sanity-warning']\n const warnings = Array.isArray(warn) ? warn : [warn]\n for (const msg of warnings) {\n if (!msg || seen[msg]) continue\n seen[msg] = true\n console.warn(msg) // eslint-disable-line no-console\n }\n return res\n },\n }\n}\n\n/** @internal */\nexport function defineHttpRequest(envMiddleware: Middlewares): Requester {\n return getIt([\n retry({shouldRetry}),\n ...envMiddleware,\n printWarnings(),\n jsonRequest(),\n jsonResponse(),\n progress(),\n httpError,\n observable({implementation: Observable}),\n ])\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction shouldRetry(err: any, attempt: number, options: any) {\n // Allow opting out of retries\n if (options.maxRetries === 0) return false\n\n // By default `retry.shouldRetry` doesn't retry on server errors so we add our own logic.\n\n const isSafe = options.method === 'GET' || options.method === 'HEAD'\n const uri = options.uri || options.url\n const isQuery = uri.startsWith('/data/query')\n const isRetriableResponse =\n err.response &&\n (err.response.statusCode === 429 ||\n err.response.statusCode === 502 ||\n err.response.statusCode === 503)\n\n // We retry the following errors:\n // - 429 means that the request was rate limited. It's a bit difficult\n // to know exactly how long it makes sense to wait and/or how many\n // attempts we should retry, but the backoff should alleviate the\n // additional load.\n // - 502/503 can occur when certain components struggle to talk to their\n // upstream dependencies. This is most likely a temporary problem\n // and retrying makes sense.\n\n if ((isSafe || isQuery) && isRetriableResponse) return true\n\n return retry.shouldRetry(err, attempt, options)\n}\n","import {defer, isObservable, mergeMap, Observable, of} from 'rxjs'\n\nimport {type Any} from '../types'\n\n/**\n * @public\n * Thrown if the EventSource connection could not be established.\n * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.\n */\nexport class ConnectionFailedError extends Error {\n readonly name = 'ConnectionFailedError'\n}\n\n/**\n * The listener has been told to explicitly disconnect.\n * This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n * eg in the case of a deleted dataset, a blocked project or similar events.\n * @public\n */\nexport class DisconnectError extends Error {\n readonly name = 'DisconnectError'\n readonly reason?: string\n constructor(message: string, reason?: string, options: ErrorOptions = {}) {\n super(message, options)\n this.reason = reason\n }\n}\n\n/**\n * @public\n * The server sent a `channelError` message. Usually indicative of a bad or malformed request\n */\nexport class ChannelError extends Error {\n readonly name = 'ChannelError'\n readonly data?: unknown\n constructor(message: string, data: unknown) {\n super(message)\n this.data = data\n }\n}\n\n/**\n * @public\n * The server sent an `error`-event to tell the client that an unexpected error has happened.\n */\nexport class MessageError extends Error {\n readonly name = 'MessageError'\n readonly data?: unknown\n constructor(message: string, data: unknown, options: ErrorOptions = {}) {\n super(message, options)\n this.data = data\n }\n}\n\n/**\n * @public\n * An error occurred while parsing the message sent by the server as JSON. Should normally not happen.\n */\nexport class MessageParseError extends Error {\n readonly name = 'MessageParseError'\n}\n\n/**\n * @public\n */\nexport interface ServerSentEvent<Name extends string> {\n type: Name\n id?: string\n data?: unknown\n}\n\n// Always listen for these events, no matter what\nconst REQUIRED_EVENTS = ['channelError', 'disconnect']\n\n/**\n * @internal\n */\nexport type EventSourceEvent<Name extends string> = ServerSentEvent<Name>\n\n/**\n * @internal\n */\nexport type EventSourceInstance = InstanceType<typeof globalThis.EventSource>\n\n/**\n * Sanity API specific EventSource handler shared between the listen and live APIs\n *\n * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance\n * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers)\n * via the passed `initEventSource` function which must return an EventSource instance.\n *\n * Possible errors to be thrown on the returned observable are:\n * - {@link MessageError}\n * - {@link MessageParseError}\n * - {@link ChannelError}\n * - {@link DisconnectError}\n * - {@link ConnectionFailedError}\n *\n * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance\n * @param events - an array of named events from the API to listen for.\n *\n * @internal\n */\nexport function connectEventSource<EventName extends string>(\n initEventSource: () => EventSourceInstance | Observable<EventSourceInstance>,\n events: EventName[],\n) {\n return defer(() => {\n const es = initEventSource()\n return isObservable(es) ? es : of(es)\n }).pipe(mergeMap((es) => connectWithESInstance(es, events))) as Observable<\n ServerSentEvent<EventName>\n >\n}\n\n/**\n * Provides an observable from the passed EventSource instance, subscribing to the passed list of names of events types to listen for\n * Handles connection logic, adding/removing event listeners, payload parsing, error propagation, etc.\n *\n * @param es - The EventSource instance\n * @param events - List of event names to listen for\n */\nfunction connectWithESInstance<EventTypeName extends string>(\n es: EventSourceInstance,\n events: EventTypeName[],\n) {\n return new Observable<EventSourceEvent<EventTypeName>>((observer) => {\n const emitOpen = (events as string[]).includes('open')\n const emitReconnect = (events as string[]).includes('reconnect')\n\n // EventSource will emit a regular Event if it fails to connect, however the API may also emit an `error` MessageEvent\n // So we need to handle both cases\n function onError(evt: MessageEvent | Event) {\n // If the event has a `data` property, then it`s a MessageEvent emitted by the API and we should forward the error\n if ('data' in evt) {\n const [parseError, event] = parseEvent(evt as MessageEvent)\n observer.error(\n parseError\n ? new MessageParseError('Unable to parse EventSource error message', {cause: event})\n : new MessageError((event?.data as {message: string}).message, event),\n )\n return\n }\n\n // We should never be in a disconnected state. By default, EventSource will reconnect\n // automatically, but in some cases (like when a laptop lid is closed), it will trigger onError\n // if it can't reconnect.\n // see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model\n if (es.readyState === es.CLOSED) {\n // In these cases we'll signal to consumers (via the error path) that a retry/reconnect is needed.\n observer.error(new ConnectionFailedError('EventSource connection failed'))\n } else if (emitReconnect) {\n observer.next({type: 'reconnect' as EventTypeName})\n }\n }\n\n function onOpen() {\n // The open event of the EventSource API is fired when a connection with an event source is opened.\n observer.next({type: 'open' as EventTypeName})\n }\n\n function onMessage(message: MessageEvent) {\n const [parseError, event] = parseEvent(message)\n if (parseError) {\n observer.error(\n new MessageParseError('Unable to parse EventSource message', {cause: parseError}),\n )\n return\n }\n if (message.type === 'channelError') {\n // An error occurred. This is different from a network-level error (which will be emitted as 'error').\n // Possible causes are things such as malformed filters, non-existant datasets or similar.\n observer.error(new ChannelError(extractErrorMessage(event?.data), event.data))\n return\n }\n if (message.type === 'disconnect') {\n // The listener has been told to explicitly disconnect and not reconnect.\n // This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n // eg in the case of a deleted dataset, a blocked project or similar events.\n observer.error(\n new DisconnectError(\n `Server disconnected client: ${\n (event.data as {reason?: string})?.reason || 'unknown error'\n }`,\n ),\n )\n return\n }\n observer.next({\n type: message.type as EventTypeName,\n id: message.lastEventId,\n ...(event.data ? {data: event.data} : {}),\n })\n }\n\n es.addEventListener('error', onError)\n\n if (emitOpen) {\n es.addEventListener('open', onOpen)\n }\n\n // Make sure we have a unique list of events types to avoid listening multiple times,\n const cleanedEvents = [...new Set([...REQUIRED_EVENTS, ...events])]\n // filter out events that are handled separately\n .filter((type) => type !== 'error' && type !== 'open' && type !== 'reconnect')\n\n cleanedEvents.forEach((type: string) => es.addEventListener(type, onMessage))\n\n return () => {\n es.removeEventListener('error', onError)\n if (emitOpen) {\n es.removeEventListener('open', onOpen)\n }\n cleanedEvents.forEach((type: string) => es.removeEventListener(type, onMessage))\n es.close()\n }\n })\n}\n\nfunction parseEvent(\n message: MessageEvent,\n): [null, {type: string; id: string; data?: unknown}] | [Error, null] {\n try {\n const data = typeof message.data === 'string' && JSON.parse(message.data)\n return [\n null,\n {\n type: message.type,\n id: message.lastEventId,\n ...(isEmptyObject(data) ? {} : {data}),\n },\n ]\n } catch (err) {\n return [err as Error, null]\n }\n}\n\nfunction extractErrorMessage(err: Any) {\n if (!err.error) {\n return err.message || 'Unknown listener error'\n }\n\n if (err.error.description) {\n return err.error.description\n }\n\n return typeof err.error === 'string' ? err.error : JSON.stringify(err.error, null, 2)\n}\n\nfunction isEmptyObject(data: object) {\n for (const _ in data) {\n return false\n }\n return true\n}\n","import type {MutationSelection} from '../types'\n\nexport function getSelection(sel: unknown): MutationSelection {\n if (typeof sel === 'string') {\n return {id: sel}\n }\n\n if (Array.isArray(sel)) {\n return {query: '*[_id in $ids]', params: {ids: sel}}\n }\n\n if (typeof sel === 'object' && sel !== null && 'query' in sel && typeof sel.query === 'string') {\n return 'params' in sel && typeof sel.params === 'object' && sel.params !== null\n ? {query: sel.query, params: sel.params}\n : {query: sel.query}\n }\n\n const selectionOpts = [\n '* Document ID (<docId>)',\n '* Array of document IDs',\n '* Object containing `query`',\n ].join('\\n')\n\n throw new Error(`Unknown selection - must be one of:\\n\\n${selectionOpts}`)\n}\n","import {type Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n AttributeSet,\n BaseMutationOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n MultipleMutationResult,\n PatchMutationOperation,\n PatchOperations,\n PatchSelection,\n SanityDocument,\n SingleMutationResult,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport {validateInsert, validateObject} from '../validators'\n\n/** @internal */\nexport class BasePatch {\n protected selection: PatchSelection\n protected operations: PatchOperations\n constructor(selection: PatchSelection, operations: PatchOperations = {}) {\n this.selection = selection\n this.operations = operations\n }\n\n /**\n * Sets the given attributes to the document. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n set(attrs: AttributeSet): this {\n return this._assign('set', attrs)\n }\n\n /**\n * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n setIfMissing(attrs: AttributeSet): this {\n return this._assign('setIfMissing', attrs)\n }\n\n /**\n * Performs a \"diff-match-patch\" operation on the string attributes provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"dmp\"\\}\n */\n diffMatchPatch(attrs: AttributeSet): this {\n validateObject('diffMatchPatch', attrs)\n return this._assign('diffMatchPatch', attrs)\n }\n\n /**\n * Unsets the attribute paths provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attribute paths to unset.\n */\n unset(attrs: string[]): this {\n if (!Array.isArray(attrs)) {\n throw new Error('unset(attrs) takes an array of attributes to unset, non-array given')\n }\n\n this.operations = Object.assign({}, this.operations, {unset: attrs})\n return this\n }\n\n /**\n * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to increment, values representing the number to increment by.\n */\n inc(attrs: {[key: string]: number}): this {\n return this._assign('inc', attrs)\n }\n\n /**\n * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.\n */\n dec(attrs: {[key: string]: number}): this {\n return this._assign('dec', attrs)\n }\n\n /**\n * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.\n *\n * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path\n * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key==\"abc123\"]`\n * @param items - Array of items to insert/replace\n */\n insert(at: 'before' | 'after' | 'replace', selector: string, items: Any[]): this {\n validateInsert(at, selector, items)\n return this._assign('insert', {[at]: selector, items})\n }\n\n /**\n * Append the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`\n * @param items - Array of items to append to the array\n */\n append(selector: string, items: Any[]): this {\n return this.insert('after', `${selector}[-1]`, items)\n }\n\n /**\n * Prepend the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`\n * @param items - Array of items to prepend to the array\n */\n prepend(selector: string, items: Any[]): this {\n return this.insert('before', `${selector}[0]`, items)\n }\n\n /**\n * Change the contents of an array by removing existing elements and/or adding new elements.\n *\n * @param selector - Attribute or JSONPath expression for array\n * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x\n * @param deleteCount - An integer indicating the number of old array elements to remove.\n * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.\n */\n splice(selector: string, start: number, deleteCount?: number, items?: Any[]): this {\n // Negative indexes doesn't mean the same in Sanity as they do in JS;\n // -1 means \"actually at the end of the array\", which allows inserting\n // at the end of the array without knowing its length. We therefore have\n // to substract negative indexes by one to match JS. If you want Sanity-\n // behaviour, just use `insert('replace', selector, items)` directly\n const delAll = typeof deleteCount === 'undefined' || deleteCount === -1\n const startIndex = start < 0 ? start - 1 : start\n const delCount = delAll ? -1 : Math.max(0, start + deleteCount)\n const delRange = startIndex < 0 && delCount >= 0 ? '' : delCount\n const rangeSelector = `${selector}[${startIndex}:${delRange}]`\n return this.insert('replace', rangeSelector, items || [])\n }\n\n /**\n * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value\n *\n * @param rev - Revision to lock the patch to\n */\n ifRevisionId(rev: string): this {\n this.operations.ifRevisionID = rev\n return this\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n serialize(): PatchMutationOperation {\n return {...getSelection(this.selection), ...this.operations}\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n toJSON(): PatchMutationOperation {\n return this.serialize()\n }\n\n /**\n * Clears the patch of all operations\n */\n reset(): this {\n this.operations = {}\n return this\n }\n\n protected _assign(op: keyof PatchOperations, props: Any, merge = true): this {\n validateObject(op, props)\n this.operations = Object.assign({}, this.operations, {\n [op]: Object.assign({}, (merge && this.operations[op]) || {}, props),\n })\n return this\n }\n\n protected _set(op: keyof PatchOperations, props: Any): this {\n return this._assign(op, props, false)\n }\n}\n\n/** @public */\nexport class ObservablePatch extends BasePatch {\n #client?: ObservableSanityClient\n\n constructor(\n selection: PatchSelection,\n operations?: PatchOperations,\n client?: ObservableSanityClient,\n ) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): ObservablePatch {\n return new ObservablePatch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the patch, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n\n/** @public */\nexport class Patch extends BasePatch {\n #client?: SanityClient\n constructor(selection: PatchSelection, operations?: PatchOperations, client?: SanityClient) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): Patch {\n return new Patch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the patch, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n","import type {Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n BaseMutationOptions,\n IdentifiedSanityDocumentStub,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n SanityDocument,\n SanityDocumentStub,\n SingleMutationResult,\n TransactionAllDocumentIdsMutationOptions,\n TransactionAllDocumentsMutationOptions,\n TransactionFirstDocumentIdMutationOptions,\n TransactionFirstDocumentMutationOptions,\n} from '../types'\nimport * as validators from '../validators'\nimport {ObservablePatch, Patch} from './patch'\n\n/** @public */\nexport type PatchBuilder = (patch: Patch) => Patch\n/** @public */\nexport type ObservablePatchBuilder = (patch: ObservablePatch) => ObservablePatch\n\nconst defaultMutateOptions = {returnDocuments: false}\n\n/** @internal */\nexport class BaseTransaction {\n protected operations: Mutation[]\n protected trxId?: string\n constructor(operations: Mutation[] = [], transactionId?: string) {\n this.operations = operations\n this.trxId = transactionId\n }\n /**\n * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create. Requires a `_type` property.\n */\n create<R extends Record<string, Any> = Record<string, Any>>(doc: SanityDocumentStub<R>): this {\n validators.validateObject('create', doc)\n return this._add({create: doc})\n }\n\n /**\n * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createIfNotExists'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create or replace. Requires `_id` and `_type` properties.\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createOrReplace'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Deletes the document with the given document ID\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to delete\n */\n delete(documentId: string): this {\n validators.validateDocumentId('delete', documentId)\n return this._add({delete: {id: documentId}})\n }\n\n /**\n * Gets the current transaction ID, if any\n */\n transactionId(): string | undefined\n /**\n * Set the ID of this transaction.\n *\n * @param id - Transaction ID\n */\n transactionId(id: string): this\n transactionId(id?: string): this | string | undefined {\n if (!id) {\n return this.trxId\n }\n\n this.trxId = id\n return this\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n serialize(): Mutation[] {\n return [...this.operations]\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n toJSON(): Mutation[] {\n return this.serialize()\n }\n\n /**\n * Clears the transaction of all operations\n */\n reset(): this {\n this.operations = []\n return this\n }\n\n protected _add(mut: Mutation): this {\n this.operations.push(mut)\n return this\n }\n}\n\n/** @public */\nexport class Transaction extends BaseTransaction {\n #client?: SanityClient\n constructor(operations?: Mutation[], client?: SanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): Transaction {\n return new Transaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning a promise that resolves to the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the transaction, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Promise<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Performs a patch on the given selection. Can either be a builder function or an object of patch operations.\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(patch: MutationSelection, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - Patch to execute\n */\n patch(patch: Patch): this\n patch(\n patchOrDocumentId: Patch | MutationSelection | string,\n patchOps?: PatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch = typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof Patch\n const isMutationSelection =\n typeof patchOrDocumentId === 'object' &&\n ('query' in patchOrDocumentId || 'id' in patchOrDocumentId)\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof Patch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n /**\n * transaction.patch(\n * {query: \"*[_type == 'person' && points >= $threshold]\", params: { threshold: 100 }},\n * {dec: { points: 100 }, inc: { bonuses: 1 }}\n * )\n */\n if (isMutationSelection) {\n const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client)\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n\n/** @public */\nexport class ObservableTransaction extends BaseTransaction {\n #client?: ObservableSanityClient\n constructor(operations?: Mutation[], client?: ObservableSanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): ObservableTransaction {\n return new ObservableTransaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning an observable that produces the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the transaction, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Observable<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: ObservablePatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - ObservablePatch to execute\n */\n patch(patch: ObservablePatch): this\n patch(\n patchOrDocumentId: ObservablePatch | string,\n patchOps?: ObservablePatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch =\n typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof ObservablePatch\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof ObservablePatch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n","import type {RequestOptions} from 'get-it'\n\nimport type {Any} from '../types'\n\nconst projectHeader = 'X-Sanity-Project-ID'\n\nexport function requestOptions(config: Any, overrides: Any = {}): Omit<RequestOptions, 'url'> {\n const headers: Any = {}\n\n const token = overrides.token || config.token\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n\n if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {\n headers[projectHeader] = config.projectId\n }\n\n const withCredentials = Boolean(\n typeof overrides.withCredentials === 'undefined'\n ? config.withCredentials\n : overrides.withCredentials,\n )\n\n const timeout = typeof overrides.timeout === 'undefined' ? config.timeout : overrides.timeout\n return Object.assign({}, overrides, {\n headers: Object.assign({}, headers, overrides.headers || {}),\n timeout: typeof timeout === 'undefined' ? 5 * 60 * 1000 : timeout,\n proxy: overrides.proxy || config.proxy,\n json: true,\n withCredentials,\n fetch:\n typeof overrides.fetch === 'object' && typeof config.fetch === 'object'\n ? {...config.fetch, ...overrides.fetch}\n : overrides.fetch || config.fetch,\n })\n}\n","import type {Any, ListenParams, QueryParams} from '../types'\n\nexport const encodeQueryString = ({\n query,\n params = {},\n options = {},\n}: {\n query: string\n params?: ListenParams | QueryParams\n options?: Any\n}) => {\n const searchParams = new URLSearchParams()\n // We generally want tag at the start of the query string\n const {tag, includeMutations, returnQuery, ...opts} = options\n // We're using `append` instead of `set` to support React Native: https://github.com/facebook/react-native/blob/1982c4722fcc51aa87e34cf562672ee4aff540f1/packages/react-native/Libraries/Blob/URL.js#L86-L88\n if (tag) searchParams.append('tag', tag)\n searchParams.append('query', query)\n\n // Iterate params, the keys are prefixed with `$` and their values JSON stringified\n for (const [key, value] of Object.entries(params)) {\n searchParams.append(`$${key}`, JSON.stringify(value))\n }\n // Options are passed as-is\n for (const [key, value] of Object.entries(opts)) {\n // Skip falsy values\n if (value) searchParams.append(key, `${value}`)\n }\n\n // `returnQuery` is default `true`, so needs an explicit `false` handling\n if (returnQuery === false) searchParams.append('returnQuery', 'false')\n\n // `includeMutations` is default `true`, so needs an explicit `false` handling\n if (includeMutations === false) searchParams.append('includeMutations', 'false')\n\n return `?${searchParams}`\n}\n","import {from, type MonoTypeOperatorFunction, Observable} from 'rxjs'\nimport {combineLatestWith, filter, map} from 'rxjs/operators'\n\nimport {validateApiPerspective} from '../config'\nimport {requestOptions} from '../http/requestOptions'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {stegaClean} from '../stega/stegaClean'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n HttpRequestEvent,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n InitializedStegaConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n QueryOptions,\n RawQueryResponse,\n RequestObservableOptions,\n RequestOptions,\n SanityDocument,\n SingleActionResult,\n SingleMutationResult,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport * as validate from '../validators'\nimport * as validators from '../validators'\nimport {printCdnPreviewDraftsWarning, printPreviewDraftsDeprecationWarning} from '../warnings'\nimport {encodeQueryString} from './encodeQueryString'\nimport {ObservablePatch, Patch} from './patch'\nimport {ObservableTransaction, Transaction} from './transaction'\n\ntype Client = SanityClient | ObservableSanityClient\n\nconst excludeFalsey = (param: Any, defValue: Any) => {\n const value = typeof param === 'undefined' ? defValue : param\n return param === false ? undefined : value\n}\n\nconst getMutationQuery = (options: BaseMutationOptions = {}) => {\n return {\n dryRun: options.dryRun,\n returnIds: true,\n returnDocuments: excludeFalsey(options.returnDocuments, true),\n visibility: options.visibility || 'sync',\n autoGenerateArrayKeys: options.autoGenerateArrayKeys,\n skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation,\n }\n}\n\nconst isResponse = (event: Any) => event.type === 'response'\nconst getBody = (event: Any) => event.body\n\nconst indexBy = (docs: Any[], attr: Any) =>\n docs.reduce((indexed, doc) => {\n indexed[attr(doc)] = doc\n return indexed\n }, Object.create(null))\n\nconst getQuerySizeLimit = 11264\n\n/** @internal */\nexport function _fetch<R, Q>(\n client: Client,\n httpRequest: HttpRequest,\n _stega: InitializedStegaConfig,\n query: string,\n _params: Q = {} as Q,\n options: QueryOptions = {},\n): Observable<RawQueryResponse<R> | R> {\n const stega =\n 'stega' in options\n ? {\n ...(_stega || {}),\n ...(typeof options.stega === 'boolean' ? {enabled: options.stega} : options.stega || {}),\n }\n : _stega\n const params = stega.enabled ? stegaClean(_params) : _params\n const mapResponse =\n options.filterResponse === false ? (res: Any) => res : (res: Any) => res.result\n\n const {cache, next, ...opts} = {\n // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.\n // This is necessary in React Server Components to avoid opting out of Request Memoization.\n useAbortSignal: typeof options.signal !== 'undefined',\n // Set `resultSourceMap' when stega is enabled, as it's required for encoding.\n resultSourceMap: stega.enabled ? 'withKeyArraySelector' : options.resultSourceMap,\n ...options,\n // Default to not returning the query, unless `filterResponse` is `false`,\n // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy\n returnQuery: options.filterResponse === false && options.returnQuery !== false,\n }\n const reqOpts =\n typeof cache !== 'undefined' || typeof next !== 'undefined'\n ? {...opts, fetch: {cache, next}}\n : opts\n\n const $request = _dataRequest(client, httpRequest, 'query', {query, params}, reqOpts)\n return stega.enabled\n ? $request.pipe(\n combineLatestWith(\n from(\n import('../stega/stegaEncodeSourceMap').then(\n ({stegaEncodeSourceMap}) => stegaEncodeSourceMap,\n ),\n ),\n ),\n map(\n ([res, stegaEncodeSourceMap]: [\n Any,\n (typeof import('../stega/stegaEncodeSourceMap'))['stegaEncodeSourceMap'],\n ]) => {\n const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega)\n return mapResponse({...res, result})\n },\n ),\n )\n : $request.pipe(map(mapResponse))\n}\n\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<SanityDocument<R> | undefined> {\n const options = {\n uri: _getDataUrl(client, 'doc', id),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<SanityDocument<R> | undefined>(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => event.body.documents && event.body.documents[0]),\n )\n}\n\n/** @internal */\nexport function _getDocuments<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n ids: string[],\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<(SanityDocument<R> | null)[]> {\n const options = {\n uri: _getDataUrl(client, 'doc', ids.join(',')),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<(SanityDocument<R> | null)[]>(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event: Any) => {\n const indexed = indexBy(event.body.documents || [], (doc: Any) => doc._id)\n return ids.map((id) => indexed[id] || null)\n }),\n )\n}\n\n/** @internal */\nexport function _createIfNotExists<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createIfNotExists', doc)\n return _create<R>(client, httpRequest, doc, 'createIfNotExists', options)\n}\n\n/** @internal */\nexport function _createOrReplace<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createOrReplace', doc)\n return _create<R>(client, httpRequest, doc, 'createOrReplace', options)\n}\n\n/** @internal */\nexport function _delete<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n return _dataRequest(\n client,\n httpRequest,\n 'mutate',\n {mutations: [{delete: getSelection(selection)}]},\n options,\n )\n}\n\n/** @internal */\nexport function _mutate<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n mutations: Mutation<R>[] | Patch | ObservablePatch | Transaction | ObservableTransaction,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n let mut: Mutation | Mutation[]\n if (mutations instanceof Patch || mutations instanceof ObservablePatch) {\n mut = {patch: mutations.serialize()}\n } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {\n mut = mutations.serialize()\n } else {\n mut = mutations\n }\n\n const muts = Array.isArray(mut) ? mut : [mut]\n const transactionId = (options && options.transactionId) || undefined\n return _dataRequest(client, httpRequest, 'mutate', {mutations: muts, transactionId}, options)\n}\n\n/**\n * @internal\n */\nexport function _action(\n client: Client,\n httpRequest: HttpRequest,\n actions: Action | Action[],\n options?: BaseActionOptions,\n): Observable<SingleActionResult | MultipleActionResult> {\n const acts = Array.isArray(actions) ? actions : [actions]\n const transactionId = (options && options.transactionId) || undefined\n const skipCrossDatasetReferenceValidation =\n (options && options.skipCrossDatasetReferenceValidation) || undefined\n const dryRun = (options && options.dryRun) || undefined\n\n return _dataRequest(\n client,\n httpRequest,\n 'actions',\n {actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun},\n options,\n )\n}\n\n/**\n * @internal\n */\nexport function _dataRequest(\n client: Client,\n httpRequest: HttpRequest,\n endpoint: string,\n body: Any,\n options: Any = {},\n): Any {\n const isMutation = endpoint === 'mutate'\n const isAction = endpoint === 'actions'\n const isQuery = endpoint === 'query'\n\n // Check if the query string is within a configured threshold,\n // in which case we can use GET. Otherwise, use POST.\n const strQuery = isMutation || isAction ? '' : encodeQueryString(body)\n const useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit\n const stringQuery = useGet ? strQuery : ''\n const returnFirst = options.returnFirst\n const {timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode} = options\n\n const uri = _getDataUrl(client, endpoint, stringQuery)\n\n const reqOptions = {\n method: useGet ? 'GET' : 'POST',\n uri: uri,\n json: true,\n body: useGet ? undefined : body,\n query: isMutation && getMutationQuery(options),\n timeout,\n headers,\n token,\n tag,\n returnQuery,\n perspective: options.perspective,\n resultSourceMap: options.resultSourceMap,\n lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,\n cacheMode: cacheMode,\n canUseCdn: isQuery,\n signal: options.signal,\n fetch: options.fetch,\n useAbortSignal: options.useAbortSignal,\n useCdn: options.useCdn,\n }\n\n return _requestObservable(client, httpRequest, reqOptions).pipe(\n filter(isResponse),\n map(getBody),\n map((res) => {\n if (!isMutation) {\n return res\n }\n\n // Should we return documents?\n const results = res.results || []\n if (options.returnDocuments) {\n return returnFirst\n ? results[0] && results[0].document\n : results.map((mut: Any) => mut.document)\n }\n\n // Return a reduced subset\n const key = returnFirst ? 'documentId' : 'documentIds'\n const ids = returnFirst ? results[0] && results[0].id : results.map((mut: Any) => mut.id)\n return {\n transactionId: res.transactionId,\n results: results,\n [key]: ids,\n }\n }),\n )\n}\n\n/**\n * @internal\n */\nexport function _create<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: Any,\n op: Any,\n options: Any = {},\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n const mutation = {[op]: doc}\n const opts = Object.assign({returnFirst: true, returnDocuments: true}, options)\n return _dataRequest(client, httpRequest, 'mutate', {mutations: [mutation]}, opts)\n}\n\nconst hasDataConfig = (client: Client) =>\n (client.config().dataset !== undefined && client.config().projectId !== undefined) ||\n client.config()['~experimental_resource'] !== undefined\n\nconst isQuery = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'query'))\n\nconst isMutate = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'mutate'))\n\nconst isDoc = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'doc', ''))\n\nconst isListener = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'listen'))\n\nconst isHistory = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'history', ''))\n\nconst isData = (client: Client, uri: string) =>\n uri.startsWith('/data/') ||\n isQuery(client, uri) ||\n isMutate(client, uri) ||\n isDoc(client, uri) ||\n isListener(client, uri) ||\n isHistory(client, uri)\n\n/**\n * @internal\n */\nexport function _requestObservable<R>(\n client: Client,\n httpRequest: HttpRequest,\n options: RequestObservableOptions,\n): Observable<HttpRequestEvent<R>> {\n const uri = options.url || (options.uri as string)\n const config = client.config()\n\n // If the `canUseCdn`-option is not set we detect it automatically based on the method + URL.\n // Only the /data endpoint is currently available through API-CDN.\n const canUseCdn =\n typeof options.canUseCdn === 'undefined'\n ? ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && isData(client, uri)\n : options.canUseCdn\n\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn\n\n const tag =\n options.tag && config.requestTagPrefix\n ? [config.requestTagPrefix, options.tag].join('.')\n : options.tag || config.requestTagPrefix\n\n if (tag && options.tag !== null) {\n options.query = {tag: validate.requestTag(tag), ...options.query}\n }\n\n // GROQ query-only parameters\n if (['GET', 'HEAD', 'POST'].indexOf(options.method || 'GET') >= 0 && isQuery(client, uri)) {\n const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap\n if (resultSourceMap !== undefined && resultSourceMap !== false) {\n options.query = {resultSourceMap, ...options.query}\n }\n const perspectiveOption = options.perspective || config.perspective\n if (typeof perspectiveOption !== 'undefined') {\n if (perspectiveOption === 'previewDrafts') {\n printPreviewDraftsDeprecationWarning()\n }\n validateApiPerspective(perspectiveOption)\n options.query = {\n perspective: Array.isArray(perspectiveOption)\n ? perspectiveOption.join(',')\n : perspectiveOption,\n ...options.query,\n }\n // If the perspective is set to `drafts` or multiple perspectives we can't use the CDN, the API will throw\n if (\n ((Array.isArray(perspectiveOption) && perspectiveOption.length > 0) ||\n // previewDrafts was renamed to drafts, but keep for backwards compat\n perspectiveOption === 'previewDrafts' ||\n perspectiveOption === 'drafts') &&\n useCdn\n ) {\n useCdn = false\n printCdnPreviewDraftsWarning()\n }\n }\n\n if (options.lastLiveEventId) {\n options.query = {...options.query, lastLiveEventId: options.lastLiveEventId}\n }\n\n if (options.returnQuery === false) {\n options.query = {returnQuery: 'false', ...options.query}\n }\n\n if (useCdn && options.cacheMode == 'noStale') {\n options.query = {cacheMode: 'noStale', ...options.query}\n }\n }\n\n const reqOptions = requestOptions(\n config,\n Object.assign({}, options, {\n url: _getUrl(client, uri, useCdn),\n }),\n ) as RequestOptions\n\n const request = new Observable<HttpRequestEvent<R>>((subscriber) =>\n httpRequest(reqOptions, config.requester!).subscribe(subscriber),\n )\n\n return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request\n}\n\n/**\n * @internal\n */\nexport function _request<R>(client: Client, httpRequest: HttpRequest, options: Any): Observable<R> {\n const observable = _requestObservable<R>(client, httpRequest, options).pipe(\n filter((event: Any) => event.type === 'response'),\n map((event: Any) => event.body),\n )\n\n return observable\n}\n\n/**\n * @internal\n */\nexport function _getDataUrl(client: Client, operation: string, path?: string): string {\n const config = client.config()\n if (config['~experimental_resource']) {\n validators.resourceConfig(config)\n const resourceBase = resourceDataBase(config)\n const uri = path !== undefined ? `${operation}/${path}` : operation\n return `${resourceBase}/${uri}`.replace(/\\/($|\\?)/, '$1')\n }\n const catalog = validators.hasDataset(config)\n const baseUri = `/${operation}/${catalog}`\n const uri = path !== undefined ? `${baseUri}/${path}` : baseUri\n return `/data${uri}`.replace(/\\/($|\\?)/, '$1')\n}\n\n/**\n * @internal\n */\nexport function _getUrl(client: Client, uri: string, canUseCdn = false): string {\n const {url, cdnUrl} = client.config()\n const base = canUseCdn ? cdnUrl : url\n return `${base}/${uri.replace(/^\\//, '')}`\n}\n\n/**\n * @internal\n */\nfunction _withAbortSignal<T>(signal: AbortSignal): MonoTypeOperatorFunction<T> {\n return (input) => {\n return new Observable((observer) => {\n const abort = () => observer.error(_createAbortError(signal))\n\n if (signal && signal.aborted) {\n abort()\n return\n }\n const subscription = input.subscribe(observer)\n signal.addEventListener('abort', abort)\n return () => {\n signal.removeEventListener('abort', abort)\n subscription.unsubscribe()\n }\n })\n }\n}\n// DOMException is supported on most modern browsers and Node.js 18+.\n// @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException#browser_compatibility\nconst isDomExceptionSupported = Boolean(globalThis.DOMException)\n\n/**\n * @internal\n * @param signal\n * Original source copied from https://github.com/sindresorhus/ky/blob/740732c78aad97e9aec199e9871bdbf0ae29b805/source/errors/DOMException.ts\n * TODO: When targeting Node.js 18, use `signal.throwIfAborted()` (https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted)\n */\nfunction _createAbortError(signal?: AbortSignal) {\n /*\n NOTE: Use DomException with AbortError name as specified in MDN docs (https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)\n > When abort() is called, the fetch() promise rejects with an Error of type DOMException, with name AbortError.\n */\n if (isDomExceptionSupported) {\n return new DOMException(signal?.reason ?? 'The operation was aborted.', 'AbortError')\n }\n\n // DOMException not supported. Fall back to use of error and override name.\n const error = new Error(signal?.reason ?? 'The operation was aborted.')\n error.name = 'AbortError'\n\n return error\n}\n\nconst resourceDataBase = (config: InitializedClientConfig): string => {\n if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_resource']\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset ID must be in the format \"project.dataset\"')\n }\n return `/projects/${segments[0]}/datasets/${segments[1]}`\n }\n case 'canvas': {\n return `/canvases/${id}`\n }\n case 'media-library': {\n return `/media-libraries/${id}`\n }\n case 'dashboard': {\n return `/dashboards/${id}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport {_requestObservable} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n HttpRequest,\n HttpRequestEvent,\n InitializedClientConfig,\n ResponseEvent,\n SanityAssetDocument,\n SanityImageAssetDocument,\n UploadBody,\n UploadClientConfig,\n} from '../types'\nimport * as validators from '../validators'\n\n/** @internal */\nexport class ObservableAssetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument}>>\n\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityImageAssetDocument}>>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n return _upload(this.#client, this.#httpRequest, assetType, body, options)\n }\n}\n\n/** @internal */\nexport class AssetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument>\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityImageAssetDocument>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument> {\n const observable = _upload(this.#client, this.#httpRequest, assetType, body, options)\n return lastValueFrom(\n observable.pipe(\n filter((event: Any) => event.type === 'response'),\n map(\n (event) =>\n (event as ResponseEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>)\n .body.document,\n ),\n ),\n )\n }\n}\n\nfunction _upload(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n assetType: 'image' | 'file',\n body: UploadBody,\n opts: UploadClientConfig = {},\n): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n validators.validateAssetType(assetType)\n\n // If an empty array is given, explicitly set `none` to override API defaults\n let meta = opts.extract || undefined\n if (meta && !meta.length) {\n meta = ['none']\n }\n\n const config = client.config()\n const options = optionsFromFile(opts, body)\n const {tag, label, title, description, creditLine, filename, source} = options\n const query: Any = {\n label,\n title,\n description,\n filename,\n meta,\n creditLine,\n }\n if (source) {\n query.sourceId = source.id\n query.sourceName = source.name\n query.sourceUrl = source.url\n }\n\n return _requestObservable(client, httpRequest, {\n tag,\n method: 'POST',\n timeout: options.timeout || 0,\n uri: buildAssetUploadUrl(config, assetType),\n headers: options.contentType ? {'Content-Type': options.contentType} : {},\n query,\n body,\n })\n}\n\nfunction buildAssetUploadUrl(config: InitializedClientConfig, assetType: 'image' | 'file'): string {\n const assetTypeEndpoint = assetType === 'image' ? 'images' : 'files'\n\n if (config['~experimental_resource']) {\n const {type, id} = config['~experimental_resource']\n switch (type) {\n case 'dataset': {\n throw new Error(\n 'Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.',\n )\n }\n case 'canvas': {\n return `/canvases/${id}/assets/${assetTypeEndpoint}`\n }\n case 'media-library': {\n return `/media-libraries/${id}/upload`\n }\n case 'dashboard': {\n return `/dashboards/${id}/assets/${assetTypeEndpoint}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n }\n\n const dataset = validators.hasDataset(config)\n return `assets/${assetTypeEndpoint}/${dataset}`\n}\n\nfunction optionsFromFile(opts: Record<string, Any>, file: Any) {\n if (typeof File === 'undefined' || !(file instanceof File)) {\n return opts\n }\n\n return Object.assign(\n {\n filename: opts.preserveFilename === false ? undefined : file.name,\n contentType: file.type,\n },\n opts,\n )\n}\n","import type {Any} from '../types'\n\nexport default (obj: Any, defaults: Any) =>\n Object.keys(defaults)\n .concat(Object.keys(obj))\n .reduce((target, prop) => {\n target[prop] = typeof obj[prop] === 'undefined' ? defaults[prop] : obj[prop]\n\n return target\n }, {} as Any)\n","import {type Any} from '../types'\n\nexport const pick = (obj: Any, props: Any) =>\n props.reduce((selection: Any, prop: Any) => {\n if (typeof obj[prop] === 'undefined') {\n return selection\n }\n\n selection[prop] = obj[prop]\n return selection\n }, {})\n","import {defer, shareReplay} from 'rxjs'\nimport {map} from 'rxjs/operators'\n\nexport const eventSourcePolyfill = defer(() => import('@sanity/eventsource')).pipe(\n map(({default: EventSource}) => EventSource as unknown as typeof globalThis.EventSource),\n shareReplay(1),\n)\n","import {\n catchError,\n concat,\n mergeMap,\n Observable,\n of,\n type OperatorFunction,\n throwError,\n timer,\n} from 'rxjs'\n\nimport {ConnectionFailedError} from './eventsource'\n\n/**\n * Note: connection failure is not the same as network disconnect which may happen more frequent.\n * The EventSource instance will automatically reconnect in case of a network disconnect, however,\n * in some rare cases a ConnectionFailed Error will be thrown and this operator explicitly retries these\n */\nexport function reconnectOnConnectionFailure<T>(): OperatorFunction<T, T | {type: 'reconnect'}> {\n return function (source: Observable<T>) {\n return source.pipe(\n catchError((err, caught) => {\n if (err instanceof ConnectionFailedError) {\n return concat(of({type: 'reconnect' as const}), timer(1000).pipe(mergeMap(() => caught)))\n }\n return throwError(() => err)\n }),\n )\n }\n}\n","import {Observable, of, throwError} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {\n type Any,\n type ListenEvent,\n type ListenOptions,\n type ListenParams,\n type MutationEvent,\n} from '../types'\nimport defaults from '../util/defaults'\nimport {pick} from '../util/pick'\nimport {_getDataUrl} from './dataMethods'\nimport {encodeQueryString} from './encodeQueryString'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\n// Limit is 16K for a _request_, eg including headers. Have to account for an\n// unknown range of headers, but an average EventSource request from Chrome seems\n// to have around 700 bytes of cruft, so let us account for 1.2K to be \"safe\"\nconst MAX_URL_LENGTH = 16000 - 1200\n\nconst possibleOptions = [\n 'includePreviousRevision',\n 'includeResult',\n 'includeMutations',\n 'includeAllVersions',\n 'visibility',\n 'effectFormat',\n 'tag',\n]\n\nconst defaultOptions = {\n includeResult: true,\n}\n\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n): Observable<MutationEvent<R>>\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n options?: ListenOptions,\n): Observable<ListenEvent<R>>\n/** @public */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n opts: ListenOptions = {},\n): Observable<MutationEvent<R> | ListenEvent<R>> {\n const {url, token, withCredentials, requestTagPrefix} = this.config()\n const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join('.') : opts.tag\n const options = {...defaults(opts, defaultOptions), tag}\n const listenOpts = pick(options, possibleOptions)\n const qs = encodeQueryString({query, params, options: {tag, ...listenOpts}})\n\n const uri = `${url}${_getDataUrl(this, 'listen', qs)}`\n if (uri.length > MAX_URL_LENGTH) {\n return throwError(() => new Error('Query too large for listener'))\n }\n\n const listenFor = options.events ? options.events : ['mutation']\n\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (withCredentials) {\n esOptions.withCredentials = true\n }\n\n if (token) {\n esOptions.headers = {\n Authorization: `Bearer ${token}`,\n }\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(uri, esOptions)))\n\n return connectEventSource(initEventSource, listenFor).pipe(\n reconnectOnConnectionFailure(),\n filter((event) => listenFor.includes(event.type)),\n map(\n (event) =>\n ({\n type: event.type,\n ...('data' in event ? (event.data as object) : {}),\n }) as MutationEvent<R> | ListenEvent<R>,\n ),\n )\n}\n","import {\n finalize,\n merge,\n type MonoTypeOperatorFunction,\n Observable,\n share,\n type ShareConfig,\n tap,\n} from 'rxjs'\n\nexport type ShareReplayLatestConfig<T> = ShareConfig<T> & {predicate: (value: T) => boolean}\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param predicate - Predicate function to determine which value to replay\n */\nexport function shareReplayLatest<T>(predicate: (value: T) => boolean): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param config - ShareConfig with additional predicate function\n */\nexport function shareReplayLatest<T>(\n config: ShareReplayLatestConfig<T>,\n): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param configOrPredicate - Predicate function to determine which value to replay\n * @param config - Optional ShareConfig\n */\nexport function shareReplayLatest<T>(\n configOrPredicate: ShareReplayLatestConfig<T> | ShareReplayLatestConfig<T>['predicate'],\n config?: ShareConfig<T>,\n) {\n return _shareReplayLatest(\n typeof configOrPredicate === 'function'\n ? {predicate: configOrPredicate, ...config}\n : configOrPredicate,\n )\n}\nfunction _shareReplayLatest<T>(config: ShareReplayLatestConfig<T>): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => {\n let latest: T | undefined\n let emitted = false\n\n // eslint-disable-next-line unused-imports/no-unused-vars\n const {predicate, ...shareConfig} = config\n\n const wrapped = source.pipe(\n tap((value) => {\n if (config.predicate(value)) {\n emitted = true\n latest = value\n }\n }),\n finalize(() => {\n emitted = false\n latest = undefined\n }),\n share(shareConfig),\n )\n const emitLatest = new Observable<T>((subscriber) => {\n if (emitted) {\n subscriber.next(\n // this cast is safe because of the emitted check which asserts that we got T from the source\n latest as T,\n )\n }\n subscriber.complete()\n })\n return merge(wrapped, emitLatest)\n }\n}\n","import {catchError, concat, EMPTY, mergeMap, Observable, of} from 'rxjs'\nimport {finalize, map} from 'rxjs/operators'\n\nimport {CorsOriginError} from '../http/errors'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n LiveEvent,\n LiveEventGoAway,\n LiveEventMessage,\n LiveEventReconnect,\n LiveEventRestart,\n LiveEventWelcome,\n SyncTag,\n} from '../types'\nimport {shareReplayLatest} from '../util/shareReplayLatest'\nimport * as validate from '../validators'\nimport {_getDataUrl} from './dataMethods'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\nconst requiredApiVersion = '2021-03-25'\n\n/**\n * @public\n */\nexport class LiveClient {\n #client: SanityClient | ObservableSanityClient\n constructor(client: SanityClient | ObservableSanityClient) {\n this.#client = client\n }\n\n /**\n * Requires `apiVersion` to be `2021-03-25` or later.\n */\n events({\n includeDrafts = false,\n tag: _tag,\n }: {\n includeDrafts?: boolean\n /**\n * Optional request tag for the listener. Use to identify the request in logs.\n *\n * @defaultValue `undefined`\n */\n tag?: string\n } = {}): Observable<LiveEvent> {\n validate.resourceGuard('live', this.#client.config())\n const {\n projectId,\n apiVersion: _apiVersion,\n token,\n withCredentials,\n requestTagPrefix,\n } = this.#client.config()\n const apiVersion = _apiVersion.replace(/^v/, '')\n if (apiVersion !== 'X' && apiVersion < requiredApiVersion) {\n throw new Error(\n `The live events API requires API version ${requiredApiVersion} or later. ` +\n `The current API version is ${apiVersion}. ` +\n `Please update your API version to use this feature.`,\n )\n }\n if (includeDrafts && !token && !withCredentials) {\n throw new Error(\n `The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.`,\n )\n }\n const path = _getDataUrl(this.#client, 'live/events')\n const url = new URL(this.#client.getUrl(path, false))\n const tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join('.') : _tag\n if (tag) {\n url.searchParams.set('tag', tag)\n }\n if (includeDrafts) {\n url.searchParams.set('includeDrafts', 'true')\n }\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (includeDrafts && token) {\n esOptions.headers = {\n Authorization: `Bearer ${token}`,\n }\n }\n if (includeDrafts && withCredentials) {\n esOptions.withCredentials = true\n }\n\n const key = `${url.href}::${JSON.stringify(esOptions)}`\n const existing = eventsCache.get(key)\n\n if (existing) {\n return existing\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(url.href, esOptions)))\n\n const events = connectEventSource(initEventSource, [\n 'message',\n 'restart',\n 'welcome',\n 'reconnect',\n 'goaway',\n ]).pipe(\n reconnectOnConnectionFailure(),\n map((event) => {\n if (event.type === 'message') {\n const {data, ...rest} = event\n // Splat data properties from the eventsource message onto the returned event\n return {...rest, tags: (data as {tags: SyncTag[]}).tags} as LiveEventMessage\n }\n return event as LiveEventRestart | LiveEventReconnect | LiveEventWelcome | LiveEventGoAway\n }),\n )\n\n // Detect if CORS is allowed, the way the CORS is checked supports preflight caching, so when the EventSource boots up it knows it sees the preflight was already made and we're good to go\n const checkCors = fetchObservable(url, {\n method: 'OPTIONS',\n mode: 'cors',\n credentials: esOptions.withCredentials ? 'include' : 'omit',\n headers: esOptions.headers,\n }).pipe(\n mergeMap(() => EMPTY),\n catchError(() => {\n // If the request fails, then we assume it was due to CORS, and we rethrow a special error that allows special handling in userland\n throw new CorsOriginError({projectId: projectId!})\n }),\n )\n const observable = concat(checkCors, events).pipe(\n finalize(() => eventsCache.delete(key)),\n shareReplayLatest({\n predicate: (event) => event.type === 'welcome',\n }),\n )\n eventsCache.set(key, observable)\n return observable\n }\n}\n\nfunction fetchObservable(url: URL, init: RequestInit) {\n return new Observable((observer) => {\n const controller = new AbortController()\n const signal = controller.signal\n fetch(url, {...init, signal: controller.signal}).then(\n (response) => {\n observer.next(response)\n observer.complete()\n },\n (err) => {\n if (!signal.aborted) {\n observer.error(err)\n }\n },\n )\n return () => controller.abort()\n })\n}\n\nconst eventsCache = new Map<string, Observable<LiveEvent>>()\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {DatasetAclMode, DatasetResponse, DatasetsResponse, HttpRequest} from '../types'\nimport * as validate from '../validators'\n\n/** @internal */\nexport class ObservableDatasetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options)\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options)\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Observable<{deleted: true}> {\n return _modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name)\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Observable<DatasetsResponse> {\n return _request<DatasetsResponse>(this.#client, this.#httpRequest, {\n uri: '/datasets',\n tag: null,\n })\n }\n}\n\n/** @internal */\nexport class DatasetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options),\n )\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options),\n )\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Promise<{deleted: true}> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(_modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name))\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Promise<DatasetsResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _request<DatasetsResponse>(this.#client, this.#httpRequest, {uri: '/datasets', tag: null}),\n )\n }\n}\n\nfunction _modify<R = unknown>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n method: 'DELETE' | 'PATCH' | 'PUT',\n name: string,\n options?: {aclMode?: DatasetAclMode},\n) {\n validate.resourceGuard('dataset', client.config())\n validate.dataset(name)\n return _request<R>(client, httpRequest, {\n method,\n uri: `/datasets/${name}`,\n body: options,\n tag: null,\n })\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {HttpRequest, SanityProject} from '../types'\nimport * as validate from '../validators'\n\n/** @internal */\nexport class ObservableProjectsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * @param options.includeMembers - Whether to include members in the response (default: true)\n */\n list(options?: {includeMembers?: true}): Observable<SanityProject[]>\n list(options?: {includeMembers?: false}): Observable<Omit<SanityProject, 'members'>[]>\n list(options?: {\n includeMembers?: boolean\n }): Observable<SanityProject[] | Omit<SanityProject, 'members'>[]> {\n validate.resourceGuard('projects', this.#client.config())\n const uri = options?.includeMembers === false ? '/projects?includeMembers=false' : '/projects'\n return _request<SanityProject[]>(this.#client, this.#httpRequest, {uri})\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Observable<SanityProject> {\n validate.resourceGuard('projects', this.#client.config())\n return _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`})\n }\n}\n\n/** @internal */\nexport class ProjectsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * @param options.includeMembers - Whether to include members in the response (default: true)\n */\n list(options?: {includeMembers?: true}): Promise<SanityProject[]>\n list(options?: {includeMembers?: false}): Promise<Omit<SanityProject, 'members'>[]>\n list(options?: {includeMembers?: boolean}): Promise<SanityProject[]> {\n validate.resourceGuard('projects', this.#client.config())\n const uri = options?.includeMembers === false ? '/projects?includeMembers=false' : '/projects'\n return lastValueFrom(_request<SanityProject[]>(this.#client, this.#httpRequest, {uri}))\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Promise<SanityProject> {\n validate.resourceGuard('projects', this.#client.config())\n return lastValueFrom(\n _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`}),\n )\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {CurrentSanityUser, HttpRequest, SanityUser} from '../types'\n\n/** @public */\nexport class ObservableUsersClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return _request<T extends 'me' ? CurrentSanityUser : SanityUser>(\n this.#client,\n this.#httpRequest,\n {uri: `/users/${id}`},\n )\n }\n}\n\n/** @public */\nexport class UsersClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Promise<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return lastValueFrom(\n _request<T extends 'me' ? CurrentSanityUser : SanityUser>(this.#client, this.#httpRequest, {\n uri: `/users/${id}`,\n }),\n )\n }\n}\n","import {lastValueFrom, Observable} from 'rxjs'\n\nimport {AssetsClient, ObservableAssetsClient} from './assets/AssetsClient'\nimport {defaultConfig, initConfig} from './config'\nimport * as dataMethods from './data/dataMethods'\nimport {_listen} from './data/listen'\nimport {LiveClient} from './data/live'\nimport {ObservablePatch, Patch} from './data/patch'\nimport {ObservableTransaction, Transaction} from './data/transaction'\nimport {DatasetsClient, ObservableDatasetsClient} from './datasets/DatasetsClient'\nimport {ObservableProjectsClient, ProjectsClient} from './projects/ProjectsClient'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n ClientConfig,\n ClientReturn,\n FilteredResponseQueryOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n PatchSelection,\n QueryOptions,\n QueryParams,\n QueryWithoutParams,\n RawQuerylessQueryResponse,\n RawQueryResponse,\n RawRequestOptions,\n SanityDocument,\n SanityDocumentStub,\n SingleActionResult,\n SingleMutationResult,\n UnfilteredResponseQueryOptions,\n UnfilteredResponseWithoutQuery,\n} from './types'\nimport {ObservableUsersClient, UsersClient} from './users/UsersClient'\n\nexport type {\n _listen,\n AssetsClient,\n DatasetsClient,\n LiveClient,\n ObservableAssetsClient,\n ObservableDatasetsClient,\n ObservableProjectsClient,\n ObservableUsersClient,\n ProjectsClient,\n UsersClient,\n}\n\n/** @public */\nexport class ObservableSanityClient {\n assets: ObservableAssetsClient\n datasets: ObservableDatasetsClient\n live: LiveClient\n projects: ObservableProjectsClient\n users: ObservableUsersClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new ObservableAssetsClient(this, this.#httpRequest)\n this.datasets = new ObservableDatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.projects = new ObservableProjectsClient(this, this.#httpRequest)\n this.users = new ObservableUsersClient(this, this.#httpRequest)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): ObservableSanityClient {\n return new ObservableSanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): ObservableSanityClient {\n const thisConfig = this.config()\n return new ObservableSanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: string,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Observable<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Observable<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Observable<RawQueryResponse<R> | R> {\n return dataMethods._fetch<R, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {tag?: string},\n ): Observable<SanityDocument<R> | undefined> {\n return dataMethods._getDocument<R>(this, this.#httpRequest, id, options)\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {tag?: string},\n ): Observable<(SanityDocument<R> | null)[]> {\n return dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options)\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._create<R>(this, this.#httpRequest, document, 'create', options)\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._delete<R>(this, this.#httpRequest, selection, options)\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns an observable that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._mutate<R>(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: PatchSelection, operations?: PatchOperations): ObservablePatch {\n return new ObservablePatch(selection, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): ObservableTransaction {\n return new ObservableTransaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n return dataMethods._action(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Perform an HTTP request against the Sanity API\n *\n * @param options - Request options\n */\n request<R = Any>(options: RawRequestOptions): Observable<R> {\n return dataMethods._request(this, this.#httpRequest, options)\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n\n/** @public */\nexport class SanityClient {\n assets: AssetsClient\n datasets: DatasetsClient\n live: LiveClient\n projects: ProjectsClient\n users: UsersClient\n\n /**\n * Observable version of the Sanity client, with the same configuration as the promise-based one\n */\n observable: ObservableSanityClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new AssetsClient(this, this.#httpRequest)\n this.datasets = new DatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.projects = new ProjectsClient(this, this.#httpRequest)\n this.users = new UsersClient(this, this.#httpRequest)\n\n this.observable = new ObservableSanityClient(httpRequest, config)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): SanityClient {\n return new SanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n if (this.observable) {\n this.observable.config(newConfig)\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): SanityClient {\n const thisConfig = this.config()\n return new SanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Promise<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>> | ClientReturn<G, R>> {\n return lastValueFrom(\n dataMethods._fetch<ClientReturn<G, R>, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n ),\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<SanityDocument<R> | undefined> {\n return lastValueFrom(dataMethods._getDocument<R>(this, this.#httpRequest, id, options))\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<(SanityDocument<R> | null)[]> {\n return lastValueFrom(dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options))\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._create<R>(this, this.#httpRequest, document, 'create', options),\n )\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._delete<R>(this, this.#httpRequest, selection, options))\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns a promise that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._mutate<R>(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: PatchSelection, operations?: PatchOperations): Patch {\n return new Patch(documentId, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): Transaction {\n return new Transaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n * Returns a promise that resolves to the transaction result\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n return lastValueFrom(dataMethods._action(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Perform a request against the Sanity API\n * NOTE: Only use this for Sanity API endpoints, not for your own APIs!\n *\n * @param options - Request options\n * @returns Promise resolving to the response body\n */\n request<R = Any>(options: RawRequestOptions): Promise<R> {\n return lastValueFrom(dataMethods._request<R>(this, this.#httpRequest, options))\n }\n\n /**\n * Perform an HTTP request a `/data` sub-endpoint\n * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.\n *\n * @deprecated - Use `request()` or your own HTTP library instead\n * @param endpoint - Endpoint to hit (mutate, query etc)\n * @param body - Request body\n * @param options - Request options\n * @internal\n */\n dataRequest(endpoint: string, body: unknown, options?: BaseMutationOptions): Promise<Any> {\n return lastValueFrom(dataMethods._dataRequest(this, this.#httpRequest, endpoint, body, options))\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n","import type {Middlewares} from 'get-it'\n\nimport {defineHttpRequest} from './http/request'\nimport type {Any, ClientConfig, HttpRequest} from './types'\n\nexport {validateApiPerspective} from './config'\nexport {\n ChannelError,\n connectEventSource,\n ConnectionFailedError,\n DisconnectError,\n type EventSourceEvent,\n type EventSourceInstance,\n MessageError,\n MessageParseError,\n type ServerSentEvent,\n} from './data/eventsource'\nexport * from './data/patch'\nexport * from './data/transaction'\nexport {ClientError, CorsOriginError, ServerError} from './http/errors'\nexport * from './SanityClient'\nexport * from './types'\n\n/** @alpha */\nexport {adapter as unstable__adapter, environment as unstable__environment} from 'get-it'\n\n/**\n * Create the `requester` and `createClient` exports, that have environment specific middleware for node and browsers\n * @internal\n */\nexport default function defineCreateClientExports<\n SanityClientType,\n ClientConfigType extends ClientConfig,\n>(\n envMiddleware: Middlewares,\n ClassConstructor: new (httpRequest: HttpRequest, config: ClientConfigType) => SanityClientType,\n) {\n // Set the http client to use for requests, and its environment specific middleware\n const defaultRequester = defineHttpRequest(envMiddleware)\n\n const createClient = (config: ClientConfigType) => {\n const clientRequester = defineHttpRequest(envMiddleware)\n return new ClassConstructor(\n (options, requester) =>\n (requester || clientRequester)({\n maxRedirects: 0,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n ...options,\n } as Any),\n config,\n )\n }\n\n return {requester: defaultRequester, createClient}\n}\n","import {printNoDefaultExport} from './warnings'\n\n/* @internal */\nexport function defineDeprecatedCreateClient<SanityClientType, ClientConfigType>(\n createClient: (config: ClientConfigType) => SanityClientType,\n) {\n return function deprecatedCreateClient(config: ClientConfigType) {\n printNoDefaultExport()\n return createClient(config)\n }\n}\n","import {agent, debug, headers} from 'get-it/middleware'\n\nimport {name, version} from '../../package.json'\n\nconst middleware = [\n debug({verbose: true, namespace: 'sanity:client'}),\n headers({'User-Agent': `${name} ${version}`}),\n\n // Enable keep-alive, and in addition limit the number of sockets that can be opened.\n // This avoids opening too many connections to the server if someone tries to execute\n // a bunch of requests in parallel. It's recommended to have a concurrency limit\n // at a \"higher limit\" (i.e. you shouldn't actually execute hundreds of requests in parallel),\n // and this is mainly to minimize the impact for the network and server.\n //\n // We're currently matching the same defaults as browsers:\n // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op\n agent({\n keepAlive: true,\n maxSockets: 30,\n maxTotalSockets: 256,\n }),\n]\n\nexport default middleware\n","import defineCreateClientExports, {type ClientConfig, SanityClient} from './defineCreateClient'\nimport {defineDeprecatedCreateClient} from './defineDeprecatedCreateClient'\nimport envMiddleware from './http/nodeMiddleware'\n\nexport * from './defineCreateClient'\n\nconst exp = defineCreateClientExports<SanityClient, ClientConfig>(envMiddleware, SanityClient)\n\n/** @public */\nexport const requester = exp.requester\n\n/**\n * @remarks\n * As of API version `v2025-02-19`, the default perspective used by the client has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}\n * @public\n */\nexport const createClient = exp.createClient\n\n/**\n * @public\n * @deprecated Use the named export `createClient` instead of the `default` export\n */\nconst deprecatedCreateClient = defineDeprecatedCreateClient(createClient)\nexport default deprecatedCreateClient\n"],"names":["isQuery","merge","validators.validateObject","validators.requireDocumentId","validators.validateDocumentId","headers","validate.requestTag","validators.resourceConfig","uri","validators.hasDataset","observable","validators.validateAssetType","dataset","defaults","EventSource","validate.resourceGuard","finalize","name","validate.dataset","dataMethods._fetch","dataMethods._getDocument","dataMethods._getDocuments","dataMethods._create","dataMethods._createIfNotExists","dataMethods._createOrReplace","dataMethods._delete","dataMethods._mutate","dataMethods._action","dataMethods._request","dataMethods._getUrl","dataMethods._getDataUrl","dataMethods._dataRequest","requester","createClient","envMiddleware"],"mappings":";;;;;;;AAKO,MAAM,oBAAoB,MAAM;AAAA,EACrC;AAAA,EACA,aAAuC;AAAA,EACvC;AAAA,EACA;AAAA,EAEA,YAAY,KAAU;AACd,UAAA,QAAQ,kBAAkB,GAAG;AACnC,UAAM,MAAM,OAAO,GACnB,OAAO,OAAO,MAAM,KAAK;AAAA,EAAA;AAE7B;AAGO,MAAM,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