@sanity/client 6.21.1 → 6.21.3-bundle-perspective

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"stegaClean.js","sources":["../../node_modules/@vercel/stega/dist/index.mjs","../../src/stega/stegaClean.ts"],"sourcesContent":["var s={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},c={0:8203,1:8204,2:8205,3:65279},u=new Array(4).fill(String.fromCodePoint(c[0])).join(\"\"),m=String.fromCharCode(0);function E(t){let e=JSON.stringify(t);return`${u}${Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(4).padStart(4,\"0\")).map(o=>String.fromCodePoint(c[o])).join(\"\")}).join(\"\")}`}function y(t){let e=JSON.stringify(t);return Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(16).padStart(2,\"0\")).map(o=>String.fromCodePoint(s[o])).join(\"\")}).join(\"\")}function I(t){return!Number.isNaN(Number(t))||/[a-z]/i.test(t)&&!/\\d+(?:[-:\\/]\\d+){2}(?:T\\d+(?:[-:\\/]\\d+){1,2}(\\.\\d+)?Z?)?/.test(t)?!1:Boolean(Date.parse(t))}function T(t){try{new URL(t,t.startsWith(\"/\")?\"https://acme.com\":void 0)}catch{return!1}return!0}function C(t,e,r=\"auto\"){return r===!0||r===\"auto\"&&(I(t)||T(t))?t:`${t}${E(e)}`}var x=Object.fromEntries(Object.entries(c).map(t=>t.reverse())),g=Object.fromEntries(Object.entries(s).map(t=>t.reverse())),S=`${Object.values(s).map(t=>`\\\\u{${t.toString(16)}}`).join(\"\")}`,f=new RegExp(`[${S}]{4,}`,\"gu\");function G(t){let e=t.match(f);if(!!e)return h(e[0],!0)[0]}function $(t){let e=t.match(f);if(!!e)return e.map(r=>h(r)).flat()}function h(t,e=!1){let r=Array.from(t);if(r.length%2===0){if(r.length%4||!t.startsWith(u))return A(r,e)}else throw new Error(\"Encoded data has invalid length\");let n=[];for(let o=r.length*.25;o--;){let p=r.slice(o*4,o*4+4).map(d=>x[d.codePointAt(0)]).join(\"\");n.unshift(String.fromCharCode(parseInt(p,4)))}if(e){n.shift();let o=n.indexOf(m);return o===-1&&(o=n.length),[JSON.parse(n.slice(0,o).join(\"\"))]}return n.join(\"\").split(m).filter(Boolean).map(o=>JSON.parse(o))}function A(t,e){var d;let r=[];for(let i=t.length*.5;i--;){let a=`${g[t[i*2].codePointAt(0)]}${g[t[i*2+1].codePointAt(0)]}`;r.unshift(String.fromCharCode(parseInt(a,16)))}let n=[],o=[r.join(\"\")],p=10;for(;o.length;){let i=o.shift();try{if(n.push(JSON.parse(i)),e)return n}catch(a){if(!p--)throw a;let l=+((d=a.message.match(/\\sposition\\s(\\d+)$/))==null?void 0:d[1]);if(!l)throw a;o.unshift(i.substring(0,l),i.substring(l))}}return n}function _(t){var e;return{cleaned:t.replace(f,\"\"),encoded:((e=t.match(f))==null?void 0:e[0])||\"\"}}function O(t){return t&&JSON.parse(_(JSON.stringify(t)).cleaned)}export{f as VERCEL_STEGA_REGEX,y as legacyStegaEncode,O as vercelStegaClean,C as vercelStegaCombine,G as vercelStegaDecode,$ as vercelStegaDecodeAll,E as vercelStegaEncode,_ as vercelStegaSplit};\n","import {vercelStegaClean} from '@vercel/stega'\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @public\n */\nexport function stegaClean<Result = unknown>(result: Result): Result {\n return vercelStegaClean<Result>(result)\n}\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @alpha\n * @deprecated Use `stega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,EAAE,GAAE,GAAE,IAAE,QAAO;AAAC,SAAO,MAAI,MAAI,MAAI,WAAS,EAAE,CAAC,KAAG,EAAE,CAAC,KAAG,IAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;AAAE;AAAO,OAAO,YAAY,OAAO,QAAQ,CAAC,EAAE,IAAI,OAAG,EAAE,QAAS,CAAA,CAAC;AAAI,OAAO,YAAY,OAAO,QAAQ,CAAC,EAAE,IAAI,OAAG,EAAE,QAAO,CAAE,CAAC;AAAE,IAAA,IAAE,GAAG,OAAO,OAAO,CAAC,EAAE,IAAI,OAAG,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,IAAG,IAAE,IAAI,OAAO,IAAI,CAAC,SAAQ,IAAI;AAAugC,SAAS,EAAE,GAAE;AAAC,MAAI;AAAE,SAAM,EAAC,SAAQ,EAAE,QAAQ,GAAE,EAAE,GAAE,WAAU,IAAE,EAAE,MAAM,CAAC,MAAI,OAAK,SAAO,EAAE,CAAC,MAAI,GAAE;AAAC;AAAC,SAAS,EAAE,GAAE;AAAC,SAAO,KAAG,KAAK,MAAM,EAAE,KAAK,UAAU,CAAC,CAAC,EAAE,OAAO;AAAC;ACO1kF,SAAS,WAA6B,QAAwB;AACnE,SAAOA,EAAyB,MAAM;AACxC;AAQO,MAAM,sBAAsB;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"stegaClean.js","sources":["../../node_modules/.pnpm/@vercel+stega@0.1.2/node_modules/@vercel/stega/dist/index.mjs","../../src/stega/stegaClean.ts"],"sourcesContent":["var s={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},c={0:8203,1:8204,2:8205,3:65279},u=new Array(4).fill(String.fromCodePoint(c[0])).join(\"\"),m=String.fromCharCode(0);function E(t){let e=JSON.stringify(t);return`${u}${Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(4).padStart(4,\"0\")).map(o=>String.fromCodePoint(c[o])).join(\"\")}).join(\"\")}`}function y(t){let e=JSON.stringify(t);return Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(16).padStart(2,\"0\")).map(o=>String.fromCodePoint(s[o])).join(\"\")}).join(\"\")}function I(t){return!Number.isNaN(Number(t))||/[a-z]/i.test(t)&&!/\\d+(?:[-:\\/]\\d+){2}(?:T\\d+(?:[-:\\/]\\d+){1,2}(\\.\\d+)?Z?)?/.test(t)?!1:Boolean(Date.parse(t))}function T(t){try{new URL(t,t.startsWith(\"/\")?\"https://acme.com\":void 0)}catch{return!1}return!0}function C(t,e,r=\"auto\"){return r===!0||r===\"auto\"&&(I(t)||T(t))?t:`${t}${E(e)}`}var x=Object.fromEntries(Object.entries(c).map(t=>t.reverse())),g=Object.fromEntries(Object.entries(s).map(t=>t.reverse())),S=`${Object.values(s).map(t=>`\\\\u{${t.toString(16)}}`).join(\"\")}`,f=new RegExp(`[${S}]{4,}`,\"gu\");function G(t){let e=t.match(f);if(!!e)return h(e[0],!0)[0]}function $(t){let e=t.match(f);if(!!e)return e.map(r=>h(r)).flat()}function h(t,e=!1){let r=Array.from(t);if(r.length%2===0){if(r.length%4||!t.startsWith(u))return A(r,e)}else throw new Error(\"Encoded data has invalid length\");let n=[];for(let o=r.length*.25;o--;){let p=r.slice(o*4,o*4+4).map(d=>x[d.codePointAt(0)]).join(\"\");n.unshift(String.fromCharCode(parseInt(p,4)))}if(e){n.shift();let o=n.indexOf(m);return o===-1&&(o=n.length),[JSON.parse(n.slice(0,o).join(\"\"))]}return n.join(\"\").split(m).filter(Boolean).map(o=>JSON.parse(o))}function A(t,e){var d;let r=[];for(let i=t.length*.5;i--;){let a=`${g[t[i*2].codePointAt(0)]}${g[t[i*2+1].codePointAt(0)]}`;r.unshift(String.fromCharCode(parseInt(a,16)))}let n=[],o=[r.join(\"\")],p=10;for(;o.length;){let i=o.shift();try{if(n.push(JSON.parse(i)),e)return n}catch(a){if(!p--)throw a;let l=+((d=a.message.match(/\\sposition\\s(\\d+)$/))==null?void 0:d[1]);if(!l)throw a;o.unshift(i.substring(0,l),i.substring(l))}}return n}function _(t){var e;return{cleaned:t.replace(f,\"\"),encoded:((e=t.match(f))==null?void 0:e[0])||\"\"}}function O(t){return t&&JSON.parse(_(JSON.stringify(t)).cleaned)}export{f as VERCEL_STEGA_REGEX,y as legacyStegaEncode,O as vercelStegaClean,C as vercelStegaCombine,G as vercelStegaDecode,$ as vercelStegaDecodeAll,E as vercelStegaEncode,_ as vercelStegaSplit};\n","import {vercelStegaClean} from '@vercel/stega'\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @public\n */\nexport function stegaClean<Result = unknown>(result: Result): Result {\n return vercelStegaClean<Result>(result)\n}\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @alpha\n * @deprecated Use `stegaClean` instead\n */\nexport const vercelStegaCleanAll = stegaClean\n"],"names":["vercelStegaClean"],"mappings":"AAAG,IAAC,IAAE,EAAC,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,OAAM,GAAE,MAAK,GAAE,QAAO,GAAE,QAAO,GAAE,QAAO,GAAE,QAAO,GAAE,QAAO,GAAE,QAAO,GAAE,QAAO,GAAE,OAAM,GAAE,IAAE,EAAC,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,IAAE,IAAI,MAAM,CAAC,EAAE,KAAK,OAAO,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE;AAA2B,SAAS,EAAE,GAAE;AAAC,MA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I;AAAugC,SAAS,EAAE,GAAE;AAAC,MAAI;AAAE,SAAM,EAAC,SAAQ,EAAE,QAAQ,GAAE,EAAE,GAAE,WAAU,IAAE,EAAE,MAAM,CAAC,MAAI,OAAK,SAAO,EAAE,CAAC,MAAI,GAAE;AAAC;AAAC,SAAS,EAAE,GAAE;AAAC,SAAO,KAAG,KAAK,MAAM,EAAE,KAAK,UAAU,CAAC,CAAC,EAAE,OAAO;AAAC;ACO1kF,SAAS,WAA6B,QAAwB;AACnE,SAAOA,EAAyB,MAAM;AACxC;AAQO,MAAM,sBAAsB;","x_google_ignoreList":[0]}
@@ -85,7 +85,7 @@ function jsonPathToMappingPath(path) {
85
85
  });
86
86
  }
87
87
  function resolveMapping(resultPath, csm) {
88
- if (!(csm != null && csm.mappings))
88
+ if (!csm?.mappings)
89
89
  return;
90
90
  const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath));
91
91
  if (csm.mappings[resultMappingPath] !== void 0)
@@ -244,21 +244,20 @@ function hasTypeLike(path) {
244
244
  }
245
245
  const TRUNCATE_LENGTH = 20;
246
246
  function stegaEncodeSourceMap(result, resultSourceMap, config) {
247
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
248
247
  const { filter, logger, enabled } = config;
249
248
  if (!enabled) {
250
249
  const msg = "config.enabled must be true, don't call this function otherwise";
251
- throw (_a = logger == null ? void 0 : logger.error) == null || _a.call(logger, `[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), new TypeError(msg);
250
+ throw logger?.error?.(`[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), new TypeError(msg);
252
251
  }
253
252
  if (!resultSourceMap)
254
- return (_b = logger == null ? void 0 : logger.error) == null || _b.call(logger, "[@sanity/client]: Missing Content Source Map from response body", {
253
+ return logger?.error?.("[@sanity/client]: Missing Content Source Map from response body", {
255
254
  result,
256
255
  resultSourceMap,
257
256
  config
258
257
  }), result;
259
258
  if (!config.studioUrl) {
260
259
  const msg = "config.studioUrl must be defined";
261
- throw (_c = logger == null ? void 0 : logger.error) == null || _c.call(logger, `[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), new TypeError(msg);
260
+ throw logger?.error?.(`[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), new TypeError(msg);
262
261
  }
263
262
  const report = {
264
263
  encoded: [],
@@ -281,8 +280,7 @@ function stegaEncodeSourceMap(result, resultSourceMap, config) {
281
280
  const { baseUrl, workspace, tool } = resolveStudioBaseRoute(
282
281
  typeof config.studioUrl == "function" ? config.studioUrl(sourceDocument) : config.studioUrl
283
282
  );
284
- if (!baseUrl)
285
- return value;
283
+ if (!baseUrl) return value;
286
284
  const { _id: id, _type: type, _projectId: projectId, _dataset: dataset } = sourceDocument;
287
285
  return C(
288
286
  value,
@@ -305,16 +303,15 @@ function stegaEncodeSourceMap(result, resultSourceMap, config) {
305
303
  );
306
304
  if (logger) {
307
305
  const isSkipping = report.skipped.length, isEncoding = report.encoded.length;
308
- if ((isSkipping || isEncoding) && ((_d = (logger == null ? void 0 : logger.groupCollapsed) || logger.log) == null || _d("[@sanity/client]: Encoding source map into result"), (_e = logger.log) == null || _e.call(
309
- logger,
306
+ if ((isSkipping || isEncoding) && ((logger?.groupCollapsed || logger.log)?.("[@sanity/client]: Encoding source map into result"), logger.log?.(
310
307
  `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`
311
- )), report.encoded.length > 0 && ((_f = logger == null ? void 0 : logger.log) == null || _f.call(logger, "[@sanity/client]: Table of encoded paths"), (_g = (logger == null ? void 0 : logger.table) || logger.log) == null || _g(report.encoded)), report.skipped.length > 0) {
308
+ )), report.encoded.length > 0 && (logger?.log?.("[@sanity/client]: Table of encoded paths"), (logger?.table || logger.log)?.(report.encoded)), report.skipped.length > 0) {
312
309
  const skipped = /* @__PURE__ */ new Set();
313
310
  for (const { path } of report.skipped)
314
311
  skipped.add(path.replace(reKeySegment, "0").replace(/\[\d+\]/g, "[]"));
315
- (_h = logger == null ? void 0 : logger.log) == null || _h.call(logger, "[@sanity/client]: List of skipped paths", [...skipped.values()]);
312
+ logger?.log?.("[@sanity/client]: List of skipped paths", [...skipped.values()]);
316
313
  }
317
- (isSkipping || isEncoding) && ((_i = logger == null ? void 0 : logger.groupEnd) == null || _i.call(logger));
314
+ (isSkipping || isEncoding) && logger?.groupEnd?.();
318
315
  }
319
316
  return resultWithStega;
320
317
  }
@@ -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 type {ContentSourceMap} from '@sanity/client/csm'\n\nimport {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\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,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,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.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 type {ContentSourceMap} from '@sanity/client/csm'\n\nimport {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\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,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,OAAO,QAAQ,QAC5B,aAAa,OAAO,QAAQ;AAC9B,SAAA,cAAc,iBACd,QAAQ,kBAAkB,OAAO,OAAO,mDAAmD,GAC7F,OAAO;AAAA,MACL,oCAAoC,OAAO,QAAQ,MAAM,cAAc,OAAO,QAAQ,MAAM;AAAA,IAAA,IAG5F,OAAO,QAAQ,SAAS,MAC1B,QAAQ,MAAM,0CAA0C,IACtD,QAAQ,SAAS,OAAO,OAAO,OAAO,OAAO,IAE7C,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,cAAQ,MAAM,2CAA2C,CAAC,GAAG,QAAQ,OAAQ,CAAA,CAAC;AAAA,IAChF;AAEI,KAAA,cAAc,eAChB,QAAQ,WAAW;AAAA,EAEvB;AAEO,SAAA;AACT;AAEA,SAAS,qBAAqB,MAA0C;AAC/D,SAAAC,SAAmB,qBAAqB,IAAI,CAAC;AACtD;;;;;"}
package/dist/csm.cjs CHANGED
@@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: !0 });
3
3
  var resolveEditInfo = require("./_chunks-cjs/resolveEditInfo.cjs");
4
4
  const defaultUpdateFunction = (changed) => changed;
5
5
  function applySourceDocuments(result, resultSourceMap, getCachedDocument, updateFn = defaultUpdateFunction, perspective = "raw") {
6
- if (!resultSourceMap)
7
- return result;
6
+ if (!resultSourceMap) return result;
8
7
  if (perspective !== "published" && perspective !== "raw" && perspective !== "previewDrafts")
9
8
  throw new Error(`Unknown perspective "${perspective}"`);
10
9
  return resolveEditInfo.walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {
package/dist/csm.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"csm.cjs","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["walkMap","resolveMapping","parseJsonPath","paths.toString","DRAFTS_PREFIX","getPublishedId","paths.get","jsonPath","studioPathToJsonPath","resolveEditInfo","createEditUrl"],"mappings":";;;AAeA,MAAM,wBAAwB,CAAc,YAAkB;AAOvD,SAAS,qBACd,QACA,iBACA,mBAGA,WAA+C,uBAC/C,cAAiC,OACzB;AACR,MAAI,CAAC;AAAwB,WAAA;AAE7B,MAAI,gBAAgB,eAAe,gBAAgB,SAAS,gBAAgB;AAC1E,UAAM,IAAI,MAAM,wBAAwB,WAAW,GAAG;AAGjD,SAAAA,gBAAA,QAAQ,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,GAAG,CAAC,OAAO,SAAS;AAC5D,UAAA,uBAAuBC,gBAAAA,eAAe,MAAM,eAAe;AACjE,QAAI,CAAC;AAEI,aAAA;AAGH,UAAA,EAAC,SAAS,WAAc,IAAA;AAK9B,QAJI,QAAQ,SAAS,WAIjB,QAAQ,OAAO,SAAS;AACnB,aAAA;AAGT,UAAM,iBAAiB,gBAAgB,UAAU,QAAQ,OAAO,QAAQ,GAClE,aAAa,gBAAgB,MAAM,QAAQ,OAAO,IAAI;AAE5D,QAAI,gBAAgB;AACZ,YAAA,aAAaC,8BAAc,aAAa,UAAU,GAClD,kBAAkBC,gBAAAA,SAAe,UAAkB;AAGzD,UAAI,oBAAoB;AACf,eAAA;AAGL,UAAA;AACA,UAAA,gBAAgB,mBAClB,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAWC,gBAAa,aAAA,IACvC,iBACA,EAAC,GAAG,gBAAgB,KAAK,GAAGA,gBAAAA,aAAa,GAAG,eAAe,GAAG,IAAG;AAAA,MAAA,GAElE,mBACH,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAWA,gBAAAA,aAAa,IACvC,EAAC,GAAG,gBAAgB,KAAKC,gBAAAA,eAAe,eAAe,GAAG,EAC1D,IAAA;AAAA,MAAA,IAGJ,mBACF,iBAAiB;AAAA,QACf,GAAG;AAAA,QACH,KAAKA,gBAAAA,eAAe,eAAe,GAAG;AAAA,QACtC,aAAa,eAAe;AAAA,MAIhC,MAAA,iBAAiB,kBAAkB,cAAc,GAG/C,CAAC;AACI,eAAA;AAGT,YAAM,eAAe,iBACjBC,oBAAgC,gBAAgB,iBAAiB,KAAK,IACtE;AACJ,aAAO,UAAU,eACb,QACA,SAA+B,cAAqB;AAAA,QAClD;AAAA,QACA,eAAe;AAAA,QACf;AAAA,QACA,YAAY;AAAA,MAAA,CACb;AAAA,IACP;AAEO,WAAA;AAAA,EAAA,CACR;AACH;ACvGO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAkB,IAAA,SAEhD,qBAAqB,eAAe,SAAY,CAAK,IAAAJ,gBAAA,cAAc,UAAU,GAE7E,eAAe,gBAAgB,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,GAEvF,qBAAqB,aAAa,SAASK,gBAAAA,SAAS,YAAY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAAL,gBAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAaM,gBAAA,qBAAqB,QAAQ,UAAU,GAEpD,WAAWC,gBAAAA,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAOC,gBAAAA,cAAc,QAAQ;AAC/B;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"csm.cjs","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["walkMap","resolveMapping","parseJsonPath","paths.toString","DRAFTS_PREFIX","getPublishedId","paths.get","jsonPath","studioPathToJsonPath","resolveEditInfo","createEditUrl"],"mappings":";;;AAeA,MAAM,wBAAwB,CAAc,YAAkB;AAOvD,SAAS,qBACd,QACA,iBACA,mBAGA,WAA+C,uBAC/C,cAAiC,OACzB;AACJ,MAAA,CAAC,gBAAwB,QAAA;AAE7B,MAAI,gBAAgB,eAAe,gBAAgB,SAAS,gBAAgB;AAC1E,UAAM,IAAI,MAAM,wBAAwB,WAAW,GAAG;AAGjD,SAAAA,gBAAA,QAAQ,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,GAAG,CAAC,OAAO,SAAS;AAC5D,UAAA,uBAAuBC,gBAAAA,eAAe,MAAM,eAAe;AACjE,QAAI,CAAC;AAEI,aAAA;AAGH,UAAA,EAAC,SAAS,WAAc,IAAA;AAK9B,QAJI,QAAQ,SAAS,WAIjB,QAAQ,OAAO,SAAS;AACnB,aAAA;AAGT,UAAM,iBAAiB,gBAAgB,UAAU,QAAQ,OAAO,QAAQ,GAClE,aAAa,gBAAgB,MAAM,QAAQ,OAAO,IAAI;AAE5D,QAAI,gBAAgB;AACZ,YAAA,aAAaC,8BAAc,aAAa,UAAU,GAClD,kBAAkBC,gBAAAA,SAAe,UAAkB;AAGzD,UAAI,oBAAoB;AACf,eAAA;AAGL,UAAA;AACA,UAAA,gBAAgB,mBAClB,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAWC,gBAAa,aAAA,IACvC,iBACA,EAAC,GAAG,gBAAgB,KAAK,GAAGA,gBAAAA,aAAa,GAAG,eAAe,GAAG,IAAG;AAAA,MAAA,GAElE,mBACH,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAWA,gBAAAA,aAAa,IACvC,EAAC,GAAG,gBAAgB,KAAKC,gBAAAA,eAAe,eAAe,GAAG,EAC1D,IAAA;AAAA,MAAA,IAGJ,mBACF,iBAAiB;AAAA,QACf,GAAG;AAAA,QACH,KAAKA,gBAAAA,eAAe,eAAe,GAAG;AAAA,QACtC,aAAa,eAAe;AAAA,MAIhC,MAAA,iBAAiB,kBAAkB,cAAc,GAG/C,CAAC;AACI,eAAA;AAGT,YAAM,eAAe,iBACjBC,oBAAgC,gBAAgB,iBAAiB,KAAK,IACtE;AACJ,aAAO,UAAU,eACb,QACA,SAA+B,cAAqB;AAAA,QAClD;AAAA,QACA,eAAe;AAAA,QACf;AAAA,QACA,YAAY;AAAA,MAAA,CACb;AAAA,IACP;AAEO,WAAA;AAAA,EAAA,CACR;AACH;ACvGO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAkB,IAAA,SAEhD,qBAAqB,eAAe,SAAY,CAAK,IAAAJ,gBAAA,cAAc,UAAU,GAE7E,eAAe,gBAAgB,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,GAEvF,qBAAqB,aAAa,SAASK,gBAAAA,SAAS,YAAY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAAL,gBAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAaM,gBAAA,qBAAqB,QAAQ,UAAU,GAEpD,WAAWC,gBAAAA,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAOC,gBAAAA,cAAc,QAAQ;AAC/B;;;;;;;;;;;;;;"}
package/dist/csm.js CHANGED
@@ -2,8 +2,7 @@ import { walkMap, resolveMapping, parseJsonPath, toString, DRAFTS_PREFIX, getPub
2
2
  import { jsonPathToStudioPath, studioPath } from "./_chunks-es/resolveEditInfo.js";
3
3
  const defaultUpdateFunction = (changed) => changed;
4
4
  function applySourceDocuments(result, resultSourceMap, getCachedDocument, updateFn = defaultUpdateFunction, perspective = "raw") {
5
- if (!resultSourceMap)
6
- return result;
5
+ if (!resultSourceMap) return result;
7
6
  if (perspective !== "published" && perspective !== "raw" && perspective !== "previewDrafts")
8
7
  throw new Error(`Unknown perspective "${perspective}"`);
9
8
  return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {
package/dist/csm.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"csm.js","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["paths.toString","paths.get"],"mappings":";;AAeA,MAAM,wBAAwB,CAAc,YAAkB;AAOvD,SAAS,qBACd,QACA,iBACA,mBAGA,WAA+C,uBAC/C,cAAiC,OACzB;AACR,MAAI,CAAC;AAAwB,WAAA;AAE7B,MAAI,gBAAgB,eAAe,gBAAgB,SAAS,gBAAgB;AAC1E,UAAM,IAAI,MAAM,wBAAwB,WAAW,GAAG;AAGjD,SAAA,QAAQ,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,GAAG,CAAC,OAAO,SAAS;AAC5D,UAAA,uBAAuB,eAAe,MAAM,eAAe;AACjE,QAAI,CAAC;AAEI,aAAA;AAGH,UAAA,EAAC,SAAS,WAAc,IAAA;AAK9B,QAJI,QAAQ,SAAS,WAIjB,QAAQ,OAAO,SAAS;AACnB,aAAA;AAGT,UAAM,iBAAiB,gBAAgB,UAAU,QAAQ,OAAO,QAAQ,GAClE,aAAa,gBAAgB,MAAM,QAAQ,OAAO,IAAI;AAE5D,QAAI,gBAAgB;AACZ,YAAA,aAAa,cAAc,aAAa,UAAU,GAClD,kBAAkBA,SAAe,UAAkB;AAGzD,UAAI,oBAAoB;AACf,eAAA;AAGL,UAAA;AACA,UAAA,gBAAgB,mBAClB,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAW,aAAa,IACvC,iBACA,EAAC,GAAG,gBAAgB,KAAK,GAAG,aAAa,GAAG,eAAe,GAAG,IAAG;AAAA,MAAA,GAElE,mBACH,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAW,aAAa,IACvC,EAAC,GAAG,gBAAgB,KAAK,eAAe,eAAe,GAAG,EAC1D,IAAA;AAAA,MAAA,IAGJ,mBACF,iBAAiB;AAAA,QACf,GAAG;AAAA,QACH,KAAK,eAAe,eAAe,GAAG;AAAA,QACtC,aAAa,eAAe;AAAA,MAIhC,MAAA,iBAAiB,kBAAkB,cAAc,GAG/C,CAAC;AACI,eAAA;AAGT,YAAM,eAAe,iBACjBC,IAAgC,gBAAgB,iBAAiB,KAAK,IACtE;AACJ,aAAO,UAAU,eACb,QACA,SAA+B,cAAqB;AAAA,QAClD;AAAA,QACA,eAAe;AAAA,QACf;AAAA,QACA,YAAY;AAAA,MAAA,CACb;AAAA,IACP;AAEO,WAAA;AAAA,EAAA,CACR;AACH;ACvGO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAkB,IAAA,SAEhD,qBAAqB,eAAe,SAAY,CAAK,IAAA,cAAc,UAAU,GAE7E,eAAe,gBAAgB,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,GAEvF,qBAAqB,aAAa,SAAS,SAAS,YAAY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAa,qBAAqB,QAAQ,UAAU,GAEpD,WAAW,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAO,cAAc,QAAQ;AAC/B;"}
1
+ {"version":3,"file":"csm.js","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\nconst defaultUpdateFunction = <T = unknown>(changed: T): T => changed\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => Partial<SanityDocument> | null | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction = defaultUpdateFunction,\n perspective: ClientPerspective = 'raw',\n): Result {\n if (!resultSourceMap) return result\n\n if (perspective !== 'published' && perspective !== 'raw' && perspective !== 'previewDrafts') {\n throw new Error(`Unknown perspective \"${perspective}\"`)\n }\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n // console.warn('no mapping for path', path)\n return value\n }\n\n const {mapping, pathSuffix} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n\n // The _id is sometimes used used as `key` in lists, and should not be changed optimistically\n if (stringifiedPath === '_id') {\n return value\n }\n\n let cachedDocument: Partial<SanityDocument> | null | undefined\n if (perspective === 'previewDrafts') {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? sourceDocument\n : {...sourceDocument, _id: `${DRAFTS_PREFIX}${sourceDocument._id}}`},\n )\n if (!cachedDocument) {\n cachedDocument = getCachedDocument(\n sourceDocument._id.startsWith(DRAFTS_PREFIX)\n ? {...sourceDocument, _id: getPublishedId(sourceDocument._id)}\n : sourceDocument,\n )\n }\n if (cachedDocument) {\n cachedDocument = {\n ...cachedDocument,\n _id: getPublishedId(sourceDocument._id),\n _originalId: sourceDocument._id,\n }\n }\n } else {\n cachedDocument = getCachedDocument(sourceDocument)\n }\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["paths.toString","paths.get"],"mappings":";;AAeA,MAAM,wBAAwB,CAAc,YAAkB;AAOvD,SAAS,qBACd,QACA,iBACA,mBAGA,WAA+C,uBAC/C,cAAiC,OACzB;AACJ,MAAA,CAAC,gBAAwB,QAAA;AAE7B,MAAI,gBAAgB,eAAe,gBAAgB,SAAS,gBAAgB;AAC1E,UAAM,IAAI,MAAM,wBAAwB,WAAW,GAAG;AAGjD,SAAA,QAAQ,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,GAAG,CAAC,OAAO,SAAS;AAC5D,UAAA,uBAAuB,eAAe,MAAM,eAAe;AACjE,QAAI,CAAC;AAEI,aAAA;AAGH,UAAA,EAAC,SAAS,WAAc,IAAA;AAK9B,QAJI,QAAQ,SAAS,WAIjB,QAAQ,OAAO,SAAS;AACnB,aAAA;AAGT,UAAM,iBAAiB,gBAAgB,UAAU,QAAQ,OAAO,QAAQ,GAClE,aAAa,gBAAgB,MAAM,QAAQ,OAAO,IAAI;AAE5D,QAAI,gBAAgB;AACZ,YAAA,aAAa,cAAc,aAAa,UAAU,GAClD,kBAAkBA,SAAe,UAAkB;AAGzD,UAAI,oBAAoB;AACf,eAAA;AAGL,UAAA;AACA,UAAA,gBAAgB,mBAClB,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAW,aAAa,IACvC,iBACA,EAAC,GAAG,gBAAgB,KAAK,GAAG,aAAa,GAAG,eAAe,GAAG,IAAG;AAAA,MAAA,GAElE,mBACH,iBAAiB;AAAA,QACf,eAAe,IAAI,WAAW,aAAa,IACvC,EAAC,GAAG,gBAAgB,KAAK,eAAe,eAAe,GAAG,EAC1D,IAAA;AAAA,MAAA,IAGJ,mBACF,iBAAiB;AAAA,QACf,GAAG;AAAA,QACH,KAAK,eAAe,eAAe,GAAG;AAAA,QACtC,aAAa,eAAe;AAAA,MAI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