@sanity/client 6.15.10 → 6.15.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks-cjs/nodeMiddleware.cjs +1 -1
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +5 -2
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
- package/dist/_chunks-es/nodeMiddleware.js +1 -1
- package/dist/_chunks-es/stegaEncodeSourceMap.js +5 -2
- package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
- package/package.json +1 -1
- package/src/stega/filterDefault.ts +12 -2
- package/umd/sanityClient.js +5 -2
- package/umd/sanityClient.min.js +3 -3
|
@@ -1474,7 +1474,7 @@ function defineCreateClientExports(envMiddleware, ClassConstructor) {
|
|
|
1474
1474
|
config
|
|
1475
1475
|
) };
|
|
1476
1476
|
}
|
|
1477
|
-
var name = "@sanity/client", version = "6.15.
|
|
1477
|
+
var name = "@sanity/client", version = "6.15.11";
|
|
1478
1478
|
const middleware = [
|
|
1479
1479
|
middleware$1.debug({ verbose: !0, namespace: "sanity:client" }),
|
|
1480
1480
|
middleware$1.headers({ "User-Agent": `${name} ${version}` }),
|
|
@@ -182,13 +182,13 @@ function resolveStudioBaseRoute(studioUrl) {
|
|
|
182
182
|
let baseUrl = typeof studioUrl == "string" ? studioUrl : studioUrl.baseUrl;
|
|
183
183
|
return baseUrl !== "/" && (baseUrl = baseUrl.replace(/\/$/, "")), typeof studioUrl == "string" ? { baseUrl } : { ...studioUrl, baseUrl };
|
|
184
184
|
}
|
|
185
|
-
const filterDefault = ({ sourcePath, value }) => {
|
|
185
|
+
const filterDefault = ({ sourcePath, resultPath, value }) => {
|
|
186
186
|
if (isValidDate(value) || isValidURL(value))
|
|
187
187
|
return !1;
|
|
188
188
|
const endPath = sourcePath.at(-1);
|
|
189
189
|
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && endPath.startsWith("_") || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
190
190
|
(path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo"
|
|
191
|
-
) || typeof endPath == "string" && denylist.has(endPath));
|
|
191
|
+
) || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath));
|
|
192
192
|
}, denylist = /* @__PURE__ */ new Set([
|
|
193
193
|
"color",
|
|
194
194
|
"colour",
|
|
@@ -240,6 +240,9 @@ function isValidURL(url) {
|
|
|
240
240
|
}
|
|
241
241
|
return !0;
|
|
242
242
|
}
|
|
243
|
+
function hasTypeLike(path) {
|
|
244
|
+
return path.some((segment) => typeof segment == "string" && segment.match(/type/i) !== null);
|
|
245
|
+
}
|
|
243
246
|
const TRUNCATE_LENGTH = 20;
|
|
244
247
|
function stegaEncodeSourceMap(result, resultSourceMap, config) {
|
|
245
248
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
@@ -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 {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;AAC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A,MAAA;AAAA,MACE,oCAAoC,OAAO,QAAQ,MAAM,cAAc,OAAO,QAAQ,MAAM;AAAA,IAAA,IAG5F,OAAO,QAAQ,SAAS,OAC1B,KAAQ,UAAA,OAAA,SAAA,OAAA,QAAR,wBAAc,0CACZ,IAAA,MAAA,UAAA,OAAA,SAAA,OAAQ,UAAS,OAAO,QAAxB,QAA+B,GAAA,OAAO,WAEtC,OAAO,QAAQ,SAAS,GAAG;AACvB,YAAA,8BAAc;AACT,iBAAA,EAAC,UAAS,OAAO;AAClB,gBAAA,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;;;;;;;;"}
|
|
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 {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 {ContentSourceMapParsedPath, FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, resultPath, 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 // If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most\n // of the time used for logic that breaks if it contains stega characters\n if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {\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\nfunction hasTypeLike(path: ContentSourceMapParsedPath): boolean {\n return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)\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,QA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envMiddleware, ClassConstructor) {
|
|
|
1455
1455
|
config
|
|
1456
1456
|
) };
|
|
1457
1457
|
}
|
|
1458
|
-
var name = "@sanity/client", version = "6.15.
|
|
1458
|
+
var name = "@sanity/client", version = "6.15.11";
|
|
1459
1459
|
const middleware = [
|
|
1460
1460
|
debug({ verbose: !0, namespace: "sanity:client" }),
|
|
1461
1461
|
headers({ "User-Agent": `${name} ${version}` }),
|
|
@@ -181,13 +181,13 @@ function resolveStudioBaseRoute(studioUrl) {
|
|
|
181
181
|
let baseUrl = typeof studioUrl == "string" ? studioUrl : studioUrl.baseUrl;
|
|
182
182
|
return baseUrl !== "/" && (baseUrl = baseUrl.replace(/\/$/, "")), typeof studioUrl == "string" ? { baseUrl } : { ...studioUrl, baseUrl };
|
|
183
183
|
}
|
|
184
|
-
const filterDefault = ({ sourcePath, value }) => {
|
|
184
|
+
const filterDefault = ({ sourcePath, resultPath, value }) => {
|
|
185
185
|
if (isValidDate(value) || isValidURL(value))
|
|
186
186
|
return !1;
|
|
187
187
|
const endPath = sourcePath.at(-1);
|
|
188
188
|
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && endPath.startsWith("_") || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
189
189
|
(path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo"
|
|
190
|
-
) || typeof endPath == "string" && denylist.has(endPath));
|
|
190
|
+
) || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath));
|
|
191
191
|
}, denylist = /* @__PURE__ */ new Set([
|
|
192
192
|
"color",
|
|
193
193
|
"colour",
|
|
@@ -239,6 +239,9 @@ function isValidURL(url) {
|
|
|
239
239
|
}
|
|
240
240
|
return !0;
|
|
241
241
|
}
|
|
242
|
+
function hasTypeLike(path) {
|
|
243
|
+
return path.some((segment) => typeof segment == "string" && segment.match(/type/i) !== null);
|
|
244
|
+
}
|
|
242
245
|
const TRUNCATE_LENGTH = 20;
|
|
243
246
|
function stegaEncodeSourceMap(result, resultSourceMap, config) {
|
|
244
247
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
@@ -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 {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;AASr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AAQ,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 {ContentSourceMapParsedPath, FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, resultPath, 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 // If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most\n // of the time used for logic that breaks if it contains stega characters\n if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {\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\nfunction hasTypeLike(path: ContentSourceMapParsedPath): boolean {\n return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)\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,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M;AAAA,IAAA,IAG5F,OAAO,QAAQ,SAAS,OAC1B,KAAQ,UAAA,OAAA,SAAA,OAAA,QAAR,wBAAc,0CACZ,IAAA,MAAA,UAAA,OAAA,SAAA,OAAQ,UAAS,OAAO,QAAxB,QAA+B,GAAA,OAAO,WAEtC,OAAO,QAAQ,SAAS,GAAG;AACvB,YAAA,8BAAc;AACT,iBAAA,EAAC,UAAS,OAAO;AAClB,gBAAA,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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type {FilterDefault} from './types'
|
|
1
|
+
import type {ContentSourceMapParsedPath, FilterDefault} from './types'
|
|
2
2
|
|
|
3
|
-
export const filterDefault: FilterDefault = ({sourcePath, value}) => {
|
|
3
|
+
export const filterDefault: FilterDefault = ({sourcePath, resultPath, value}) => {
|
|
4
4
|
// Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()
|
|
5
5
|
if (isValidDate(value) || isValidURL(value)) {
|
|
6
6
|
return false
|
|
@@ -50,6 +50,12 @@ export const filterDefault: FilterDefault = ({sourcePath, value}) => {
|
|
|
50
50
|
return false
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
// If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most
|
|
54
|
+
// of the time used for logic that breaks if it contains stega characters
|
|
55
|
+
if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {
|
|
56
|
+
return false
|
|
57
|
+
}
|
|
58
|
+
|
|
53
59
|
// Finally, we ignore a bunch of paths that are typically used for page building
|
|
54
60
|
if (typeof endPath === 'string' && denylist.has(endPath)) {
|
|
55
61
|
return false
|
|
@@ -111,3 +117,7 @@ function isValidURL(url: string) {
|
|
|
111
117
|
}
|
|
112
118
|
return true
|
|
113
119
|
}
|
|
120
|
+
|
|
121
|
+
function hasTypeLike(path: ContentSourceMapParsedPath): boolean {
|
|
122
|
+
return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)
|
|
123
|
+
}
|
package/umd/sanityClient.js
CHANGED
|
@@ -4017,13 +4017,13 @@ ${selectionOpts}`);
|
|
|
4017
4017
|
let baseUrl = typeof studioUrl == "string" ? studioUrl : studioUrl.baseUrl;
|
|
4018
4018
|
return baseUrl !== "/" && (baseUrl = baseUrl.replace(/\/$/, "")), typeof studioUrl == "string" ? { baseUrl } : { ...studioUrl, baseUrl };
|
|
4019
4019
|
}
|
|
4020
|
-
const filterDefault = ({ sourcePath, value }) => {
|
|
4020
|
+
const filterDefault = ({ sourcePath, resultPath, value }) => {
|
|
4021
4021
|
if (isValidDate(value) || isValidURL(value))
|
|
4022
4022
|
return !1;
|
|
4023
4023
|
const endPath = sourcePath.at(-1);
|
|
4024
4024
|
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && endPath.startsWith("_") || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
4025
4025
|
(path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo"
|
|
4026
|
-
) || typeof endPath == "string" && denylist.has(endPath));
|
|
4026
|
+
) || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath));
|
|
4027
4027
|
}, denylist = /* @__PURE__ */ new Set([
|
|
4028
4028
|
"color",
|
|
4029
4029
|
"colour",
|
|
@@ -4075,6 +4075,9 @@ ${selectionOpts}`);
|
|
|
4075
4075
|
}
|
|
4076
4076
|
return !0;
|
|
4077
4077
|
}
|
|
4078
|
+
function hasTypeLike(path) {
|
|
4079
|
+
return path.some((segment) => typeof segment == "string" && segment.match(/type/i) !== null);
|
|
4080
|
+
}
|
|
4078
4081
|
const TRUNCATE_LENGTH = 20;
|
|
4079
4082
|
function stegaEncodeSourceMap(result, resultSourceMap, config) {
|
|
4080
4083
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
package/umd/sanityClient.min.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SanityClient={})}(this,(function(e){"use strict";const t={timeout:!(typeof navigator>"u")&&"ReactNative"===navigator.product?6e4:12e4},r=function(e){const r={...t,..."string"==typeof e?{url:e}:e};if(r.timeout=o(r.timeout),r.query){const{url:e,searchParams:t}=function(e){const t=e.indexOf("?");if(-1===t)return{url:e,searchParams:new URLSearchParams};const r=e.slice(0,t),o=e.slice(t+1),i=new URLSearchParams(o);if("function"==typeof i.set)return{url:r,searchParams:i};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const s=new URLSearchParams;for(const e of o.split("&")){const[t,r]=e.split("=");t&&s.append(n(t),n(r||""))}return{url:r,searchParams:s}}(r.url);for(const[n,o]of Object.entries(r.query)){if(void 0!==o)if(Array.isArray(o))for(const e of o)t.append(n,e);else t.append(n,o);const i=t.toString();i&&(r.url=`${e}?${i}`)}}return r.method=r.body&&!r.method?"POST":(r.method||"GET").toUpperCase(),r};function n(e){return decodeURIComponent(e.replace(/\+/g," "))}function o(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?o(t.timeout):{connect:r,socket:r}}const i=/^https?:\/\//i,s=function(e){if(!i.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};var a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var c=function(e){return e.replace(/^\s+|\s+$/g,"")},l=u((function(e){if(!e)return{};for(var t,r={},n=c(e).split("\n"),o=0;o<n.length;o++){var i=n[o],s=i.indexOf(":"),a=c(i.slice(0,s)).toLowerCase(),u=c(i.slice(s+1));void 0===r[a]?r[a]=u:(t=r[a],"[object Array]"===Object.prototype.toString.call(t)?r[a].push(u):r[a]=[r[a],u])}return r}));const f=["request","response","progress","error","abort"],d=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function h(e,t){const n=[],o=d.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[r],validateOptions:[s]});function i(e){const r=f.reduce(((e,t)=>(e[t]=function(){const e=Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const n=t++;return e[n]=r,function(){delete e[n]}}}}(),e)),{}),n=(e=>function(t,r,...n){const o="onError"===t;let i=r;for(let r=0;r<e[t].length&&(i=(0,e[t][r])(i,...n),!o||i);r++);return i})(o),i=n("processOptions",e);n("validateOptions",i);const s={options:i,channels:r,applyMiddleware:n};let a;const u=r.request.subscribe((e=>{a=t(e,((t,o)=>((e,t,o)=>{let i=e,s=t;if(!i)try{s=n("onResponse",t,o)}catch(e){s=null,i=e}i=i&&n("onError",i,o),i?r.error.publish(i):s&&r.response.publish(s)})(t,o,e)))}));r.abort.subscribe((()=>{u(),a&&a.abort()}));const c=n("onReturn",r,s);return c===r&&r.request.publish(s),c}return i.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&o.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return d.forEach((t=>{e[t]&&o[t].push(e[t])})),n.push(e),i},i.clone=()=>h(n,t),e.forEach(i.use),i}var p,y,g,m,v,b,w,C=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},E=(e,t,r)=>(C(e,t,"read from private field"),r?r.call(e):t.get(e)),x=(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)},S=(e,t,r,n)=>(C(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class T{constructor(){this.readyState=0,this.responseType="",x(this,p,void 0),x(this,y,void 0),x(this,g,void 0),x(this,m,{}),x(this,v,void 0),x(this,b,{}),x(this,w,void 0)}open(e,t,r){S(this,p,e),S(this,y,t),S(this,g,""),this.readyState=1,this.onreadystatechange(),S(this,v,void 0)}abort(){E(this,v)&&E(this,v).abort()}getAllResponseHeaders(){return E(this,g)}setRequestHeader(e,t){E(this,m)[e]=t}setInit(e,t=!0){S(this,b,e),S(this,w,t)}send(e){const t="arraybuffer"!==this.responseType,r={...E(this,b),method:E(this,p),headers:E(this,m),body:e};"function"==typeof AbortController&&E(this,w)&&(S(this,v,new AbortController),typeof EventTarget<"u"&&E(this,v).signal instanceof EventTarget&&(r.signal=E(this,v).signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(E(this,y),r).then((e=>(e.headers.forEach(((e,t)=>{S(this,g,E(this,g)+`${t}: ${e}\r\n`)})),this.status=e.status,this.statusText=e.statusText,this.readyState=3,t?e.text():e.arrayBuffer()))).then((e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange()})).catch((e=>{var t;"AbortError"!==e.name?null==(t=this.onerror)||t.call(this,e):this.onabort()}))}}p=new WeakMap,y=new WeakMap,g=new WeakMap,m=new WeakMap,v=new WeakMap,b=new WeakMap,w=new WeakMap;const _="function"==typeof XMLHttpRequest?"xhr":"fetch",O="xhr"===_?XMLHttpRequest:T,$=(e,t)=>{var r;const n=e.options,o=e.applyMiddleware("finalizeOptions",n),i={},s=e.applyMiddleware("interceptRequest",void 0,{adapter:_,context:e});if(s){const e=setTimeout(t,0,null,s);return{abort:()=>clearTimeout(e)}}let a=new O;a instanceof T&&"object"==typeof o.fetch&&a.setInit(o.fetch,null==(r=o.useAbortSignal)||r);const u=o.headers,c=o.timeout;let f=!1,d=!1,h=!1;if(a.onerror=e=>{g(new Error(`Request error while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},a.ontimeout=e=>{g(new Error(`Request timeout while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},a.onabort=()=>{y(!0),f=!0},a.onreadystatechange=()=>{c&&(y(),i.socket=setTimeout((()=>p("ESOCKETTIMEDOUT")),c.socket)),!f&&4===a.readyState&&0!==a.status&&function(){if(!(f||d||h)){if(0===a.status)return void g(new Error("Unknown XHR error"));y(),d=!0,t(null,{body:a.response||(""===a.responseType||"text"===a.responseType?a.responseText:""),url:o.url,method:o.method,headers:l(a.getAllResponseHeaders()),statusCode:a.status,statusMessage:a.statusText})}}()},a.open(o.method,o.url,!0),a.withCredentials=!!o.withCredentials,u&&a.setRequestHeader)for(const e in u)u.hasOwnProperty(e)&&a.setRequestHeader(e,u[e]);return o.rawBody&&(a.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:o,adapter:_,request:a,context:e}),a.send(o.body||null),c&&(i.connect=setTimeout((()=>p("ETIMEDOUT")),c.connect)),{abort:function(){f=!0,a&&a.abort()}};function p(t){h=!0,a.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${o.url}`:`Connection timed out on request to ${o.url}`);r.code=t,e.channels.error.publish(r)}function y(e){(e||f||a.readyState>=2&&i.connect)&&clearTimeout(i.connect),i.socket&&clearTimeout(i.socket)}function g(e){if(d)return;y(!0),d=!0,a=null;const r=e||new Error(`Network error while attempting to reach ${o.url}`);r.isNetworkError=!0,r.request=o,t(r)}},j=(e=[],t=$)=>h(e,t);var k,A,I={exports:{}};function P(){if(A)return k;A=1;var e=1e3,t=60*e,r=60*t,n=24*r,o=7*n,i=365.25*n;function s(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}return k=function(a,u){u=u||{};var c=typeof a;if("string"===c&&a.length>0)return function(s){if((s=String(s)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!a)return;var u=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return u*i;case"weeks":case"week":case"w":return u*o;case"days":case"day":case"d":return u*n;case"hours":case"hour":case"hrs":case"hr":case"h":return u*r;case"minutes":case"minute":case"mins":case"min":case"m":return u*t;case"seconds":case"second":case"secs":case"sec":case"s":return u*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}(a);if("number"===c&&isFinite(a))return u.long?function(o){var i=Math.abs(o);if(i>=n)return s(o,i,n,"day");if(i>=r)return s(o,i,r,"hour");if(i>=t)return s(o,i,t,"minute");if(i>=e)return s(o,i,e,"second");return o+" ms"}(a):function(o){var i=Math.abs(o);if(i>=n)return Math.round(o/n)+"d";if(i>=r)return Math.round(o/r)+"h";if(i>=t)return Math.round(o/t)+"m";if(i>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var R=function(e){function t(e){let n,o,i,s=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),i=o-(n||o);r.diff=i,r.prev=n,r.curr=o,n=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,o)=>{if("%%"===n)return"%";s++;const i=t.formatters[o];if("function"==typeof i){const t=e[s];n=i.call(r,t),e.splice(s,1),s--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(o!==t.namespaces&&(o=t.namespaces,i=t.enabled(e)),i),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=P(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SanityClient={})}(this,(function(e){"use strict";const t={timeout:!(typeof navigator>"u")&&"ReactNative"===navigator.product?6e4:12e4},r=function(e){const r={...t,..."string"==typeof e?{url:e}:e};if(r.timeout=o(r.timeout),r.query){const{url:e,searchParams:t}=function(e){const t=e.indexOf("?");if(-1===t)return{url:e,searchParams:new URLSearchParams};const r=e.slice(0,t),o=e.slice(t+1),i=new URLSearchParams(o);if("function"==typeof i.set)return{url:r,searchParams:i};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const s=new URLSearchParams;for(const e of o.split("&")){const[t,r]=e.split("=");t&&s.append(n(t),n(r||""))}return{url:r,searchParams:s}}(r.url);for(const[n,o]of Object.entries(r.query)){if(void 0!==o)if(Array.isArray(o))for(const e of o)t.append(n,e);else t.append(n,o);const i=t.toString();i&&(r.url=`${e}?${i}`)}}return r.method=r.body&&!r.method?"POST":(r.method||"GET").toUpperCase(),r};function n(e){return decodeURIComponent(e.replace(/\+/g," "))}function o(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?o(t.timeout):{connect:r,socket:r}}const i=/^https?:\/\//i,s=function(e){if(!i.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};var a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var c=function(e){return e.replace(/^\s+|\s+$/g,"")},l=u((function(e){if(!e)return{};for(var t,r={},n=c(e).split("\n"),o=0;o<n.length;o++){var i=n[o],s=i.indexOf(":"),a=c(i.slice(0,s)).toLowerCase(),u=c(i.slice(s+1));void 0===r[a]?r[a]=u:(t=r[a],"[object Array]"===Object.prototype.toString.call(t)?r[a].push(u):r[a]=[r[a],u])}return r}));const f=["request","response","progress","error","abort"],d=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function h(e,t){const n=[],o=d.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[r],validateOptions:[s]});function i(e){const r=f.reduce(((e,t)=>(e[t]=function(){const e=Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const n=t++;return e[n]=r,function(){delete e[n]}}}}(),e)),{}),n=(e=>function(t,r,...n){const o="onError"===t;let i=r;for(let r=0;r<e[t].length&&(i=(0,e[t][r])(i,...n),!o||i);r++);return i})(o),i=n("processOptions",e);n("validateOptions",i);const s={options:i,channels:r,applyMiddleware:n};let a;const u=r.request.subscribe((e=>{a=t(e,((t,o)=>((e,t,o)=>{let i=e,s=t;if(!i)try{s=n("onResponse",t,o)}catch(e){s=null,i=e}i=i&&n("onError",i,o),i?r.error.publish(i):s&&r.response.publish(s)})(t,o,e)))}));r.abort.subscribe((()=>{u(),a&&a.abort()}));const c=n("onReturn",r,s);return c===r&&r.request.publish(s),c}return i.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&o.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return d.forEach((t=>{e[t]&&o[t].push(e[t])})),n.push(e),i},i.clone=()=>h(n,t),e.forEach(i.use),i}var p,y,m,g,v,b,w,C=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},E=(e,t,r)=>(C(e,t,"read from private field"),r?r.call(e):t.get(e)),x=(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)},S=(e,t,r,n)=>(C(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class T{constructor(){this.readyState=0,this.responseType="",x(this,p,void 0),x(this,y,void 0),x(this,m,void 0),x(this,g,{}),x(this,v,void 0),x(this,b,{}),x(this,w,void 0)}open(e,t,r){S(this,p,e),S(this,y,t),S(this,m,""),this.readyState=1,this.onreadystatechange(),S(this,v,void 0)}abort(){E(this,v)&&E(this,v).abort()}getAllResponseHeaders(){return E(this,m)}setRequestHeader(e,t){E(this,g)[e]=t}setInit(e,t=!0){S(this,b,e),S(this,w,t)}send(e){const t="arraybuffer"!==this.responseType,r={...E(this,b),method:E(this,p),headers:E(this,g),body:e};"function"==typeof AbortController&&E(this,w)&&(S(this,v,new AbortController),typeof EventTarget<"u"&&E(this,v).signal instanceof EventTarget&&(r.signal=E(this,v).signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(E(this,y),r).then((e=>(e.headers.forEach(((e,t)=>{S(this,m,E(this,m)+`${t}: ${e}\r\n`)})),this.status=e.status,this.statusText=e.statusText,this.readyState=3,t?e.text():e.arrayBuffer()))).then((e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange()})).catch((e=>{var t;"AbortError"!==e.name?null==(t=this.onerror)||t.call(this,e):this.onabort()}))}}p=new WeakMap,y=new WeakMap,m=new WeakMap,g=new WeakMap,v=new WeakMap,b=new WeakMap,w=new WeakMap;const _="function"==typeof XMLHttpRequest?"xhr":"fetch",O="xhr"===_?XMLHttpRequest:T,$=(e,t)=>{var r;const n=e.options,o=e.applyMiddleware("finalizeOptions",n),i={},s=e.applyMiddleware("interceptRequest",void 0,{adapter:_,context:e});if(s){const e=setTimeout(t,0,null,s);return{abort:()=>clearTimeout(e)}}let a=new O;a instanceof T&&"object"==typeof o.fetch&&a.setInit(o.fetch,null==(r=o.useAbortSignal)||r);const u=o.headers,c=o.timeout;let f=!1,d=!1,h=!1;if(a.onerror=e=>{m(new Error(`Request error while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},a.ontimeout=e=>{m(new Error(`Request timeout while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},a.onabort=()=>{y(!0),f=!0},a.onreadystatechange=()=>{c&&(y(),i.socket=setTimeout((()=>p("ESOCKETTIMEDOUT")),c.socket)),!f&&4===a.readyState&&0!==a.status&&function(){if(!(f||d||h)){if(0===a.status)return void m(new Error("Unknown XHR error"));y(),d=!0,t(null,{body:a.response||(""===a.responseType||"text"===a.responseType?a.responseText:""),url:o.url,method:o.method,headers:l(a.getAllResponseHeaders()),statusCode:a.status,statusMessage:a.statusText})}}()},a.open(o.method,o.url,!0),a.withCredentials=!!o.withCredentials,u&&a.setRequestHeader)for(const e in u)u.hasOwnProperty(e)&&a.setRequestHeader(e,u[e]);return o.rawBody&&(a.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:o,adapter:_,request:a,context:e}),a.send(o.body||null),c&&(i.connect=setTimeout((()=>p("ETIMEDOUT")),c.connect)),{abort:function(){f=!0,a&&a.abort()}};function p(t){h=!0,a.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${o.url}`:`Connection timed out on request to ${o.url}`);r.code=t,e.channels.error.publish(r)}function y(e){(e||f||a.readyState>=2&&i.connect)&&clearTimeout(i.connect),i.socket&&clearTimeout(i.socket)}function m(e){if(d)return;y(!0),d=!0,a=null;const r=e||new Error(`Network error while attempting to reach ${o.url}`);r.isNetworkError=!0,r.request=o,t(r)}},j=(e=[],t=$)=>h(e,t);var k,A,P={exports:{}};function I(){if(A)return k;A=1;var e=1e3,t=60*e,r=60*t,n=24*r,o=7*n,i=365.25*n;function s(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}return k=function(a,u){u=u||{};var c=typeof a;if("string"===c&&a.length>0)return function(s){if((s=String(s)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!a)return;var u=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return u*i;case"weeks":case"week":case"w":return u*o;case"days":case"day":case"d":return u*n;case"hours":case"hour":case"hrs":case"hr":case"h":return u*r;case"minutes":case"minute":case"mins":case"min":case"m":return u*t;case"seconds":case"second":case"secs":case"sec":case"s":return u*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}(a);if("number"===c&&isFinite(a))return u.long?function(o){var i=Math.abs(o);if(i>=n)return s(o,i,n,"day");if(i>=r)return s(o,i,r,"hour");if(i>=t)return s(o,i,t,"minute");if(i>=e)return s(o,i,e,"second");return o+" ms"}(a):function(o){var i=Math.abs(o);if(i>=n)return Math.round(o/n)+"d";if(i>=r)return Math.round(o/r)+"h";if(i>=t)return Math.round(o/t)+"m";if(i>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var R=function(e){function t(e){let n,o,i,s=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),i=o-(n||o);r.diff=i,r.prev=n,r.curr=o,n=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,o)=>{if("%%"===n)return"%";s++;const i=t.formatters[o];if("function"==typeof i){const t=e[s];n=i.call(r,t),e.splice(s,1),s--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(o!==t.namespaces&&(o=t.namespaces,i=t.enabled(e)),i),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=I(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};
|
|
2
2
|
/*!
|
|
3
3
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
4
4
|
*
|
|
5
5
|
* Copyright (c) 2014-2017, Jon Schlinkert.
|
|
6
6
|
* Released under the MIT License.
|
|
7
7
|
*/
|
|
8
|
-
function M(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=R(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(I,I.exports);const D=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e),F=["boolean","string","number"];function q(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||D(t)||-1===F.indexOf(typeof t)&&!Array.isArray(t)&&(!1===M(r=t)||void 0!==(n=r.constructor)&&(!1===M(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 N(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 U={};typeof globalThis<"u"?U=globalThis:typeof window<"u"?U=window:typeof global<"u"?U=global:typeof self<"u"&&(U=self);var W=U;function L(e={}){const t=e.implementation||W.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 B=(e,t,r)=>("GET"===r.method||"HEAD"===r.method)&&(e.isNetworkError||!1);function J(e){return 100*Math.pow(2,e)+100*Math.random()}const G=(e={})=>(e=>{const t=e.maxRetries||5,r=e.retryDelay||J,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:B,...e});G.shouldRetry=B;var V=function(e,t){return V=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])},V(e,t)};function Q(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}V(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Y(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 X(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 K(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 Z(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 ee(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 te(e){return this instanceof te?(this.v=e,this):new te(e)}function re(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 te?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 ne(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=K(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 oe(e){return"function"==typeof e}function ie(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 se=ie((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 ae(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var ue=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=K(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(oe(u))try{u()}catch(e){o=e instanceof se?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var l=K(c),f=l.next();!f.done;f=l.next()){var d=f.value;try{le(d)}catch(e){o=null!=o?o:[],e instanceof se?o=ee(ee([],Z(o)),Z(e.errors)):o.push(e)}}}catch(e){r={error:e}}finally{try{f&&!f.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(o)throw new se(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)le(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)&&ae(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&ae(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function ce(e){return e instanceof ue||e&&"closed"in e&&oe(e.remove)&&oe(e.add)&&oe(e.unsubscribe)}function le(e){oe(e)?e():e.unsubscribe()}ue.EMPTY;var fe={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,ee([e,t],Z(r)))},clearTimeout:function(e){var t=de.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function he(e){de.setTimeout((function(){throw e}))}function pe(){}var ye=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,ce(t)&&t.add(r)):r.destination=Ce,r}return Q(t,e),t.create=function(e,t,r){return new be(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}(ue),ge=Function.prototype.bind;function me(e,t){return ge.call(e,t)}var ve=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){we(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){we(e)}else we(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){we(e)}},e}(),be=function(e){function t(t,r,n){var o,i,s=e.call(this)||this;oe(t)||!t?o={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:s&&fe.useDeprecatedNextContext?((i=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&me(t.next,i),error:t.error&&me(t.error,i),complete:t.complete&&me(t.complete,i)}):o=t;return s.destination=new ve(o),s}return Q(t,e),t}(ye);function we(e){he(e)}var Ce={closed:!0,next:pe,error:function(e){throw e},complete:pe},Ee="function"==typeof Symbol&&Symbol.observable||"@@observable";function xe(e){return e}function Se(e){return 0===e.length?xe:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Te=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 ye||function(e){return e&&oe(e.next)&&oe(e.error)&&oe(e.complete)}(n)&&ce(n)?e:new be(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=_e(t))((function(t,n){var o=new be({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[Ee]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Se(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=_e(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 _e(e){var t;return null!==(t=null!=e?e:fe.Promise)&&void 0!==t?t:Promise}function Oe(e){return function(t){if(function(e){return oe(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 $e(e,t,r,n,o){return new je(e,t,r,n,o)}var je=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 Q(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}(ye);var ke=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function Ae(e){return oe(null==e?void 0:e.then)}function Ie(e){return oe(e[Ee])}function Pe(e){return Symbol.asyncIterator&&oe(null==e?void 0:e[Symbol.asyncIterator])}function Re(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 Me="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function De(e){return oe(null==e?void 0:e[Me])}function Fe(e){return re(this,arguments,(function(){var t,r,n;return X(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,te(t.read())];case 3:return r=o.sent(),n=r.value,r.done?[4,te(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,te(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 qe(e){return oe(null==e?void 0:e.getReader)}function Ne(e){if(e instanceof Te)return e;if(null!=e){if(Ie(e))return o=e,new Te((function(e){var t=o[Ee]();if(oe(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(ke(e))return n=e,new Te((function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()}));if(Ae(e))return r=e,new Te((function(e){r.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,he)}));if(Pe(e))return Ue(e);if(De(e))return t=e,new Te((function(e){var r,n;try{for(var o=K(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(qe(e))return Ue(Fe(e))}var t,r,n,o;throw Re(e)}function Ue(e){return new Te((function(t){(function(e,t){var r,n,o,i;return Y(this,void 0,void 0,(function(){var s,a;return X(this,(function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),r=ne(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 We(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 Le(e,t){return void 0===t&&(t=0),Oe((function(r,n){r.subscribe($e(n,(function(r){return We(n,e,(function(){return n.next(r)}),t)}),(function(){return We(n,e,(function(){return n.complete()}),t)}),(function(r){return We(n,e,(function(){return n.error(r)}),t)})))}))}function He(e,t){return void 0===t&&(t=0),Oe((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 Te((function(r){We(r,t,(function(){var n=e[Symbol.asyncIterator]();We(r,t,(function(){n.next().then((function(e){e.done?r.complete():r.next(e.value)}))}),0,!0)}))}))}function Be(e,t){if(null!=e){if(Ie(e))return function(e,t){return Ne(e).pipe(He(t),Le(t))}(e,t);if(ke(e))return function(e,t){return new Te((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(Ae(e))return function(e,t){return Ne(e).pipe(He(t),Le(t))}(e,t);if(Pe(e))return ze(e,t);if(De(e))return function(e,t){return new Te((function(r){var n;return We(r,t,(function(){n=e[Me](),We(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 oe(null==n?void 0:n.return)&&n.return()}}))}(e,t);if(qe(e))return function(e,t){return ze(Fe(e),t)}(e,t)}throw Re(e)}function Je(e,t){return t?Be(e,t):Ne(e)}var Ge=ie((function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Ve(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 Ge)}})}))}function Qe(e,t){return Oe((function(r,n){var o=0;r.subscribe($e(n,(function(r){n.next(e.call(t,r,o++))})))}))}var Ye=Array.isArray;function Xe(e){return Qe((function(t){return function(e,t){return Ye(t)?e.apply(void 0,ee([],Z(t))):e(t)}(e,t)}))}function Ke(e,t,r){e?We(r,e,t):t()}var Ze=Array.isArray;function et(e,t){return Oe((function(r,n){var o=0;r.subscribe($e(n,(function(r){return e.call(t,r,o++)&&n.next(r)})))}))}function tt(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(e){return oe((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 Se(e)}(tt.apply(void 0,ee([],Z(e))),Xe(r)):Oe((function(t,r){var n,o,i;(n=ee([t],Z(function(e){return 1===e.length&&Ze(e[0])?e[0]:e}(e))),void 0===i&&(i=xe),function(e){Ke(o,(function(){for(var t=n.length,r=new Array(t),s=t,a=t,u=function(t){Ke(o,(function(){var u=Je(n[t],o),c=!1;u.subscribe($e(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 rt extends Error{constructor(e){const t=ot(e);super(t.message),this.statusCode=400,Object.assign(this,t)}}class nt extends Error{constructor(e){const t=ot(e);super(t.message),this.statusCode=500,Object.assign(this,t)}}function ot(e){const t=e.body,r={response:e,statusCode:e.statusCode,responseBody:st(t,e),message:"",details:void 0};if(t.error&&t.message)return r.message=`${t.error} - ${t.message}`,r;if(function(e){return it(e)&&it(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 it(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function st(e,t){return-1!==(t.headers["content-type"]||"").toLowerCase().indexOf("application/json")?JSON.stringify(e,null,2):e}const at={onResponse:e=>{if(e.statusCode>=500)throw new nt(e);if(e.statusCode>=400)throw new rt(e);return e}},ut={onResponse:e=>{const t=e.headers["x-sanity-warning"];return(Array.isArray(t)?t:[t]).filter(Boolean).forEach((e=>console.warn(e))),e}};function ct(e,{maxRetries:t=5,retryDelay:r}){const n=j([t>0?G({retryDelay:r,maxRetries:t,shouldRetry:lt}):{},...e,ut,q(),N(),{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"))}},at,L({implementation:Te})]);function o(e,t=n){return t({maxRedirects:0,...e})}return o.defaultRequester=n,o}function lt(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)||G.shouldRetry(e,t,r)}function ft(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"],ht=["before","after","replace"],pt=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")},yt=(e,t)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new Error(`${e}() takes an object of properties`)},gt=(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`)},mt=(e,t)=>{if(!t._id)throw new Error(`${e}() requires that the document contains an ID ("_id" property)`);gt(e,t._id)},vt=e=>{if(!e.dataset)throw new Error("`dataset` must be provided to perform queries");return e.dataset||""},bt=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 wt,Ct=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Et=(e,t,r)=>(Ct(e,t,"read from private field"),r?r.call(e):t.get(e)),xt=(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)},St=(e,t,r,n)=>(Ct(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Tt{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 yt("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===ht.indexOf(e)){const e=ht.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{...ft(this.selection),...this.operations}}toJSON(){return this.serialize()}reset(){return this.operations={},this}_assign(e,t,r=!0){return yt(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)}}wt=new WeakMap;let _t=class e extends Tt{constructor(e,t,r){super(e,t),xt(this,wt,void 0),St(this,wt,r)}clone(){return new e(this.selection,{...this.operations},Et(this,wt))}commit(e){if(!Et(this,wt))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 Et(this,wt).mutate({patch:this.serialize()},r)}};var Ot;Ot=new WeakMap;let $t=class e extends Tt{constructor(e,t,r){super(e,t),xt(this,Ot,void 0),St(this,Ot,r)}clone(){return new e(this.selection,{...this.operations},Et(this,Ot))}commit(e){if(!Et(this,Ot))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 Et(this,Ot).mutate({patch:this.serialize()},r)}};var jt=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},kt=(e,t,r)=>(jt(e,t,"read from private field"),r?r.call(e):t.get(e)),At=(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)},It=(e,t,r,n)=>(jt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);const Pt={returnDocuments:!1};class Rt{constructor(e=[],t){this.operations=e,this.trxId=t}create(e){return yt("create",e),this._add({create:e})}createIfNotExists(e){const t="createIfNotExists";return yt(t,e),mt(t,e),this._add({[t]:e})}createOrReplace(e){const t="createOrReplace";return yt(t,e),mt(t,e),this._add({[t]:e})}delete(e){return gt("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 Mt;Mt=new WeakMap;let Dt=class e extends Rt{constructor(e,t,r){super(e,r),At(this,Mt,void 0),It(this,Mt,t)}clone(){return new e([...this.operations],kt(this,Mt),this.trxId)}commit(e){if(!kt(this,Mt))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return kt(this,Mt).mutate(this.serialize(),Object.assign({transactionId:this.trxId},Pt,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof $t)return this._add({patch:e.serialize()});if(r){const r=t(new $t(e,{},kt(this,Mt)));if(!(r instanceof $t))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 Ft;Ft=new WeakMap;let qt=class e extends Rt{constructor(e,t,r){super(e,r),At(this,Ft,void 0),It(this,Ft,t)}clone(){return new e([...this.operations],kt(this,Ft),this.trxId)}commit(e){if(!kt(this,Ft))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return kt(this,Ft).mutate(this.serialize(),Object.assign({transactionId:this.trxId},Pt,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof _t)return this._add({patch:e.serialize()});if(r){const r=t(new _t(e,{},kt(this,Ft)));if(!(r instanceof _t))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 Nt(e){return"https://www.sanity.io/help/"+e}const Ut=e=>function(e){let t,r=!1;return(...n)=>(r||(t=e(...n),r=!0),t)}(((...t)=>console.warn(e.join(" "),...t))),Wt=Ut(["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."]),Lt=Ut(["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=Ut(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",`See ${Nt("js-client-browser-token")} for more information and how to hide this warning.`]),zt=Ut(["Using the Sanity client without specifying an API version is deprecated.",`See ${Nt("js-client-api-version")}`]),Bt=Ut(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]),Jt={apiHost:"https://api.sanity.io",apiVersion:"1",useProjectHostname:!0,stega:{enabled:!1}},Gt=["localhost","127.0.0.1","0.0.0.0"];const Vt=function(e){switch(e){case"previewDrafts":case"published":case"raw":return;default:throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`")}},Qt=(e,t)=>{const r={...t,...e,stega:{..."boolean"==typeof t.stega?{enabled:t.stega}:t.stega||Jt.stega,..."boolean"==typeof e.stega?{enabled:e.stega}:e.stega||{}}};r.apiVersion||zt();const n={...Jt,...r},o=n.useProjectHostname;if(typeof Promise>"u"){const e=Nt("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&&Vt(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!==Gt.indexOf(e))(window.location.hostname);i&&s&&n.token&&!0!==n.ignoreBrowserTokenWarning?Ht():typeof n.useCdn>"u"&&Wt(),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&&pt(n.dataset),"requestTagPrefix"in n&&(n.requestTagPrefix=n.requestTagPrefix?bt(n.requestTagPrefix).replace(/\.+$/,""):void 0),n.apiVersion=`${n.apiVersion}`.replace(/^v/,""),n.isDefaultApi=n.apiHost===Jt.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},Yt="X-Sanity-Project-ID";var Xt={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},Kt={0:8203,1:8204,2:8205,3:65279},Zt=new Array(4).fill(String.fromCodePoint(Kt[0])).join("");function er(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`${Zt}${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(Kt[e]))).join("")})).join("")}`}(t)}`}Object.fromEntries(Object.entries(Kt).map((e=>e.reverse()))),Object.fromEntries(Object.entries(Xt).map((e=>e.reverse())));var tr=`${Object.values(Xt).map((e=>`\\u{${e.toString(16)}}`)).join("")}`,rr=new RegExp(`[${tr}]{4,}`,"gu");function nr(e){try{return JSON.parse(JSON.stringify(e,((e,t)=>{return"string"!=typeof t?t:(r=t,{cleaned:r.replace(rr,""),encoded:(null==(n=r.match(rr))?void 0:n[0])||""}).cleaned;var r,n})))}catch{return e}}const or=({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}`},ir=(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},sr=e=>"response"===e.type,ar=e=>e.body,ur=11264;function cr(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?nr(o):o,u=!1===i.filterResponse?e=>e:e=>e.result,{cache:c,next:l,...f}={useAbortSignal:typeof i.signal<"u",resultSourceMap:s.enabled?"withKeyArraySelector":i.resultSourceMap,...i,returnQuery:!1===i.filterResponse&&!1!==i.returnQuery},d=gr(e,t,"query",{query:n,params:a},typeof c<"u"||typeof l<"u"?{...f,fetch:{cache:c,next:l}}:f);return s.enabled?d.pipe(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return tt.apply(void 0,ee([],Z(e)))}(Je(Promise.resolve().then((function(){return Yn})).then((function(e){return e.a})).then((({stegaEncodeSourceMap:e})=>e)))),Qe((([e,t])=>{const r=t(e.result,e.resultSourceMap,s);return u({...e,result:r})}))):d.pipe(Qe(u))}function lr(e,t,r,n={}){return vr(e,t,{uri:wr(e,"doc",r),json:!0,tag:n.tag}).pipe(et(sr),Qe((e=>e.body.documents&&e.body.documents[0])))}function fr(e,t,r,n={}){return vr(e,t,{uri:wr(e,"doc",r.join(",")),json:!0,tag:n.tag}).pipe(et(sr),Qe((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 mt("createIfNotExists",r),mr(e,t,r,"createIfNotExists",n)}function hr(e,t,r,n){return mt("createOrReplace",r),mr(e,t,r,"createOrReplace",n)}function pr(e,t,r,n){return gr(e,t,"mutate",{mutations:[{delete:ft(r)}]},n)}function yr(e,t,r,n){let o;o=r instanceof $t||r instanceof _t?{patch:r.serialize()}:r instanceof Dt||r instanceof qt?r.serialize():r;return gr(e,t,"mutate",{mutations:Array.isArray(o)?o:[o],transactionId:n&&n.transactionId||void 0},n)}function gr(e,t,r,n,o={}){const i="mutate"===r,s="query"===r,a=i?"":or(n),u=!i&&a.length<ur,c=u?a:"",l=o.returnFirst,{timeout:f,token:d,tag:h,headers:p,returnQuery:y}=o;return vr(e,t,{method:u?"GET":"POST",uri:wr(e,r,c),json:!0,body:u?void 0:n,query:i&&ir(o),timeout:f,headers:p,token:d,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(et(sr),Qe(ar),Qe((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 mr(e,t,r,n,o={}){return gr(e,t,"mutate",{mutations:[{[n]:r}]},Object.assign({returnFirst:!0,returnDocuments:!0},o))}function vr(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:bt(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&&(Vt(t),r.query={perspective:t,...r.query},"previewDrafts"===t&&u&&(u=!1,Lt())),!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[Yt]=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:Cr(e,i,u)})),f=new Te((e=>t(l,s.requester).subscribe(e)));return r.signal?f.pipe((d=r.signal,e=>new Te((t=>{const r=()=>t.error(function(e){var t,r;if(Er)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}(d));if(d&&d.aborted)return void r();const n=e.subscribe(t);return d.addEventListener("abort",r),()=>{d.removeEventListener("abort",r),n.unsubscribe()}})))):f;var d}function br(e,t,r){return vr(e,t,r).pipe(et((e=>"response"===e.type)),Qe((e=>e.body)))}function wr(e,t,r){const n=e.config(),o=`/${t}/${vt(n)}`;return`/data${r?`${o}/${r}`:o}`.replace(/\/($|\?)/,"$1")}function Cr(e,t,r=!1){const{url:n,cdnUrl:o}=e.config();return`${r?o:n}/${t.replace(/^\//,"")}`}const Er=!!globalThis.DOMException;var xr,Sr,Tr,_r,Or=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},$r=(e,t,r)=>(Or(e,t,"read from private field"),r?r.call(e):t.get(e)),jr=(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)},kr=(e,t,r,n)=>(Or(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Ar{constructor(e,t){jr(this,xr,void 0),jr(this,Sr,void 0),kr(this,xr,e),kr(this,Sr,t)}upload(e,t,r){return Pr($r(this,xr),$r(this,Sr),e,t,r)}}xr=new WeakMap,Sr=new WeakMap;class Ir{constructor(e,t){jr(this,Tr,void 0),jr(this,_r,void 0),kr(this,Tr,e),kr(this,_r,t)}upload(e,t,r){return Ve(Pr($r(this,Tr),$r(this,_r),e,t,r).pipe(et((e=>"response"===e.type)),Qe((e=>e.body.document))))}}function Pr(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=vt(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:f,description:d,creditLine:h,filename:p,source:y}=u,g={label:l,title:f,description:d,filename:p,meta:i,creditLine:h};return y&&(g.sourceId=y.id,g.sourceName=y.name,g.sourceUrl=y.url),vr(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})}Tr=new WeakMap,_r=new WeakMap;const Rr=["includePreviousRevision","includeResult","visibility","effectFormat","tag"],Mr={includeResult:!0};function Dr(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={...(f=r,d=Mr,Object.keys(d).concat(Object.keys(f)).reduce(((e,t)=>(e[t]=typeof f[t]>"u"?d[t]:f[t],e)),{})),tag:a},c=((e,t)=>t.reduce(((t,r)=>(typeof e[r]>"u"||(t[r]=e[r]),t)),{}))(u,Rr),l=`${n}${wr(this,"listen",or({query:e,params:t,options:{tag:a,...c}}))}`;var f,d;if(l.length>14800)return new Te((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 Te((e=>{let t;c().then((e=>{t=e})).catch((t=>{e.error(t),d()}));let r,n=!1;function o(){n||(p&&e.next({type:"reconnect"}),!n&&t.readyState===t.CLOSED&&(u(),clearTimeout(r),r=setTimeout(f,100)))}function i(t){e.error(function(e){if(e instanceof Error)return e;const t=Fr(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=Fr(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 Zn})),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 f(){c().then((e=>{t=e})).catch((t=>{e.error(t),d()}))}function d(){n=!0,u()}return d}))}function Fr(e){try{const t=e.data&&JSON.parse(e.data)||{};return Object.assign({type:e.type},t)}catch(e){return e}}var qr,Nr,Ur,Wr,Lr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Hr=(e,t,r)=>(Lr(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)},Br=(e,t,r,n)=>(Lr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Jr{constructor(e,t){zr(this,qr,void 0),zr(this,Nr,void 0),Br(this,qr,e),Br(this,Nr,t)}create(e,t){return Vr(Hr(this,qr),Hr(this,Nr),"PUT",e,t)}edit(e,t){return Vr(Hr(this,qr),Hr(this,Nr),"PATCH",e,t)}delete(e){return Vr(Hr(this,qr),Hr(this,Nr),"DELETE",e)}list(){return br(Hr(this,qr),Hr(this,Nr),{uri:"/datasets",tag:null})}}qr=new WeakMap,Nr=new WeakMap;class Gr{constructor(e,t){zr(this,Ur,void 0),zr(this,Wr,void 0),Br(this,Ur,e),Br(this,Wr,t)}create(e,t){return Ve(Vr(Hr(this,Ur),Hr(this,Wr),"PUT",e,t))}edit(e,t){return Ve(Vr(Hr(this,Ur),Hr(this,Wr),"PATCH",e,t))}delete(e){return Ve(Vr(Hr(this,Ur),Hr(this,Wr),"DELETE",e))}list(){return Ve(br(Hr(this,Ur),Hr(this,Wr),{uri:"/datasets",tag:null}))}}function Vr(e,t,r,n,o){return pt(n),br(e,t,{method:r,uri:`/datasets/${n}`,body:o,tag:null})}Ur=new WeakMap,Wr=new WeakMap;var Qr,Yr,Xr,Kr,Zr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},en=(e,t,r)=>(Zr(e,t,"read from private field"),r?r.call(e):t.get(e)),tn=(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)},rn=(e,t,r,n)=>(Zr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class nn{constructor(e,t){tn(this,Qr,void 0),tn(this,Yr,void 0),rn(this,Qr,e),rn(this,Yr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return br(en(this,Qr),en(this,Yr),{uri:t})}getById(e){return br(en(this,Qr),en(this,Yr),{uri:`/projects/${e}`})}}Qr=new WeakMap,Yr=new WeakMap;class on{constructor(e,t){tn(this,Xr,void 0),tn(this,Kr,void 0),rn(this,Xr,e),rn(this,Kr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return Ve(br(en(this,Xr),en(this,Kr),{uri:t}))}getById(e){return Ve(br(en(this,Xr),en(this,Kr),{uri:`/projects/${e}`}))}}Xr=new WeakMap,Kr=new WeakMap;var sn,an,un,cn,ln=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},fn=(e,t,r)=>(ln(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)},hn=(e,t,r,n)=>(ln(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class pn{constructor(e,t){dn(this,sn,void 0),dn(this,an,void 0),hn(this,sn,e),hn(this,an,t)}getById(e){return br(fn(this,sn),fn(this,an),{uri:`/users/${e}`})}}sn=new WeakMap,an=new WeakMap;class yn{constructor(e,t){dn(this,un,void 0),dn(this,cn,void 0),hn(this,un,e),hn(this,cn,t)}getById(e){return Ve(br(fn(this,un),fn(this,cn),{uri:`/users/${e}`}))}}un=new WeakMap,cn=new WeakMap;var gn,mn,vn=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},bn=(e,t,r)=>(vn(e,t,"read from private field"),r?r.call(e):t.get(e)),wn=(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)},Cn=(e,t,r,n)=>(vn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);gn=new WeakMap,mn=new WeakMap;let En=class e{constructor(e,t=Jt){wn(this,gn,void 0),wn(this,mn,void 0),this.listen=Dr,this.config(t),Cn(this,mn,e),this.assets=new Ar(this,bn(this,mn)),this.datasets=new Jr(this,bn(this,mn)),this.projects=new nn(this,bn(this,mn)),this.users=new pn(this,bn(this,mn))}clone(){return new e(bn(this,mn),this.config())}config(e){if(void 0===e)return{...bn(this,gn)};if(bn(this,gn)&&!1===bn(this,gn).allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return Cn(this,gn,Qt(e,bn(this,gn)||{})),this}withConfig(t){const r=this.config();return new e(bn(this,mn),{...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 cr(this,bn(this,mn),bn(this,gn).stega,e,t,r)}getDocument(e,t){return lr(this,bn(this,mn),e,t)}getDocuments(e,t){return fr(this,bn(this,mn),e,t)}create(e,t){return mr(this,bn(this,mn),e,"create",t)}createIfNotExists(e,t){return dr(this,bn(this,mn),e,t)}createOrReplace(e,t){return hr(this,bn(this,mn),e,t)}delete(e,t){return pr(this,bn(this,mn),e,t)}mutate(e,t){return yr(this,bn(this,mn),e,t)}patch(e,t){return new _t(e,t,this)}transaction(e){return new qt(e,this)}request(e){return br(this,bn(this,mn),e)}getUrl(e,t){return Cr(this,e,t)}getDataUrl(e,t){return wr(this,e,t)}};var xn,Sn;xn=new WeakMap,Sn=new WeakMap;let Tn=class e{constructor(e,t=Jt){wn(this,xn,void 0),wn(this,Sn,void 0),this.listen=Dr,this.config(t),Cn(this,Sn,e),this.assets=new Ir(this,bn(this,Sn)),this.datasets=new Gr(this,bn(this,Sn)),this.projects=new on(this,bn(this,Sn)),this.users=new yn(this,bn(this,Sn)),this.observable=new En(e,t)}clone(){return new e(bn(this,Sn),this.config())}config(e){if(void 0===e)return{...bn(this,xn)};if(bn(this,xn)&&!1===bn(this,xn).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),Cn(this,xn,Qt(e,bn(this,xn)||{})),this}withConfig(t){const r=this.config();return new e(bn(this,Sn),{...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 Ve(cr(this,bn(this,Sn),bn(this,xn).stega,e,t,r))}getDocument(e,t){return Ve(lr(this,bn(this,Sn),e,t))}getDocuments(e,t){return Ve(fr(this,bn(this,Sn),e,t))}create(e,t){return Ve(mr(this,bn(this,Sn),e,"create",t))}createIfNotExists(e,t){return Ve(dr(this,bn(this,Sn),e,t))}createOrReplace(e,t){return Ve(hr(this,bn(this,Sn),e,t))}delete(e,t){return Ve(pr(this,bn(this,Sn),e,t))}mutate(e,t){return Ve(yr(this,bn(this,Sn),e,t))}patch(e,t){return new $t(e,t,this)}transaction(e){return new Dt(e,this)}request(e){return Ve(br(this,bn(this,Sn),e))}dataRequest(e,t,r){return Ve(gr(this,bn(this,Sn),e,t,r))}getUrl(e,t){return Cr(this,e,t)}getDataUrl(e,t){return wr(this,e,t)}};const _n=(In=Tn,{requester:ct(An=[],{}).defaultRequester,createClient:e=>new In(ct(An,{maxRetries:e.maxRetries,retryDelay:e.retryDelay}),e)}),On=_n.requester,$n=_n.createClient,jn=(kn=$n,function(e){return Bt(),kn(e)});var kn,An,In;const Pn=/_key\s*==\s*['"](.*)['"]/;function Rn(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?Pn.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 Mn={"\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","'":"\\'","\\":"\\\\"},Dn={"\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t","\\'":"'","\\\\":"\\"};function Fn(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=>Dn[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=>Dn[e]));t.push(e)}return t}function qn(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 Nn(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=>Mn[e]))}']`:"number"==typeof e?`[${e}]`:""!==e._key?`[?(@._key=='${e._key.replace(/['\\]/g,(e=>Mn[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 Un(e){return"object"==typeof e&&null!==e}function Wn(e,t,r=[]){return function(e){return null!==e&&Array.isArray(e)}(e)?e.map(((e,n)=>{if(Un(e)){const o=e._key;if("string"==typeof o)return Wn(e,t,r.concat({_key:o,_index:n}))}return Wn(e,t,r.concat(n))})):Un(e)?Object.fromEntries(Object.entries(e).map((([e,n])=>[e,Wn(n,t,r.concat(e))]))):t(e,r)}function Ln(e,t,r){return Wn(e,((e,n)=>{if("string"!=typeof e)return e;const o=Nn(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=Fn(s),l=Fn(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,f=function(e){return e.startsWith(Hn)?e.slice(Hn.length):e}(o),d=Array.isArray(s)?Rn(qn(s)):s,h=new URLSearchParams({baseUrl:t,id:f,type:i,path:d});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=${f}`,`type=${i}`,`path=${encodeURIComponent(d)}`];return l&&y.push(`tool=${l}`),p.push("intent","edit",`${y.join(";")}?${h}`),p.join("/")}const Bn=({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&&Jn.has(n))},Jn=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 Gn(e,t,r){var n,o,i,s,a,u,c,l,f;const{filter:d,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=Ln(e,t,(({sourcePath:e,sourceDocument:t,resultPath:n,value:o})=>{if(!1===("function"==typeof d?d({sourcePath:e,resultPath:n,filterDefault:Bn,sourceDocument:t,value:o}):Bn({sourcePath:e,resultPath:n,filterDefault:Bn,sourceDocument:t,value:o})))return h&&y.skipped.push({path:Vn(e),value:`${o.slice(0,20)}${o.length>20?"...":""}`,length:o.length}),o;h&&y.encoded.push({path:Vn(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:f}=t;return er(o,{origin:"sanity.io",href:zn({baseUrl:i,workspace:s,tool:a,id:u,type:c,path:e,...!r.omitCrossDatasetReferenceData&&{dataset:f,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(Pn,"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==(f=null==h?void 0:h.groupEnd)||f.call(h))}return g}function Vn(e){return Rn(qn(e))}var Qn=Object.freeze({__proto__:null,stegaEncodeSourceMap:Gn}),Yn=Object.freeze({__proto__:null,a:Qn,e:Ln,s:Gn}),Xn={exports:{}};
|
|
8
|
+
function M(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=R(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(P,P.exports);const D=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e),F=["boolean","string","number"];function q(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||D(t)||-1===F.indexOf(typeof t)&&!Array.isArray(t)&&(!1===M(r=t)||void 0!==(n=r.constructor)&&(!1===M(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 N(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 U={};typeof globalThis<"u"?U=globalThis:typeof window<"u"?U=window:typeof global<"u"?U=global:typeof self<"u"&&(U=self);var W=U;function L(e={}){const t=e.implementation||W.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 B=(e,t,r)=>("GET"===r.method||"HEAD"===r.method)&&(e.isNetworkError||!1);function J(e){return 100*Math.pow(2,e)+100*Math.random()}const G=(e={})=>(e=>{const t=e.maxRetries||5,r=e.retryDelay||J,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:B,...e});G.shouldRetry=B;var V=function(e,t){return V=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])},V(e,t)};function Q(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}V(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Y(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 X(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 K(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 Z(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 ee(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 te(e){return this instanceof te?(this.v=e,this):new te(e)}function re(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 te?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 ne(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=K(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 oe(e){return"function"==typeof e}function ie(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 se=ie((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 ae(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var ue=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=K(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(oe(u))try{u()}catch(e){o=e instanceof se?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var l=K(c),f=l.next();!f.done;f=l.next()){var d=f.value;try{le(d)}catch(e){o=null!=o?o:[],e instanceof se?o=ee(ee([],Z(o)),Z(e.errors)):o.push(e)}}}catch(e){r={error:e}}finally{try{f&&!f.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(o)throw new se(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)le(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)&&ae(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&ae(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function ce(e){return e instanceof ue||e&&"closed"in e&&oe(e.remove)&&oe(e.add)&&oe(e.unsubscribe)}function le(e){oe(e)?e():e.unsubscribe()}ue.EMPTY;var fe={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,ee([e,t],Z(r)))},clearTimeout:function(e){var t=de.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function he(e){de.setTimeout((function(){throw e}))}function pe(){}var ye=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,ce(t)&&t.add(r)):r.destination=Ce,r}return Q(t,e),t.create=function(e,t,r){return new be(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}(ue),me=Function.prototype.bind;function ge(e,t){return me.call(e,t)}var ve=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){we(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){we(e)}else we(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){we(e)}},e}(),be=function(e){function t(t,r,n){var o,i,s=e.call(this)||this;oe(t)||!t?o={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:s&&fe.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 ve(o),s}return Q(t,e),t}(ye);function we(e){he(e)}var Ce={closed:!0,next:pe,error:function(e){throw e},complete:pe},Ee="function"==typeof Symbol&&Symbol.observable||"@@observable";function xe(e){return e}function Se(e){return 0===e.length?xe:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Te=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 ye||function(e){return e&&oe(e.next)&&oe(e.error)&&oe(e.complete)}(n)&&ce(n)?e:new be(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=_e(t))((function(t,n){var o=new be({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[Ee]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Se(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=_e(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 _e(e){var t;return null!==(t=null!=e?e:fe.Promise)&&void 0!==t?t:Promise}function Oe(e){return function(t){if(function(e){return oe(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 $e(e,t,r,n,o){return new je(e,t,r,n,o)}var je=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 Q(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}(ye);var ke=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function Ae(e){return oe(null==e?void 0:e.then)}function Pe(e){return oe(e[Ee])}function Ie(e){return Symbol.asyncIterator&&oe(null==e?void 0:e[Symbol.asyncIterator])}function Re(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 Me="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function De(e){return oe(null==e?void 0:e[Me])}function Fe(e){return re(this,arguments,(function(){var t,r,n;return X(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,te(t.read())];case 3:return r=o.sent(),n=r.value,r.done?[4,te(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,te(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 qe(e){return oe(null==e?void 0:e.getReader)}function Ne(e){if(e instanceof Te)return e;if(null!=e){if(Pe(e))return o=e,new Te((function(e){var t=o[Ee]();if(oe(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(ke(e))return n=e,new Te((function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()}));if(Ae(e))return r=e,new Te((function(e){r.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,he)}));if(Ie(e))return Ue(e);if(De(e))return t=e,new Te((function(e){var r,n;try{for(var o=K(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(qe(e))return Ue(Fe(e))}var t,r,n,o;throw Re(e)}function Ue(e){return new Te((function(t){(function(e,t){var r,n,o,i;return Y(this,void 0,void 0,(function(){var s,a;return X(this,(function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),r=ne(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 We(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 Le(e,t){return void 0===t&&(t=0),Oe((function(r,n){r.subscribe($e(n,(function(r){return We(n,e,(function(){return n.next(r)}),t)}),(function(){return We(n,e,(function(){return n.complete()}),t)}),(function(r){return We(n,e,(function(){return n.error(r)}),t)})))}))}function He(e,t){return void 0===t&&(t=0),Oe((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 Te((function(r){We(r,t,(function(){var n=e[Symbol.asyncIterator]();We(r,t,(function(){n.next().then((function(e){e.done?r.complete():r.next(e.value)}))}),0,!0)}))}))}function Be(e,t){if(null!=e){if(Pe(e))return function(e,t){return Ne(e).pipe(He(t),Le(t))}(e,t);if(ke(e))return function(e,t){return new Te((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(Ae(e))return function(e,t){return Ne(e).pipe(He(t),Le(t))}(e,t);if(Ie(e))return ze(e,t);if(De(e))return function(e,t){return new Te((function(r){var n;return We(r,t,(function(){n=e[Me](),We(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 oe(null==n?void 0:n.return)&&n.return()}}))}(e,t);if(qe(e))return function(e,t){return ze(Fe(e),t)}(e,t)}throw Re(e)}function Je(e,t){return t?Be(e,t):Ne(e)}var Ge=ie((function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Ve(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 Ge)}})}))}function Qe(e,t){return Oe((function(r,n){var o=0;r.subscribe($e(n,(function(r){n.next(e.call(t,r,o++))})))}))}var Ye=Array.isArray;function Xe(e){return Qe((function(t){return function(e,t){return Ye(t)?e.apply(void 0,ee([],Z(t))):e(t)}(e,t)}))}function Ke(e,t,r){e?We(r,e,t):t()}var Ze=Array.isArray;function et(e,t){return Oe((function(r,n){var o=0;r.subscribe($e(n,(function(r){return e.call(t,r,o++)&&n.next(r)})))}))}function tt(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(e){return oe((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 Se(e)}(tt.apply(void 0,ee([],Z(e))),Xe(r)):Oe((function(t,r){var n,o,i;(n=ee([t],Z(function(e){return 1===e.length&&Ze(e[0])?e[0]:e}(e))),void 0===i&&(i=xe),function(e){Ke(o,(function(){for(var t=n.length,r=new Array(t),s=t,a=t,u=function(t){Ke(o,(function(){var u=Je(n[t],o),c=!1;u.subscribe($e(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 rt extends Error{constructor(e){const t=ot(e);super(t.message),this.statusCode=400,Object.assign(this,t)}}class nt extends Error{constructor(e){const t=ot(e);super(t.message),this.statusCode=500,Object.assign(this,t)}}function ot(e){const t=e.body,r={response:e,statusCode:e.statusCode,responseBody:st(t,e),message:"",details:void 0};if(t.error&&t.message)return r.message=`${t.error} - ${t.message}`,r;if(function(e){return it(e)&&it(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 it(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function st(e,t){return-1!==(t.headers["content-type"]||"").toLowerCase().indexOf("application/json")?JSON.stringify(e,null,2):e}const at={onResponse:e=>{if(e.statusCode>=500)throw new nt(e);if(e.statusCode>=400)throw new rt(e);return e}},ut={onResponse:e=>{const t=e.headers["x-sanity-warning"];return(Array.isArray(t)?t:[t]).filter(Boolean).forEach((e=>console.warn(e))),e}};function ct(e,{maxRetries:t=5,retryDelay:r}){const n=j([t>0?G({retryDelay:r,maxRetries:t,shouldRetry:lt}):{},...e,ut,q(),N(),{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"))}},at,L({implementation:Te})]);function o(e,t=n){return t({maxRedirects:0,...e})}return o.defaultRequester=n,o}function lt(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)||G.shouldRetry(e,t,r)}function ft(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"],ht=["before","after","replace"],pt=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")},yt=(e,t)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new Error(`${e}() takes an object of properties`)},mt=(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)`);mt(e,t._id)},vt=e=>{if(!e.dataset)throw new Error("`dataset` must be provided to perform queries");return e.dataset||""},bt=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 wt,Ct=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Et=(e,t,r)=>(Ct(e,t,"read from private field"),r?r.call(e):t.get(e)),xt=(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)},St=(e,t,r,n)=>(Ct(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Tt{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 yt("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===ht.indexOf(e)){const e=ht.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{...ft(this.selection),...this.operations}}toJSON(){return this.serialize()}reset(){return this.operations={},this}_assign(e,t,r=!0){return yt(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)}}wt=new WeakMap;let _t=class e extends Tt{constructor(e,t,r){super(e,t),xt(this,wt,void 0),St(this,wt,r)}clone(){return new e(this.selection,{...this.operations},Et(this,wt))}commit(e){if(!Et(this,wt))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 Et(this,wt).mutate({patch:this.serialize()},r)}};var Ot;Ot=new WeakMap;let $t=class e extends Tt{constructor(e,t,r){super(e,t),xt(this,Ot,void 0),St(this,Ot,r)}clone(){return new e(this.selection,{...this.operations},Et(this,Ot))}commit(e){if(!Et(this,Ot))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 Et(this,Ot).mutate({patch:this.serialize()},r)}};var jt=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},kt=(e,t,r)=>(jt(e,t,"read from private field"),r?r.call(e):t.get(e)),At=(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)},Pt=(e,t,r,n)=>(jt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);const It={returnDocuments:!1};class Rt{constructor(e=[],t){this.operations=e,this.trxId=t}create(e){return yt("create",e),this._add({create:e})}createIfNotExists(e){const t="createIfNotExists";return yt(t,e),gt(t,e),this._add({[t]:e})}createOrReplace(e){const t="createOrReplace";return yt(t,e),gt(t,e),this._add({[t]:e})}delete(e){return mt("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 Mt;Mt=new WeakMap;let Dt=class e extends Rt{constructor(e,t,r){super(e,r),At(this,Mt,void 0),Pt(this,Mt,t)}clone(){return new e([...this.operations],kt(this,Mt),this.trxId)}commit(e){if(!kt(this,Mt))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return kt(this,Mt).mutate(this.serialize(),Object.assign({transactionId:this.trxId},It,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof $t)return this._add({patch:e.serialize()});if(r){const r=t(new $t(e,{},kt(this,Mt)));if(!(r instanceof $t))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 Ft;Ft=new WeakMap;let qt=class e extends Rt{constructor(e,t,r){super(e,r),At(this,Ft,void 0),Pt(this,Ft,t)}clone(){return new e([...this.operations],kt(this,Ft),this.trxId)}commit(e){if(!kt(this,Ft))throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return kt(this,Ft).mutate(this.serialize(),Object.assign({transactionId:this.trxId},It,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof _t)return this._add({patch:e.serialize()});if(r){const r=t(new _t(e,{},kt(this,Ft)));if(!(r instanceof _t))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 Nt(e){return"https://www.sanity.io/help/"+e}const Ut=e=>function(e){let t,r=!1;return(...n)=>(r||(t=e(...n),r=!0),t)}(((...t)=>console.warn(e.join(" "),...t))),Wt=Ut(["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."]),Lt=Ut(["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=Ut(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",`See ${Nt("js-client-browser-token")} for more information and how to hide this warning.`]),zt=Ut(["Using the Sanity client without specifying an API version is deprecated.",`See ${Nt("js-client-api-version")}`]),Bt=Ut(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]),Jt={apiHost:"https://api.sanity.io",apiVersion:"1",useProjectHostname:!0,stega:{enabled:!1}},Gt=["localhost","127.0.0.1","0.0.0.0"];const Vt=function(e){switch(e){case"previewDrafts":case"published":case"raw":return;default:throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`")}},Qt=(e,t)=>{const r={...t,...e,stega:{..."boolean"==typeof t.stega?{enabled:t.stega}:t.stega||Jt.stega,..."boolean"==typeof e.stega?{enabled:e.stega}:e.stega||{}}};r.apiVersion||zt();const n={...Jt,...r},o=n.useProjectHostname;if(typeof Promise>"u"){const e=Nt("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&&Vt(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!==Gt.indexOf(e))(window.location.hostname);i&&s&&n.token&&!0!==n.ignoreBrowserTokenWarning?Ht():typeof n.useCdn>"u"&&Wt(),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&&pt(n.dataset),"requestTagPrefix"in n&&(n.requestTagPrefix=n.requestTagPrefix?bt(n.requestTagPrefix).replace(/\.+$/,""):void 0),n.apiVersion=`${n.apiVersion}`.replace(/^v/,""),n.isDefaultApi=n.apiHost===Jt.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},Yt="X-Sanity-Project-ID";var Xt={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},Kt={0:8203,1:8204,2:8205,3:65279},Zt=new Array(4).fill(String.fromCodePoint(Kt[0])).join("");function er(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`${Zt}${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(Kt[e]))).join("")})).join("")}`}(t)}`}Object.fromEntries(Object.entries(Kt).map((e=>e.reverse()))),Object.fromEntries(Object.entries(Xt).map((e=>e.reverse())));var tr=`${Object.values(Xt).map((e=>`\\u{${e.toString(16)}}`)).join("")}`,rr=new RegExp(`[${tr}]{4,}`,"gu");function nr(e){try{return JSON.parse(JSON.stringify(e,((e,t)=>{return"string"!=typeof t?t:(r=t,{cleaned:r.replace(rr,""),encoded:(null==(n=r.match(rr))?void 0:n[0])||""}).cleaned;var r,n})))}catch{return e}}const or=({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}`},ir=(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},sr=e=>"response"===e.type,ar=e=>e.body,ur=11264;function cr(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?nr(o):o,u=!1===i.filterResponse?e=>e:e=>e.result,{cache:c,next:l,...f}={useAbortSignal:typeof i.signal<"u",resultSourceMap:s.enabled?"withKeyArraySelector":i.resultSourceMap,...i,returnQuery:!1===i.filterResponse&&!1!==i.returnQuery},d=mr(e,t,"query",{query:n,params:a},typeof c<"u"||typeof l<"u"?{...f,fetch:{cache:c,next:l}}:f);return s.enabled?d.pipe(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return tt.apply(void 0,ee([],Z(e)))}(Je(Promise.resolve().then((function(){return Xn})).then((function(e){return e.a})).then((({stegaEncodeSourceMap:e})=>e)))),Qe((([e,t])=>{const r=t(e.result,e.resultSourceMap,s);return u({...e,result:r})}))):d.pipe(Qe(u))}function lr(e,t,r,n={}){return vr(e,t,{uri:wr(e,"doc",r),json:!0,tag:n.tag}).pipe(et(sr),Qe((e=>e.body.documents&&e.body.documents[0])))}function fr(e,t,r,n={}){return vr(e,t,{uri:wr(e,"doc",r.join(",")),json:!0,tag:n.tag}).pipe(et(sr),Qe((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 hr(e,t,r,n){return gt("createOrReplace",r),gr(e,t,r,"createOrReplace",n)}function pr(e,t,r,n){return mr(e,t,"mutate",{mutations:[{delete:ft(r)}]},n)}function yr(e,t,r,n){let o;o=r instanceof $t||r instanceof _t?{patch:r.serialize()}:r instanceof Dt||r instanceof qt?r.serialize():r;return mr(e,t,"mutate",{mutations:Array.isArray(o)?o:[o],transactionId:n&&n.transactionId||void 0},n)}function mr(e,t,r,n,o={}){const i="mutate"===r,s="query"===r,a=i?"":or(n),u=!i&&a.length<ur,c=u?a:"",l=o.returnFirst,{timeout:f,token:d,tag:h,headers:p,returnQuery:y}=o;return vr(e,t,{method:u?"GET":"POST",uri:wr(e,r,c),json:!0,body:u?void 0:n,query:i&&ir(o),timeout:f,headers:p,token:d,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(et(sr),Qe(ar),Qe((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 mr(e,t,"mutate",{mutations:[{[n]:r}]},Object.assign({returnFirst:!0,returnDocuments:!0},o))}function vr(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:bt(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&&(Vt(t),r.query={perspective:t,...r.query},"previewDrafts"===t&&u&&(u=!1,Lt())),!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[Yt]=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:Cr(e,i,u)})),f=new Te((e=>t(l,s.requester).subscribe(e)));return r.signal?f.pipe((d=r.signal,e=>new Te((t=>{const r=()=>t.error(function(e){var t,r;if(Er)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}(d));if(d&&d.aborted)return void r();const n=e.subscribe(t);return d.addEventListener("abort",r),()=>{d.removeEventListener("abort",r),n.unsubscribe()}})))):f;var d}function br(e,t,r){return vr(e,t,r).pipe(et((e=>"response"===e.type)),Qe((e=>e.body)))}function wr(e,t,r){const n=e.config(),o=`/${t}/${vt(n)}`;return`/data${r?`${o}/${r}`:o}`.replace(/\/($|\?)/,"$1")}function Cr(e,t,r=!1){const{url:n,cdnUrl:o}=e.config();return`${r?o:n}/${t.replace(/^\//,"")}`}const Er=!!globalThis.DOMException;var xr,Sr,Tr,_r,Or=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},$r=(e,t,r)=>(Or(e,t,"read from private field"),r?r.call(e):t.get(e)),jr=(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)},kr=(e,t,r,n)=>(Or(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Ar{constructor(e,t){jr(this,xr,void 0),jr(this,Sr,void 0),kr(this,xr,e),kr(this,Sr,t)}upload(e,t,r){return Ir($r(this,xr),$r(this,Sr),e,t,r)}}xr=new WeakMap,Sr=new WeakMap;class Pr{constructor(e,t){jr(this,Tr,void 0),jr(this,_r,void 0),kr(this,Tr,e),kr(this,_r,t)}upload(e,t,r){return Ve(Ir($r(this,Tr),$r(this,_r),e,t,r).pipe(et((e=>"response"===e.type)),Qe((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=vt(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:f,description:d,creditLine:h,filename:p,source:y}=u,m={label:l,title:f,description:d,filename:p,meta:i,creditLine:h};return y&&(m.sourceId=y.id,m.sourceName=y.name,m.sourceUrl=y.url),vr(e,t,{tag:c,method:"POST",timeout:u.timeout||0,uri:`/assets/${a}/${s}`,headers:u.contentType?{"Content-Type":u.contentType}:{},query:m,body:n})}Tr=new WeakMap,_r=new WeakMap;const Rr=["includePreviousRevision","includeResult","visibility","effectFormat","tag"],Mr={includeResult:!0};function Dr(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={...(f=r,d=Mr,Object.keys(d).concat(Object.keys(f)).reduce(((e,t)=>(e[t]=typeof f[t]>"u"?d[t]:f[t],e)),{})),tag:a},c=((e,t)=>t.reduce(((t,r)=>(typeof e[r]>"u"||(t[r]=e[r]),t)),{}))(u,Rr),l=`${n}${wr(this,"listen",or({query:e,params:t,options:{tag:a,...c}}))}`;var f,d;if(l.length>14800)return new Te((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 Te((e=>{let t;c().then((e=>{t=e})).catch((t=>{e.error(t),d()}));let r,n=!1;function o(){n||(p&&e.next({type:"reconnect"}),!n&&t.readyState===t.CLOSED&&(u(),clearTimeout(r),r=setTimeout(f,100)))}function i(t){e.error(function(e){if(e instanceof Error)return e;const t=Fr(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=Fr(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 eo})),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 f(){c().then((e=>{t=e})).catch((t=>{e.error(t),d()}))}function d(){n=!0,u()}return d}))}function Fr(e){try{const t=e.data&&JSON.parse(e.data)||{};return Object.assign({type:e.type},t)}catch(e){return e}}var qr,Nr,Ur,Wr,Lr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Hr=(e,t,r)=>(Lr(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)},Br=(e,t,r,n)=>(Lr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class Jr{constructor(e,t){zr(this,qr,void 0),zr(this,Nr,void 0),Br(this,qr,e),Br(this,Nr,t)}create(e,t){return Vr(Hr(this,qr),Hr(this,Nr),"PUT",e,t)}edit(e,t){return Vr(Hr(this,qr),Hr(this,Nr),"PATCH",e,t)}delete(e){return Vr(Hr(this,qr),Hr(this,Nr),"DELETE",e)}list(){return br(Hr(this,qr),Hr(this,Nr),{uri:"/datasets",tag:null})}}qr=new WeakMap,Nr=new WeakMap;class Gr{constructor(e,t){zr(this,Ur,void 0),zr(this,Wr,void 0),Br(this,Ur,e),Br(this,Wr,t)}create(e,t){return Ve(Vr(Hr(this,Ur),Hr(this,Wr),"PUT",e,t))}edit(e,t){return Ve(Vr(Hr(this,Ur),Hr(this,Wr),"PATCH",e,t))}delete(e){return Ve(Vr(Hr(this,Ur),Hr(this,Wr),"DELETE",e))}list(){return Ve(br(Hr(this,Ur),Hr(this,Wr),{uri:"/datasets",tag:null}))}}function Vr(e,t,r,n,o){return pt(n),br(e,t,{method:r,uri:`/datasets/${n}`,body:o,tag:null})}Ur=new WeakMap,Wr=new WeakMap;var Qr,Yr,Xr,Kr,Zr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},en=(e,t,r)=>(Zr(e,t,"read from private field"),r?r.call(e):t.get(e)),tn=(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)},rn=(e,t,r,n)=>(Zr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class nn{constructor(e,t){tn(this,Qr,void 0),tn(this,Yr,void 0),rn(this,Qr,e),rn(this,Yr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return br(en(this,Qr),en(this,Yr),{uri:t})}getById(e){return br(en(this,Qr),en(this,Yr),{uri:`/projects/${e}`})}}Qr=new WeakMap,Yr=new WeakMap;class on{constructor(e,t){tn(this,Xr,void 0),tn(this,Kr,void 0),rn(this,Xr,e),rn(this,Kr,t)}list(e){const t=!1===(null==e?void 0:e.includeMembers)?"/projects?includeMembers=false":"/projects";return Ve(br(en(this,Xr),en(this,Kr),{uri:t}))}getById(e){return Ve(br(en(this,Xr),en(this,Kr),{uri:`/projects/${e}`}))}}Xr=new WeakMap,Kr=new WeakMap;var sn,an,un,cn,ln=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},fn=(e,t,r)=>(ln(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)},hn=(e,t,r,n)=>(ln(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);class pn{constructor(e,t){dn(this,sn,void 0),dn(this,an,void 0),hn(this,sn,e),hn(this,an,t)}getById(e){return br(fn(this,sn),fn(this,an),{uri:`/users/${e}`})}}sn=new WeakMap,an=new WeakMap;class yn{constructor(e,t){dn(this,un,void 0),dn(this,cn,void 0),hn(this,un,e),hn(this,cn,t)}getById(e){return Ve(br(fn(this,un),fn(this,cn),{uri:`/users/${e}`}))}}un=new WeakMap,cn=new WeakMap;var mn,gn,vn=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},bn=(e,t,r)=>(vn(e,t,"read from private field"),r?r.call(e):t.get(e)),wn=(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)},Cn=(e,t,r,n)=>(vn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);mn=new WeakMap,gn=new WeakMap;let En=class e{constructor(e,t=Jt){wn(this,mn,void 0),wn(this,gn,void 0),this.listen=Dr,this.config(t),Cn(this,gn,e),this.assets=new Ar(this,bn(this,gn)),this.datasets=new Jr(this,bn(this,gn)),this.projects=new nn(this,bn(this,gn)),this.users=new pn(this,bn(this,gn))}clone(){return new e(bn(this,gn),this.config())}config(e){if(void 0===e)return{...bn(this,mn)};if(bn(this,mn)&&!1===bn(this,mn).allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return Cn(this,mn,Qt(e,bn(this,mn)||{})),this}withConfig(t){const r=this.config();return new e(bn(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 cr(this,bn(this,gn),bn(this,mn).stega,e,t,r)}getDocument(e,t){return lr(this,bn(this,gn),e,t)}getDocuments(e,t){return fr(this,bn(this,gn),e,t)}create(e,t){return gr(this,bn(this,gn),e,"create",t)}createIfNotExists(e,t){return dr(this,bn(this,gn),e,t)}createOrReplace(e,t){return hr(this,bn(this,gn),e,t)}delete(e,t){return pr(this,bn(this,gn),e,t)}mutate(e,t){return yr(this,bn(this,gn),e,t)}patch(e,t){return new _t(e,t,this)}transaction(e){return new qt(e,this)}request(e){return br(this,bn(this,gn),e)}getUrl(e,t){return Cr(this,e,t)}getDataUrl(e,t){return wr(this,e,t)}};var xn,Sn;xn=new WeakMap,Sn=new WeakMap;let Tn=class e{constructor(e,t=Jt){wn(this,xn,void 0),wn(this,Sn,void 0),this.listen=Dr,this.config(t),Cn(this,Sn,e),this.assets=new Pr(this,bn(this,Sn)),this.datasets=new Gr(this,bn(this,Sn)),this.projects=new on(this,bn(this,Sn)),this.users=new yn(this,bn(this,Sn)),this.observable=new En(e,t)}clone(){return new e(bn(this,Sn),this.config())}config(e){if(void 0===e)return{...bn(this,xn)};if(bn(this,xn)&&!1===bn(this,xn).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),Cn(this,xn,Qt(e,bn(this,xn)||{})),this}withConfig(t){const r=this.config();return new e(bn(this,Sn),{...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 Ve(cr(this,bn(this,Sn),bn(this,xn).stega,e,t,r))}getDocument(e,t){return Ve(lr(this,bn(this,Sn),e,t))}getDocuments(e,t){return Ve(fr(this,bn(this,Sn),e,t))}create(e,t){return Ve(gr(this,bn(this,Sn),e,"create",t))}createIfNotExists(e,t){return Ve(dr(this,bn(this,Sn),e,t))}createOrReplace(e,t){return Ve(hr(this,bn(this,Sn),e,t))}delete(e,t){return Ve(pr(this,bn(this,Sn),e,t))}mutate(e,t){return Ve(yr(this,bn(this,Sn),e,t))}patch(e,t){return new $t(e,t,this)}transaction(e){return new Dt(e,this)}request(e){return Ve(br(this,bn(this,Sn),e))}dataRequest(e,t,r){return Ve(mr(this,bn(this,Sn),e,t,r))}getUrl(e,t){return Cr(this,e,t)}getDataUrl(e,t){return wr(this,e,t)}};const _n=(Pn=Tn,{requester:ct(An=[],{}).defaultRequester,createClient:e=>new Pn(ct(An,{maxRetries:e.maxRetries,retryDelay:e.retryDelay}),e)}),On=_n.requester,$n=_n.createClient,jn=(kn=$n,function(e){return Bt(),kn(e)});var kn,An,Pn;const In=/_key\s*==\s*['"](.*)['"]/;function Rn(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 Mn={"\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","'":"\\'","\\":"\\\\"},Dn={"\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t","\\'":"'","\\\\":"\\"};function Fn(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=>Dn[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=>Dn[e]));t.push(e)}return t}function qn(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 Nn(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=>Mn[e]))}']`:"number"==typeof e?`[${e}]`:""!==e._key?`[?(@._key=='${e._key.replace(/['\\]/g,(e=>Mn[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 Un(e){return"object"==typeof e&&null!==e}function Wn(e,t,r=[]){return function(e){return null!==e&&Array.isArray(e)}(e)?e.map(((e,n)=>{if(Un(e)){const o=e._key;if("string"==typeof o)return Wn(e,t,r.concat({_key:o,_index:n}))}return Wn(e,t,r.concat(n))})):Un(e)?Object.fromEntries(Object.entries(e).map((([e,n])=>[e,Wn(n,t,r.concat(e))]))):t(e,r)}function Ln(e,t,r){return Wn(e,((e,n)=>{if("string"!=typeof e)return e;const o=Nn(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=Fn(s),l=Fn(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,f=function(e){return e.startsWith(Hn)?e.slice(Hn.length):e}(o),d=Array.isArray(s)?Rn(qn(s)):s,h=new URLSearchParams({baseUrl:t,id:f,type:i,path:d});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=${f}`,`type=${i}`,`path=${encodeURIComponent(d)}`];return l&&y.push(`tool=${l}`),p.push("intent","edit",`${y.join(";")}?${h}`),p.join("/")}const Bn=({sourcePath:e,resultPath:t,value:r})=>{if(/^\d{4}-\d{2}-\d{2}/.test(n=r)&&Date.parse(n)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(r))return!1;var n;const o=e.at(-1);return!("slug"===e.at(-2)&&"current"===o||"string"==typeof o&&o.startsWith("_")||"number"==typeof o&&"marks"===e.at(-2)||"href"===o&&"number"==typeof e.at(-2)&&"markDefs"===e.at(-3)||"style"===o||"listItem"===o||e.some((e=>"meta"===e||"metadata"===e||"openGraph"===e||"seo"===e))||Gn(e)||Gn(t)||"string"==typeof o&&Jn.has(o))},Jn=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 Gn(e){return e.some((e=>"string"==typeof e&&null!==e.match(/type/i)))}function Vn(e,t,r){var n,o,i,s,a,u,c,l,f;const{filter:d,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:[]},m=Ln(e,t,(({sourcePath:e,sourceDocument:t,resultPath:n,value:o})=>{if(!1===("function"==typeof d?d({sourcePath:e,resultPath:n,filterDefault:Bn,sourceDocument:t,value:o}):Bn({sourcePath:e,resultPath:n,filterDefault:Bn,sourceDocument:t,value:o})))return h&&y.skipped.push({path:Qn(e),value:`${o.slice(0,20)}${o.length>20?"...":""}`,length:o.length}),o;h&&y.encoded.push({path:Qn(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:f}=t;return er(o,{origin:"sanity.io",href:zn({baseUrl:i,workspace:s,tool:a,id:u,type:c,path:e,...!r.omitCrossDatasetReferenceData&&{dataset:f,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==(f=null==h?void 0:h.groupEnd)||f.call(h))}return m}function Qn(e){return Rn(qn(e))}var Yn=Object.freeze({__proto__:null,stegaEncodeSourceMap:Vn}),Xn=Object.freeze({__proto__:null,a:Yn,e:Ln,s:Vn}),Kn={exports:{}};
|
|
9
9
|
/** @license
|
|
10
10
|
* eventsource.js
|
|
11
11
|
* Available under MIT License (MIT)
|
|
12
12
|
* https://github.com/Yaffle/EventSource/
|
|
13
13
|
*/
|
|
14
|
-
!function(e,t){!function(r){var n=r.setTimeout,o=r.clearTimeout,i=r.XMLHttpRequest,s=r.XDomainRequest,a=r.ActiveXObject,u=r.EventSource,c=r.document,l=r.Promise,f=r.fetch,d=r.Response,h=r.TextDecoder,p=r.TextEncoder,y=r.AbortController;if("undefined"==typeof window||void 0===c||"readyState"in c||null!=c.body||(c.readyState="loading",window.addEventListener("load",(function(e){c.readyState="complete"}),!1)),null==i&&null!=a&&(i=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==y){var g=f;f=function(e,t){var r=t.signal;return g(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return r._reader=t,r._aborted&&r._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},y=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function m(){this.bitsNeeded=0,this.codePoint=0}m.prototype.decode=function(e){function t(e,t,r){if(1===r)return e>=128>>t&&e<<t<=2047;if(2===r)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===r)return e>=65536>>t&&e<<t<=1114111;throw new Error}function r(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var n=65533,o="",i=this.bitsNeeded,s=this.codePoint,a=0;a<e.length;a+=1){var u=e[a];0!==i&&(u<128||u>191||!t(s<<6|63&u,i-6,r(i,s)))&&(i=0,s=n,o+=String.fromCharCode(s)),0===i?(u>=0&&u<=127?(i=0,s=u):u>=192&&u<=223?(i=6,s=31&u):u>=224&&u<=239?(i=12,s=15&u):u>=240&&u<=247?(i=18,s=7&u):(i=0,s=n),0===i||t(s,i,r(i,s))||(i=0,s=n)):(i-=6,s=s<<6|63&u),0===i&&(s<=65535?o+=String.fromCharCode(s):(o+=String.fromCharCode(55296+(s-65535-1>>10)),o+=String.fromCharCode(56320+(s-65535-1&1023))))}return this.bitsNeeded=i,this.codePoint=s,o};null!=h&&null!=p&&function(){try{return"test"===(new h).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(h=m);var v=function(){};function b(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=v,this.onload=v,this.onerror=v,this.onreadystatechange=v,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=v}function w(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function C(e){for(var t=Object.create(null),r=e.split("\r\n"),n=0;n<r.length;n+=1){var o=r[n].split(": "),i=o.shift(),s=o.join(": ");t[w(i)]=s}this._map=t}function E(){}function x(e){this._headers=e}function S(){}function T(){this._listeners=Object.create(null)}function _(e){n((function(){throw e}),0)}function O(e){this.type=e,this.target=void 0}function $(e,t){O.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function j(e,t){O.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function k(e,t){O.call(this,e),this.error=t.error}b.prototype.open=function(e,t){this._abort(!0);var r=this,s=this._xhr,a=1,u=0;this._abort=function(e){0!==r._sendTimeout&&(o(r._sendTimeout),r._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,s.onload=v,s.onerror=v,s.onabort=v,s.onprogress=v,s.onreadystatechange=v,s.abort(),0!==u&&(o(u),u=0),e||(r.readyState=4,r.onabort(null),r.onreadystatechange())),a=0};var c=function(){if(1===a){var e=0,t="",n=void 0;if("contentType"in s)e=200,t="OK",n=s.contentType;else try{e=s.status,t=s.statusText,n=s.getResponseHeader("Content-Type")}catch(r){e=0,t="",n=void 0}0!==e&&(a=2,r.readyState=2,r.status=e,r.statusText=t,r._contentType=n,r.onreadystatechange())}},l=function(){if(c(),2===a||3===a){a=3;var e="";try{e=s.responseText}catch(e){}r.readyState=3,r.responseText=e,r.onprogress()}},f=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:v}),l(),1===a||2===a||3===a){if(a=4,0!==u&&(o(u),u=0),r.readyState=4,"load"===e)r.onload(t);else if("error"===e)r.onerror(t);else{if("abort"!==e)throw new TypeError;r.onabort(t)}r.onreadystatechange()}},d=function(){u=n((function(){d()}),500),3===s.readyState&&l()};"onload"in s&&(s.onload=function(e){f("load",e)}),"onerror"in s&&(s.onerror=function(e){f("error",e)}),"onabort"in s&&(s.onabort=function(e){f("abort",e)}),"onprogress"in s&&(s.onprogress=l),"onreadystatechange"in s&&(s.onreadystatechange=function(e){!function(e){null!=s&&(4===s.readyState?"onload"in s&&"onerror"in s&&"onabort"in s||f(""===s.responseText?"error":"load",e):3===s.readyState?"onprogress"in s||l():2===s.readyState&&c())}(e)}),!("contentType"in s)&&"ontimeout"in i.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),s.open(e,t,!0),"readyState"in s&&(u=n((function(){d()}),0))},b.prototype.abort=function(){this._abort(!1)},b.prototype.getResponseHeader=function(e){return this._contentType},b.prototype.setRequestHeader=function(e,t){var r=this._xhr;"setRequestHeader"in r&&r.setRequestHeader(e,t)},b.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},b.prototype.send=function(){if("ontimeout"in i.prototype&&("sendAsBinary"in i.prototype||"mozAnon"in i.prototype)||null==c||null==c.readyState||"complete"===c.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=n((function(){t._sendTimeout=0,t.send()}),4)}},C.prototype.get=function(e){return this._map[w(e)]},null!=i&&null==i.HEADERS_RECEIVED&&(i.HEADERS_RECEIVED=2),E.prototype.open=function(e,t,r,n,o,s,a){e.open("GET",o);var u=0;for(var c in e.onprogress=function(){var t=e.responseText.slice(u);u+=t.length,r(t)},e.onerror=function(e){e.preventDefault(),n(new Error("NetworkError"))},e.onload=function(){n(null)},e.onabort=function(){n(null)},e.onreadystatechange=function(){if(e.readyState===i.HEADERS_RECEIVED){var r=e.status,n=e.statusText,o=e.getResponseHeader("Content-Type"),s=e.getAllResponseHeaders();t(r,n,o,new C(s))}},e.withCredentials=s,a)Object.prototype.hasOwnProperty.call(a,c)&&e.setRequestHeader(c,a[c]);return e.send(),e},x.prototype.get=function(e){return this._headers.get(e)},S.prototype.open=function(e,t,r,n,o,i,s){var a=null,u=new y,c=u.signal,d=new h;return f(o,{headers:s,credentials:i?"include":"same-origin",signal:c,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new x(e.headers)),new l((function(e,t){var n=function(){a.read().then((function(t){if(t.done)e(void 0);else{var o=d.decode(t.value,{stream:!0});r(o),n()}})).catch((function(e){t(e)}))};n()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){n(e)})),{abort:function(){null!=a&&a.cancel(),u.abort()}}},T.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var r=t.length,n=0;n<r;n+=1){var o=t[n];try{"function"==typeof o.handleEvent?o.handleEvent(e):o.call(this,e)}catch(e){_(e)}}},T.prototype.addEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];null==n&&(n=[],r[e]=n);for(var o=!1,i=0;i<n.length;i+=1)n[i]===t&&(o=!0);o||n.push(t)},T.prototype.removeEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];if(null!=n){for(var o=[],i=0;i<n.length;i+=1)n[i]!==t&&o.push(n[i]);0===o.length?delete r[e]:r[e]=o}},$.prototype=Object.create(O.prototype),j.prototype=Object.create(O.prototype),k.prototype=Object.create(O.prototype);var A=-1,I=0,P=1,R=2,M=-1,D=0,F=1,q=2,N=3,U=/^text\/event\-stream(;.*)?$/i,W=function(e,t){var r=null==e?t:parseInt(e,10);return r!=r&&(r=t),L(r)},L=function(e){return Math.min(Math.max(e,1e3),18e6)},H=function(e,t,r){try{"function"==typeof t&&t.call(e,r)}catch(e){_(e)}};function z(e,t){T.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,r){t=String(t);var a=Boolean(r.withCredentials),u=r.lastEventIdQueryParameterName||"lastEventId",c=L(1e3),l=W(r.heartbeatTimeout,45e3),f="",d=c,h=!1,p=0,y=r.headers||{},g=r.Transport,m=B&&null==g?void 0:new b(null!=g?new g:null!=i&&"withCredentials"in i.prototype||null==s?new i:new s),v=null!=g&&"string"!=typeof g?new g:null==m?new S:new E,w=void 0,C=0,x=A,T="",_="",O="",z="",J=D,G=0,V=0,Q=function(t,r,n,o){if(x===I)if(200===t&&null!=n&&U.test(n)){x=P,h=Date.now(),d=c,e.readyState=P;var i=new j("open",{status:t,statusText:r,headers:o});e.dispatchEvent(i),H(e,e.onopen,i)}else{var s="";200!==t?(r&&(r=r.replace(/\s+/g," ")),s="EventSource's response has a status "+t+" "+r+" that is not 200. Aborting the connection."):s="EventSource's response has a Content-Type specifying an unsupported type: "+(null==n?"-":n.replace(/\s+/g," "))+". Aborting the connection.",K();i=new j("error",{status:t,statusText:r,headers:o});e.dispatchEvent(i),H(e,e.onerror,i),console.error(s)}},Y=function(t){if(x===P){for(var r=-1,i=0;i<t.length;i+=1){(u=t.charCodeAt(i))!=="\n".charCodeAt(0)&&u!=="\r".charCodeAt(0)||(r=i)}var s=(-1!==r?z:"")+t.slice(0,r+1);z=(-1===r?z:"")+t.slice(r+1),""!==t&&(h=Date.now(),p+=t.length);for(var a=0;a<s.length;a+=1){var u=s.charCodeAt(a);if(J===M&&u==="\n".charCodeAt(0))J=D;else if(J===M&&(J=D),u==="\r".charCodeAt(0)||u==="\n".charCodeAt(0)){if(J!==D){J===F&&(V=a+1);var y=s.slice(G,V-1),g=s.slice(V+(V<a&&s.charCodeAt(V)===" ".charCodeAt(0)?1:0),a);"data"===y?(T+="\n",T+=g):"id"===y?_=g:"event"===y?O=g:"retry"===y?(c=W(g,c),d=c):"heartbeatTimeout"===y&&(l=W(g,l),0!==C&&(o(C),C=n((function(){Z()}),l)))}if(J===D){if(""!==T){f=_,""===O&&(O="message");var m=new $(O,{data:T.slice(1),lastEventId:_});if(e.dispatchEvent(m),"open"===O?H(e,e.onopen,m):"message"===O?H(e,e.onmessage,m):"error"===O&&H(e,e.onerror,m),x===R)return}T="",O=""}J=u==="\r".charCodeAt(0)?M:D}else J===D&&(G=a,J=F),J===F?u===":".charCodeAt(0)&&(V=a+1,J=q):J===q&&(J=N)}}},X=function(t){if(x===P||x===I){x=A,0!==C&&(o(C),C=0),C=n((function(){Z()}),d),d=L(Math.min(16*c,2*d)),e.readyState=I;var r=new k("error",{error:t});e.dispatchEvent(r),H(e,e.onerror,r),null!=t&&console.error(t)}},K=function(){x=R,null!=w&&(w.abort(),w=void 0),0!==C&&(o(C),C=0),e.readyState=R},Z=function(){if(C=0,x===A){h=!1,p=0,C=n((function(){Z()}),l),x=I,T="",O="",_=f,z="",G=0,V=0,J=D;var r=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==f){var o=t.indexOf("?");r=-1===o?t:t.slice(0,o+1)+t.slice(o+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===u?"":e})),r+=(-1===t.indexOf("?")?"?":"&")+u+"="+encodeURIComponent(f)}var i=e.withCredentials,s={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(s[c]=a[c]);try{w=v.open(m,Q,Y,X,r,i,s)}catch(e){throw K(),e}}else if(h||null==w){var d=Math.max((h||Date.now())+l-Date.now(),1);h=!1,C=n((function(){Z()}),d)}else X(new Error("No activity within "+l+" milliseconds. "+(x===I?"No response received.":p+" chars received.")+" Reconnecting.")),null!=w&&(w.abort(),w=void 0)};e.url=t,e.readyState=I,e.withCredentials=a,e.headers=y,e._close=K,Z()}(this,e,t)}var B=null!=f&&null!=d&&"body"in d.prototype;z.prototype=Object.create(T.prototype),z.prototype.CONNECTING=I,z.prototype.OPEN=P,z.prototype.CLOSED=R,z.prototype.close=function(){this._close()},z.CONNECTING=I,z.OPEN=P,z.CLOSED=R,z.prototype.withCredentials=void 0;var J,G=u;null==i||null!=u&&"withCredentials"in u.prototype||(G=z),J=function(e){e.EventSourcePolyfill=z,e.NativeEventSource=u,e.EventSource=G}(t),void 0!==J&&(e.exports=J)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:a:globalThis)}(Xn,Xn.exports);var Kn=u(Xn.exports.EventSourcePolyfill),Zn=Object.freeze({__proto__:null,default:Kn});e.BasePatch=Tt,e.BaseTransaction=Rt,e.ClientError=rt,e.ObservablePatch=_t,e.ObservableSanityClient=En,e.ObservableTransaction=qt,e.Patch=$t,e.SanityClient=Tn,e.ServerError=nt,e.Transaction=Dt,e.createClient=$n,e.default=jn,e.requester=On,e.unstable__adapter=_,e.unstable__environment="browser",Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
14
|
+
!function(e,t){!function(r){var n=r.setTimeout,o=r.clearTimeout,i=r.XMLHttpRequest,s=r.XDomainRequest,a=r.ActiveXObject,u=r.EventSource,c=r.document,l=r.Promise,f=r.fetch,d=r.Response,h=r.TextDecoder,p=r.TextEncoder,y=r.AbortController;if("undefined"==typeof window||void 0===c||"readyState"in c||null!=c.body||(c.readyState="loading",window.addEventListener("load",(function(e){c.readyState="complete"}),!1)),null==i&&null!=a&&(i=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==y){var m=f;f=function(e,t){var r=t.signal;return m(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return r._reader=t,r._aborted&&r._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},y=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function g(){this.bitsNeeded=0,this.codePoint=0}g.prototype.decode=function(e){function t(e,t,r){if(1===r)return e>=128>>t&&e<<t<=2047;if(2===r)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===r)return e>=65536>>t&&e<<t<=1114111;throw new Error}function r(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var n=65533,o="",i=this.bitsNeeded,s=this.codePoint,a=0;a<e.length;a+=1){var u=e[a];0!==i&&(u<128||u>191||!t(s<<6|63&u,i-6,r(i,s)))&&(i=0,s=n,o+=String.fromCharCode(s)),0===i?(u>=0&&u<=127?(i=0,s=u):u>=192&&u<=223?(i=6,s=31&u):u>=224&&u<=239?(i=12,s=15&u):u>=240&&u<=247?(i=18,s=7&u):(i=0,s=n),0===i||t(s,i,r(i,s))||(i=0,s=n)):(i-=6,s=s<<6|63&u),0===i&&(s<=65535?o+=String.fromCharCode(s):(o+=String.fromCharCode(55296+(s-65535-1>>10)),o+=String.fromCharCode(56320+(s-65535-1&1023))))}return this.bitsNeeded=i,this.codePoint=s,o};null!=h&&null!=p&&function(){try{return"test"===(new h).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(h=g);var v=function(){};function b(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=v,this.onload=v,this.onerror=v,this.onreadystatechange=v,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=v}function w(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function C(e){for(var t=Object.create(null),r=e.split("\r\n"),n=0;n<r.length;n+=1){var o=r[n].split(": "),i=o.shift(),s=o.join(": ");t[w(i)]=s}this._map=t}function E(){}function x(e){this._headers=e}function S(){}function T(){this._listeners=Object.create(null)}function _(e){n((function(){throw e}),0)}function O(e){this.type=e,this.target=void 0}function $(e,t){O.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function j(e,t){O.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function k(e,t){O.call(this,e),this.error=t.error}b.prototype.open=function(e,t){this._abort(!0);var r=this,s=this._xhr,a=1,u=0;this._abort=function(e){0!==r._sendTimeout&&(o(r._sendTimeout),r._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,s.onload=v,s.onerror=v,s.onabort=v,s.onprogress=v,s.onreadystatechange=v,s.abort(),0!==u&&(o(u),u=0),e||(r.readyState=4,r.onabort(null),r.onreadystatechange())),a=0};var c=function(){if(1===a){var e=0,t="",n=void 0;if("contentType"in s)e=200,t="OK",n=s.contentType;else try{e=s.status,t=s.statusText,n=s.getResponseHeader("Content-Type")}catch(r){e=0,t="",n=void 0}0!==e&&(a=2,r.readyState=2,r.status=e,r.statusText=t,r._contentType=n,r.onreadystatechange())}},l=function(){if(c(),2===a||3===a){a=3;var e="";try{e=s.responseText}catch(e){}r.readyState=3,r.responseText=e,r.onprogress()}},f=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:v}),l(),1===a||2===a||3===a){if(a=4,0!==u&&(o(u),u=0),r.readyState=4,"load"===e)r.onload(t);else if("error"===e)r.onerror(t);else{if("abort"!==e)throw new TypeError;r.onabort(t)}r.onreadystatechange()}},d=function(){u=n((function(){d()}),500),3===s.readyState&&l()};"onload"in s&&(s.onload=function(e){f("load",e)}),"onerror"in s&&(s.onerror=function(e){f("error",e)}),"onabort"in s&&(s.onabort=function(e){f("abort",e)}),"onprogress"in s&&(s.onprogress=l),"onreadystatechange"in s&&(s.onreadystatechange=function(e){!function(e){null!=s&&(4===s.readyState?"onload"in s&&"onerror"in s&&"onabort"in s||f(""===s.responseText?"error":"load",e):3===s.readyState?"onprogress"in s||l():2===s.readyState&&c())}(e)}),!("contentType"in s)&&"ontimeout"in i.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),s.open(e,t,!0),"readyState"in s&&(u=n((function(){d()}),0))},b.prototype.abort=function(){this._abort(!1)},b.prototype.getResponseHeader=function(e){return this._contentType},b.prototype.setRequestHeader=function(e,t){var r=this._xhr;"setRequestHeader"in r&&r.setRequestHeader(e,t)},b.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},b.prototype.send=function(){if("ontimeout"in i.prototype&&("sendAsBinary"in i.prototype||"mozAnon"in i.prototype)||null==c||null==c.readyState||"complete"===c.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=n((function(){t._sendTimeout=0,t.send()}),4)}},C.prototype.get=function(e){return this._map[w(e)]},null!=i&&null==i.HEADERS_RECEIVED&&(i.HEADERS_RECEIVED=2),E.prototype.open=function(e,t,r,n,o,s,a){e.open("GET",o);var u=0;for(var c in e.onprogress=function(){var t=e.responseText.slice(u);u+=t.length,r(t)},e.onerror=function(e){e.preventDefault(),n(new Error("NetworkError"))},e.onload=function(){n(null)},e.onabort=function(){n(null)},e.onreadystatechange=function(){if(e.readyState===i.HEADERS_RECEIVED){var r=e.status,n=e.statusText,o=e.getResponseHeader("Content-Type"),s=e.getAllResponseHeaders();t(r,n,o,new C(s))}},e.withCredentials=s,a)Object.prototype.hasOwnProperty.call(a,c)&&e.setRequestHeader(c,a[c]);return e.send(),e},x.prototype.get=function(e){return this._headers.get(e)},S.prototype.open=function(e,t,r,n,o,i,s){var a=null,u=new y,c=u.signal,d=new h;return f(o,{headers:s,credentials:i?"include":"same-origin",signal:c,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new x(e.headers)),new l((function(e,t){var n=function(){a.read().then((function(t){if(t.done)e(void 0);else{var o=d.decode(t.value,{stream:!0});r(o),n()}})).catch((function(e){t(e)}))};n()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){n(e)})),{abort:function(){null!=a&&a.cancel(),u.abort()}}},T.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var r=t.length,n=0;n<r;n+=1){var o=t[n];try{"function"==typeof o.handleEvent?o.handleEvent(e):o.call(this,e)}catch(e){_(e)}}},T.prototype.addEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];null==n&&(n=[],r[e]=n);for(var o=!1,i=0;i<n.length;i+=1)n[i]===t&&(o=!0);o||n.push(t)},T.prototype.removeEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];if(null!=n){for(var o=[],i=0;i<n.length;i+=1)n[i]!==t&&o.push(n[i]);0===o.length?delete r[e]:r[e]=o}},$.prototype=Object.create(O.prototype),j.prototype=Object.create(O.prototype),k.prototype=Object.create(O.prototype);var A=-1,P=0,I=1,R=2,M=-1,D=0,F=1,q=2,N=3,U=/^text\/event\-stream(;.*)?$/i,W=function(e,t){var r=null==e?t:parseInt(e,10);return r!=r&&(r=t),L(r)},L=function(e){return Math.min(Math.max(e,1e3),18e6)},H=function(e,t,r){try{"function"==typeof t&&t.call(e,r)}catch(e){_(e)}};function z(e,t){T.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,r){t=String(t);var a=Boolean(r.withCredentials),u=r.lastEventIdQueryParameterName||"lastEventId",c=L(1e3),l=W(r.heartbeatTimeout,45e3),f="",d=c,h=!1,p=0,y=r.headers||{},m=r.Transport,g=B&&null==m?void 0:new b(null!=m?new m:null!=i&&"withCredentials"in i.prototype||null==s?new i:new s),v=null!=m&&"string"!=typeof m?new m:null==g?new S:new E,w=void 0,C=0,x=A,T="",_="",O="",z="",J=D,G=0,V=0,Q=function(t,r,n,o){if(x===P)if(200===t&&null!=n&&U.test(n)){x=I,h=Date.now(),d=c,e.readyState=I;var i=new j("open",{status:t,statusText:r,headers:o});e.dispatchEvent(i),H(e,e.onopen,i)}else{var s="";200!==t?(r&&(r=r.replace(/\s+/g," ")),s="EventSource's response has a status "+t+" "+r+" that is not 200. Aborting the connection."):s="EventSource's response has a Content-Type specifying an unsupported type: "+(null==n?"-":n.replace(/\s+/g," "))+". Aborting the connection.",K();i=new j("error",{status:t,statusText:r,headers:o});e.dispatchEvent(i),H(e,e.onerror,i),console.error(s)}},Y=function(t){if(x===I){for(var r=-1,i=0;i<t.length;i+=1){(u=t.charCodeAt(i))!=="\n".charCodeAt(0)&&u!=="\r".charCodeAt(0)||(r=i)}var s=(-1!==r?z:"")+t.slice(0,r+1);z=(-1===r?z:"")+t.slice(r+1),""!==t&&(h=Date.now(),p+=t.length);for(var a=0;a<s.length;a+=1){var u=s.charCodeAt(a);if(J===M&&u==="\n".charCodeAt(0))J=D;else if(J===M&&(J=D),u==="\r".charCodeAt(0)||u==="\n".charCodeAt(0)){if(J!==D){J===F&&(V=a+1);var y=s.slice(G,V-1),m=s.slice(V+(V<a&&s.charCodeAt(V)===" ".charCodeAt(0)?1:0),a);"data"===y?(T+="\n",T+=m):"id"===y?_=m:"event"===y?O=m:"retry"===y?(c=W(m,c),d=c):"heartbeatTimeout"===y&&(l=W(m,l),0!==C&&(o(C),C=n((function(){Z()}),l)))}if(J===D){if(""!==T){f=_,""===O&&(O="message");var g=new $(O,{data:T.slice(1),lastEventId:_});if(e.dispatchEvent(g),"open"===O?H(e,e.onopen,g):"message"===O?H(e,e.onmessage,g):"error"===O&&H(e,e.onerror,g),x===R)return}T="",O=""}J=u==="\r".charCodeAt(0)?M:D}else J===D&&(G=a,J=F),J===F?u===":".charCodeAt(0)&&(V=a+1,J=q):J===q&&(J=N)}}},X=function(t){if(x===I||x===P){x=A,0!==C&&(o(C),C=0),C=n((function(){Z()}),d),d=L(Math.min(16*c,2*d)),e.readyState=P;var r=new k("error",{error:t});e.dispatchEvent(r),H(e,e.onerror,r),null!=t&&console.error(t)}},K=function(){x=R,null!=w&&(w.abort(),w=void 0),0!==C&&(o(C),C=0),e.readyState=R},Z=function(){if(C=0,x===A){h=!1,p=0,C=n((function(){Z()}),l),x=P,T="",O="",_=f,z="",G=0,V=0,J=D;var r=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==f){var o=t.indexOf("?");r=-1===o?t:t.slice(0,o+1)+t.slice(o+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===u?"":e})),r+=(-1===t.indexOf("?")?"?":"&")+u+"="+encodeURIComponent(f)}var i=e.withCredentials,s={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(s[c]=a[c]);try{w=v.open(g,Q,Y,X,r,i,s)}catch(e){throw K(),e}}else if(h||null==w){var d=Math.max((h||Date.now())+l-Date.now(),1);h=!1,C=n((function(){Z()}),d)}else X(new Error("No activity within "+l+" milliseconds. "+(x===P?"No response received.":p+" chars received.")+" Reconnecting.")),null!=w&&(w.abort(),w=void 0)};e.url=t,e.readyState=P,e.withCredentials=a,e.headers=y,e._close=K,Z()}(this,e,t)}var B=null!=f&&null!=d&&"body"in d.prototype;z.prototype=Object.create(T.prototype),z.prototype.CONNECTING=P,z.prototype.OPEN=I,z.prototype.CLOSED=R,z.prototype.close=function(){this._close()},z.CONNECTING=P,z.OPEN=I,z.CLOSED=R,z.prototype.withCredentials=void 0;var J,G=u;null==i||null!=u&&"withCredentials"in u.prototype||(G=z),J=function(e){e.EventSourcePolyfill=z,e.NativeEventSource=u,e.EventSource=G}(t),void 0!==J&&(e.exports=J)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:a:globalThis)}(Kn,Kn.exports);var Zn=u(Kn.exports.EventSourcePolyfill),eo=Object.freeze({__proto__:null,default:Zn});e.BasePatch=Tt,e.BaseTransaction=Rt,e.ClientError=rt,e.ObservablePatch=_t,e.ObservableSanityClient=En,e.ObservableTransaction=qt,e.Patch=$t,e.SanityClient=Tn,e.ServerError=nt,e.Transaction=Dt,e.createClient=$n,e.default=jn,e.requester=On,e.unstable__adapter=_,e.unstable__environment="browser",Object.defineProperty(e,"__esModule",{value:!0})}));
|