@sanity/client 6.14.4 → 6.15.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.
@@ -1474,7 +1474,7 @@ function defineCreateClientExports(envMiddleware, ClassConstructor) {
1474
1474
  config
1475
1475
  ) };
1476
1476
  }
1477
- var name = "@sanity/client", version = "6.14.4";
1477
+ var name = "@sanity/client", version = "6.15.0";
1478
1478
  const middleware = [
1479
1479
  middleware$1.debug({ verbose: !0, namespace: "sanity:client" }),
1480
1480
  middleware$1.headers({ "User-Agent": `${name} ${version}` }),
@@ -1455,7 +1455,7 @@ function defineCreateClientExports(envMiddleware, ClassConstructor) {
1455
1455
  config
1456
1456
  ) };
1457
1457
  }
1458
- var name = "@sanity/client", version = "6.14.4";
1458
+ var name = "@sanity/client", version = "6.15.0";
1459
1459
  const middleware = [
1460
1460
  debug({ verbose: !0, namespace: "sanity:client" }),
1461
1461
  headers({ "User-Agent": `${name} ${version}` }),
@@ -227,7 +227,7 @@ function createEditUrl(options) {
227
227
  type,
228
228
  path: stringifiedPath
229
229
  });
230
- workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset);
230
+ workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset), _id.startsWith(DRAFTS_PREFIX) && searchParams.set("isDraft", "");
231
231
  const segments = [baseUrl === "/" ? "" : baseUrl];
232
232
  workspace && segments.push(workspace);
233
233
  const routerParams = [
@@ -1 +1 @@
1
- {"version":3,"file":"resolveEditInfo.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/getPublishedId.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n // eslint-disable-next-line no-warning-comments\n // @TODO allow passing draft prefixed IDs, to better open the right perspective mode\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","studioPath.toString"],"mappings":";AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAM,CAAA,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AAGO,SAAS,aAAa,SAA6C;AACxE,MAAI,OAAO,WAAY,YAAY,aAAa,KAAK,OAAO;AACnD,WAAA;AAGT,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AACzC,WAAA;AAGH,QAAA,CAAC,MAAM,EAAE,IAAI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AAQ,aAAc,aAAa,QAAQ,UAAU,SAAS,IAAI,QAAQ;AAAA,IAAA;AAEnF,QAAI,CAAC;AAAS;AACd,UAAM,EAAC,KAAK,OAAO,YAAY,aAAY;AACpC,WAAA;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM,cAAc,aAAa,UAAU;AAAA,MAC3C,WAAW;AAAA,MACX,SAAS;AAAA,IAAA;AAAA,EAEb;AAGF;AAGO,SAAS,uBAAuB,WAAuC;AAC5E,MAAI,UAAyB,OAAO,aAAc,WAAW,YAAY,UAAU;AAInF,SAHI,YAAY,QACd,UAAU,QAAQ,QAAQ,OAAO,EAAE,IAEjC,OAAO,aAAc,WAChB,EAAC,QAAA,IAEH,EAAC,GAAG,WAAW;AACxB;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"resolveEditInfo.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/getPublishedId.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","studioPath.toString"],"mappings":";AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAM,CAAA,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AAGO,SAAS,aAAa,SAA6C;AACxE,MAAI,OAAO,WAAY,YAAY,aAAa,KAAK,OAAO;AACnD,WAAA;AAGT,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AACzC,WAAA;AAGH,QAAA,CAAC,MAAM,EAAE,IAAI;AACX,UAAA,OAAO,QAAS,YAAY,SAAS,QAAQ,OAAO,MAAO,YAAY,OAAO;AACxF;AAGgB,SAAA,IACd,KACA,MACA,YAC4B;AAC5B,QAAM,SAAS,OAAO,QAAS,WAAW,WAAW,IAAI,IAAI;AACzD,MAAA,CAAC,MAAM,QAAQ,MAAM;AACjB,UAAA,IAAI,MAAM,mCAAmC;AAGrD,MAAI,MAA2B;AAC/B,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AAChC,UAAA,UAAU,OAAO,CAAC;AACpB,QAAA,eAAe,OAAO,GAAG;AACvB,UAAA,CAAC,MAAM,QAAQ,GAAG;AACb,eAAA;AAGT,YAAM,IAAI,OAAO;AAAA,IACnB;AAEI,Q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AY,QACd,UAAU,QAAQ,QAAQ,OAAO,EAAE,IAEjC,OAAO,aAAc,WAChB,EAAC,QAAA,IAEH,EAAC,GAAG,WAAW;AACxB;;;;;;;;;;;;;;;;"}
@@ -226,7 +226,7 @@ function createEditUrl(options) {
226
226
  type,
227
227
  path: stringifiedPath
228
228
  });
229
- workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset);
229
+ workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset), _id.startsWith(DRAFTS_PREFIX) && searchParams.set("isDraft", "");
230
230
  const segments = [baseUrl === "/" ? "" : baseUrl];
231
231
  workspace && segments.push(workspace);
232
232
  const routerParams = [
@@ -1 +1 @@
1
- {"version":3,"file":"resolveEditInfo.js","sources":["../../src/csm/studioPath.ts","../../src/csm/getPublishedId.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n // eslint-disable-next-line no-warning-comments\n // @TODO allow passing draft prefixed IDs, to better open the right perspective mode\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","studioPath.toString"],"mappings":"AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAM,CAAA,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AAGO,SAAS,aAAa,SAA6C;AACxE,MAAI,OAAO,WAAY,YAAY,aAAa,KAAK,OAAO;AACnD,WAAA;AAGT,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AACzC,WAAA;AAGH,QAAA,CAAC,MAAM,EAAE,IAAI;AACX,UAAA,OAAO,QAAS,YAAY,SAAS,QAAQ,OAAO,MAAO,YAAY,OAAO;AACxF;AAGgB,SAAA,IACd,KACA,MACA,YAC4B;AAC5B,QAAM,SAAS,OAAO,QAAS,WAAW,WAAW,IAAI,IAAI;AACzD,MAAA,CAAC,MAAM,QAAQ,MAAM;AACjB,UAAA,IAAI,MAAM,mCAAmC;AAGrD,MAAI,MAA2B;AAC/B,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AAChC,UAAA,UAAU,OAAO,CAAC;AACpB,QAAA,eAAe,OAAO,GAAG;AACvB,UAAA,CAAC,MAAM,QAAQ,GAAG;AACb,eAAA;AAGT,YAAM,IAAI,OAAO;AAAA,IACnB;AAEI,QAAA,aAAa,OAAO,GAAG;AAC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AEH,EAAC,GAAG,WAAW;AACxB;"}
1
+ {"version":3,"file":"resolveEditInfo.js","sources":["../../src/csm/studioPath.ts","../../src/csm/getPublishedId.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","studioPath.toString"],"mappings":"AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,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,IAAc,SACrC,EAAC,SAAS,WAAc,IAAA,eAAe,YAAY,GAAG,KAAK,CAAA;AAE7D,MAAA,CAAC,WAKD,QAAQ,OAAO,SAAS,aAIxB,QAAQ,OAAO,SAAS;AAC1B;AAGF,QAAM,YAAY,IAAI,UAAU,QAAQ,OAAO,QAAQ,GACjD,aAAa,IAAI,MAAM,QAAQ,OAAO,IAAI;AAEhD,MAAI,aAAa,YAAY;AAC3B,UAAM,EAAC,SAAS,WAAW,KAAQ,IAAA;AAAA,MACjC,OAAO,QAAQ,aAAc,aAAa,QAAQ,UAAU,SAAS,IAAI,QAAQ;AAAA,IAAA;AAEnF,QAAI,CAAC;AAAS;AACd,UAAM,EAAC,KAAK,OAAO,YAAY,aAAY;AACpC,WAAA;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM,cAAc,aAAa,UAAU;AAAA,MAC3C,WAAW;AAAA,MACX,SAAS;AAAA,IAAA;AAAA,EAEb;AAGF;AAGO,SAAS,uBAAuB,WAAuC;AAC5E,MAAI,UAAyB,OAAO,aAAc,WAAW,YAAY,UAAU;AAInF,SAHI,YAAY,QACd,UAAU,QAAQ,QAAQ,OAAO,EAAE,IAEjC,OAAO,aAAc,WAChB,EAAC,QAAA,IAEH,EAAC,GAAG,WAAW;AACxB;"}
@@ -167,7 +167,7 @@ function createEditUrl(options) {
167
167
  type,
168
168
  path: stringifiedPath
169
169
  });
170
- workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset);
170
+ workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset), _id.startsWith(DRAFTS_PREFIX) && searchParams.set("isDraft", "");
171
171
  const segments = [baseUrl === "/" ? "" : baseUrl];
172
172
  workspace && segments.push(workspace);
173
173
  const routerParams = [
@@ -1 +1 @@
1
- {"version":3,"file":"stegaEncodeSourceMap.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport type {ContentSourceMap} from '../csm/types'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n // eslint-disable-next-line no-warning-comments\n // @TODO allow passing draft prefixed IDs, to better open the right perspective mode\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n","import type {FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, needs better heuristics but it works for now\n if (typeof endPath === 'string' && endPath.startsWith('_')) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"mappings":";;AAeO,MAAM,eAAe;AASrB,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAM,CAAA,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AA8DO,SAAS,SAAS,MAAoB;AACvC,MAAA,CAAC,MAAM,QAAQ,IAAI;AACf,UAAA,IAAI,MAAM,sBA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eSourceMap.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport type {ContentSourceMap} from '../csm/types'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n","import type {FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, needs better heuristics but it works for now\n if (typeof endPath === 'string' && endPath.startsWith('_')) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"mappings":";;AAeO,MAAM,eAAe;AASrB,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAM,CAAA,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AA8DO,SAAS,SAAS,MAAoB;AACvC,MAAA,CAAC,MAAM,QAAQ,IAAI;AACf,UAAA,IAAI,MAAM,sBAAsB;AAGxC,S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AACtD;;;;;;;;"}
@@ -166,7 +166,7 @@ function createEditUrl(options) {
166
166
  type,
167
167
  path: stringifiedPath
168
168
  });
169
- workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset);
169
+ workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset), _id.startsWith(DRAFTS_PREFIX) && searchParams.set("isDraft", "");
170
170
  const segments = [baseUrl === "/" ? "" : baseUrl];
171
171
  workspace && segments.push(workspace);
172
172
  const routerParams = [
@@ -1 +1 @@
1
- {"version":3,"file":"stegaEncodeSourceMap.js","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport type {ContentSourceMap} from '../csm/types'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n // eslint-disable-next-line no-warning-comments\n // @TODO allow passing draft prefixed IDs, to better open the right perspective mode\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n","import type {FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, needs better heuristics but it works for now\n if (typeof endPath === 'string' && endPath.startsWith('_')) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"mappings":";AAeO,MAAM,eAAe;AASrB,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAM,CAAA,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AA8DO,SAAS,SAAS,MAAoB;AACvC,MAAA,CAAC,MAAM,QAAQ,IAAI;AACf,UAAA,IAAI,MAAM,sBAAsB;AAGxC,SAAO,KAAK,OAAe,CAAC,QAAQ,SAAS,MAAM;AACjD,UAAM,cAAc,OAAO;AAC3B,QAAI,gBAAgB;AACX,aAAA,GAAG,MAAM,IAAI,OAAO;AAG7B,QAAI,gBAAgB;AAEX,aAAA,GAAG,MAAM,GADE,MAAM,IAAI,KAAK,GACL,GAAG,OAAO;AAGpC,QAAA,aAAa,OAAO,KAAK,QAAQ;AACnC,aAAO,GAAG,MAAM,WAAW,QAAQ,IAAI;AAGrC,QAAA,MAAM,QAAQ,OAAO,GAAG;AACpB,YAAA,CAAC,MAAM,EAAE,IAAI;AACnB,aAAO,GAAG,MAAM,IAAI,IAAI,IAAI,EAAE;AAAA,IAChC;AAEA,UAAM,IAAI,MAAM,8BAA8B,KAAK,UAAU,OAAO,CAAC,IAAI;AAAA,KACxE,EAAE;AACP;AC/GA,MAAM,SAAiC;AAAA,EACrC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AACR,GAEM,WAAmC;AAAA,EACvC,OAAO;AAAA,EACP,OAAO;AAAA;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AACV;AAKO,SAAS,SAAS,MAAiE;AACjF,SAAA,IAAI,KACR,I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AG,EAAE,QAAQ,YAAY,IAAI,CAAC;AAEvE,OAAA,KAAA,UAAA,OAAA,SAAA,OAAQ,QAAR,QAAc,GAAA,KAAA,QAAA,2CAA2C,CAAC,GAAG,QAAQ,OAAQ,CAAA,CAAA;AAAA,IAC/E;AAEI,KAAA,cAAc,iBAChB,KAAA,UAAA,OAAA,SAAA,OAAQ,aAAR,QAAA,GAAA,KAAA,MAAA;AAAA,EAEJ;AAEO,SAAA;AACT;AAEA,SAAS,qBAAqB,MAA0C;AAC/D,SAAAC,SAAmB,qBAAqB,IAAI,CAAC;AACtD;;;;;"}
1
+ {"version":3,"file":"stegaEncodeSourceMap.js","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport type {ContentSourceMap} from '../csm/types'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n","import type {FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, needs better heuristics but it works for now\n if (typeof endPath === 'string' && endPath.startsWith('_')) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"mappings":";AAeO,MAAM,eAAe;AASrB,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAM,CAAA,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AA8DO,SAAS,SAAS,MAAoB;AACvC,MAAA,CAAC,MAAM,QAAQ,IAAI;AACf,UAAA,IAAI,MAAM,sBAAsB;AAGxC,SAAO,KAAK,OAAe,CAAC,QAAQ,SAAS,MAAM;AACjD,UAAM,cAAc,OAAO;AAC3B,QAAI,gBAAgB;AACX,aAAA,GAAG,MAAM,IAAI,OAAO;AAG7B,QAAI,gBAAgB;AAEX,aAAA,GAAG,MAAM,GADE,MAAM,IAAI,KAAK,GACL,GAAG,OAAO;AAGpC,QAAA,aAAa,OAAO,KAAK,QAAQ;AACnC,aAAO,GAAG,MAAM,WAAW,QAAQ,IAAI;AAGrC,QAAA,MAAM,QAAQ,OAAO,GAAG;AACpB,YAAA,CAAC,MAAM,EAAE,IAAI;AACnB,aAAO,GAAG,MAAM,IAAI,IAAI,IAAI,EAAE;AAAA,IAChC;AAEA,UAAM,IAAI,MAAM,8BAA8B,KAAK,UAAU,OAAO,CAAC,IAAI;AAAA,KACxE,EAAE;AACP;AC/GA,MAAM,SAAiC;AAAA,EACrC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AACR,GAEM,WAAmC;AAAA,EACvC,OAAO;AAAA,EACP,OAAO;AAAA;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AACV;AAKO,SAAS,SAAS,MAAiE;AACjF,SAAA,IAAI,KACR,IAAI,CAAC,YACA,OAAO,WAAY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,IAAI,KAAK,QAAQ,cAAc,GAAG,EAAE,QAAQ,YAAY,IAAI,CAAC;AAEvE,OAAA,KAAA,UAAA,OAAA,SAAA,OAAQ,QAAR,QAAc,GAAA,KAAA,QAAA,2CAA2C,CAAC,GAAG,QAAQ,OAAQ,CAAA,CAAA;AAAA,IAC/E;AAEI,KAAA,cAAc,iBAChB,KAAA,UAAA,OAAA,SAAA,OAAQ,aAAR,QAAA,GAAA,KAAA,MAAA;AAAA,EAEJ;AAEO,SAAA;AACT;AAEA,SAAS,qBAAqB,MAA0C;AAC/D,SAAAC,SAAmB,qBAAqB,IAAI,CAAC;AACtD;;;;;"}
package/dist/csm.cjs CHANGED
@@ -21,7 +21,7 @@ function applySourceDocuments(result, resultSourceMap, getCachedDocument, update
21
21
  return value;
22
22
  let cachedDocument;
23
23
  if (perspective === "previewDrafts" ? (cachedDocument = getCachedDocument(
24
- sourceDocument._id.startsWith(resolveEditInfo.DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${resolveEditInfo.DRAFTS_PREFIX}.${sourceDocument._id}}` }
24
+ sourceDocument._id.startsWith(resolveEditInfo.DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${resolveEditInfo.DRAFTS_PREFIX}${sourceDocument._id}}` }
25
25
  ), cachedDocument || (cachedDocument = getCachedDocument(
26
26
  sourceDocument._id.startsWith(resolveEditInfo.DRAFTS_PREFIX) ? { ...sourceDocument, _id: resolveEditInfo.getPublishedId(sourceDocument._id) } : sourceDocument
27
27
  )), cachedDocument && (cachedDocument = {
package/dist/csm.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"csm.cjs","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}.${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["walkMap","resolveMapping","parseJsonPath","paths.toString","DRAFTS_PREFIX","getPublishedId","paths.get","jsonPath","studioPathToJsonPath","resolveEditInfo","createEditUrl"],"mappings":";;;AAeA,MAAM,wBAAwB,CAAc,YAAkB;AAOvD,SAAS,qBACd,QACA,iBACA,mBAGA,WAA+C,uBAC/C,cAAiC,OACzB;AACR,MAAI,CAAC;AAAwB,WAAA;AAE7B,MAAI,gBAAgB,eAAe,gBAAgB,SAAS,gBAAgB;AAC1E,UAAM,IAAI,MAAM,wBAAwB,WAAW,GAAG;AAGjD,SAAAA,gBAAA,QAAQ,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,GAAG,CAAC,OAAO,SAAS;AAC5D,UAAA,uBAAuBC,gBAAAA,eAAe,MAAM,eAAe;AACjE,QAAI,CAAC;AAEI,aAAA;AAGH,UAAA,EAAC,SAAS,WAAc,IAAA;AAK9B,QAJI,QAAQ,SAAS,WAIjB,QAAQ,OAAO,SAAS;AACnB,aAAA;AAGT,UAAM,iBAAiB,gBAAgB,UAAU,QAAQ,OAAO,QAAQ,GAClE,aAAa,gBAAgB,MAAM,QAAQ,OAAO,IAAI;AAE5D,QAAI,gBAAgB;AACZ,YAAA,aAAaC,8BAAc,aAAa,UAAU,GAClD,kBAAkBC,gBAAAA,SAAe,UAAkB;AAGzD,UAAI,oBAAoB;AACf,eAAA;AAGL,UAAA;AACA,UAAA,gBAAgB,mBAClB,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAWC,gBAAa,aAAA,IACvC,iBACA,EAAC,GAAG,gBAAgB,KAAK,GAAGA,gBAAAA,aAAa,IAAI,eAAe,GAAG,IAAG;AAAA,MAAA,GAEnE,mBACH,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAWA,gBAAAA,aAAa,IACvC,EAAC,GAAG,gBAAgB,KAAKC,gBAAAA,eAAe,eAAe,GAAG,EAC1D,IAAA;AAAA,MAAA,IAGJ,mBACF,iBAAiB;AAAA,QACf,GAAG;AAAA,QACH,KAAKA,gBAAAA,eAAe,eAAe,GAAG;AAAA,QACtC,aAAa,eAAe;AAAA,MAIhC,MAAA,iBAAiB,kBAAkB,cAAc,GAG/C,CAAC;AACI,eAAA;AAGT,YAAM,eAAe,iBACjBC,oBAAgC,gBAAgB,iBAAiB,KAAK,IACtE;AACJ,aAAO,UAAU,eACb,QACA,SAA+B,cAAqB;AAAA,QAClD;AAAA,QACA,eAAe;AAAA,QACf;AAAA,QACA,YAAY;AAAA,MAAA,CACb;AAAA,IACP;AAEO,WAAA;AAAA,EAAA,CACR;AACH;ACvGO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAkB,IAAA,SAEhD,qBAAqB,eAAe,SAAY,CAAK,IAAAJ,gBAAA,cAAc,UAAU,GAE7E,eAAe,gBAAgB,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,GAEvF,qBAAqB,aAAa,SAASK,gBAAAA,SAAS,YAAY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAAL,gBAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAaM,gBAAA,qBAAqB,QAAQ,UAAU,GAEpD,WAAWC,gBAAAA,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAOC,gBAAAA,cAAc,QAAQ;AAC/B;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"csm.cjs","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["walkMap","resolveMapping","parseJsonPath","paths.toString","DRAFTS_PREFIX","getPublishedId","paths.get","jsonPath","studioPathToJs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,kBAAkB,cAAc,GAG/C,CAAC;AACI,eAAA;AAGT,YAAM,eAAe,iBACjBC,oBAAgC,gBAAgB,iBAAiB,KAAK,IACtE;AACJ,aAAO,UAAU,eACb,QACA,SAA+B,cAAqB;AAAA,QAClD;AAAA,QACA,eAAe;AAAA,QACf;AAAA,QACA,YAAY;AAAA,MAAA,CACb;AAAA,IACP;AAEO,WAAA;AAAA,EAAA,CACR;AACH;ACvGO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAkB,IAAA,SAEhD,qBAAqB,eAAe,SAAY,CAAK,IAAAJ,gBAAA,cAAc,UAAU,GAE7E,eAAe,gBAAgB,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,GAEvF,qBAAqB,aAAa,SAASK,gBAAAA,SAAS,YAAY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAAL,gBAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAaM,gBAAA,qBAAqB,QAAQ,UAAU,GAEpD,WAAWC,gBAAAA,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAOC,gBAAAA,cAAc,QAAQ;AAC/B;;;;;;;;;;;;;;"}
package/dist/csm.js CHANGED
@@ -20,7 +20,7 @@ function applySourceDocuments(result, resultSourceMap, getCachedDocument, update
20
20
  return value;
21
21
  let cachedDocument;
22
22
  if (perspective === "previewDrafts" ? (cachedDocument = getCachedDocument(
23
- sourceDocument._id.startsWith(DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${DRAFTS_PREFIX}.${sourceDocument._id}}` }
23
+ sourceDocument._id.startsWith(DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}` }
24
24
  ), cachedDocument || (cachedDocument = getCachedDocument(
25
25
  sourceDocument._id.startsWith(DRAFTS_PREFIX) ? { ...sourceDocument, _id: getPublishedId(sourceDocument._id) } : sourceDocument
26
26
  )), cachedDocument && (cachedDocument = {
package/dist/csm.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"csm.js","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}.${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["paths.toString","paths.get"],"mappings":";;AAeA,MAAM,wBAAwB,CAAc,YAAkB;AAOvD,SAAS,qBACd,QACA,iBACA,mBAGA,WAA+C,uBAC/C,cAAiC,OACzB;AACR,MAAI,CAAC;AAAwB,WAAA;AAE7B,MAAI,gBAAgB,eAAe,gBAAgB,SAAS,gBAAgB;AAC1E,UAAM,IAAI,MAAM,wBAAwB,WAAW,GAAG;AAGjD,SAAA,QAAQ,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,GAAG,CAAC,OAAO,SAAS;AAC5D,UAAA,uBAAuB,eAAe,MAAM,eAAe;AACjE,QAAI,CAAC;AAEI,aAAA;AAGH,UAAA,EAAC,SAAS,WAAc,IAAA;AAK9B,QAJI,QAAQ,SAAS,WAIjB,QAAQ,OAAO,SAAS;AACnB,aAAA;AAGT,UAAM,iBAAiB,gBAAgB,UAAU,QAAQ,OAAO,QAAQ,GAClE,aAAa,gBAAgB,MAAM,QAAQ,OAAO,IAAI;AAE5D,QAAI,gBAAgB;AACZ,YAAA,aAAa,cAAc,aAAa,UAAU,GAClD,kBAAkBA,SAAe,UAAkB;AAGzD,UAAI,oBAAoB;AACf,eAAA;AAGL,UAAA;AACA,UAAA,gBAAgB,mBAClB,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAW,aAAa,IACvC,iBACA,EAAC,GAAG,gBAAgB,KAAK,GAAG,aAAa,IAAI,eAAe,GAAG,IAAG;AAAA,MAAA,GAEnE,mBACH,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAW,aAAa,IACvC,EAAC,GAAG,gBAAgB,KAAK,eAAe,eAAe,GAAG,EAC1D,IAAA;AAAA,MAAA,IAGJ,mBACF,iBAAiB;AAAA,QACf,GAAG;AAAA,QACH,KAAK,eAAe,eAAe,GAAG;AAAA,QACtC,aAAa,eAAe;AAAA,MAIhC,MAAA,iBAAiB,kBAAkB,cAAc,GAG/C,CAAC;AACI,eAAA;AAGT,YAAM,eAAe,iBACjBC,IAAgC,gBAAgB,iBAAiB,KAAK,IACtE;AACJ,aAAO,UAAU,eACb,QACA,SAA+B,cAAqB;AAAA,QAClD;AAAA,QACA,eAAe;AAAA,QACf;AAAA,QACA,YAAY;AAAA,MAAA,CACb;AAAA,IACP;AAEO,WAAA;AAAA,EAAA,CACR;AACH;ACvGO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAkB,IAAA,SAEhD,qBAAqB,eAAe,SAAY,CAAK,IAAA,cAAc,UAAU,GAE7E,eAAe,gBAAgB,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,GAEvF,qBAAqB,aAAa,SAAS,SAAS,YAAY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAa,qBAAqB,QAAQ,UAAU,GAEpD,WAAW,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAO,cAAc,QAAQ;AAC/B;"}
1
+ {"version":3,"file":"csm.js","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if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eAAA;AAGT,YAAM,eAAe,iBACjBC,IAAgC,gBAAgB,iBAAiB,KAAK,IACtE;AACJ,aAAO,UAAU,eACb,QACA,SAA+B,cAAqB;AAAA,QAClD;AAAA,QACA,eAAe;AAAA,QACf;AAAA,QACA,YAAY;AAAA,MAAA,CACb;AAAA,IACP;AAEO,WAAA;AAAA,EAAA,CACR;AACH;ACvGO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAkB,IAAA,SAEhD,qBAAqB,eAAe,SAAY,CAAK,IAAA,cAAc,UAAU,GAE7E,eAAe,gBAAgB,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,GAEvF,qBAAqB,aAAa,SAAS,SAAS,YAAY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAa,qBAAqB,QAAQ,UAAU,GAEpD,WAAW,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAO,cAAc,QAAQ;AAC/B;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/client",
3
- "version": "6.14.4",
3
+ "version": "6.15.0",
4
4
  "description": "Client for retrieving, creating and patching data from Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -68,7 +68,7 @@ export function applySourceDocuments<Result = unknown>(
68
68
  cachedDocument = getCachedDocument(
69
69
  sourceDocument._id.startsWith(DRAFTS_PREFIX)
70
70
  ? sourceDocument
71
- : {...sourceDocument, _id: `${DRAFTS_PREFIX}.${sourceDocument._id}}`},
71
+ : {...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}`},
72
72
  )
73
73
  if (!cachedDocument) {
74
74
  cachedDocument = getCachedDocument(
@@ -1,4 +1,4 @@
1
- import {getPublishedId} from './getPublishedId'
1
+ import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'
2
2
  import {jsonPathToStudioPath} from './jsonPath'
3
3
  import * as studioPath from './studioPath'
4
4
  import type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'
@@ -31,8 +31,6 @@ export function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}$
31
31
 
32
32
  const workspace = _workspace === 'default' ? undefined : _workspace
33
33
  const tool = _tool === 'default' ? undefined : _tool
34
- // eslint-disable-next-line no-warning-comments
35
- // @TODO allow passing draft prefixed IDs, to better open the right perspective mode
36
34
  const id = getPublishedId(_id)
37
35
  const stringifiedPath = Array.isArray(path)
38
36
  ? studioPath.toString(jsonPathToStudioPath(path))
@@ -58,6 +56,9 @@ export function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}$
58
56
  if (dataset) {
59
57
  searchParams.set('dataset', dataset)
60
58
  }
59
+ if (_id.startsWith(DRAFTS_PREFIX)) {
60
+ searchParams.set('isDraft', '')
61
+ }
61
62
 
62
63
  const segments = [baseUrl === '/' ? '' : baseUrl]
63
64
  if (workspace) {
@@ -3978,7 +3978,7 @@ ${selectionOpts}`);
3978
3978
  type,
3979
3979
  path: stringifiedPath
3980
3980
  });
3981
- workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset);
3981
+ workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset), _id.startsWith(DRAFTS_PREFIX) && searchParams.set("isDraft", "");
3982
3982
  const segments = [baseUrl === "/" ? "" : baseUrl];
3983
3983
  workspace && segments.push(workspace);
3984
3984
  const routerParams = [
@@ -5,7 +5,7 @@
5
5
  * Copyright (c) 2014-2017, Jon Schlinkert.
6
6
  * Released under the MIT License.
7
7
  */
8
- function R(e){return"[object Object]"===Object.prototype.toString.call(e)}!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=P(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(A,A.exports);const M=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e),D=["boolean","string","number"];function F(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||M(t)||-1===D.indexOf(typeof t)&&!Array.isArray(t)&&(!1===R(r=t)||void 0!==(n=r.constructor)&&(!1===R(o=n.prototype)||!1===o.hasOwnProperty("isPrototypeOf")))?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})});var r,n,o}}}function q(e){return{onResponse:r=>{const n=r.headers["content-type"]||"",o=e&&e.force||-1!==n.indexOf("application/json");return r.body&&n&&o?Object.assign({},r,{body:t(r.body)}):r},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:"application/json"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}let N={};typeof globalThis<"u"?N=globalThis:typeof window<"u"?N=window:typeof global<"u"?N=global:typeof self<"u"&&(N=self);var U=N;function W(e={}){const t=e.implementation||U.Observable;if(!t)throw new Error("`Observable` is not available in global scope, and no implementation was passed");return{onReturn:(e,r)=>new t((t=>(e.error.subscribe((e=>t.error(e))),e.progress.subscribe((e=>t.next(Object.assign({type:"progress"},e)))),e.response.subscribe((e=>{t.next(Object.assign({type:"response"},e)),t.complete()})),e.request.publish(r),()=>e.abort.publish())))}}class H{constructor(e){this.__CANCEL__=!0,this.message=e}toString(){return"Cancel"+(this.message?`: ${this.message}`:"")}}const z=class{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t=null;this.promise=new Promise((e=>{t=e})),e((e=>{this.reason||(this.reason=new H(e),t(this.reason))}))}};z.source=()=>{let e;return{token:new z((t=>{e=t})),cancel:e}};var L=(e,t,r)=>("GET"===r.method||"HEAD"===r.method)&&(e.isNetworkError||!1);function B(e){return 100*Math.pow(2,e)+100*Math.random()}const J=(e={})=>(e=>{const t=e.maxRetries||5,r=e.retryDelay||B,n=e.shouldRetry;return{onError:(e,o)=>{const i=o.options,s=i.maxRetries||t,a=i.shouldRetry||n,u=i.attemptNumber||0;if(null!==(c=i.body)&&"object"==typeof c&&"function"==typeof c.pipe||!a(e,u,i)||u>=s)return e;var c;const l=Object.assign({},o,{options:Object.assign({},i,{attemptNumber:u+1})});return setTimeout((()=>o.channels.request.publish(l)),r(u)),null}}})({shouldRetry:L,...e});J.shouldRetry=L;var G=function(e,t){return G=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},G(e,t)};function V(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}G(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Q(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))}function Y(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(u){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function X(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function K(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function Z(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}function ee(e){return this instanceof ee?(this.v=e,this):new ee(e)}function te(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n={},s("next"),s("throw"),s("return"),n[Symbol.asyncIterator]=function(){return this},n;function s(e){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))})}function a(e,t){try{(r=o[e](t)).value instanceof ee?Promise.resolve(r.value.v).then(u,c):l(i[0][2],r)}catch(e){l(i[0][3],e)}var r}function u(e){a("next",e)}function c(e){a("throw",e)}function l(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function re(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=X(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,o,(t=e[r](t)).done,t.value)}))}}}function ne(e){return"function"==typeof e}function oe(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var ie=oe((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function se(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var ae=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=X(i),a=s.next();!a.done;a=s.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var u=this.initialTeardown;if(ne(u))try{u()}catch(e){o=e instanceof ie?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var l=X(c),d=l.next();!d.done;d=l.next()){var f=d.value;try{ce(f)}catch(e){o=null!=o?o:[],e instanceof ie?o=Z(Z([],K(o)),K(e.errors)):o.push(e)}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(o)throw new ie(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)ce(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&se(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&se(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function ue(e){return e instanceof ae||e&&"closed"in e&&ne(e.remove)&&ne(e.add)&&ne(e.unsubscribe)}function ce(e){ne(e)?e():e.unsubscribe()}ae.EMPTY;var le={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},de={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,Z([e,t],K(r)))},clearTimeout:function(e){var t=de.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function fe(e){de.setTimeout((function(){throw e}))}function he(){}var pe=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,ue(t)&&t.add(r)):r.destination=we,r}return V(t,e),t.create=function(e,t,r){return new ve(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(ae),ye=Function.prototype.bind;function ge(e,t){return ye.call(e,t)}var me=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){be(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){be(e)}else be(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){be(e)}},e}(),ve=function(e){function t(t,r,n){var o,i,s=e.call(this)||this;ne(t)||!t?o={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:s&&le.useDeprecatedNextContext?((i=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&ge(t.next,i),error:t.error&&ge(t.error,i),complete:t.complete&&ge(t.complete,i)}):o=t;return s.destination=new me(o),s}return V(t,e),t}(pe);function be(e){fe(e)}var we={closed:!0,next:he,error:function(e){throw e},complete:he},Ce="function"==typeof Symbol&&Symbol.observable||"@@observable";function Ee(e){return e}function xe(e){return 0===e.length?Ee:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Se=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var n,o=this,i=(n=e)&&n instanceof pe||function(e){return e&&ne(e.next)&&ne(e.error)&&ne(e.complete)}(n)&&ue(n)?e:new ve(e,t,r);return function(){var e=o,t=e.operator,r=e.source;i.add(t?t.call(i,r):r?o._subscribe(i):o._trySubscribe(i))}(),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=Te(t))((function(t,n){var o=new ve({next:function(t){try{e(t)}catch(e){n(e),o.unsubscribe()}},error:n,complete:t});r.subscribe(o)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[Ce]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return xe(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=Te(e))((function(e,r){var n;t.subscribe((function(e){return n=e}),(function(e){return r(e)}),(function(){return e(n)}))}))},e.create=function(t){return new e(t)},e}();function Te(e){var t;return null!==(t=null!=e?e:le.Promise)&&void 0!==t?t:Promise}function _e(e){return function(t){if(function(e){return ne(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}function Oe(e,t,r,n,o){return new $e(e,t,r,n,o)}var $e=function(e){function t(t,r,n,o,i,s){var a=e.call(this,t)||this;return a.onFinalize=i,a.shouldUnsubscribe=s,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return V(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(pe);var je=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function ke(e){return ne(null==e?void 0:e.then)}function Ae(e){return ne(e[Ce])}function Ie(e){return Symbol.asyncIterator&&ne(null==e?void 0:e[Symbol.asyncIterator])}function Pe(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var Re="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function Me(e){return ne(null==e?void 0:e[Re])}function De(e){return te(this,arguments,(function(){var t,r,n;return Y(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,ee(t.read())];case 3:return r=o.sent(),n=r.value,r.done?[4,ee(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,ee(n)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function Fe(e){return ne(null==e?void 0:e.getReader)}function qe(e){if(e instanceof Se)return e;if(null!=e){if(Ae(e))return o=e,new Se((function(e){var t=o[Ce]();if(ne(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(je(e))return n=e,new Se((function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()}));if(ke(e))return r=e,new Se((function(e){r.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,fe)}));if(Ie(e))return Ne(e);if(Me(e))return t=e,new Se((function(e){var r,n;try{for(var o=X(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()}));if(Fe(e))return Ne(De(e))}var t,r,n,o;throw Pe(e)}function Ne(e){return new Se((function(t){(function(e,t){var r,n,o,i;return Q(this,void 0,void 0,(function(){var s,a;return Y(this,(function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),r=re(e),u.label=1;case 1:return[4,r.next()];case 2:if((n=u.sent()).done)return[3,4];if(s=n.value,t.next(s),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=u.sent(),o={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(i=r.return)?[4,i.call(r)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function Ue(e,t,r,n,o){void 0===n&&(n=0),void 0===o&&(o=!1);var i=t.schedule((function(){r(),o?e.add(this.schedule(null,n)):this.unsubscribe()}),n);if(e.add(i),!o)return i}function We(e,t){return void 0===t&&(t=0),_e((function(r,n){r.subscribe(Oe(n,(function(r){return Ue(n,e,(function(){return n.next(r)}),t)}),(function(){return Ue(n,e,(function(){return n.complete()}),t)}),(function(r){return Ue(n,e,(function(){return n.error(r)}),t)})))}))}function He(e,t){return void 0===t&&(t=0),_e((function(r,n){n.add(e.schedule((function(){return r.subscribe(n)}),t))}))}function ze(e,t){if(!e)throw new Error("Iterable cannot be null");return new Se((function(r){Ue(r,t,(function(){var n=e[Symbol.asyncIterator]();Ue(r,t,(function(){n.next().then((function(e){e.done?r.complete():r.next(e.value)}))}),0,!0)}))}))}function Le(e,t){if(null!=e){if(Ae(e))return function(e,t){return qe(e).pipe(He(t),We(t))}(e,t);if(je(e))return function(e,t){return new Se((function(r){var n=0;return t.schedule((function(){n===e.length?r.complete():(r.next(e[n++]),r.closed||this.schedule())}))}))}(e,t);if(ke(e))return function(e,t){return qe(e).pipe(He(t),We(t))}(e,t);if(Ie(e))return ze(e,t);if(Me(e))return function(e,t){return new Se((function(r){var n;return Ue(r,t,(function(){n=e[Re](),Ue(r,t,(function(){var e,t,o;try{t=(e=n.next()).value,o=e.done}catch(e){return void r.error(e)}o?r.complete():r.next(t)}),0,!0)})),function(){return ne(null==n?void 0:n.return)&&n.return()}}))}(e,t);if(Fe(e))return function(e,t){return ze(De(e),t)}(e,t)}throw Pe(e)}function Be(e,t){return t?Le(e,t):qe(e)}var Je=oe((function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Ge(e,t){var r="object"==typeof t;return new Promise((function(n,o){var i,s=!1;e.subscribe({next:function(e){i=e,s=!0},error:o,complete:function(){s?n(i):r?n(t.defaultValue):o(new Je)}})}))}function Ve(e,t){return _e((function(r,n){var o=0;r.subscribe(Oe(n,(function(r){n.next(e.call(t,r,o++))})))}))}var Qe=Array.isArray;function Ye(e){return Ve((function(t){return function(e,t){return Qe(t)?e.apply(void 0,Z([],K(t))):e(t)}(e,t)}))}function Xe(e,t,r){e?Ue(r,e,t):t()}var Ke=Array.isArray;function Ze(e,t){return _e((function(r,n){var o=0;r.subscribe(Oe(n,(function(r){return e.call(t,r,o++)&&n.next(r)})))}))}function et(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(e){return ne((t=e)[t.length-1])?e.pop():void 0;var t}(e);return r?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return xe(e)}(et.apply(void 0,Z([],K(e))),Ye(r)):_e((function(t,r){var n,o,i;(n=Z([t],K(function(e){return 1===e.length&&Ke(e[0])?e[0]:e}(e))),void 0===i&&(i=Ee),function(e){Xe(o,(function(){for(var t=n.length,r=new Array(t),s=t,a=t,u=function(t){Xe(o,(function(){var u=Be(n[t],o),c=!1;u.subscribe(Oe(e,(function(n){r[t]=n,c||(c=!0,a--),a||e.next(i(r.slice()))}),(function(){--s||e.complete()})))}),e)},c=0;c<t;c++)u(c)}),e)})(r)}))}class tt extends Error{constructor(e){const t=nt(e);super(t.message),this.statusCode=400,Object.assign(this,t)}}class rt extends Error{constructor(e){const t=nt(e);super(t.message),this.statusCode=500,Object.assign(this,t)}}function nt(e){const t=e.body,r={response:e,statusCode:e.statusCode,responseBody:it(t,e),message:"",details:void 0};if(t.error&&t.message)return r.message=`${t.error} - ${t.message}`,r;if(function(e){return ot(e)&&ot(e.error)&&"mutationError"===e.error.type&&"string"==typeof e.error.description}(t)){const e=t.error.items||[],n=e.slice(0,5).map((e=>{var t;return null==(t=e.error)?void 0:t.description})).filter(Boolean);let o=n.length?`:\n- ${n.join("\n- ")}`:"";return e.length>5&&(o+=`\n...and ${e.length-5} more`),r.message=`${t.error.description}${o}`,r.details=t.error,r}return t.error&&t.error.description?(r.message=t.error.description,r.details=t.error,r):(r.message=t.error||t.message||function(e){const t=e.statusMessage?` ${e.statusMessage}`:"";return`${e.method}-request to ${e.url} resulted in HTTP ${e.statusCode}${t}`}(e),r)}function ot(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function it(e,t){return-1!==(t.headers["content-type"]||"").toLowerCase().indexOf("application/json")?JSON.stringify(e,null,2):e}const st={onResponse:e=>{if(e.statusCode>=500)throw new rt(e);if(e.statusCode>=400)throw new tt(e);return e}},at={onResponse:e=>{const t=e.headers["x-sanity-warning"];return(Array.isArray(t)?t:[t]).filter(Boolean).forEach((e=>console.warn(e))),e}};function ut(e,{maxRetries:t=5,retryDelay:r}){const n=$([t>0?J({retryDelay:r,maxRetries:t,shouldRetry:ct}):{},...e,at,F(),q(),{onRequest:e=>{if("xhr"!==e.adapter)return;const t=e.request,r=e.context;function n(e){return t=>{const n=t.lengthComputable?t.loaded/t.total*100:-1;r.channels.progress.publish({stage:e,percent:n,total:t.total,loaded:t.loaded,lengthComputable:t.lengthComputable})}}"upload"in t&&"onprogress"in t.upload&&(t.upload.onprogress=n("upload")),"onprogress"in t&&(t.onprogress=n("download"))}},st,W({implementation:Se})]);function o(e,t=n){return t({maxRedirects:0,...e})}return o.defaultRequester=n,o}function ct(e,t,r){const n="GET"===r.method||"HEAD"===r.method,o=(r.uri||r.url).startsWith("/data/query"),i=e.response&&(429===e.response.statusCode||502===e.response.statusCode||503===e.response.statusCode);return!(!n&&!o||!i)||J.shouldRetry(e,t,r)}function lt(e){if("string"==typeof e)return{id:e};if(Array.isArray(e))return{query:"*[_id in $ids]",params:{ids:e}};if("object"==typeof e&&null!==e&&"query"in e&&"string"==typeof e.query)return"params"in e&&"object"==typeof e.params&&null!==e.params?{query:e.query,params:e.params}:{query:e.query};const t=["* Document ID (<docId>)","* Array of document IDs","* Object containing `query`"].join("\n");throw new Error(`Unknown selection - must be one of:\n\n${t}`)}const dt=["image","file"],ft=["before","after","replace"],ht=e=>{if(!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(e))throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters")},pt=(e,t)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new Error(`${e}() takes an object of properties`)},yt=(e,t)=>{if("string"!=typeof t||!/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(t)||t.includes(".."))throw new Error(`${e}(): "${t}" is not a valid document ID`)},gt=(e,t)=>{if(!t._id)throw new Error(`${e}() requires that the document contains an ID ("_id" property)`);yt(e,t._id)},mt=e=>{if(!e.dataset)throw new Error("`dataset` must be provided to perform queries");return e.dataset||""},vt=e=>{if("string"!=typeof e||!/^[a-z0-9._-]{1,75}$/i.test(e))throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");return e};var bt,wt=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Ct=(e,t,r)=>(wt(e,t,"read from private field"),r?r.call(e):t.get(e)),Et=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},xt=(e,t,r,n)=>(wt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class St{constructor(e,t={}){this.selection=e,this.operations=t}set(e){return this._assign("set",e)}setIfMissing(e){return this._assign("setIfMissing",e)}diffMatchPatch(e){return pt("diffMatchPatch",e),this._assign("diffMatchPatch",e)}unset(e){if(!Array.isArray(e))throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");return this.operations=Object.assign({},this.operations,{unset:e}),this}inc(e){return this._assign("inc",e)}dec(e){return this._assign("dec",e)}insert(e,t,r){return((e,t,r)=>{const n="insert(at, selector, items)";if(-1===ft.indexOf(e)){const e=ft.map((e=>`"${e}"`)).join(", ");throw new Error(`${n} takes an "at"-argument which is one of: ${e}`)}if("string"!=typeof t)throw new Error(`${n} takes a "selector"-argument which must be a string`);if(!Array.isArray(r))throw new Error(`${n} takes an "items"-argument which must be an array`)})(e,t,r),this._assign("insert",{[e]:t,items:r})}append(e,t){return this.insert("after",`${e}[-1]`,t)}prepend(e,t){return this.insert("before",`${e}[0]`,t)}splice(e,t,r,n){const o=t<0?t-1:t,i=typeof r>"u"||-1===r?-1:Math.max(0,t+r),s=`${e}[${o}:${o<0&&i>=0?"":i}]`;return this.insert("replace",s,n||[])}ifRevisionId(e){return this.operations.ifRevisionID=e,this}serialize(){return{...lt(this.selection),...this.operations}}toJSON(){return this.serialize()}reset(){return this.operations={},this}_assign(e,t,r=!0){return pt(e,t),this.operations=Object.assign({},this.operations,{[e]:Object.assign({},r&&this.operations[e]||{},t)}),this}_set(e,t){return this._assign(e,t,!1)}}bt=new WeakMap;let Tt=class e extends St{constructor(e,t,r){super(e,t),Et(this,bt,void 0),xt(this,bt,r)}clone(){return new e(this.selection,{...this.operations},Ct(this,bt))}commit(e){if(!Ct(this,bt))throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return Ct(this,bt).mutate({patch:this.serialize()},r)}};var _t;_t=new WeakMap;let Ot=class e extends St{constructor(e,t,r){super(e,t),Et(this,_t,void 0),xt(this,_t,r)}clone(){return new e(this.selection,{...this.operations},Ct(this,_t))}commit(e){if(!Ct(this,_t))throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return Ct(this,_t).mutate({patch:this.serialize()},r)}};var $t=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},jt=(e,t,r)=>($t(e,t,"read from private field"),r?r.call(e):t.get(e)),kt=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},At=(e,t,r,n)=>($t(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);const It={returnDocuments:!1};class Pt{constructor(e=[],t){this.operations=e,this.trxId=t}create(e){return pt("create",e),this._add({create:e})}createIfNotExists(e){const t="createIfNotExists";return pt(t,e),gt(t,e),this._add({[t]:e})}createOrReplace(e){const t="createOrReplace";return pt(t,e),gt(t,e),this._add({[t]:e})}delete(e){return yt("delete",e),this._add({delete:{id:e}})}transactionId(e){return e?(this.trxId=e,this):this.trxId}serialize(){return[...this.operations]}toJSON(){return this.serialize()}reset(){return this.operations=[],this}_add(e){return this.operations.push(e),this}}var Rt;Rt=new WeakMap;let Mt=class e extends Pt{constructor(e,t,r){super(e,r),kt(this,Rt,void 0),At(this,Rt,t)}clone(){return new e([...this.operations],jt(this,Rt),this.trxId)}commit(e){if(!jt(this,Rt))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return jt(this,Rt).mutate(this.serialize(),Object.assign({transactionId:this.trxId},It,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof Ot)return this._add({patch:e.serialize()});if(r){const r=t(new Ot(e,{},jt(this,Rt)));if(!(r instanceof Ot))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}};var Dt;Dt=new WeakMap;let Ft=class e extends Pt{constructor(e,t,r){super(e,r),kt(this,Dt,void 0),At(this,Dt,t)}clone(){return new e([...this.operations],jt(this,Dt),this.trxId)}commit(e){if(!jt(this,Dt))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return jt(this,Dt).mutate(this.serialize(),Object.assign({transactionId:this.trxId},It,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof Tt)return this._add({patch:e.serialize()});if(r){const r=t(new Tt(e,{},jt(this,Dt)));if(!(r instanceof Tt))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}};function qt(e){return"https://www.sanity.io/help/"+e}const Nt=e=>function(e){let t,r=!1;return(...n)=>(r||(t=e(...n),r=!0),t)}(((...t)=>console.warn(e.join(" "),...t))),Ut=Nt(["Since you haven't set a value for `useCdn`, we will deliver content using our","global, edge-cached API-CDN. If you wish to have content delivered faster, set","`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]),Wt=Nt(["The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.","The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]),Ht=Nt(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",`See ${qt("js-client-browser-token")} for more information and how to hide this warning.`]),zt=Nt(["Using the Sanity client without specifying an API version is deprecated.",`See ${qt("js-client-api-version")}`]),Lt=Nt(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]),Bt={apiHost:"https://api.sanity.io",apiVersion:"1",useProjectHostname:!0,stega:{enabled:!1}},Jt=["localhost","127.0.0.1","0.0.0.0"];const Gt=function(e){switch(e){case"previewDrafts":case"published":case"raw":return;default:throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`")}},Vt=(e,t)=>{const r={...t,...e,stega:{..."boolean"==typeof t.stega?{enabled:t.stega}:t.stega||Bt.stega,..."boolean"==typeof e.stega?{enabled:e.stega}:e.stega||{}}};r.apiVersion||zt();const n={...Bt,...r},o=n.useProjectHostname;if(typeof Promise>"u"){const e=qt("js-client-promise-polyfill");throw new Error(`No native Promise-implementation found, polyfill needed - see ${e}`)}if(o&&!n.projectId)throw new Error("Configuration must contain `projectId`");if("string"==typeof n.perspective&&Gt(n.perspective),"encodeSourceMap"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?");if("encodeSourceMapAtPath"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?");if("boolean"!=typeof n.stega.enabled)throw new Error(`stega.enabled must be a boolean, received ${n.stega.enabled}`);if(n.stega.enabled&&void 0===n.stega.studioUrl)throw new Error("stega.studioUrl must be defined when stega.enabled is true");if(n.stega.enabled&&"string"!=typeof n.stega.studioUrl&&"function"!=typeof n.stega.studioUrl)throw new Error(`stega.studioUrl must be a string or a function, received ${n.stega.studioUrl}`);const i=typeof window<"u"&&window.location&&window.location.hostname,s=i&&(e=>-1!==Jt.indexOf(e))(window.location.hostname);i&&s&&n.token&&!0!==n.ignoreBrowserTokenWarning?Ht():typeof n.useCdn>"u"&&Ut(),o&&(e=>{if(!/^[-a-z0-9]+$/i.test(e))throw new Error("`projectId` can only contain only a-z, 0-9 and dashes")})(n.projectId),n.dataset&&ht(n.dataset),"requestTagPrefix"in n&&(n.requestTagPrefix=n.requestTagPrefix?vt(n.requestTagPrefix).replace(/\.+$/,""):void 0),n.apiVersion=`${n.apiVersion}`.replace(/^v/,""),n.isDefaultApi=n.apiHost===Bt.apiHost,n.useCdn=!1!==n.useCdn&&!n.withCredentials,function(e){if("1"===e||"X"===e)return;const t=new Date(e);if(!(/^\d{4}-\d{2}-\d{2}$/.test(e)&&t instanceof Date&&t.getTime()>0))throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`")}(n.apiVersion);const a=n.apiHost.split("://",2),u=a[0],c=a[1],l=n.isDefaultApi?"apicdn.sanity.io":c;return n.useProjectHostname?(n.url=`${u}://${n.projectId}.${c}/v${n.apiVersion}`,n.cdnUrl=`${u}://${n.projectId}.${l}/v${n.apiVersion}`):(n.url=`${n.apiHost}/v${n.apiVersion}`,n.cdnUrl=n.url),n},Qt="X-Sanity-Project-ID";var Yt={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},Xt={0:8203,1:8204,2:8205,3:65279},Kt=new Array(4).fill(String.fromCodePoint(Xt[0])).join("");function Zt(e,t,r="auto"){return!0===r||"auto"===r&&(function(e){return!!Number.isNaN(Number(e))&&!!Date.parse(e)}(e)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(e))?e:`${e}${function(e){let t=JSON.stringify(e);return`${Kt}${Array.from(t).map((e=>{let r=e.charCodeAt(0);if(r>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${t} on character ${e} (${r})`);return Array.from(r.toString(4).padStart(4,"0")).map((e=>String.fromCodePoint(Xt[e]))).join("")})).join("")}`}(t)}`}Object.fromEntries(Object.entries(Xt).map((e=>e.reverse()))),Object.fromEntries(Object.entries(Yt).map((e=>e.reverse())));var er=`${Object.values(Yt).map((e=>`\\u{${e.toString(16)}}`)).join("")}`,tr=new RegExp(`[${er}]{4,}`,"gu");function rr(e){try{return JSON.parse(JSON.stringify(e,((e,t)=>{return"string"!=typeof t?t:(r=t,{cleaned:r.replace(tr,""),encoded:(null==(n=r.match(tr))?void 0:n[0])||""}).cleaned;var r,n})))}catch{return e}}const nr=({query:e,params:t={},options:r={}})=>{const n=new URLSearchParams,{tag:o,returnQuery:i,...s}=r;o&&n.append("tag",o),n.append("query",e);for(const[e,r]of Object.entries(t))n.append(`$${e}`,JSON.stringify(r));for(const[e,t]of Object.entries(s))t&&n.append(e,`${t}`);return!1===i&&n.append("returnQuery","false"),`?${n}`},or=(e={})=>{return{dryRun:e.dryRun,returnIds:!0,returnDocuments:(t=e.returnDocuments,r=!0,!1===t?void 0:typeof t>"u"?r:t),visibility:e.visibility||"sync",autoGenerateArrayKeys:e.autoGenerateArrayKeys,skipCrossDatasetReferenceValidation:e.skipCrossDatasetReferenceValidation};var t,r},ir=e=>"response"===e.type,sr=e=>e.body,ar=11264;function ur(e,t,r,n,o={},i={}){const s="stega"in i?{...r||{},..."boolean"==typeof i.stega?{enabled:i.stega}:i.stega||{}}:r,a=s.enabled?rr(o):o,u=!1===i.filterResponse?e=>e:e=>e.result,{cache:c,next:l,...d}={useAbortSignal:typeof i.signal<"u",resultSourceMap:s.enabled?"withKeyArraySelector":i.resultSourceMap,...i,returnQuery:!1===i.filterResponse&&!1!==i.returnQuery},f=yr(e,t,"query",{query:n,params:a},typeof c<"u"||typeof l<"u"?{...d,fetch:{cache:c,next:l}}:d);return s.enabled?f.pipe(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return et.apply(void 0,Z([],K(e)))}(Be(Promise.resolve().then((function(){return Qn})).then((function(e){return e.a})).then((({stegaEncodeSourceMap:e})=>e)))),Ve((([e,t])=>{const r=t(e.result,e.resultSourceMap,s);return u({...e,result:r})}))):f.pipe(Ve(u))}function cr(e,t,r,n={}){return mr(e,t,{uri:br(e,"doc",r),json:!0,tag:n.tag}).pipe(Ze(ir),Ve((e=>e.body.documents&&e.body.documents[0])))}function lr(e,t,r,n={}){return mr(e,t,{uri:br(e,"doc",r.join(",")),json:!0,tag:n.tag}).pipe(Ze(ir),Ve((e=>{const t=(n=e.body.documents||[],o=e=>e._id,n.reduce(((e,t)=>(e[o(t)]=t,e)),Object.create(null)));var n,o;return r.map((e=>t[e]||null))})))}function dr(e,t,r,n){return gt("createIfNotExists",r),gr(e,t,r,"createIfNotExists",n)}function fr(e,t,r,n){return gt("createOrReplace",r),gr(e,t,r,"createOrReplace",n)}function hr(e,t,r,n){return yr(e,t,"mutate",{mutations:[{delete:lt(r)}]},n)}function pr(e,t,r,n){let o;o=r instanceof Ot||r instanceof Tt?{patch:r.serialize()}:r instanceof Mt||r instanceof Ft?r.serialize():r;return yr(e,t,"mutate",{mutations:Array.isArray(o)?o:[o],transactionId:n&&n.transactionId||void 0},n)}function yr(e,t,r,n,o={}){const i="mutate"===r,s="query"===r,a=i?"":nr(n),u=!i&&a.length<ar,c=u?a:"",l=o.returnFirst,{timeout:d,token:f,tag:h,headers:p,returnQuery:y}=o;return mr(e,t,{method:u?"GET":"POST",uri:br(e,r,c),json:!0,body:u?void 0:n,query:i&&or(o),timeout:d,headers:p,token:f,tag:h,returnQuery:y,perspective:o.perspective,resultSourceMap:o.resultSourceMap,canUseCdn:s,signal:o.signal,fetch:o.fetch,useAbortSignal:o.useAbortSignal,useCdn:o.useCdn}).pipe(Ze(ir),Ve(sr),Ve((e=>{if(!i)return e;const t=e.results||[];if(o.returnDocuments)return l?t[0]&&t[0].document:t.map((e=>e.document));const r=l?"documentId":"documentIds",n=l?t[0]&&t[0].id:t.map((e=>e.id));return{transactionId:e.transactionId,results:t,[r]:n}})))}function gr(e,t,r,n,o={}){return yr(e,t,"mutate",{mutations:[{[n]:r}]},Object.assign({returnFirst:!0,returnDocuments:!0},o))}function mr(e,t,r){var n,o;const i=r.url||r.uri,s=e.config(),a=typeof r.canUseCdn>"u"?["GET","HEAD"].indexOf(r.method||"GET")>=0&&0===i.indexOf("/data/"):r.canUseCdn;let u=(null!=(n=r.useCdn)?n:s.useCdn)&&a;const c=r.tag&&s.requestTagPrefix?[s.requestTagPrefix,r.tag].join("."):r.tag||s.requestTagPrefix;if(c&&null!==r.tag&&(r.query={tag:vt(c),...r.query}),["GET","HEAD","POST"].indexOf(r.method||"GET")>=0&&0===i.indexOf("/data/query/")){const e=null!=(o=r.resultSourceMap)?o:s.resultSourceMap;void 0!==e&&!1!==e&&(r.query={resultSourceMap:e,...r.query});const t=r.perspective||s.perspective;"string"==typeof t&&"raw"!==t&&(Gt(t),r.query={perspective:t,...r.query},"previewDrafts"===t&&u&&(u=!1,Wt())),!1===r.returnQuery&&(r.query={returnQuery:"false",...r.query})}const l=function(e,t={}){const r={},n=t.token||e.token;n&&(r.Authorization=`Bearer ${n}`),!t.useGlobalApi&&!e.useProjectHostname&&e.projectId&&(r[Qt]=e.projectId);const o=!!(typeof t.withCredentials>"u"?e.token||e.withCredentials:t.withCredentials),i=typeof t.timeout>"u"?e.timeout:t.timeout;return Object.assign({},t,{headers:Object.assign({},r,t.headers||{}),timeout:typeof i>"u"?3e5:i,proxy:t.proxy||e.proxy,json:!0,withCredentials:o,fetch:"object"==typeof t.fetch&&"object"==typeof e.fetch?{...e.fetch,...t.fetch}:t.fetch||e.fetch})}(s,Object.assign({},r,{url:wr(e,i,u)})),d=new Se((e=>t(l,s.requester).subscribe(e)));return r.signal?d.pipe((f=r.signal,e=>new Se((t=>{const r=()=>t.error(function(e){var t,r;if(Cr)return new DOMException(null!=(t=null==e?void 0:e.reason)?t:"The operation was aborted.","AbortError");const n=new Error(null!=(r=null==e?void 0:e.reason)?r:"The operation was aborted.");return n.name="AbortError",n}(f));if(f&&f.aborted)return void r();const n=e.subscribe(t);return f.addEventListener("abort",r),()=>{f.removeEventListener("abort",r),n.unsubscribe()}})))):d;var f}function vr(e,t,r){return mr(e,t,r).pipe(Ze((e=>"response"===e.type)),Ve((e=>e.body)))}function br(e,t,r){const n=e.config(),o=`/${t}/${mt(n)}`;return`/data${r?`${o}/${r}`:o}`.replace(/\/($|\?)/,"$1")}function wr(e,t,r=!1){const{url:n,cdnUrl:o}=e.config();return`${r?o:n}/${t.replace(/^\//,"")}`}const Cr=!!globalThis.DOMException;var Er,xr,Sr,Tr,_r=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Or=(e,t,r)=>(_r(e,t,"read from private field"),r?r.call(e):t.get(e)),$r=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},jr=(e,t,r,n)=>(_r(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class kr{constructor(e,t){$r(this,Er,void 0),$r(this,xr,void 0),jr(this,Er,e),jr(this,xr,t)}upload(e,t,r){return Ir(Or(this,Er),Or(this,xr),e,t,r)}}Er=new WeakMap,xr=new WeakMap;class Ar{constructor(e,t){$r(this,Sr,void 0),$r(this,Tr,void 0),jr(this,Sr,e),jr(this,Tr,t)}upload(e,t,r){return Ge(Ir(Or(this,Sr),Or(this,Tr),e,t,r).pipe(Ze((e=>"response"===e.type)),Ve((e=>e.body.document))))}}function Ir(e,t,r,n,o={}){(e=>{if(-1===dt.indexOf(e))throw new Error(`Invalid asset type: ${e}. Must be one of ${dt.join(", ")}`)})(r);let i=o.extract||void 0;i&&!i.length&&(i=["none"]);const s=mt(e.config()),a="image"===r?"images":"files",u=function(e,t){return typeof File>"u"||!(t instanceof File)?e:Object.assign({filename:!1===e.preserveFilename?void 0:t.name,contentType:t.type},e)}(o,n),{tag:c,label:l,title:d,description:f,creditLine:h,filename:p,source:y}=u,g={label:l,title:d,description:f,filename:p,meta:i,creditLine:h};return y&&(g.sourceId=y.id,g.sourceName=y.name,g.sourceUrl=y.url),mr(e,t,{tag:c,method:"POST",timeout:u.timeout||0,uri:`/assets/${a}/${s}`,headers:u.contentType?{"Content-Type":u.contentType}:{},query:g,body:n})}Sr=new WeakMap,Tr=new WeakMap;const Pr=["includePreviousRevision","includeResult","visibility","effectFormat","tag"],Rr={includeResult:!0};function Mr(e,t,r={}){const{url:n,token:o,withCredentials:i,requestTagPrefix:s}=this.config(),a=r.tag&&s?[s,r.tag].join("."):r.tag,u={...(d=r,f=Rr,Object.keys(f).concat(Object.keys(d)).reduce(((e,t)=>(e[t]=typeof d[t]>"u"?f[t]:d[t],e)),{})),tag:a},c=((e,t)=>t.reduce(((t,r)=>(typeof e[r]>"u"||(t[r]=e[r]),t)),{}))(u,Pr),l=`${n}${br(this,"listen",nr({query:e,params:t,options:{tag:a,...c}}))}`;var d,f;if(l.length>14800)return new Se((e=>e.error(new Error("Query too large for listener"))));const h=u.events?u.events:["mutation"],p=-1!==h.indexOf("reconnect"),y={};return(o||i)&&(y.withCredentials=!0),o&&(y.headers={Authorization:`Bearer ${o}`}),new Se((e=>{let t;c().then((e=>{t=e})).catch((t=>{e.error(t),f()}));let r,n=!1;function o(){n||(p&&e.next({type:"reconnect"}),!n&&t.readyState===t.CLOSED&&(u(),clearTimeout(r),r=setTimeout(d,100)))}function i(t){e.error(function(e){if(e instanceof Error)return e;const t=Dr(e);return t instanceof Error?t:new Error(function(e){return e.error?e.error.description?e.error.description:"string"==typeof e.error?e.error:JSON.stringify(e.error,null,2):e.message||"Unknown listener error"}(t))}(t))}function s(t){const r=Dr(t);return r instanceof Error?e.error(r):e.next(r)}function a(){n=!0,u(),e.complete()}function u(){t&&(t.removeEventListener("error",o),t.removeEventListener("channelError",i),t.removeEventListener("disconnect",a),h.forEach((e=>t.removeEventListener(e,s))),t.close())}async function c(){const{default:e}=await Promise.resolve().then((function(){return Kn})),t=new e(l,y);return t.addEventListener("error",o),t.addEventListener("channelError",i),t.addEventListener("disconnect",a),h.forEach((e=>t.addEventListener(e,s))),t}function d(){c().then((e=>{t=e})).catch((t=>{e.error(t),f()}))}function f(){n=!0,u()}return f}))}function Dr(e){try{const t=e.data&&JSON.parse(e.data)||{};return Object.assign({type:e.type},t)}catch(e){return e}}var Fr,qr,Nr,Ur,Wr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Hr=(e,t,r)=>(Wr(e,t,"read from private field"),r?r.call(e):t.get(e)),zr=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Lr=(e,t,r,n)=>(Wr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Br{constructor(e,t){zr(this,Fr,void 0),zr(this,qr,void 0),Lr(this,Fr,e),Lr(this,qr,t)}create(e,t){return Gr(Hr(this,Fr),Hr(this,qr),"PUT",e,t)}edit(e,t){return Gr(Hr(this,Fr),Hr(this,qr),"PATCH",e,t)}delete(e){return Gr(Hr(this,Fr),Hr(this,qr),"DELETE",e)}list(){return vr(Hr(this,Fr),Hr(this,qr),{uri:"/datasets",tag:null})}}Fr=new WeakMap,qr=new WeakMap;class Jr{constructor(e,t){zr(this,Nr,void 0),zr(this,Ur,void 0),Lr(this,Nr,e),Lr(this,Ur,t)}create(e,t){return Ge(Gr(Hr(this,Nr),Hr(this,Ur),"PUT",e,t))}edit(e,t){return Ge(Gr(Hr(this,Nr),Hr(this,Ur),"PATCH",e,t))}delete(e){return Ge(Gr(Hr(this,Nr),Hr(this,Ur),"DELETE",e))}list(){return Ge(vr(Hr(this,Nr),Hr(this,Ur),{uri:"/datasets",tag:null}))}}function Gr(e,t,r,n,o){return ht(n),vr(e,t,{method:r,uri:`/datasets/${n}`,body:o,tag:null})}Nr=new WeakMap,Ur=new WeakMap;var Vr,Qr,Yr,Xr,Kr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Zr=(e,t,r)=>(Kr(e,t,"read from private field"),r?r.call(e):t.get(e)),en=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},tn=(e,t,r,n)=>(Kr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class rn{constructor(e,t){en(this,Vr,void 0),en(this,Qr,void 0),tn(this,Vr,e),tn(this,Qr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return vr(Zr(this,Vr),Zr(this,Qr),{uri:t})}getById(e){return vr(Zr(this,Vr),Zr(this,Qr),{uri:`/projects/${e}`})}}Vr=new WeakMap,Qr=new WeakMap;class nn{constructor(e,t){en(this,Yr,void 0),en(this,Xr,void 0),tn(this,Yr,e),tn(this,Xr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return Ge(vr(Zr(this,Yr),Zr(this,Xr),{uri:t}))}getById(e){return Ge(vr(Zr(this,Yr),Zr(this,Xr),{uri:`/projects/${e}`}))}}Yr=new WeakMap,Xr=new WeakMap;var on,sn,an,un,cn=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},ln=(e,t,r)=>(cn(e,t,"read from private field"),r?r.call(e):t.get(e)),dn=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},fn=(e,t,r,n)=>(cn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class hn{constructor(e,t){dn(this,on,void 0),dn(this,sn,void 0),fn(this,on,e),fn(this,sn,t)}getById(e){return vr(ln(this,on),ln(this,sn),{uri:`/users/${e}`})}}on=new WeakMap,sn=new WeakMap;class pn{constructor(e,t){dn(this,an,void 0),dn(this,un,void 0),fn(this,an,e),fn(this,un,t)}getById(e){return Ge(vr(ln(this,an),ln(this,un),{uri:`/users/${e}`}))}}an=new WeakMap,un=new WeakMap;var yn,gn,mn=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},vn=(e,t,r)=>(mn(e,t,"read from private field"),r?r.call(e):t.get(e)),bn=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},wn=(e,t,r,n)=>(mn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);yn=new WeakMap,gn=new WeakMap;let Cn=class e{constructor(e,t=Bt){bn(this,yn,void 0),bn(this,gn,void 0),this.listen=Mr,this.config(t),wn(this,gn,e),this.assets=new kr(this,vn(this,gn)),this.datasets=new Br(this,vn(this,gn)),this.projects=new rn(this,vn(this,gn)),this.users=new hn(this,vn(this,gn))}clone(){return new e(vn(this,gn),this.config())}config(e){if(void 0===e)return{...vn(this,yn)};if(vn(this,yn)&&!1===vn(this,yn).allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return wn(this,yn,Vt(e,vn(this,yn)||{})),this}withConfig(t){const r=this.config();return new e(vn(this,gn),{...r,...t,stega:{...r.stega||{},..."boolean"==typeof(null==t?void 0:t.stega)?{enabled:t.stega}:(null==t?void 0:t.stega)||{}}})}fetch(e,t,r){return ur(this,vn(this,gn),vn(this,yn).stega,e,t,r)}getDocument(e,t){return cr(this,vn(this,gn),e,t)}getDocuments(e,t){return lr(this,vn(this,gn),e,t)}create(e,t){return gr(this,vn(this,gn),e,"create",t)}createIfNotExists(e,t){return dr(this,vn(this,gn),e,t)}createOrReplace(e,t){return fr(this,vn(this,gn),e,t)}delete(e,t){return hr(this,vn(this,gn),e,t)}mutate(e,t){return pr(this,vn(this,gn),e,t)}patch(e,t){return new Tt(e,t,this)}transaction(e){return new Ft(e,this)}request(e){return vr(this,vn(this,gn),e)}getUrl(e,t){return wr(this,e,t)}getDataUrl(e,t){return br(this,e,t)}};var En,xn;En=new WeakMap,xn=new WeakMap;let Sn=class e{constructor(e,t=Bt){bn(this,En,void 0),bn(this,xn,void 0),this.listen=Mr,this.config(t),wn(this,xn,e),this.assets=new Ar(this,vn(this,xn)),this.datasets=new Jr(this,vn(this,xn)),this.projects=new nn(this,vn(this,xn)),this.users=new pn(this,vn(this,xn)),this.observable=new Cn(e,t)}clone(){return new e(vn(this,xn),this.config())}config(e){if(void 0===e)return{...vn(this,En)};if(vn(this,En)&&!1===vn(this,En).allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.observable&&this.observable.config(e),wn(this,En,Vt(e,vn(this,En)||{})),this}withConfig(t){const r=this.config();return new e(vn(this,xn),{...r,...t,stega:{...r.stega||{},..."boolean"==typeof(null==t?void 0:t.stega)?{enabled:t.stega}:(null==t?void 0:t.stega)||{}}})}fetch(e,t,r){return Ge(ur(this,vn(this,xn),vn(this,En).stega,e,t,r))}getDocument(e,t){return Ge(cr(this,vn(this,xn),e,t))}getDocuments(e,t){return Ge(lr(this,vn(this,xn),e,t))}create(e,t){return Ge(gr(this,vn(this,xn),e,"create",t))}createIfNotExists(e,t){return Ge(dr(this,vn(this,xn),e,t))}createOrReplace(e,t){return Ge(fr(this,vn(this,xn),e,t))}delete(e,t){return Ge(hr(this,vn(this,xn),e,t))}mutate(e,t){return Ge(pr(this,vn(this,xn),e,t))}patch(e,t){return new Ot(e,t,this)}transaction(e){return new Mt(e,this)}request(e){return Ge(vr(this,vn(this,xn),e))}dataRequest(e,t,r){return Ge(yr(this,vn(this,xn),e,t,r))}getUrl(e,t){return wr(this,e,t)}getDataUrl(e,t){return br(this,e,t)}};const Tn=(An=Sn,{requester:ut(kn=[],{}).defaultRequester,createClient:e=>new An(ut(kn,{maxRetries:e.maxRetries,retryDelay:e.retryDelay}),e)}),_n=Tn.requester,On=Tn.createClient,$n=(jn=On,function(e){return Lt(),jn(e)});var jn,kn,An;const In=/_key\s*==\s*['"](.*)['"]/;function Pn(e){if(!Array.isArray(e))throw new Error("Path is not an array");return e.reduce(((e,t,r)=>{const n=typeof t;if("number"===n)return`${e}[${t}]`;if("string"===n)return`${e}${0===r?"":"."}${t}`;if(function(e){return"string"==typeof e?In.test(e.trim()):"object"==typeof e&&"_key"in e}(t)&&t._key)return`${e}[_key=="${t._key}"]`;if(Array.isArray(t)){const[r,n]=t;return`${e}[${r}:${n}]`}throw new Error(`Unsupported path segment \`${JSON.stringify(t)}\``)}),"")}const Rn={"\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","'":"\\'","\\":"\\\\"},Mn={"\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t","\\'":"'","\\\\":"\\"};function Dn(e){const t=[],r=/\['(.*?)'\]|\[(\d+)\]|\[\?\(@\._key=='(.*?)'\)\]/g;let n;for(;null!==(n=r.exec(e));)if(void 0===n[1])if(void 0===n[2])if(void 0===n[3]);else{const e=n[3].replace(/\\(\\')/g,(e=>Mn[e]));t.push({_key:e,_index:-1})}else t.push(parseInt(n[2],10));else{const e=n[1].replace(/\\(\\|f|n|r|t|')/g,(e=>Mn[e]));t.push(e)}return t}function Fn(e){return e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(""!==e._key)return{_key:e._key};if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)}))}function qn(e,t){if(null==t||!t.mappings)return;const r=function(e){return`$${e.map((e=>"string"==typeof e?`['${e.replace(/[\f\n\r\t'\\]/g,(e=>Rn[e]))}']`:"number"==typeof e?`[${e}]`:""!==e._key?`[?(@._key=='${e._key.replace(/['\\]/g,(e=>Rn[e]))}')]`:`[${e._index}]`)).join("")}`}(e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)})));if(void 0!==t.mappings[r])return{mapping:t.mappings[r],matchedPath:r,pathSuffix:""};const n=Object.entries(t.mappings).filter((([e])=>r.startsWith(e))).sort((([e],[t])=>t.length-e.length));if(0==n.length)return;const[o,i]=n[0];return{mapping:i,matchedPath:o,pathSuffix:r.substring(o.length)}}function Nn(e){return"object"==typeof e&&null!==e}function Un(e,t,r=[]){return function(e){return null!==e&&Array.isArray(e)}(e)?e.map(((e,n)=>{if(Nn(e)){const o=e._key;if("string"==typeof o)return Un(e,t,r.concat({_key:o,_index:n}))}return Un(e,t,r.concat(n))})):Nn(e)?Object.fromEntries(Object.entries(e).map((([e,n])=>[e,Un(n,t,r.concat(e))]))):t(e,r)}function Wn(e,t,r){return Un(e,((e,n)=>{if("string"!=typeof e)return e;const o=qn(n,t);if(!o)return e;const{mapping:i,matchedPath:s}=o;if("value"!==i.type||"documentValue"!==i.source.type)return e;const a=t.documents[i.source.document],u=t.paths[i.source.path],c=Dn(s),l=Dn(u).concat(n.slice(c.length));return r({sourcePath:l,sourceDocument:a,resultPath:n,value:e})}))}const Hn="drafts.";function zn(e){const{baseUrl:t,workspace:r="default",tool:n="default",id:o,type:i,path:s,projectId:a,dataset:u}=e;if(!t)throw new Error("baseUrl is required");if(!s)throw new Error("path is required");if(!o)throw new Error("id is required");if("/"!==t&&t.endsWith("/"))throw new Error("baseUrl must not end with a slash");const c="default"===r?void 0:r,l="default"===n?void 0:n,d=function(e){return e.startsWith(Hn)?e.slice(Hn.length):e}(o),f=Array.isArray(s)?Pn(Fn(s)):s,h=new URLSearchParams({baseUrl:t,id:d,type:i,path:f});c&&h.set("workspace",c),l&&h.set("tool",l),a&&h.set("projectId",a),u&&h.set("dataset",u);const p=["/"===t?"":t];c&&p.push(c);const y=["mode=presentation",`id=${d}`,`type=${i}`,`path=${encodeURIComponent(f)}`];return l&&y.push(`tool=${l}`),p.push("intent","edit",`${y.join(";")}?${h}`),p.join("/")}const Ln=({sourcePath:e,value:t})=>{if(/^\d{4}-\d{2}-\d{2}/.test(r=t)&&Date.parse(r)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(t))return!1;var r;const n=e.at(-1);return!("slug"===e.at(-2)&&"current"===n||"string"==typeof n&&n.startsWith("_")||"number"==typeof n&&"marks"===e.at(-2)||"href"===n&&"number"==typeof e.at(-2)&&"markDefs"===e.at(-3)||"style"===n||"listItem"===n||e.some((e=>"meta"===e||"metadata"===e||"openGraph"===e||"seo"===e))||"string"==typeof n&&Bn.has(n))},Bn=new Set(["color","colour","currency","email","format","gid","hex","href","hsl","hsla","icon","id","index","key","language","layout","link","linkAction","locale","lqip","page","path","ref","rgb","rgba","route","secret","slug","status","tag","template","theme","type","unit","url","username","variant","website"]);function Jn(e,t,r){var n,o,i,s,a,u,c,l,d;const{filter:f,logger:h,enabled:p}=r;if(!p){const o="config.enabled must be true, don't call this function otherwise";throw null==(n=null==h?void 0:h.error)||n.call(h,`[@sanity/client]: ${o}`,{result:e,resultSourceMap:t,config:r}),new TypeError(o)}if(!t)return null==(o=null==h?void 0:h.error)||o.call(h,"[@sanity/client]: Missing Content Source Map from response body",{result:e,resultSourceMap:t,config:r}),e;if(!r.studioUrl){const n="config.studioUrl must be defined";throw null==(i=null==h?void 0:h.error)||i.call(h,`[@sanity/client]: ${n}`,{result:e,resultSourceMap:t,config:r}),new TypeError(n)}const y={encoded:[],skipped:[]},g=Wn(e,t,(({sourcePath:e,sourceDocument:t,resultPath:n,value:o})=>{if(!1===("function"==typeof f?f({sourcePath:e,resultPath:n,filterDefault:Ln,sourceDocument:t,value:o}):Ln({sourcePath:e,resultPath:n,filterDefault:Ln,sourceDocument:t,value:o})))return h&&y.skipped.push({path:Gn(e),value:`${o.slice(0,20)}${o.length>20?"...":""}`,length:o.length}),o;h&&y.encoded.push({path:Gn(e),value:`${o.slice(0,20)}${o.length>20?"...":""}`,length:o.length});const{baseUrl:i,workspace:s,tool:a}=function(e){let t="string"==typeof e?e:e.baseUrl;return"/"!==t&&(t=t.replace(/\/$/,"")),"string"==typeof e?{baseUrl:t}:{...e,baseUrl:t}}("function"==typeof r.studioUrl?r.studioUrl(t):r.studioUrl);if(!i)return o;const{_id:u,_type:c,_projectId:l,_dataset:d}=t;return Zt(o,{origin:"sanity.io",href:zn({baseUrl:i,workspace:s,tool:a,id:u,type:c,path:e,...!r.omitCrossDatasetReferenceData&&{dataset:d,projectId:l}})},!1)}));if(h){const e=y.skipped.length,t=y.encoded.length;if((e||t)&&(null==(s=(null==h?void 0:h.groupCollapsed)||h.log)||s("[@sanity/client]: Encoding source map into result"),null==(a=h.log)||a.call(h,`[@sanity/client]: Paths encoded: ${y.encoded.length}, skipped: ${y.skipped.length}`)),y.encoded.length>0&&(null==(u=null==h?void 0:h.log)||u.call(h,"[@sanity/client]: Table of encoded paths"),null==(c=(null==h?void 0:h.table)||h.log)||c(y.encoded)),y.skipped.length>0){const e=new Set;for(const{path:t}of y.skipped)e.add(t.replace(In,"0").replace(/\[\d+\]/g,"[]"));null==(l=null==h?void 0:h.log)||l.call(h,"[@sanity/client]: List of skipped paths",[...e.values()])}(e||t)&&(null==(d=null==h?void 0:h.groupEnd)||d.call(h))}return g}function Gn(e){return Pn(Fn(e))}var Vn=Object.freeze({__proto__:null,stegaEncodeSourceMap:Jn}),Qn=Object.freeze({__proto__:null,a:Vn,e:Wn,s:Jn}),Yn={exports:{}};
8
+ function R(e){return"[object Object]"===Object.prototype.toString.call(e)}!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=P(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(A,A.exports);const M=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e),D=["boolean","string","number"];function F(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||M(t)||-1===D.indexOf(typeof t)&&!Array.isArray(t)&&(!1===R(r=t)||void 0!==(n=r.constructor)&&(!1===R(o=n.prototype)||!1===o.hasOwnProperty("isPrototypeOf")))?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})});var r,n,o}}}function q(e){return{onResponse:r=>{const n=r.headers["content-type"]||"",o=e&&e.force||-1!==n.indexOf("application/json");return r.body&&n&&o?Object.assign({},r,{body:t(r.body)}):r},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:"application/json"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}let N={};typeof globalThis<"u"?N=globalThis:typeof window<"u"?N=window:typeof global<"u"?N=global:typeof self<"u"&&(N=self);var U=N;function W(e={}){const t=e.implementation||U.Observable;if(!t)throw new Error("`Observable` is not available in global scope, and no implementation was passed");return{onReturn:(e,r)=>new t((t=>(e.error.subscribe((e=>t.error(e))),e.progress.subscribe((e=>t.next(Object.assign({type:"progress"},e)))),e.response.subscribe((e=>{t.next(Object.assign({type:"response"},e)),t.complete()})),e.request.publish(r),()=>e.abort.publish())))}}class H{constructor(e){this.__CANCEL__=!0,this.message=e}toString(){return"Cancel"+(this.message?`: ${this.message}`:"")}}const z=class{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t=null;this.promise=new Promise((e=>{t=e})),e((e=>{this.reason||(this.reason=new H(e),t(this.reason))}))}};z.source=()=>{let e;return{token:new z((t=>{e=t})),cancel:e}};var L=(e,t,r)=>("GET"===r.method||"HEAD"===r.method)&&(e.isNetworkError||!1);function B(e){return 100*Math.pow(2,e)+100*Math.random()}const J=(e={})=>(e=>{const t=e.maxRetries||5,r=e.retryDelay||B,n=e.shouldRetry;return{onError:(e,o)=>{const i=o.options,s=i.maxRetries||t,a=i.shouldRetry||n,u=i.attemptNumber||0;if(null!==(c=i.body)&&"object"==typeof c&&"function"==typeof c.pipe||!a(e,u,i)||u>=s)return e;var c;const l=Object.assign({},o,{options:Object.assign({},i,{attemptNumber:u+1})});return setTimeout((()=>o.channels.request.publish(l)),r(u)),null}}})({shouldRetry:L,...e});J.shouldRetry=L;var G=function(e,t){return G=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},G(e,t)};function V(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}G(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Q(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))}function Y(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(u){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function X(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function K(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function Z(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}function ee(e){return this instanceof ee?(this.v=e,this):new ee(e)}function te(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n={},s("next"),s("throw"),s("return"),n[Symbol.asyncIterator]=function(){return this},n;function s(e){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))})}function a(e,t){try{(r=o[e](t)).value instanceof ee?Promise.resolve(r.value.v).then(u,c):l(i[0][2],r)}catch(e){l(i[0][3],e)}var r}function u(e){a("next",e)}function c(e){a("throw",e)}function l(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function re(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=X(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,o,(t=e[r](t)).done,t.value)}))}}}function ne(e){return"function"==typeof e}function oe(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var ie=oe((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function se(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var ae=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=X(i),a=s.next();!a.done;a=s.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var u=this.initialTeardown;if(ne(u))try{u()}catch(e){o=e instanceof ie?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var l=X(c),d=l.next();!d.done;d=l.next()){var f=d.value;try{ce(f)}catch(e){o=null!=o?o:[],e instanceof ie?o=Z(Z([],K(o)),K(e.errors)):o.push(e)}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(o)throw new ie(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)ce(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&se(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&se(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function ue(e){return e instanceof ae||e&&"closed"in e&&ne(e.remove)&&ne(e.add)&&ne(e.unsubscribe)}function ce(e){ne(e)?e():e.unsubscribe()}ae.EMPTY;var le={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},de={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,Z([e,t],K(r)))},clearTimeout:function(e){var t=de.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function fe(e){de.setTimeout((function(){throw e}))}function he(){}var pe=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,ue(t)&&t.add(r)):r.destination=we,r}return V(t,e),t.create=function(e,t,r){return new ve(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(ae),ye=Function.prototype.bind;function ge(e,t){return ye.call(e,t)}var me=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){be(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){be(e)}else be(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){be(e)}},e}(),ve=function(e){function t(t,r,n){var o,i,s=e.call(this)||this;ne(t)||!t?o={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:s&&le.useDeprecatedNextContext?((i=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&ge(t.next,i),error:t.error&&ge(t.error,i),complete:t.complete&&ge(t.complete,i)}):o=t;return s.destination=new me(o),s}return V(t,e),t}(pe);function be(e){fe(e)}var we={closed:!0,next:he,error:function(e){throw e},complete:he},Ce="function"==typeof Symbol&&Symbol.observable||"@@observable";function Ee(e){return e}function xe(e){return 0===e.length?Ee:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Se=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var n,o=this,i=(n=e)&&n instanceof pe||function(e){return e&&ne(e.next)&&ne(e.error)&&ne(e.complete)}(n)&&ue(n)?e:new ve(e,t,r);return function(){var e=o,t=e.operator,r=e.source;i.add(t?t.call(i,r):r?o._subscribe(i):o._trySubscribe(i))}(),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=Te(t))((function(t,n){var o=new ve({next:function(t){try{e(t)}catch(e){n(e),o.unsubscribe()}},error:n,complete:t});r.subscribe(o)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[Ce]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return xe(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=Te(e))((function(e,r){var n;t.subscribe((function(e){return n=e}),(function(e){return r(e)}),(function(){return e(n)}))}))},e.create=function(t){return new e(t)},e}();function Te(e){var t;return null!==(t=null!=e?e:le.Promise)&&void 0!==t?t:Promise}function _e(e){return function(t){if(function(e){return ne(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}function Oe(e,t,r,n,o){return new $e(e,t,r,n,o)}var $e=function(e){function t(t,r,n,o,i,s){var a=e.call(this,t)||this;return a.onFinalize=i,a.shouldUnsubscribe=s,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return V(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(pe);var je=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function ke(e){return ne(null==e?void 0:e.then)}function Ae(e){return ne(e[Ce])}function Ie(e){return Symbol.asyncIterator&&ne(null==e?void 0:e[Symbol.asyncIterator])}function Pe(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var Re="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function Me(e){return ne(null==e?void 0:e[Re])}function De(e){return te(this,arguments,(function(){var t,r,n;return Y(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,ee(t.read())];case 3:return r=o.sent(),n=r.value,r.done?[4,ee(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,ee(n)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function Fe(e){return ne(null==e?void 0:e.getReader)}function qe(e){if(e instanceof Se)return e;if(null!=e){if(Ae(e))return o=e,new Se((function(e){var t=o[Ce]();if(ne(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(je(e))return n=e,new Se((function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()}));if(ke(e))return r=e,new Se((function(e){r.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,fe)}));if(Ie(e))return Ne(e);if(Me(e))return t=e,new Se((function(e){var r,n;try{for(var o=X(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()}));if(Fe(e))return Ne(De(e))}var t,r,n,o;throw Pe(e)}function Ne(e){return new Se((function(t){(function(e,t){var r,n,o,i;return Q(this,void 0,void 0,(function(){var s,a;return Y(this,(function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),r=re(e),u.label=1;case 1:return[4,r.next()];case 2:if((n=u.sent()).done)return[3,4];if(s=n.value,t.next(s),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=u.sent(),o={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(i=r.return)?[4,i.call(r)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function Ue(e,t,r,n,o){void 0===n&&(n=0),void 0===o&&(o=!1);var i=t.schedule((function(){r(),o?e.add(this.schedule(null,n)):this.unsubscribe()}),n);if(e.add(i),!o)return i}function We(e,t){return void 0===t&&(t=0),_e((function(r,n){r.subscribe(Oe(n,(function(r){return Ue(n,e,(function(){return n.next(r)}),t)}),(function(){return Ue(n,e,(function(){return n.complete()}),t)}),(function(r){return Ue(n,e,(function(){return n.error(r)}),t)})))}))}function He(e,t){return void 0===t&&(t=0),_e((function(r,n){n.add(e.schedule((function(){return r.subscribe(n)}),t))}))}function ze(e,t){if(!e)throw new Error("Iterable cannot be null");return new Se((function(r){Ue(r,t,(function(){var n=e[Symbol.asyncIterator]();Ue(r,t,(function(){n.next().then((function(e){e.done?r.complete():r.next(e.value)}))}),0,!0)}))}))}function Le(e,t){if(null!=e){if(Ae(e))return function(e,t){return qe(e).pipe(He(t),We(t))}(e,t);if(je(e))return function(e,t){return new Se((function(r){var n=0;return t.schedule((function(){n===e.length?r.complete():(r.next(e[n++]),r.closed||this.schedule())}))}))}(e,t);if(ke(e))return function(e,t){return qe(e).pipe(He(t),We(t))}(e,t);if(Ie(e))return ze(e,t);if(Me(e))return function(e,t){return new Se((function(r){var n;return Ue(r,t,(function(){n=e[Re](),Ue(r,t,(function(){var e,t,o;try{t=(e=n.next()).value,o=e.done}catch(e){return void r.error(e)}o?r.complete():r.next(t)}),0,!0)})),function(){return ne(null==n?void 0:n.return)&&n.return()}}))}(e,t);if(Fe(e))return function(e,t){return ze(De(e),t)}(e,t)}throw Pe(e)}function Be(e,t){return t?Le(e,t):qe(e)}var Je=oe((function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Ge(e,t){var r="object"==typeof t;return new Promise((function(n,o){var i,s=!1;e.subscribe({next:function(e){i=e,s=!0},error:o,complete:function(){s?n(i):r?n(t.defaultValue):o(new Je)}})}))}function Ve(e,t){return _e((function(r,n){var o=0;r.subscribe(Oe(n,(function(r){n.next(e.call(t,r,o++))})))}))}var Qe=Array.isArray;function Ye(e){return Ve((function(t){return function(e,t){return Qe(t)?e.apply(void 0,Z([],K(t))):e(t)}(e,t)}))}function Xe(e,t,r){e?Ue(r,e,t):t()}var Ke=Array.isArray;function Ze(e,t){return _e((function(r,n){var o=0;r.subscribe(Oe(n,(function(r){return e.call(t,r,o++)&&n.next(r)})))}))}function et(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(e){return ne((t=e)[t.length-1])?e.pop():void 0;var t}(e);return r?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return xe(e)}(et.apply(void 0,Z([],K(e))),Ye(r)):_e((function(t,r){var n,o,i;(n=Z([t],K(function(e){return 1===e.length&&Ke(e[0])?e[0]:e}(e))),void 0===i&&(i=Ee),function(e){Xe(o,(function(){for(var t=n.length,r=new Array(t),s=t,a=t,u=function(t){Xe(o,(function(){var u=Be(n[t],o),c=!1;u.subscribe(Oe(e,(function(n){r[t]=n,c||(c=!0,a--),a||e.next(i(r.slice()))}),(function(){--s||e.complete()})))}),e)},c=0;c<t;c++)u(c)}),e)})(r)}))}class tt extends Error{constructor(e){const t=nt(e);super(t.message),this.statusCode=400,Object.assign(this,t)}}class rt extends Error{constructor(e){const t=nt(e);super(t.message),this.statusCode=500,Object.assign(this,t)}}function nt(e){const t=e.body,r={response:e,statusCode:e.statusCode,responseBody:it(t,e),message:"",details:void 0};if(t.error&&t.message)return r.message=`${t.error} - ${t.message}`,r;if(function(e){return ot(e)&&ot(e.error)&&"mutationError"===e.error.type&&"string"==typeof e.error.description}(t)){const e=t.error.items||[],n=e.slice(0,5).map((e=>{var t;return null==(t=e.error)?void 0:t.description})).filter(Boolean);let o=n.length?`:\n- ${n.join("\n- ")}`:"";return e.length>5&&(o+=`\n...and ${e.length-5} more`),r.message=`${t.error.description}${o}`,r.details=t.error,r}return t.error&&t.error.description?(r.message=t.error.description,r.details=t.error,r):(r.message=t.error||t.message||function(e){const t=e.statusMessage?` ${e.statusMessage}`:"";return`${e.method}-request to ${e.url} resulted in HTTP ${e.statusCode}${t}`}(e),r)}function ot(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function it(e,t){return-1!==(t.headers["content-type"]||"").toLowerCase().indexOf("application/json")?JSON.stringify(e,null,2):e}const st={onResponse:e=>{if(e.statusCode>=500)throw new rt(e);if(e.statusCode>=400)throw new tt(e);return e}},at={onResponse:e=>{const t=e.headers["x-sanity-warning"];return(Array.isArray(t)?t:[t]).filter(Boolean).forEach((e=>console.warn(e))),e}};function ut(e,{maxRetries:t=5,retryDelay:r}){const n=$([t>0?J({retryDelay:r,maxRetries:t,shouldRetry:ct}):{},...e,at,F(),q(),{onRequest:e=>{if("xhr"!==e.adapter)return;const t=e.request,r=e.context;function n(e){return t=>{const n=t.lengthComputable?t.loaded/t.total*100:-1;r.channels.progress.publish({stage:e,percent:n,total:t.total,loaded:t.loaded,lengthComputable:t.lengthComputable})}}"upload"in t&&"onprogress"in t.upload&&(t.upload.onprogress=n("upload")),"onprogress"in t&&(t.onprogress=n("download"))}},st,W({implementation:Se})]);function o(e,t=n){return t({maxRedirects:0,...e})}return o.defaultRequester=n,o}function ct(e,t,r){const n="GET"===r.method||"HEAD"===r.method,o=(r.uri||r.url).startsWith("/data/query"),i=e.response&&(429===e.response.statusCode||502===e.response.statusCode||503===e.response.statusCode);return!(!n&&!o||!i)||J.shouldRetry(e,t,r)}function lt(e){if("string"==typeof e)return{id:e};if(Array.isArray(e))return{query:"*[_id in $ids]",params:{ids:e}};if("object"==typeof e&&null!==e&&"query"in e&&"string"==typeof e.query)return"params"in e&&"object"==typeof e.params&&null!==e.params?{query:e.query,params:e.params}:{query:e.query};const t=["* Document ID (<docId>)","* Array of document IDs","* Object containing `query`"].join("\n");throw new Error(`Unknown selection - must be one of:\n\n${t}`)}const dt=["image","file"],ft=["before","after","replace"],ht=e=>{if(!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(e))throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters")},pt=(e,t)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new Error(`${e}() takes an object of properties`)},yt=(e,t)=>{if("string"!=typeof t||!/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(t)||t.includes(".."))throw new Error(`${e}(): "${t}" is not a valid document ID`)},gt=(e,t)=>{if(!t._id)throw new Error(`${e}() requires that the document contains an ID ("_id" property)`);yt(e,t._id)},mt=e=>{if(!e.dataset)throw new Error("`dataset` must be provided to perform queries");return e.dataset||""},vt=e=>{if("string"!=typeof e||!/^[a-z0-9._-]{1,75}$/i.test(e))throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");return e};var bt,wt=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Ct=(e,t,r)=>(wt(e,t,"read from private field"),r?r.call(e):t.get(e)),Et=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},xt=(e,t,r,n)=>(wt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class St{constructor(e,t={}){this.selection=e,this.operations=t}set(e){return this._assign("set",e)}setIfMissing(e){return this._assign("setIfMissing",e)}diffMatchPatch(e){return pt("diffMatchPatch",e),this._assign("diffMatchPatch",e)}unset(e){if(!Array.isArray(e))throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");return this.operations=Object.assign({},this.operations,{unset:e}),this}inc(e){return this._assign("inc",e)}dec(e){return this._assign("dec",e)}insert(e,t,r){return((e,t,r)=>{const n="insert(at, selector, items)";if(-1===ft.indexOf(e)){const e=ft.map((e=>`"${e}"`)).join(", ");throw new Error(`${n} takes an "at"-argument which is one of: ${e}`)}if("string"!=typeof t)throw new Error(`${n} takes a "selector"-argument which must be a string`);if(!Array.isArray(r))throw new Error(`${n} takes an "items"-argument which must be an array`)})(e,t,r),this._assign("insert",{[e]:t,items:r})}append(e,t){return this.insert("after",`${e}[-1]`,t)}prepend(e,t){return this.insert("before",`${e}[0]`,t)}splice(e,t,r,n){const o=t<0?t-1:t,i=typeof r>"u"||-1===r?-1:Math.max(0,t+r),s=`${e}[${o}:${o<0&&i>=0?"":i}]`;return this.insert("replace",s,n||[])}ifRevisionId(e){return this.operations.ifRevisionID=e,this}serialize(){return{...lt(this.selection),...this.operations}}toJSON(){return this.serialize()}reset(){return this.operations={},this}_assign(e,t,r=!0){return pt(e,t),this.operations=Object.assign({},this.operations,{[e]:Object.assign({},r&&this.operations[e]||{},t)}),this}_set(e,t){return this._assign(e,t,!1)}}bt=new WeakMap;let Tt=class e extends St{constructor(e,t,r){super(e,t),Et(this,bt,void 0),xt(this,bt,r)}clone(){return new e(this.selection,{...this.operations},Ct(this,bt))}commit(e){if(!Ct(this,bt))throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return Ct(this,bt).mutate({patch:this.serialize()},r)}};var _t;_t=new WeakMap;let Ot=class e extends St{constructor(e,t,r){super(e,t),Et(this,_t,void 0),xt(this,_t,r)}clone(){return new e(this.selection,{...this.operations},Ct(this,_t))}commit(e){if(!Ct(this,_t))throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return Ct(this,_t).mutate({patch:this.serialize()},r)}};var $t=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},jt=(e,t,r)=>($t(e,t,"read from private field"),r?r.call(e):t.get(e)),kt=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},At=(e,t,r,n)=>($t(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);const It={returnDocuments:!1};class Pt{constructor(e=[],t){this.operations=e,this.trxId=t}create(e){return pt("create",e),this._add({create:e})}createIfNotExists(e){const t="createIfNotExists";return pt(t,e),gt(t,e),this._add({[t]:e})}createOrReplace(e){const t="createOrReplace";return pt(t,e),gt(t,e),this._add({[t]:e})}delete(e){return yt("delete",e),this._add({delete:{id:e}})}transactionId(e){return e?(this.trxId=e,this):this.trxId}serialize(){return[...this.operations]}toJSON(){return this.serialize()}reset(){return this.operations=[],this}_add(e){return this.operations.push(e),this}}var Rt;Rt=new WeakMap;let Mt=class e extends Pt{constructor(e,t,r){super(e,r),kt(this,Rt,void 0),At(this,Rt,t)}clone(){return new e([...this.operations],jt(this,Rt),this.trxId)}commit(e){if(!jt(this,Rt))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return jt(this,Rt).mutate(this.serialize(),Object.assign({transactionId:this.trxId},It,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof Ot)return this._add({patch:e.serialize()});if(r){const r=t(new Ot(e,{},jt(this,Rt)));if(!(r instanceof Ot))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}};var Dt;Dt=new WeakMap;let Ft=class e extends Pt{constructor(e,t,r){super(e,r),kt(this,Dt,void 0),At(this,Dt,t)}clone(){return new e([...this.operations],jt(this,Dt),this.trxId)}commit(e){if(!jt(this,Dt))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return jt(this,Dt).mutate(this.serialize(),Object.assign({transactionId:this.trxId},It,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof Tt)return this._add({patch:e.serialize()});if(r){const r=t(new Tt(e,{},jt(this,Dt)));if(!(r instanceof Tt))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}};function qt(e){return"https://www.sanity.io/help/"+e}const Nt=e=>function(e){let t,r=!1;return(...n)=>(r||(t=e(...n),r=!0),t)}(((...t)=>console.warn(e.join(" "),...t))),Ut=Nt(["Since you haven't set a value for `useCdn`, we will deliver content using our","global, edge-cached API-CDN. If you wish to have content delivered faster, set","`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]),Wt=Nt(["The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.","The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]),Ht=Nt(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",`See ${qt("js-client-browser-token")} for more information and how to hide this warning.`]),zt=Nt(["Using the Sanity client without specifying an API version is deprecated.",`See ${qt("js-client-api-version")}`]),Lt=Nt(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]),Bt={apiHost:"https://api.sanity.io",apiVersion:"1",useProjectHostname:!0,stega:{enabled:!1}},Jt=["localhost","127.0.0.1","0.0.0.0"];const Gt=function(e){switch(e){case"previewDrafts":case"published":case"raw":return;default:throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`")}},Vt=(e,t)=>{const r={...t,...e,stega:{..."boolean"==typeof t.stega?{enabled:t.stega}:t.stega||Bt.stega,..."boolean"==typeof e.stega?{enabled:e.stega}:e.stega||{}}};r.apiVersion||zt();const n={...Bt,...r},o=n.useProjectHostname;if(typeof Promise>"u"){const e=qt("js-client-promise-polyfill");throw new Error(`No native Promise-implementation found, polyfill needed - see ${e}`)}if(o&&!n.projectId)throw new Error("Configuration must contain `projectId`");if("string"==typeof n.perspective&&Gt(n.perspective),"encodeSourceMap"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?");if("encodeSourceMapAtPath"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?");if("boolean"!=typeof n.stega.enabled)throw new Error(`stega.enabled must be a boolean, received ${n.stega.enabled}`);if(n.stega.enabled&&void 0===n.stega.studioUrl)throw new Error("stega.studioUrl must be defined when stega.enabled is true");if(n.stega.enabled&&"string"!=typeof n.stega.studioUrl&&"function"!=typeof n.stega.studioUrl)throw new Error(`stega.studioUrl must be a string or a function, received ${n.stega.studioUrl}`);const i=typeof window<"u"&&window.location&&window.location.hostname,s=i&&(e=>-1!==Jt.indexOf(e))(window.location.hostname);i&&s&&n.token&&!0!==n.ignoreBrowserTokenWarning?Ht():typeof n.useCdn>"u"&&Ut(),o&&(e=>{if(!/^[-a-z0-9]+$/i.test(e))throw new Error("`projectId` can only contain only a-z, 0-9 and dashes")})(n.projectId),n.dataset&&ht(n.dataset),"requestTagPrefix"in n&&(n.requestTagPrefix=n.requestTagPrefix?vt(n.requestTagPrefix).replace(/\.+$/,""):void 0),n.apiVersion=`${n.apiVersion}`.replace(/^v/,""),n.isDefaultApi=n.apiHost===Bt.apiHost,n.useCdn=!1!==n.useCdn&&!n.withCredentials,function(e){if("1"===e||"X"===e)return;const t=new Date(e);if(!(/^\d{4}-\d{2}-\d{2}$/.test(e)&&t instanceof Date&&t.getTime()>0))throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`")}(n.apiVersion);const a=n.apiHost.split("://",2),u=a[0],c=a[1],l=n.isDefaultApi?"apicdn.sanity.io":c;return n.useProjectHostname?(n.url=`${u}://${n.projectId}.${c}/v${n.apiVersion}`,n.cdnUrl=`${u}://${n.projectId}.${l}/v${n.apiVersion}`):(n.url=`${n.apiHost}/v${n.apiVersion}`,n.cdnUrl=n.url),n},Qt="X-Sanity-Project-ID";var Yt={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},Xt={0:8203,1:8204,2:8205,3:65279},Kt=new Array(4).fill(String.fromCodePoint(Xt[0])).join("");function Zt(e,t,r="auto"){return!0===r||"auto"===r&&(function(e){return!!Number.isNaN(Number(e))&&!!Date.parse(e)}(e)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(e))?e:`${e}${function(e){let t=JSON.stringify(e);return`${Kt}${Array.from(t).map((e=>{let r=e.charCodeAt(0);if(r>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${t} on character ${e} (${r})`);return Array.from(r.toString(4).padStart(4,"0")).map((e=>String.fromCodePoint(Xt[e]))).join("")})).join("")}`}(t)}`}Object.fromEntries(Object.entries(Xt).map((e=>e.reverse()))),Object.fromEntries(Object.entries(Yt).map((e=>e.reverse())));var er=`${Object.values(Yt).map((e=>`\\u{${e.toString(16)}}`)).join("")}`,tr=new RegExp(`[${er}]{4,}`,"gu");function rr(e){try{return JSON.parse(JSON.stringify(e,((e,t)=>{return"string"!=typeof t?t:(r=t,{cleaned:r.replace(tr,""),encoded:(null==(n=r.match(tr))?void 0:n[0])||""}).cleaned;var r,n})))}catch{return e}}const nr=({query:e,params:t={},options:r={}})=>{const n=new URLSearchParams,{tag:o,returnQuery:i,...s}=r;o&&n.append("tag",o),n.append("query",e);for(const[e,r]of Object.entries(t))n.append(`$${e}`,JSON.stringify(r));for(const[e,t]of Object.entries(s))t&&n.append(e,`${t}`);return!1===i&&n.append("returnQuery","false"),`?${n}`},or=(e={})=>{return{dryRun:e.dryRun,returnIds:!0,returnDocuments:(t=e.returnDocuments,r=!0,!1===t?void 0:typeof t>"u"?r:t),visibility:e.visibility||"sync",autoGenerateArrayKeys:e.autoGenerateArrayKeys,skipCrossDatasetReferenceValidation:e.skipCrossDatasetReferenceValidation};var t,r},ir=e=>"response"===e.type,sr=e=>e.body,ar=11264;function ur(e,t,r,n,o={},i={}){const s="stega"in i?{...r||{},..."boolean"==typeof i.stega?{enabled:i.stega}:i.stega||{}}:r,a=s.enabled?rr(o):o,u=!1===i.filterResponse?e=>e:e=>e.result,{cache:c,next:l,...d}={useAbortSignal:typeof i.signal<"u",resultSourceMap:s.enabled?"withKeyArraySelector":i.resultSourceMap,...i,returnQuery:!1===i.filterResponse&&!1!==i.returnQuery},f=yr(e,t,"query",{query:n,params:a},typeof c<"u"||typeof l<"u"?{...d,fetch:{cache:c,next:l}}:d);return s.enabled?f.pipe(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return et.apply(void 0,Z([],K(e)))}(Be(Promise.resolve().then((function(){return Qn})).then((function(e){return e.a})).then((({stegaEncodeSourceMap:e})=>e)))),Ve((([e,t])=>{const r=t(e.result,e.resultSourceMap,s);return u({...e,result:r})}))):f.pipe(Ve(u))}function cr(e,t,r,n={}){return mr(e,t,{uri:br(e,"doc",r),json:!0,tag:n.tag}).pipe(Ze(ir),Ve((e=>e.body.documents&&e.body.documents[0])))}function lr(e,t,r,n={}){return mr(e,t,{uri:br(e,"doc",r.join(",")),json:!0,tag:n.tag}).pipe(Ze(ir),Ve((e=>{const t=(n=e.body.documents||[],o=e=>e._id,n.reduce(((e,t)=>(e[o(t)]=t,e)),Object.create(null)));var n,o;return r.map((e=>t[e]||null))})))}function dr(e,t,r,n){return gt("createIfNotExists",r),gr(e,t,r,"createIfNotExists",n)}function fr(e,t,r,n){return gt("createOrReplace",r),gr(e,t,r,"createOrReplace",n)}function hr(e,t,r,n){return yr(e,t,"mutate",{mutations:[{delete:lt(r)}]},n)}function pr(e,t,r,n){let o;o=r instanceof Ot||r instanceof Tt?{patch:r.serialize()}:r instanceof Mt||r instanceof Ft?r.serialize():r;return yr(e,t,"mutate",{mutations:Array.isArray(o)?o:[o],transactionId:n&&n.transactionId||void 0},n)}function yr(e,t,r,n,o={}){const i="mutate"===r,s="query"===r,a=i?"":nr(n),u=!i&&a.length<ar,c=u?a:"",l=o.returnFirst,{timeout:d,token:f,tag:h,headers:p,returnQuery:y}=o;return mr(e,t,{method:u?"GET":"POST",uri:br(e,r,c),json:!0,body:u?void 0:n,query:i&&or(o),timeout:d,headers:p,token:f,tag:h,returnQuery:y,perspective:o.perspective,resultSourceMap:o.resultSourceMap,canUseCdn:s,signal:o.signal,fetch:o.fetch,useAbortSignal:o.useAbortSignal,useCdn:o.useCdn}).pipe(Ze(ir),Ve(sr),Ve((e=>{if(!i)return e;const t=e.results||[];if(o.returnDocuments)return l?t[0]&&t[0].document:t.map((e=>e.document));const r=l?"documentId":"documentIds",n=l?t[0]&&t[0].id:t.map((e=>e.id));return{transactionId:e.transactionId,results:t,[r]:n}})))}function gr(e,t,r,n,o={}){return yr(e,t,"mutate",{mutations:[{[n]:r}]},Object.assign({returnFirst:!0,returnDocuments:!0},o))}function mr(e,t,r){var n,o;const i=r.url||r.uri,s=e.config(),a=typeof r.canUseCdn>"u"?["GET","HEAD"].indexOf(r.method||"GET")>=0&&0===i.indexOf("/data/"):r.canUseCdn;let u=(null!=(n=r.useCdn)?n:s.useCdn)&&a;const c=r.tag&&s.requestTagPrefix?[s.requestTagPrefix,r.tag].join("."):r.tag||s.requestTagPrefix;if(c&&null!==r.tag&&(r.query={tag:vt(c),...r.query}),["GET","HEAD","POST"].indexOf(r.method||"GET")>=0&&0===i.indexOf("/data/query/")){const e=null!=(o=r.resultSourceMap)?o:s.resultSourceMap;void 0!==e&&!1!==e&&(r.query={resultSourceMap:e,...r.query});const t=r.perspective||s.perspective;"string"==typeof t&&"raw"!==t&&(Gt(t),r.query={perspective:t,...r.query},"previewDrafts"===t&&u&&(u=!1,Wt())),!1===r.returnQuery&&(r.query={returnQuery:"false",...r.query})}const l=function(e,t={}){const r={},n=t.token||e.token;n&&(r.Authorization=`Bearer ${n}`),!t.useGlobalApi&&!e.useProjectHostname&&e.projectId&&(r[Qt]=e.projectId);const o=!!(typeof t.withCredentials>"u"?e.token||e.withCredentials:t.withCredentials),i=typeof t.timeout>"u"?e.timeout:t.timeout;return Object.assign({},t,{headers:Object.assign({},r,t.headers||{}),timeout:typeof i>"u"?3e5:i,proxy:t.proxy||e.proxy,json:!0,withCredentials:o,fetch:"object"==typeof t.fetch&&"object"==typeof e.fetch?{...e.fetch,...t.fetch}:t.fetch||e.fetch})}(s,Object.assign({},r,{url:wr(e,i,u)})),d=new Se((e=>t(l,s.requester).subscribe(e)));return r.signal?d.pipe((f=r.signal,e=>new Se((t=>{const r=()=>t.error(function(e){var t,r;if(Cr)return new DOMException(null!=(t=null==e?void 0:e.reason)?t:"The operation was aborted.","AbortError");const n=new Error(null!=(r=null==e?void 0:e.reason)?r:"The operation was aborted.");return n.name="AbortError",n}(f));if(f&&f.aborted)return void r();const n=e.subscribe(t);return f.addEventListener("abort",r),()=>{f.removeEventListener("abort",r),n.unsubscribe()}})))):d;var f}function vr(e,t,r){return mr(e,t,r).pipe(Ze((e=>"response"===e.type)),Ve((e=>e.body)))}function br(e,t,r){const n=e.config(),o=`/${t}/${mt(n)}`;return`/data${r?`${o}/${r}`:o}`.replace(/\/($|\?)/,"$1")}function wr(e,t,r=!1){const{url:n,cdnUrl:o}=e.config();return`${r?o:n}/${t.replace(/^\//,"")}`}const Cr=!!globalThis.DOMException;var Er,xr,Sr,Tr,_r=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Or=(e,t,r)=>(_r(e,t,"read from private field"),r?r.call(e):t.get(e)),$r=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},jr=(e,t,r,n)=>(_r(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class kr{constructor(e,t){$r(this,Er,void 0),$r(this,xr,void 0),jr(this,Er,e),jr(this,xr,t)}upload(e,t,r){return Ir(Or(this,Er),Or(this,xr),e,t,r)}}Er=new WeakMap,xr=new WeakMap;class Ar{constructor(e,t){$r(this,Sr,void 0),$r(this,Tr,void 0),jr(this,Sr,e),jr(this,Tr,t)}upload(e,t,r){return Ge(Ir(Or(this,Sr),Or(this,Tr),e,t,r).pipe(Ze((e=>"response"===e.type)),Ve((e=>e.body.document))))}}function Ir(e,t,r,n,o={}){(e=>{if(-1===dt.indexOf(e))throw new Error(`Invalid asset type: ${e}. Must be one of ${dt.join(", ")}`)})(r);let i=o.extract||void 0;i&&!i.length&&(i=["none"]);const s=mt(e.config()),a="image"===r?"images":"files",u=function(e,t){return typeof File>"u"||!(t instanceof File)?e:Object.assign({filename:!1===e.preserveFilename?void 0:t.name,contentType:t.type},e)}(o,n),{tag:c,label:l,title:d,description:f,creditLine:h,filename:p,source:y}=u,g={label:l,title:d,description:f,filename:p,meta:i,creditLine:h};return y&&(g.sourceId=y.id,g.sourceName=y.name,g.sourceUrl=y.url),mr(e,t,{tag:c,method:"POST",timeout:u.timeout||0,uri:`/assets/${a}/${s}`,headers:u.contentType?{"Content-Type":u.contentType}:{},query:g,body:n})}Sr=new WeakMap,Tr=new WeakMap;const Pr=["includePreviousRevision","includeResult","visibility","effectFormat","tag"],Rr={includeResult:!0};function Mr(e,t,r={}){const{url:n,token:o,withCredentials:i,requestTagPrefix:s}=this.config(),a=r.tag&&s?[s,r.tag].join("."):r.tag,u={...(d=r,f=Rr,Object.keys(f).concat(Object.keys(d)).reduce(((e,t)=>(e[t]=typeof d[t]>"u"?f[t]:d[t],e)),{})),tag:a},c=((e,t)=>t.reduce(((t,r)=>(typeof e[r]>"u"||(t[r]=e[r]),t)),{}))(u,Pr),l=`${n}${br(this,"listen",nr({query:e,params:t,options:{tag:a,...c}}))}`;var d,f;if(l.length>14800)return new Se((e=>e.error(new Error("Query too large for listener"))));const h=u.events?u.events:["mutation"],p=-1!==h.indexOf("reconnect"),y={};return(o||i)&&(y.withCredentials=!0),o&&(y.headers={Authorization:`Bearer ${o}`}),new Se((e=>{let t;c().then((e=>{t=e})).catch((t=>{e.error(t),f()}));let r,n=!1;function o(){n||(p&&e.next({type:"reconnect"}),!n&&t.readyState===t.CLOSED&&(u(),clearTimeout(r),r=setTimeout(d,100)))}function i(t){e.error(function(e){if(e instanceof Error)return e;const t=Dr(e);return t instanceof Error?t:new Error(function(e){return e.error?e.error.description?e.error.description:"string"==typeof e.error?e.error:JSON.stringify(e.error,null,2):e.message||"Unknown listener error"}(t))}(t))}function s(t){const r=Dr(t);return r instanceof Error?e.error(r):e.next(r)}function a(){n=!0,u(),e.complete()}function u(){t&&(t.removeEventListener("error",o),t.removeEventListener("channelError",i),t.removeEventListener("disconnect",a),h.forEach((e=>t.removeEventListener(e,s))),t.close())}async function c(){const{default:e}=await Promise.resolve().then((function(){return Kn})),t=new e(l,y);return t.addEventListener("error",o),t.addEventListener("channelError",i),t.addEventListener("disconnect",a),h.forEach((e=>t.addEventListener(e,s))),t}function d(){c().then((e=>{t=e})).catch((t=>{e.error(t),f()}))}function f(){n=!0,u()}return f}))}function Dr(e){try{const t=e.data&&JSON.parse(e.data)||{};return Object.assign({type:e.type},t)}catch(e){return e}}var Fr,qr,Nr,Ur,Wr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Hr=(e,t,r)=>(Wr(e,t,"read from private field"),r?r.call(e):t.get(e)),zr=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Lr=(e,t,r,n)=>(Wr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Br{constructor(e,t){zr(this,Fr,void 0),zr(this,qr,void 0),Lr(this,Fr,e),Lr(this,qr,t)}create(e,t){return Gr(Hr(this,Fr),Hr(this,qr),"PUT",e,t)}edit(e,t){return Gr(Hr(this,Fr),Hr(this,qr),"PATCH",e,t)}delete(e){return Gr(Hr(this,Fr),Hr(this,qr),"DELETE",e)}list(){return vr(Hr(this,Fr),Hr(this,qr),{uri:"/datasets",tag:null})}}Fr=new WeakMap,qr=new WeakMap;class Jr{constructor(e,t){zr(this,Nr,void 0),zr(this,Ur,void 0),Lr(this,Nr,e),Lr(this,Ur,t)}create(e,t){return Ge(Gr(Hr(this,Nr),Hr(this,Ur),"PUT",e,t))}edit(e,t){return Ge(Gr(Hr(this,Nr),Hr(this,Ur),"PATCH",e,t))}delete(e){return Ge(Gr(Hr(this,Nr),Hr(this,Ur),"DELETE",e))}list(){return Ge(vr(Hr(this,Nr),Hr(this,Ur),{uri:"/datasets",tag:null}))}}function Gr(e,t,r,n,o){return ht(n),vr(e,t,{method:r,uri:`/datasets/${n}`,body:o,tag:null})}Nr=new WeakMap,Ur=new WeakMap;var Vr,Qr,Yr,Xr,Kr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Zr=(e,t,r)=>(Kr(e,t,"read from private field"),r?r.call(e):t.get(e)),en=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},tn=(e,t,r,n)=>(Kr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class rn{constructor(e,t){en(this,Vr,void 0),en(this,Qr,void 0),tn(this,Vr,e),tn(this,Qr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return vr(Zr(this,Vr),Zr(this,Qr),{uri:t})}getById(e){return vr(Zr(this,Vr),Zr(this,Qr),{uri:`/projects/${e}`})}}Vr=new WeakMap,Qr=new WeakMap;class nn{constructor(e,t){en(this,Yr,void 0),en(this,Xr,void 0),tn(this,Yr,e),tn(this,Xr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return Ge(vr(Zr(this,Yr),Zr(this,Xr),{uri:t}))}getById(e){return Ge(vr(Zr(this,Yr),Zr(this,Xr),{uri:`/projects/${e}`}))}}Yr=new WeakMap,Xr=new WeakMap;var on,sn,an,un,cn=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},ln=(e,t,r)=>(cn(e,t,"read from private field"),r?r.call(e):t.get(e)),dn=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},fn=(e,t,r,n)=>(cn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class hn{constructor(e,t){dn(this,on,void 0),dn(this,sn,void 0),fn(this,on,e),fn(this,sn,t)}getById(e){return vr(ln(this,on),ln(this,sn),{uri:`/users/${e}`})}}on=new WeakMap,sn=new WeakMap;class pn{constructor(e,t){dn(this,an,void 0),dn(this,un,void 0),fn(this,an,e),fn(this,un,t)}getById(e){return Ge(vr(ln(this,an),ln(this,un),{uri:`/users/${e}`}))}}an=new WeakMap,un=new WeakMap;var yn,gn,mn=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},vn=(e,t,r)=>(mn(e,t,"read from private field"),r?r.call(e):t.get(e)),bn=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},wn=(e,t,r,n)=>(mn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);yn=new WeakMap,gn=new WeakMap;let Cn=class e{constructor(e,t=Bt){bn(this,yn,void 0),bn(this,gn,void 0),this.listen=Mr,this.config(t),wn(this,gn,e),this.assets=new kr(this,vn(this,gn)),this.datasets=new Br(this,vn(this,gn)),this.projects=new rn(this,vn(this,gn)),this.users=new hn(this,vn(this,gn))}clone(){return new e(vn(this,gn),this.config())}config(e){if(void 0===e)return{...vn(this,yn)};if(vn(this,yn)&&!1===vn(this,yn).allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return wn(this,yn,Vt(e,vn(this,yn)||{})),this}withConfig(t){const r=this.config();return new e(vn(this,gn),{...r,...t,stega:{...r.stega||{},..."boolean"==typeof(null==t?void 0:t.stega)?{enabled:t.stega}:(null==t?void 0:t.stega)||{}}})}fetch(e,t,r){return ur(this,vn(this,gn),vn(this,yn).stega,e,t,r)}getDocument(e,t){return cr(this,vn(this,gn),e,t)}getDocuments(e,t){return lr(this,vn(this,gn),e,t)}create(e,t){return gr(this,vn(this,gn),e,"create",t)}createIfNotExists(e,t){return dr(this,vn(this,gn),e,t)}createOrReplace(e,t){return fr(this,vn(this,gn),e,t)}delete(e,t){return hr(this,vn(this,gn),e,t)}mutate(e,t){return pr(this,vn(this,gn),e,t)}patch(e,t){return new Tt(e,t,this)}transaction(e){return new Ft(e,this)}request(e){return vr(this,vn(this,gn),e)}getUrl(e,t){return wr(this,e,t)}getDataUrl(e,t){return br(this,e,t)}};var En,xn;En=new WeakMap,xn=new WeakMap;let Sn=class e{constructor(e,t=Bt){bn(this,En,void 0),bn(this,xn,void 0),this.listen=Mr,this.config(t),wn(this,xn,e),this.assets=new Ar(this,vn(this,xn)),this.datasets=new Jr(this,vn(this,xn)),this.projects=new nn(this,vn(this,xn)),this.users=new pn(this,vn(this,xn)),this.observable=new Cn(e,t)}clone(){return new e(vn(this,xn),this.config())}config(e){if(void 0===e)return{...vn(this,En)};if(vn(this,En)&&!1===vn(this,En).allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.observable&&this.observable.config(e),wn(this,En,Vt(e,vn(this,En)||{})),this}withConfig(t){const r=this.config();return new e(vn(this,xn),{...r,...t,stega:{...r.stega||{},..."boolean"==typeof(null==t?void 0:t.stega)?{enabled:t.stega}:(null==t?void 0:t.stega)||{}}})}fetch(e,t,r){return Ge(ur(this,vn(this,xn),vn(this,En).stega,e,t,r))}getDocument(e,t){return Ge(cr(this,vn(this,xn),e,t))}getDocuments(e,t){return Ge(lr(this,vn(this,xn),e,t))}create(e,t){return Ge(gr(this,vn(this,xn),e,"create",t))}createIfNotExists(e,t){return Ge(dr(this,vn(this,xn),e,t))}createOrReplace(e,t){return Ge(fr(this,vn(this,xn),e,t))}delete(e,t){return Ge(hr(this,vn(this,xn),e,t))}mutate(e,t){return Ge(pr(this,vn(this,xn),e,t))}patch(e,t){return new Ot(e,t,this)}transaction(e){return new Mt(e,this)}request(e){return Ge(vr(this,vn(this,xn),e))}dataRequest(e,t,r){return Ge(yr(this,vn(this,xn),e,t,r))}getUrl(e,t){return wr(this,e,t)}getDataUrl(e,t){return br(this,e,t)}};const Tn=(An=Sn,{requester:ut(kn=[],{}).defaultRequester,createClient:e=>new An(ut(kn,{maxRetries:e.maxRetries,retryDelay:e.retryDelay}),e)}),_n=Tn.requester,On=Tn.createClient,$n=(jn=On,function(e){return Lt(),jn(e)});var jn,kn,An;const In=/_key\s*==\s*['"](.*)['"]/;function Pn(e){if(!Array.isArray(e))throw new Error("Path is not an array");return e.reduce(((e,t,r)=>{const n=typeof t;if("number"===n)return`${e}[${t}]`;if("string"===n)return`${e}${0===r?"":"."}${t}`;if(function(e){return"string"==typeof e?In.test(e.trim()):"object"==typeof e&&"_key"in e}(t)&&t._key)return`${e}[_key=="${t._key}"]`;if(Array.isArray(t)){const[r,n]=t;return`${e}[${r}:${n}]`}throw new Error(`Unsupported path segment \`${JSON.stringify(t)}\``)}),"")}const Rn={"\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","'":"\\'","\\":"\\\\"},Mn={"\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t","\\'":"'","\\\\":"\\"};function Dn(e){const t=[],r=/\['(.*?)'\]|\[(\d+)\]|\[\?\(@\._key=='(.*?)'\)\]/g;let n;for(;null!==(n=r.exec(e));)if(void 0===n[1])if(void 0===n[2])if(void 0===n[3]);else{const e=n[3].replace(/\\(\\')/g,(e=>Mn[e]));t.push({_key:e,_index:-1})}else t.push(parseInt(n[2],10));else{const e=n[1].replace(/\\(\\|f|n|r|t|')/g,(e=>Mn[e]));t.push(e)}return t}function Fn(e){return e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(""!==e._key)return{_key:e._key};if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)}))}function qn(e,t){if(null==t||!t.mappings)return;const r=function(e){return`$${e.map((e=>"string"==typeof e?`['${e.replace(/[\f\n\r\t'\\]/g,(e=>Rn[e]))}']`:"number"==typeof e?`[${e}]`:""!==e._key?`[?(@._key=='${e._key.replace(/['\\]/g,(e=>Rn[e]))}')]`:`[${e._index}]`)).join("")}`}(e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)})));if(void 0!==t.mappings[r])return{mapping:t.mappings[r],matchedPath:r,pathSuffix:""};const n=Object.entries(t.mappings).filter((([e])=>r.startsWith(e))).sort((([e],[t])=>t.length-e.length));if(0==n.length)return;const[o,i]=n[0];return{mapping:i,matchedPath:o,pathSuffix:r.substring(o.length)}}function Nn(e){return"object"==typeof e&&null!==e}function Un(e,t,r=[]){return function(e){return null!==e&&Array.isArray(e)}(e)?e.map(((e,n)=>{if(Nn(e)){const o=e._key;if("string"==typeof o)return Un(e,t,r.concat({_key:o,_index:n}))}return Un(e,t,r.concat(n))})):Nn(e)?Object.fromEntries(Object.entries(e).map((([e,n])=>[e,Un(n,t,r.concat(e))]))):t(e,r)}function Wn(e,t,r){return Un(e,((e,n)=>{if("string"!=typeof e)return e;const o=qn(n,t);if(!o)return e;const{mapping:i,matchedPath:s}=o;if("value"!==i.type||"documentValue"!==i.source.type)return e;const a=t.documents[i.source.document],u=t.paths[i.source.path],c=Dn(s),l=Dn(u).concat(n.slice(c.length));return r({sourcePath:l,sourceDocument:a,resultPath:n,value:e})}))}const Hn="drafts.";function zn(e){const{baseUrl:t,workspace:r="default",tool:n="default",id:o,type:i,path:s,projectId:a,dataset:u}=e;if(!t)throw new Error("baseUrl is required");if(!s)throw new Error("path is required");if(!o)throw new Error("id is required");if("/"!==t&&t.endsWith("/"))throw new Error("baseUrl must not end with a slash");const c="default"===r?void 0:r,l="default"===n?void 0:n,d=function(e){return e.startsWith(Hn)?e.slice(Hn.length):e}(o),f=Array.isArray(s)?Pn(Fn(s)):s,h=new URLSearchParams({baseUrl:t,id:d,type:i,path:f});c&&h.set("workspace",c),l&&h.set("tool",l),a&&h.set("projectId",a),u&&h.set("dataset",u),o.startsWith(Hn)&&h.set("isDraft","");const p=["/"===t?"":t];c&&p.push(c);const y=["mode=presentation",`id=${d}`,`type=${i}`,`path=${encodeURIComponent(f)}`];return l&&y.push(`tool=${l}`),p.push("intent","edit",`${y.join(";")}?${h}`),p.join("/")}const Ln=({sourcePath:e,value:t})=>{if(/^\d{4}-\d{2}-\d{2}/.test(r=t)&&Date.parse(r)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(t))return!1;var r;const n=e.at(-1);return!("slug"===e.at(-2)&&"current"===n||"string"==typeof n&&n.startsWith("_")||"number"==typeof n&&"marks"===e.at(-2)||"href"===n&&"number"==typeof e.at(-2)&&"markDefs"===e.at(-3)||"style"===n||"listItem"===n||e.some((e=>"meta"===e||"metadata"===e||"openGraph"===e||"seo"===e))||"string"==typeof n&&Bn.has(n))},Bn=new Set(["color","colour","currency","email","format","gid","hex","href","hsl","hsla","icon","id","index","key","language","layout","link","linkAction","locale","lqip","page","path","ref","rgb","rgba","route","secret","slug","status","tag","template","theme","type","unit","url","username","variant","website"]);function Jn(e,t,r){var n,o,i,s,a,u,c,l,d;const{filter:f,logger:h,enabled:p}=r;if(!p){const o="config.enabled must be true, don't call this function otherwise";throw null==(n=null==h?void 0:h.error)||n.call(h,`[@sanity/client]: ${o}`,{result:e,resultSourceMap:t,config:r}),new TypeError(o)}if(!t)return null==(o=null==h?void 0:h.error)||o.call(h,"[@sanity/client]: Missing Content Source Map from response body",{result:e,resultSourceMap:t,config:r}),e;if(!r.studioUrl){const n="config.studioUrl must be defined";throw null==(i=null==h?void 0:h.error)||i.call(h,`[@sanity/client]: ${n}`,{result:e,resultSourceMap:t,config:r}),new TypeError(n)}const y={encoded:[],skipped:[]},g=Wn(e,t,(({sourcePath:e,sourceDocument:t,resultPath:n,value:o})=>{if(!1===("function"==typeof f?f({sourcePath:e,resultPath:n,filterDefault:Ln,sourceDocument:t,value:o}):Ln({sourcePath:e,resultPath:n,filterDefault:Ln,sourceDocument:t,value:o})))return h&&y.skipped.push({path:Gn(e),value:`${o.slice(0,20)}${o.length>20?"...":""}`,length:o.length}),o;h&&y.encoded.push({path:Gn(e),value:`${o.slice(0,20)}${o.length>20?"...":""}`,length:o.length});const{baseUrl:i,workspace:s,tool:a}=function(e){let t="string"==typeof e?e:e.baseUrl;return"/"!==t&&(t=t.replace(/\/$/,"")),"string"==typeof e?{baseUrl:t}:{...e,baseUrl:t}}("function"==typeof r.studioUrl?r.studioUrl(t):r.studioUrl);if(!i)return o;const{_id:u,_type:c,_projectId:l,_dataset:d}=t;return Zt(o,{origin:"sanity.io",href:zn({baseUrl:i,workspace:s,tool:a,id:u,type:c,path:e,...!r.omitCrossDatasetReferenceData&&{dataset:d,projectId:l}})},!1)}));if(h){const e=y.skipped.length,t=y.encoded.length;if((e||t)&&(null==(s=(null==h?void 0:h.groupCollapsed)||h.log)||s("[@sanity/client]: Encoding source map into result"),null==(a=h.log)||a.call(h,`[@sanity/client]: Paths encoded: ${y.encoded.length}, skipped: ${y.skipped.length}`)),y.encoded.length>0&&(null==(u=null==h?void 0:h.log)||u.call(h,"[@sanity/client]: Table of encoded paths"),null==(c=(null==h?void 0:h.table)||h.log)||c(y.encoded)),y.skipped.length>0){const e=new Set;for(const{path:t}of y.skipped)e.add(t.replace(In,"0").replace(/\[\d+\]/g,"[]"));null==(l=null==h?void 0:h.log)||l.call(h,"[@sanity/client]: List of skipped paths",[...e.values()])}(e||t)&&(null==(d=null==h?void 0:h.groupEnd)||d.call(h))}return g}function Gn(e){return Pn(Fn(e))}var Vn=Object.freeze({__proto__:null,stegaEncodeSourceMap:Jn}),Qn=Object.freeze({__proto__:null,a:Vn,e:Wn,s:Jn}),Yn={exports:{}};
9
9
  /** @license
10
10
  * eventsource.js
11
11
  * Available under MIT License (MIT)