@sanity/client 6.14.1 → 6.14.2

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.
Files changed (53) hide show
  1. package/dist/_chunks/browserMiddleware-BHXO2Lcy.cjs +1491 -0
  2. package/dist/_chunks/{browserMiddleware-FpdqDQ1o.cjs.map → browserMiddleware-BHXO2Lcy.cjs.map} +1 -1
  3. package/dist/_chunks/browserMiddleware-jPnXCUlp.js +1474 -0
  4. package/dist/_chunks/{browserMiddleware-DhUBf_19.js.map → browserMiddleware-jPnXCUlp.js.map} +1 -1
  5. package/dist/_chunks/nodeMiddleware-CrO2pNEp.js +1491 -0
  6. package/dist/_chunks/{nodeMiddleware-BSZoKrW0.js.map → nodeMiddleware-CrO2pNEp.js.map} +1 -1
  7. package/dist/_chunks/nodeMiddleware-JJNfI4Rf.cjs +1508 -0
  8. package/dist/_chunks/{nodeMiddleware-DmcqX3kz.cjs.map → nodeMiddleware-JJNfI4Rf.cjs.map} +1 -1
  9. package/dist/_chunks/resolveEditInfo-BNCwZySb.cjs +284 -0
  10. package/dist/_chunks/{resolveEditInfo-BB1WiUDY.cjs.map → resolveEditInfo-BNCwZySb.cjs.map} +1 -1
  11. package/dist/_chunks/resolveEditInfo-qA5twkfC.js +285 -0
  12. package/dist/_chunks/{resolveEditInfo-Cf8D1Agp.js.map → resolveEditInfo-qA5twkfC.js.map} +1 -1
  13. package/dist/_chunks/stegaEncodeSourceMap-B9_uz7Zb.cjs +166 -0
  14. package/dist/_chunks/{stegaEncodeSourceMap-8TjLXjYU.cjs.map → stegaEncodeSourceMap-B9_uz7Zb.cjs.map} +1 -1
  15. package/dist/_chunks/stegaEncodeSourceMap-BvBJpbrr.cjs +329 -0
  16. package/dist/_chunks/{stegaEncodeSourceMap-DIcuvN0P.cjs.map → stegaEncodeSourceMap-BvBJpbrr.cjs.map} +1 -1
  17. package/dist/_chunks/stegaEncodeSourceMap-De3F_oJN.js +330 -0
  18. package/dist/_chunks/{stegaEncodeSourceMap-DLon0Yls.js.map → stegaEncodeSourceMap-De3F_oJN.js.map} +1 -1
  19. package/dist/_chunks/stegaEncodeSourceMap-bRxIGJ-b.js +168 -0
  20. package/dist/_chunks/{stegaEncodeSourceMap-DU95idpa.js.map → stegaEncodeSourceMap-bRxIGJ-b.js.map} +1 -1
  21. package/dist/csm.cjs +22 -56
  22. package/dist/csm.cjs.map +1 -1
  23. package/dist/csm.js +36 -54
  24. package/dist/csm.js.map +1 -1
  25. package/dist/index.browser.cjs +15 -21
  26. package/dist/index.browser.cjs.map +1 -1
  27. package/dist/index.browser.js +24 -15
  28. package/dist/index.browser.js.map +1 -1
  29. package/dist/index.cjs +15 -21
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.js +24 -15
  32. package/dist/index.js.map +1 -1
  33. package/dist/stega.browser.cjs +12 -17
  34. package/dist/stega.browser.cjs.map +1 -1
  35. package/dist/stega.browser.js +26 -11
  36. package/dist/stega.browser.js.map +1 -1
  37. package/dist/stega.cjs +12 -17
  38. package/dist/stega.cjs.map +1 -1
  39. package/dist/stega.js +26 -11
  40. package/dist/stega.js.map +1 -1
  41. package/package.json +3 -3
  42. package/umd/sanityClient.js +2670 -3360
  43. package/umd/sanityClient.min.js +3 -3
  44. package/dist/_chunks/browserMiddleware-DhUBf_19.js +0 -1761
  45. package/dist/_chunks/browserMiddleware-FpdqDQ1o.cjs +0 -1777
  46. package/dist/_chunks/nodeMiddleware-BSZoKrW0.js +0 -1780
  47. package/dist/_chunks/nodeMiddleware-DmcqX3kz.cjs +0 -1796
  48. package/dist/_chunks/resolveEditInfo-BB1WiUDY.cjs +0 -422
  49. package/dist/_chunks/resolveEditInfo-Cf8D1Agp.js +0 -406
  50. package/dist/_chunks/stegaEncodeSourceMap-8TjLXjYU.cjs +0 -229
  51. package/dist/_chunks/stegaEncodeSourceMap-DIcuvN0P.cjs +0 -486
  52. package/dist/_chunks/stegaEncodeSourceMap-DLon0Yls.js +0 -482
  53. package/dist/_chunks/stegaEncodeSourceMap-DU95idpa.js +0 -225
@@ -0,0 +1,168 @@
1
+ import { b } from "./nodeMiddleware-CrO2pNEp.js";
2
+ import { walkMap, resolveMapping, parseJsonPath, resolveStudioBaseRoute, createEditUrl, reKeySegment, toString, jsonPathToStudioPath } from "./resolveEditInfo-qA5twkfC.js";
3
+ function encodeIntoResult(result, csm, encoder) {
4
+ return walkMap(result, (value, path) => {
5
+ if (typeof value != "string")
6
+ return value;
7
+ const resolveMappingResult = resolveMapping(path, csm);
8
+ if (!resolveMappingResult)
9
+ return value;
10
+ const { mapping, matchedPath } = resolveMappingResult;
11
+ if (mapping.type !== "value" || mapping.source.type !== "documentValue")
12
+ return value;
13
+ const sourceDocument = csm.documents[mapping.source.document], sourcePath = csm.paths[mapping.source.path], matchPathSegments = parseJsonPath(matchedPath), fullSourceSegments = parseJsonPath(sourcePath).concat(path.slice(matchPathSegments.length));
14
+ return encoder({
15
+ sourcePath: fullSourceSegments,
16
+ sourceDocument,
17
+ resultPath: path,
18
+ value
19
+ });
20
+ });
21
+ }
22
+ const filterDefault = ({ sourcePath, value }) => {
23
+ if (isValidDate(value) || isValidURL(value))
24
+ return !1;
25
+ const endPath = sourcePath.at(-1);
26
+ 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(
27
+ (path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo"
28
+ ) || typeof endPath == "string" && denylist.has(endPath));
29
+ }, denylist = /* @__PURE__ */ new Set([
30
+ "color",
31
+ "colour",
32
+ "currency",
33
+ "email",
34
+ "format",
35
+ "gid",
36
+ "hex",
37
+ "href",
38
+ "hsl",
39
+ "hsla",
40
+ "icon",
41
+ "id",
42
+ "index",
43
+ "key",
44
+ "language",
45
+ "layout",
46
+ "link",
47
+ "linkAction",
48
+ "locale",
49
+ "lqip",
50
+ "page",
51
+ "path",
52
+ "ref",
53
+ "rgb",
54
+ "rgba",
55
+ "route",
56
+ "secret",
57
+ "slug",
58
+ "status",
59
+ "tag",
60
+ "template",
61
+ "theme",
62
+ "type",
63
+ "unit",
64
+ "url",
65
+ "username",
66
+ "variant",
67
+ "website"
68
+ ]);
69
+ function isValidDate(dateString) {
70
+ return /^\d{4}-\d{2}-\d{2}/.test(dateString) ? !!Date.parse(dateString) : !1;
71
+ }
72
+ function isValidURL(url) {
73
+ try {
74
+ new URL(url, url.startsWith("/") ? "https://acme.com" : void 0);
75
+ } catch {
76
+ return !1;
77
+ }
78
+ return !0;
79
+ }
80
+ const TRUNCATE_LENGTH = 20;
81
+ function stegaEncodeSourceMap(result, resultSourceMap, config) {
82
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
83
+ const { filter, logger, enabled } = config;
84
+ if (!enabled) {
85
+ const msg = "config.enabled must be true, don't call this function otherwise";
86
+ throw (_a = logger == null ? void 0 : logger.error) == null || _a.call(logger, `[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), new TypeError(msg);
87
+ }
88
+ if (!resultSourceMap)
89
+ return (_b = logger == null ? void 0 : logger.error) == null || _b.call(logger, "[@sanity/client]: Missing Content Source Map from response body", {
90
+ result,
91
+ resultSourceMap,
92
+ config
93
+ }), result;
94
+ if (!config.studioUrl) {
95
+ const msg = "config.studioUrl must be defined";
96
+ throw (_c = logger == null ? void 0 : logger.error) == null || _c.call(logger, `[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), new TypeError(msg);
97
+ }
98
+ const report = {
99
+ encoded: [],
100
+ skipped: []
101
+ }, resultWithStega = encodeIntoResult(
102
+ result,
103
+ resultSourceMap,
104
+ ({ sourcePath, sourceDocument, resultPath, value }) => {
105
+ if ((typeof filter == "function" ? filter({ sourcePath, resultPath, filterDefault, sourceDocument, value }) : filterDefault({ sourcePath, resultPath, filterDefault, sourceDocument, value })) === !1)
106
+ return logger && report.skipped.push({
107
+ path: prettyPathForLogging(sourcePath),
108
+ value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? "..." : ""}`,
109
+ length: value.length
110
+ }), value;
111
+ logger && report.encoded.push({
112
+ path: prettyPathForLogging(sourcePath),
113
+ value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? "..." : ""}`,
114
+ length: value.length
115
+ });
116
+ const { baseUrl, workspace, tool } = resolveStudioBaseRoute(
117
+ typeof config.studioUrl == "function" ? config.studioUrl(sourceDocument) : config.studioUrl
118
+ );
119
+ if (!baseUrl)
120
+ return value;
121
+ const { _id: id, _type: type, _projectId: projectId, _dataset: dataset } = sourceDocument;
122
+ return b(
123
+ value,
124
+ {
125
+ origin: "sanity.io",
126
+ href: createEditUrl({
127
+ baseUrl,
128
+ workspace,
129
+ tool,
130
+ id,
131
+ type,
132
+ path: sourcePath,
133
+ ...!config.omitCrossDatasetReferenceData && { dataset, projectId }
134
+ })
135
+ },
136
+ // We use custom logic to determine if we should skip encoding
137
+ !1
138
+ );
139
+ }
140
+ );
141
+ if (logger) {
142
+ const isSkipping = report.skipped.length, isEncoding = report.encoded.length;
143
+ 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(
144
+ logger,
145
+ `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`
146
+ )), 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) {
147
+ const skipped = /* @__PURE__ */ new Set();
148
+ for (const { path } of report.skipped)
149
+ skipped.add(path.replace(reKeySegment, "0").replace(/\[\d+\]/g, "[]"));
150
+ (_h = logger == null ? void 0 : logger.log) == null || _h.call(logger, "[@sanity/client]: List of skipped paths", [...skipped.values()]);
151
+ }
152
+ (isSkipping || isEncoding) && ((_i = logger == null ? void 0 : logger.groupEnd) == null || _i.call(logger));
153
+ }
154
+ return resultWithStega;
155
+ }
156
+ function prettyPathForLogging(path) {
157
+ return toString(jsonPathToStudioPath(path));
158
+ }
159
+ var stegaEncodeSourceMap$1 = /* @__PURE__ */ Object.freeze({
160
+ __proto__: null,
161
+ stegaEncodeSourceMap
162
+ });
163
+ export {
164
+ encodeIntoResult,
165
+ stegaEncodeSourceMap,
166
+ stegaEncodeSourceMap$1
167
+ };
168
+ //# sourceMappingURL=stegaEncodeSourceMap-bRxIGJ-b.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stegaEncodeSourceMap-DU95idpa.js","sources":["../../src/stega/encodeIntoResult.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.ts"],"sourcesContent":["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","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":["vercelStegaCombine","studioPathToString"],"mappings":";;;AASgB,SAAA,gBAAA,CACd,MACA,EAAA,GAAA,EACA,OACQ,EAAA;AACR,EAAA,OAAO,OAAQ,CAAA,MAAA,EAAQ,CAAC,KAAA,EAAO,IAAS,KAAA;AAEtC,IAAI,IAAA,OAAO,UAAU,QAAU,EAAA;AAC7B,MAAO,OAAA,KAAA,CAAA;AAAA,KACT;AAEA,IAAM,MAAA,oBAAA,GAAuB,cAAe,CAAA,IAAA,EAAM,GAAG,CAAA,CAAA;AACrD,IAAA,IAAI,CAAC,oBAAsB,EAAA;AACzB,MAAO,OAAA,KAAA,CAAA;AAAA,KACT;AAEA,IAAM,MAAA,EAAC,OAAS,EAAA,WAAA,EAAe,GAAA,oBAAA,CAAA;AAC/B,IAAI,IAAA,OAAA,CAAQ,SAAS,OAAS,EAAA;AAC5B,MAAO,OAAA,KAAA,CAAA;AAAA,KACT;AAEA,IAAI,IAAA,OAAA,CAAQ,MAAO,CAAA,IAAA,KAAS,eAAiB,EAAA;AAC3C,MAAO,OAAA,KAAA,CAAA;AAAA,KACT;AAEA,IAAA,MAAM,cAAiB,GAAA,GAAA,CAAI,SAAU,CAAA,OAAA,CAAQ,OAAO,QAAS,CAAA,CAA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AA,CAAA;AAChC,MAAA,KAAA,MAAW,EAAC,IAAA,EAAS,IAAA,MAAA,CAAO,OAAS,EAAA;AACnC,QAAQ,OAAA,CAAA,GAAA,CAAI,KAAK,OAAQ,CAAA,YAAA,EAAc,GAAG,CAAE,CAAA,OAAA,CAAQ,UAAY,EAAA,IAAI,CAAC,CAAA,CAAA;AAAA,OACvE;AACA,MAAA,CAAA,EAAA,GAAA,MAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,MAAA,CAAQ,QAAR,IAAc,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAA,CAAA,MAAA,EAAA,CAAA,uCAAA,CAAA,EAA2C,CAAC,GAAG,OAAA,CAAQ,QAAQ,CAAA,CAAA,CAAA;AAAA,KAC/E;AAEA,IAAA,IAAI,cAAc,UAAY,EAAA;AAC5B,MAAA,CAAA,EAAA,GAAA,MAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,MAAA,CAAQ,QAAR,KAAA,IAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAA,CAAA,MAAA,CAAA,CAAA;AAAA,KACF;AAAA,GACF;AAEA,EAAO,OAAA,eAAA,CAAA;AACT,CAAA;AAEA,SAAS,qBAAqB,IAA0C,EAAA;AACtE,EAAO,OAAAC,QAAA,CAAmB,oBAAqB,CAAA,IAAI,CAAC,CAAA,CAAA;AACtD;;;;;;;;;"}
1
+ {"version":3,"file":"stegaEncodeSourceMap-bRxIGJ-b.js","sources":["../../src/stega/encodeIntoResult.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.ts"],"sourcesContent":["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","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":["vercelStegaCombine","studioPathToString"],"mappings":";;AASgB,SAAA,iBACd,QACA,KACA,SACQ;AACR,SAAO,QAAQ,QAAQ,CAAC,OAAO,SAAS;AAEtC,QAAI,OAAO,SAAU;AACZ,aAAA;AAGH,UAAA,uBAAuB,eAAe,MAAM,GAAG;AACrD,QAAI,CAAC;AACI,aAAA;AAGH,UAAA,EAAC,SAAS,YAAe,IAAA;AAK/B,QAJI,QAAQ,SAAS,WAIjB,QAAQ,OAAO,SAAS;AACnB,aAAA;AAGH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AAA;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;;;;;"}
package/dist/csm.cjs CHANGED
@@ -1,59 +1,35 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var resolveEditInfo = require('./_chunks/resolveEditInfo-BB1WiUDY.cjs');
6
-
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: !0 });
3
+ var resolveEditInfo = require("./_chunks/resolveEditInfo-BNCwZySb.cjs");
7
4
  const defaultUpdateFunction = (changed) => changed;
8
5
  function applySourceDocuments(result, resultSourceMap, getCachedDocument, updateFn = defaultUpdateFunction, perspective = "raw") {
9
6
  if (!resultSourceMap)
10
7
  return result;
11
- if (perspective !== "published" && perspective !== "raw" && perspective !== "previewDrafts") {
8
+ if (perspective !== "published" && perspective !== "raw" && perspective !== "previewDrafts")
12
9
  throw new Error(`Unknown perspective "${perspective}"`);
13
- }
14
10
  return resolveEditInfo.walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {
15
11
  const resolveMappingResult = resolveEditInfo.resolveMapping(path, resultSourceMap);
16
- if (!resolveMappingResult) {
12
+ if (!resolveMappingResult)
17
13
  return value;
18
- }
19
14
  const { mapping, pathSuffix } = resolveMappingResult;
20
- if (mapping.type !== "value") {
21
- return value;
22
- }
23
- if (mapping.source.type !== "documentValue") {
15
+ if (mapping.type !== "value" || mapping.source.type !== "documentValue")
24
16
  return value;
25
- }
26
- const sourceDocument = resultSourceMap.documents[mapping.source.document];
27
- const sourcePath = resultSourceMap.paths[mapping.source.path];
17
+ const sourceDocument = resultSourceMap.documents[mapping.source.document], sourcePath = resultSourceMap.paths[mapping.source.path];
28
18
  if (sourceDocument) {
29
- const parsedPath = resolveEditInfo.parseJsonPath(sourcePath + pathSuffix);
30
- const stringifiedPath = resolveEditInfo.toString(parsedPath);
31
- if (stringifiedPath === "_id") {
19
+ const parsedPath = resolveEditInfo.parseJsonPath(sourcePath + pathSuffix), stringifiedPath = resolveEditInfo.toString(parsedPath);
20
+ if (stringifiedPath === "_id")
32
21
  return value;
33
- }
34
22
  let cachedDocument;
35
- if (perspective === "previewDrafts") {
36
- cachedDocument = getCachedDocument(
37
- sourceDocument._id.startsWith(resolveEditInfo.DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${resolveEditInfo.DRAFTS_PREFIX}.${sourceDocument._id}}` }
38
- );
39
- if (!cachedDocument) {
40
- cachedDocument = getCachedDocument(
41
- sourceDocument._id.startsWith(resolveEditInfo.DRAFTS_PREFIX) ? { ...sourceDocument, _id: resolveEditInfo.getPublishedId(sourceDocument._id) } : sourceDocument
42
- );
43
- }
44
- if (cachedDocument) {
45
- cachedDocument = {
46
- ...cachedDocument,
47
- _id: resolveEditInfo.getPublishedId(sourceDocument._id),
48
- _originalId: sourceDocument._id
49
- };
50
- }
51
- } else {
52
- cachedDocument = getCachedDocument(sourceDocument);
53
- }
54
- if (!cachedDocument) {
23
+ if (perspective === "previewDrafts" ? (cachedDocument = getCachedDocument(
24
+ sourceDocument._id.startsWith(resolveEditInfo.DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${resolveEditInfo.DRAFTS_PREFIX}.${sourceDocument._id}}` }
25
+ ), cachedDocument || (cachedDocument = getCachedDocument(
26
+ sourceDocument._id.startsWith(resolveEditInfo.DRAFTS_PREFIX) ? { ...sourceDocument, _id: resolveEditInfo.getPublishedId(sourceDocument._id) } : sourceDocument
27
+ )), cachedDocument && (cachedDocument = {
28
+ ...cachedDocument,
29
+ _id: resolveEditInfo.getPublishedId(sourceDocument._id),
30
+ _originalId: sourceDocument._id
31
+ })) : cachedDocument = getCachedDocument(sourceDocument), !cachedDocument)
55
32
  return value;
56
- }
57
33
  const changedValue = cachedDocument ? resolveEditInfo.get(cachedDocument, stringifiedPath, value) : value;
58
34
  return value === changedValue ? value : updateFn(changedValue, {
59
35
  cachedDocument,
@@ -65,29 +41,19 @@ function applySourceDocuments(result, resultSourceMap, getCachedDocument, update
65
41
  return value;
66
42
  });
67
43
  }
68
-
69
44
  function resolvedKeyedSourcePath(options) {
70
- const { keyedResultPath, pathSuffix, sourceBasePath } = options;
71
- const inferredResultPath = pathSuffix === void 0 ? [] : resolveEditInfo.parseJsonPath(pathSuffix);
72
- const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length);
73
- const inferredPathSuffix = inferredPath.length ? resolveEditInfo.jsonPath(inferredPath).slice(1) : "";
45
+ const { keyedResultPath, pathSuffix, sourceBasePath } = options, inferredResultPath = pathSuffix === void 0 ? [] : resolveEditInfo.parseJsonPath(pathSuffix), inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length), inferredPathSuffix = inferredPath.length ? resolveEditInfo.jsonPath(inferredPath).slice(1) : "";
74
46
  return resolveEditInfo.parseJsonPath(sourceBasePath + inferredPathSuffix);
75
47
  }
76
-
77
48
  function resolveEditUrl(options) {
78
- const { resultSourceMap, studioUrl } = options;
79
- const resultPath = resolveEditInfo.studioPathToJsonPath(options.resultPath);
80
- const editInfo = resolveEditInfo.resolveEditInfo({
49
+ const { resultSourceMap, studioUrl } = options, resultPath = resolveEditInfo.studioPathToJsonPath(options.resultPath), editInfo = resolveEditInfo.resolveEditInfo({
81
50
  resultPath,
82
51
  resultSourceMap,
83
52
  studioUrl
84
53
  });
85
- if (!editInfo) {
86
- return void 0;
87
- }
88
- return resolveEditInfo.createEditUrl(editInfo);
54
+ if (editInfo)
55
+ return resolveEditInfo.createEditUrl(editInfo);
89
56
  }
90
-
91
57
  exports.createEditUrl = resolveEditInfo.createEditUrl;
92
58
  exports.getPublishedId = resolveEditInfo.getPublishedId;
93
59
  exports.jsonPath = resolveEditInfo.jsonPath;
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,qBAAA,GAAwB,CAAc,OAAkB,KAAA,OAAA,CAAA;AAOvD,SAAS,qBACd,MACA,EAAA,eAAA,EACA,mBAGA,QAA+C,GAAA,qBAAA,EAC/C,cAAiC,KACzB,EAAA;AACR,EAAA,IAAI,CAAC,eAAA;AAAiB,IAAO,OAAA,MAAA,CAAA;AAE7B,EAAA,IAAI,WAAgB,KAAA,WAAA,IAAe,WAAgB,KAAA,KAAA,IAAS,gBAAgB,eAAiB,EAAA;AAC3F,IAAA,MAAM,IAAI,KAAA,CAAM,CAAwB,q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AA;AAEtD,EAAA,MAAM,qBAAqB,UAAe,KAAA,KAAA,CAAA,GAAY,EAAC,GAAIJ,8BAAc,UAAU,CAAA,CAAA;AAEnF,EAAA,MAAM,eAAe,eAAgB,CAAA,KAAA,CAAM,eAAgB,CAAA,MAAA,GAAS,mBAAmB,MAAM,CAAA,CAAA;AAE7F,EAAM,MAAA,kBAAA,GAAqB,aAAa,MAAS,GAAAK,wBAAA,CAAS,YAAY,CAAE,CAAA,KAAA,CAAM,CAAC,CAAI,GAAA,EAAA,CAAA;AAEnF,EAAO,OAAAL,6BAAA,CAAc,iBAAiB,kBAAkB,CAAA,CAAA;AAC1D;;ACdO,SAAS,eACd,OAC8C,EAAA;AAC9C,EAAM,MAAA,EAAC,eAAiB,EAAA,SAAA,EAAa,GAAA,OAAA,CAAA;AACrC,EAAM,MAAA,UAAA,GAAaM,oCAAqB,CAAA,OAAA,CAAQ,UAAU,CAAA,CAAA;AAE1D,EAAA,MAAM,WAAWC,+BAAgB,CAAA;AAAA,IAC/B,UAAA;AAAA,IACA,eAAA;AAAA,IACA,SAAA;AAAA,GACD,CAAA,CAAA;AACD,EAAA,IAAI,CAAC,QAAU,EAAA;AACb,IAAO,OAAA,KAAA,CAAA,CAAA;AAAA,GACT;AAEA,EAAA,OAAOC,8BAAc,QAAQ,CAAA,CAAA;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;AAO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gC,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
@@ -1,56 +1,34 @@
1
- import { walkMap, resolveMapping, parseJsonPath, toString, DRAFTS_PREFIX, getPublishedId, get, jsonPath, studioPathToJsonPath, resolveEditInfo, createEditUrl } from './_chunks/resolveEditInfo-Cf8D1Agp.js';
2
- export { jsonPathToStudioPath, studioPath } from './_chunks/resolveEditInfo-Cf8D1Agp.js';
3
-
1
+ import { walkMap, resolveMapping, parseJsonPath, toString, DRAFTS_PREFIX, getPublishedId, get, jsonPath, studioPathToJsonPath, resolveEditInfo, createEditUrl } from "./_chunks/resolveEditInfo-qA5twkfC.js";
2
+ import { jsonPathToStudioPath, studioPath } from "./_chunks/resolveEditInfo-qA5twkfC.js";
4
3
  const defaultUpdateFunction = (changed) => changed;
5
4
  function applySourceDocuments(result, resultSourceMap, getCachedDocument, updateFn = defaultUpdateFunction, perspective = "raw") {
6
5
  if (!resultSourceMap)
7
6
  return result;
8
- if (perspective !== "published" && perspective !== "raw" && perspective !== "previewDrafts") {
7
+ if (perspective !== "published" && perspective !== "raw" && perspective !== "previewDrafts")
9
8
  throw new Error(`Unknown perspective "${perspective}"`);
10
- }
11
9
  return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {
12
10
  const resolveMappingResult = resolveMapping(path, resultSourceMap);
13
- if (!resolveMappingResult) {
11
+ if (!resolveMappingResult)
14
12
  return value;
15
- }
16
13
  const { mapping, pathSuffix } = resolveMappingResult;
17
- if (mapping.type !== "value") {
18
- return value;
19
- }
20
- if (mapping.source.type !== "documentValue") {
14
+ if (mapping.type !== "value" || mapping.source.type !== "documentValue")
21
15
  return value;
22
- }
23
- const sourceDocument = resultSourceMap.documents[mapping.source.document];
24
- const sourcePath = resultSourceMap.paths[mapping.source.path];
16
+ const sourceDocument = resultSourceMap.documents[mapping.source.document], sourcePath = resultSourceMap.paths[mapping.source.path];
25
17
  if (sourceDocument) {
26
- const parsedPath = parseJsonPath(sourcePath + pathSuffix);
27
- const stringifiedPath = toString(parsedPath);
28
- if (stringifiedPath === "_id") {
18
+ const parsedPath = parseJsonPath(sourcePath + pathSuffix), stringifiedPath = toString(parsedPath);
19
+ if (stringifiedPath === "_id")
29
20
  return value;
30
- }
31
21
  let cachedDocument;
32
- if (perspective === "previewDrafts") {
33
- cachedDocument = getCachedDocument(
34
- sourceDocument._id.startsWith(DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${DRAFTS_PREFIX}.${sourceDocument._id}}` }
35
- );
36
- if (!cachedDocument) {
37
- cachedDocument = getCachedDocument(
38
- sourceDocument._id.startsWith(DRAFTS_PREFIX) ? { ...sourceDocument, _id: getPublishedId(sourceDocument._id) } : sourceDocument
39
- );
40
- }
41
- if (cachedDocument) {
42
- cachedDocument = {
43
- ...cachedDocument,
44
- _id: getPublishedId(sourceDocument._id),
45
- _originalId: sourceDocument._id
46
- };
47
- }
48
- } else {
49
- cachedDocument = getCachedDocument(sourceDocument);
50
- }
51
- if (!cachedDocument) {
22
+ if (perspective === "previewDrafts" ? (cachedDocument = getCachedDocument(
23
+ sourceDocument._id.startsWith(DRAFTS_PREFIX) ? sourceDocument : { ...sourceDocument, _id: `${DRAFTS_PREFIX}.${sourceDocument._id}}` }
24
+ ), cachedDocument || (cachedDocument = getCachedDocument(
25
+ sourceDocument._id.startsWith(DRAFTS_PREFIX) ? { ...sourceDocument, _id: getPublishedId(sourceDocument._id) } : sourceDocument
26
+ )), cachedDocument && (cachedDocument = {
27
+ ...cachedDocument,
28
+ _id: getPublishedId(sourceDocument._id),
29
+ _originalId: sourceDocument._id
30
+ })) : cachedDocument = getCachedDocument(sourceDocument), !cachedDocument)
52
31
  return value;
53
- }
54
32
  const changedValue = cachedDocument ? get(cachedDocument, stringifiedPath, value) : value;
55
33
  return value === changedValue ? value : updateFn(changedValue, {
56
34
  cachedDocument,
@@ -62,28 +40,32 @@ function applySourceDocuments(result, resultSourceMap, getCachedDocument, update
62
40
  return value;
63
41
  });
64
42
  }
65
-
66
43
  function resolvedKeyedSourcePath(options) {
67
- const { keyedResultPath, pathSuffix, sourceBasePath } = options;
68
- const inferredResultPath = pathSuffix === void 0 ? [] : parseJsonPath(pathSuffix);
69
- const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length);
70
- const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : "";
44
+ const { keyedResultPath, pathSuffix, sourceBasePath } = options, inferredResultPath = pathSuffix === void 0 ? [] : parseJsonPath(pathSuffix), inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length), inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : "";
71
45
  return parseJsonPath(sourceBasePath + inferredPathSuffix);
72
46
  }
73
-
74
47
  function resolveEditUrl(options) {
75
- const { resultSourceMap, studioUrl } = options;
76
- const resultPath = studioPathToJsonPath(options.resultPath);
77
- const editInfo = resolveEditInfo({
48
+ const { resultSourceMap, studioUrl } = options, resultPath = studioPathToJsonPath(options.resultPath), editInfo = resolveEditInfo({
78
49
  resultPath,
79
50
  resultSourceMap,
80
51
  studioUrl
81
52
  });
82
- if (!editInfo) {
83
- return void 0;
84
- }
85
- return createEditUrl(editInfo);
53
+ if (editInfo)
54
+ return createEditUrl(editInfo);
86
55
  }
87
-
88
- export { applySourceDocuments, createEditUrl, getPublishedId, jsonPath, parseJsonPath, resolveEditInfo, resolveEditUrl, resolveMapping, resolvedKeyedSourcePath, studioPathToJsonPath, walkMap };
56
+ export {
57
+ applySourceDocuments,
58
+ createEditUrl,
59
+ getPublishedId,
60
+ jsonPath,
61
+ jsonPathToStudioPath,
62
+ parseJsonPath,
63
+ resolveEditInfo,
64
+ resolveEditUrl,
65
+ resolveMapping,
66
+ resolvedKeyedSourcePath,
67
+ studioPath,
68
+ studioPathToJsonPath,
69
+ walkMap
70
+ };
89
71
  //# sourceMappingURL=csm.js.map
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,qBAAA,GAAwB,CAAc,OAAkB,KAAA,OAAA,CAAA;AAOvD,SAAS,qBACd,MACA,EAAA,eAAA,EACA,mBAGA,QAA+C,GAAA,qBAAA,EAC/C,cAAiC,KACzB,EAAA;AACR,EAAA,IAAI,CAAC,eAAA;AAAiB,IAAO,OAAA,MAAA,CAAA;AAE7B,EAAA,IAAI,WAAgB,KAAA,WAAA,IAAe,WAAgB,KAAA,KAAA,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AAA,EAAiB,UAAY,EAAA,cAAA,EAAkB,GAAA,OAAA,CAAA;AAEtD,EAAA,MAAM,qBAAqB,UAAe,KAAA,KAAA,CAAA,GAAY,EAAC,GAAI,cAAc,UAAU,CAAA,CAAA;AAEnF,EAAA,MAAM,eAAe,eAAgB,CAAA,KAAA,CAAM,eAAgB,CAAA,MAAA,GAAS,mBAAmB,MAAM,CAAA,CAAA;AAE7F,EAAM,MAAA,kBAAA,GAAqB,aAAa,MAAS,GAAA,QAAA,CAAS,YAAY,CAAE,CAAA,KAAA,CAAM,CAAC,CAAI,GAAA,EAAA,CAAA;AAEnF,EAAO,OAAA,aAAA,CAAc,iBAAiB,kBAAkB,CAAA,CAAA;AAC1D;;ACdO,SAAS,eACd,OAC8C,EAAA;AAC9C,EAAM,MAAA,EAAC,eAAiB,EAAA,SAAA,EAAa,GAAA,OAAA,CAAA;AACrC,EAAM,MAAA,UAAA,GAAa,oBAAqB,CAAA,OAAA,CAAQ,UAAU,CAAA,CAAA;AAE1D,EAAA,MAAM,WAAW,eAAgB,CAAA;AAAA,IAC/B,UAAA;AAAA,IACA,eAAA;AAAA,IACA,SAAA;AAAA,GACD,CAAA,CAAA;AACD,EAAA,IAAI,CAAC,QAAU,EAAA;AACb,IAAO,OAAA,KAAA,CAAA,CAAA;AAAA,GACT;AAEA,EAAA,OAAO,cAAc,QAAQ,CAAA,CAAA;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;AACR,M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