@sanity/client 6.27.2 → 6.27.3-canary.1

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.
@@ -85,25 +85,20 @@ function validateApiVersion(apiVersion) {
85
85
  if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
86
86
  throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
87
87
  }
88
+ const VALID_PERSPECTIVE = /^[a-z0-9_]+$/i;
88
89
  function validateApiPerspective(perspective) {
89
- if (Array.isArray(perspective)) {
90
- for (const perspectiveValue of perspective)
91
- if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
92
- throw new TypeError(
93
- "Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
94
- );
95
- return;
96
- }
97
- switch (perspective) {
98
- case "previewDrafts":
99
- case "drafts":
100
- case "published":
101
- case "raw":
102
- return;
103
- default:
104
- throw new TypeError(
105
- "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
106
- );
90
+ if (Array.isArray(perspective) && perspective.includes("raw"))
91
+ throw new TypeError(
92
+ 'Invalid API perspective value: "raw". The raw-perspective can not be combined with other perspectives'
93
+ );
94
+ const invalid = (Array.isArray(perspective) ? perspective : [perspective]).filter(
95
+ (perspectiveName) => typeof perspectiveName != "string" || !VALID_PERSPECTIVE.test(perspectiveName)
96
+ );
97
+ if (invalid.length > 0) {
98
+ const formatted = invalid.map((v) => JSON.stringify(v));
99
+ throw new TypeError(
100
+ `Invalid API perspective value${invalid.length === 1 ? "" : "s"}: ${formatted.join(", ")}, expected \`published\`, \`drafts\`, \`raw\` or a release identifier string`
101
+ );
107
102
  }
108
103
  }
109
104
  const initConfig = (config, prevConfig) => {
@@ -1 +1 @@
1
- {"version":3,"file":"config.cjs","sources":["../../src/generateHelpUrl.ts","../../src/validators.ts","../../src/util/once.ts","../../src/warnings.ts","../../src/config.ts"],"sourcesContent":["const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective)) {\n for (const perspectiveValue of perspective) {\n if (perspectiveValue === 'published') {\n continue\n }\n if (perspectiveValue === 'drafts') {\n continue\n }\n if (\n typeof perspectiveValue === 'string' &&\n perspectiveValue.startsWith('r') &&\n perspectiveValue !== 'raw'\n ) {\n continue\n }\n throw new TypeError(\n 'Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string',\n )\n }\n return\n }\n switch (perspective as ClientPerspective) {\n case 'previewDrafts':\n case 'drafts':\n case 'published':\n case 'raw':\n return\n default:\n throw new TypeError(\n 'Invalid API perspective string, expected `published`, `previewDrafts` or `raw`',\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n const projectBased = newConfig.useProjectHostname\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (newConfig.useProjectHostname) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning"],"mappings":";AAAA,MAAM,WAAW;AAEV,SAAS,gBAAgB,MAAc;AAC5C,SAAO,WAAW;AACpB;ACFA,MAAM,oBAAoB,CAAC,SAAS,MAAM,GACpC,yBAAy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G,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"config.cjs","sources":["../../src/generateHelpUrl.ts","../../src/validators.ts","../../src/util/once.ts","../../src/warnings.ts","../../src/config.ts"],"sourcesContent":["const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\nconst VALID_PERSPECTIVE = /^[a-z0-9_]+$/i\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective)) {\n if (perspective.includes('raw')) {\n throw new TypeError(\n `Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives`,\n )\n }\n }\n\n const invalid = (Array.isArray(perspective) ? perspective : [perspective]).filter(\n (perspectiveName) =>\n typeof perspectiveName !== 'string' || !VALID_PERSPECTIVE.test(perspectiveName),\n )\n if (invalid.length > 0) {\n const formatted = invalid.map((v) => JSON.stringify(v))\n throw new TypeError(\n `Invalid API perspective value${invalid.length === 1 ? '' : 's'}: ${formatted.join(', ')}, expected \\`published\\`, \\`drafts\\`, \\`raw\\` or a release identifier string`,\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n const projectBased = newConfig.useProjectHostname\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (newConfig.useProjectHostname) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning"],"mappings":";AAAA,MAAM,WAAW;AAEV,SAAS,gBAAgB,MAAc;AAC5C,SAAO,WAAW;AACpB;ACFA,MAAM,oBAAoB,CAAC,SAAS,MAAM,GACpC,yBAAyB,CAAC,UAAU,SAAS,SAAS,GAE/C,UAAU,CAAC,SAAiB;AACnC,MAAA,CAAC,qDAAqD,KAAK,IAAI;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAEJ,GAEa,YAAY,CAAC,OAAe;AACnC,MAAA,CAAC,gBAAgB,KAAK,EAAE;AACpB,UAAA,IAAI,MAAM,uDAAuD;AAE3E,GAEa,oBAAoB,CAAC,SAAiB;AAC7C,MAAA,kBAAkB,QAAQ,IAAI,MAAM;AAChC,UAAA,IAAI,MAAM,uBAAuB,IAAI,oBAAoB,kBAAkB,KAAK,IAAI,CAAC,EAAE;AAEjG,GAEa,iBAAiB,CAAC,IAAY,QAAa;AACtD,MAAI,QAAQ,QAAQ,OAAO,OAAQ,YAAY,MAAM,QAAQ,GAAG;AAC9D,UAAM,IAAI,MAAM,GAAG,EAAE,kCAAkC;AAE3D,GAEa,qBAAqB,CAAC,IAAY,OAAe;AACxD,MAAA,OAAO,MAAO,YAAY,CAAC,iCAAiC,KAAK,EAAE,KAAK,GAAG,SAAS,IAAI;AAC1F,UAAM,IAAI,MAAM,GAAG,EAAE,QAAQ,EAAE,8BAA8B;AAEjE,GAEa,oBAAoB,CAAC,IAAY,QAA6B;AACzE,MAAI,CAAC,IAAI;AACP,UAAM,IAAI,MAAM,GAAG,EAAE,+DAA+D;AAGnE,qBAAA,IAAI,IAAI,GAAG;AAChC,GAEa,iBAAiB,C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mB,UAAU,mBACnCC,WAAoB,UAAU,gBAAgB,EAAE,QAAQ,QAAQ,EAAE,IAClE,SAGN,UAAU,aAAa,GAAG,UAAU,UAAU,GAAG,QAAQ,MAAM,EAAE,GACjE,UAAU,eAAe,UAAU,YAAY,cAAc,SAEzD,UAAU,WAAW,MAAQ,UAAU,mBACzCC,qCAIF,UAAU,SAAS,UAAU,WAAW,MAAS,CAAC,UAAU,iBAE5D,mBAAmB,UAAU,UAAU;AAEvC,QAAM,YAAY,UAAU,QAAQ,MAAM,OAAO,CAAC,GAC5C,WAAW,UAAU,CAAC,GACtB,OAAO,UAAU,CAAC,GAClB,UAAU,UAAU,eAAe,iBAAiB;AAE1D,SAAI,UAAU,sBACZ,UAAU,MAAM,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;;;;;;;;;;;;;;"}
@@ -84,25 +84,20 @@ function validateApiVersion(apiVersion) {
84
84
  if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
85
85
  throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
86
86
  }
87
+ const VALID_PERSPECTIVE = /^[a-z0-9_]+$/i;
87
88
  function validateApiPerspective(perspective) {
88
- if (Array.isArray(perspective)) {
89
- for (const perspectiveValue of perspective)
90
- if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
91
- throw new TypeError(
92
- "Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
93
- );
94
- return;
95
- }
96
- switch (perspective) {
97
- case "previewDrafts":
98
- case "drafts":
99
- case "published":
100
- case "raw":
101
- return;
102
- default:
103
- throw new TypeError(
104
- "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
105
- );
89
+ if (Array.isArray(perspective) && perspective.includes("raw"))
90
+ throw new TypeError(
91
+ 'Invalid API perspective value: "raw". The raw-perspective can not be combined with other perspectives'
92
+ );
93
+ const invalid = (Array.isArray(perspective) ? perspective : [perspective]).filter(
94
+ (perspectiveName) => typeof perspectiveName != "string" || !VALID_PERSPECTIVE.test(perspectiveName)
95
+ );
96
+ if (invalid.length > 0) {
97
+ const formatted = invalid.map((v) => JSON.stringify(v));
98
+ throw new TypeError(
99
+ `Invalid API perspective value${invalid.length === 1 ? "" : "s"}: ${formatted.join(", ")}, expected \`published\`, \`drafts\`, \`raw\` or a release identifier string`
100
+ );
106
101
  }
107
102
  }
108
103
  const initConfig = (config, prevConfig) => {
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sources":["../../src/generateHelpUrl.ts","../../src/validators.ts","../../src/util/once.ts","../../src/warnings.ts","../../src/config.ts"],"sourcesContent":["const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective)) {\n for (const perspectiveValue of perspective) {\n if (perspectiveValue === 'published') {\n continue\n }\n if (perspectiveValue === 'drafts') {\n continue\n }\n if (\n typeof perspectiveValue === 'string' &&\n perspectiveValue.startsWith('r') &&\n perspectiveValue !== 'raw'\n ) {\n continue\n }\n throw new TypeError(\n 'Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string',\n )\n }\n return\n }\n switch (perspective as ClientPerspective) {\n case 'previewDrafts':\n case 'drafts':\n case 'published':\n case 'raw':\n return\n default:\n throw new TypeError(\n 'Invalid API perspective string, expected `published`, `previewDrafts` or `raw`',\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n const projectBased = newConfig.useProjectHostname\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (newConfig.useProjectHostname) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning"],"mappings":"AAAA,MAAM,WAAW;AAEV,SAAS,gBAAgB,MAAc;AAC5C,SAAO,WAAW;AACpB;ACFA,MAAM,oBAAoB,CAAC,SAAS,MAAM,GACpC,yBAAyB,CAAC,UAAU,SAAS,SAAS,GAE/C,UAAU,CAAC,SAAiB;AACnC,MAAA,CAAC,qDAAqD,KAAK,IAAI;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAEJ,GAEa,YAAY,CAAC,OAAe;AACnC,MAAA,CAAC,gBAAgB,KAAK,EAAE;AACpB,UAAA,IAAI,MAAM,uDAAuD;AAE3E,GAEa,oBAAoB,CAAC,SAAiB;AAC7C,MAAA,kBAAkB,QAAQ,IAAI,MAAM;AAChC,UAAA,IAAI,MAAM,uBAAuB,IAAI,oBAAoB,kBAAkB,KAAK,IAAI,CAAC,EAAE;AAEjG,GAEa,iBAAiB,CAAC,IAAY,QAAa;AACtD,MAAI,QAAQ,QAAQ,OAAO,OAAQ,YAAY,MAAM,QAAQ,GAAG;AAC9D,UAAM,IAAI,MAAM,GAAG,EAAE,kCAAkC;AAE3D,GAEa,qBAAqB,CAAC,IAAY,OAAe;AACxD,MAAA,OAAO,MAAO,YAAY,CAAC,iCAAiC,KAAK,EAAE,K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B,OAAO,UAAU,SAAW,OACrCC,mBAGE,gBACFC,UAAmB,UAAU,SAAU,GAGrC,UAAU,WACZC,QAAiB,UAAU,OAAO,GAGhC,sBAAsB,cAExB,UAAU,mBAAmB,UAAU,mBACnCC,WAAoB,UAAU,gBAAgB,EAAE,QAAQ,QAAQ,EAAE,IAClE,SAGN,UAAU,aAAa,GAAG,UAAU,UAAU,GAAG,QAAQ,MAAM,EAAE,GACjE,UAAU,eAAe,UAAU,YAAY,cAAc,SAEzD,UAAU,WAAW,MAAQ,UAAU,mBACzCC,qCAIF,UAAU,SAAS,UAAU,WAAW,MAAS,CAAC,UAAU,iBAE5D,mBAAmB,UAAU,UAAU;AAEvC,QAAM,YAAY,UAAU,QAAQ,MAAM,OAAO,CAAC,GAC5C,WAAW,UAAU,CAAC,GACtB,OAAO,UAAU,CAAC,GAClB,UAAU,UAAU,eAAe,iBAAiB;AAE1D,SAAI,UAAU,sBACZ,UAAU,MAAM,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;"}
1
+ {"version":3,"file":"config.js","sources":["../../src/generateHelpUrl.ts","../../src/validators.ts","../../src/util/once.ts","../../src/warnings.ts","../../src/config.ts"],"sourcesContent":["const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\nconst VALID_PERSPECTIVE = /^[a-z0-9_]+$/i\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective)) {\n if (perspective.includes('raw')) {\n throw new TypeError(\n `Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives`,\n )\n }\n }\n\n const invalid = (Array.isArray(perspective) ? perspective : [perspective]).filter(\n (perspectiveName) =>\n typeof perspectiveName !== 'string' || !VALID_PERSPECTIVE.test(perspectiveName),\n )\n if (invalid.length > 0) {\n const formatted = invalid.map((v) => JSON.stringify(v))\n throw new TypeError(\n `Invalid API perspective value${invalid.length === 1 ? '' : 's'}: ${formatted.join(', ')}, expected \\`published\\`, \\`drafts\\`, \\`raw\\` or a release identifier string`,\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n const projectBased = newConfig.useProjectHostname\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (newConfig.useProjectHostname) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning"],"mappings":"AAAA,MAAM,WAAW;AAEV,SAAS,gBAAgB,MAAc;AAC5C,SAAO,WAAW;AACpB;ACFA,MAAM,oBAAoB,CAAC,SAAS,MAAM,GACpC,yBAAyB,CAAC,UAAU,SAAS,SAAS,GAE/C,UAAU,CAAC,SAAiB;AACnC,MAAA,CAAC,qDAAqD,KAAK,IAAI;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAEJ,GAEa,YAAY,CAAC,OAAe;AACnC,MAAA,CAAC,gBAAgB,KAAK,EAAE;AACpB,UAAA,IAAI,MAAM,uDAAuD;AAE3E,GAEa,oBAAoB,CAAC,SAAiB;AAC7C,MAAA,kBAAkB,QAAQ,IAAI,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,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;"}
package/dist/csm.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"csm.cjs","sources":["../src/csm/resolvePerspectives.ts","../src/csm/createSourceDocumentResolver.ts","../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {validateApiPerspective} from '../config'\nimport type {ReleaseId} from '../types'\nimport type {ClientPerspective} from './types'\n\n/**\n * This resolves the perspectives to how documents should be resolved when applying optimistic updates,\n * like in `applySourceDocuments`.\n * @internal\n */\nexport function resolvePerspectives(\n perspective: Exclude<ClientPerspective, 'raw'>,\n): ('published' | 'drafts' | ReleaseId)[] {\n validateApiPerspective(perspective)\n\n if (Array.isArray(perspective)) {\n if (!perspective.includes('published')) {\n return [...perspective, 'published']\n }\n return perspective\n }\n switch (perspective) {\n case 'previewDrafts':\n case 'drafts':\n return ['drafts', 'published']\n case 'published':\n default:\n return ['published']\n }\n}\n","import {getDraftId, getPublishedId, getVersionId} from './draftUtils'\nimport {resolvePerspectives} from './resolvePerspectives'\nimport type {ClientPerspective, ContentSourceMapDocuments, SanityDocument} from './types'\n\n/** @internal */\nexport type ResolvedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type'>>\n\n/** @internal */\nexport type MatchedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type' | '_originalId'>>\n\n/** @internal */\nexport function createSourceDocumentResolver(\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => ResolvedDocument | null | undefined,\n _perspective: Exclude<ClientPerspective, 'raw'>,\n) {\n const perspectives = resolvePerspectives(_perspective)\n function findDocument(sourceDocument: ContentSourceMapDocuments[number]) {\n for (const perspective of perspectives) {\n let match: ReturnType<typeof getCachedDocument> = null\n if (perspective.startsWith('r')) {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getVersionId(sourceDocument._id, perspective),\n })\n }\n if (perspective === 'drafts') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getDraftId(sourceDocument._id),\n })\n }\n if (perspective === 'published') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getPublishedId(sourceDocument._id),\n })\n }\n if (match) {\n return {...match, _id: getPublishedId(match._id), _originalId: match._id}\n }\n }\n return null\n }\n // define resolver that loops over source documents and perspectives\n return function resolveSourceDocument(\n sourceDocument: ContentSourceMapDocuments[number],\n ): MatchedDocument | null {\n return findDocument(sourceDocument)\n }\n}\n","import {createSourceDocumentResolver} from './createSourceDocumentResolver'\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\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 ) =>\n | (Partial<SanityDocument> & Required<Pick<SanityDocument, '_id' | '_type'>>)\n | null\n | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction,\n perspective: Exclude<ClientPerspective, 'raw'>,\n): Result {\n if (!resultSourceMap) return result\n\n const resolveDocument = createSourceDocumentResolver(getCachedDocument, perspective)\n const cachedDocuments = resultSourceMap.documents?.map?.(resolveDocument) || []\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\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 const cachedDocument = cachedDocuments[mapping.source.document]\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":["validateApiPerspective","getVersionId","getDraftId","getPublishedId","walkMap","resolveMapping","parseJsonPath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AAA,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/resolvePerspectives.ts","../src/csm/createSourceDocumentResolver.ts","../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {validateApiPerspective} from '../config'\nimport type {StackablePerspective} from '../types'\nimport type {ClientPerspective} from './types'\n\n/**\n * This resolves the perspectives to how documents should be resolved when applying optimistic updates,\n * like in `applySourceDocuments`.\n * @internal\n */\nexport function resolvePerspectives(\n perspective: Exclude<ClientPerspective, 'raw'>,\n): ('published' | 'drafts' | StackablePerspective)[] {\n validateApiPerspective(perspective)\n\n if (Array.isArray(perspective)) {\n if (!perspective.includes('published')) {\n return [...perspective, 'published']\n }\n return perspective\n }\n switch (perspective) {\n case 'previewDrafts':\n case 'drafts':\n return ['drafts', 'published']\n case 'published':\n default:\n return ['published']\n }\n}\n","import {getDraftId, getPublishedId, getVersionId} from './draftUtils'\nimport {resolvePerspectives} from './resolvePerspectives'\nimport type {ClientPerspective, ContentSourceMapDocuments, SanityDocument} from './types'\n\n/** @internal */\nexport type ResolvedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type'>>\n\n/** @internal */\nexport type MatchedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type' | '_originalId'>>\n\n/** @internal */\nexport function createSourceDocumentResolver(\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => ResolvedDocument | null | undefined,\n _perspective: Exclude<ClientPerspective, 'raw'>,\n) {\n const perspectives = resolvePerspectives(_perspective)\n function findDocument(sourceDocument: ContentSourceMapDocuments[number]) {\n for (const perspective of perspectives) {\n let match: ReturnType<typeof getCachedDocument> = null\n if (perspective.startsWith('r')) {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getVersionId(sourceDocument._id, perspective),\n })\n }\n if (perspective === 'drafts') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getDraftId(sourceDocument._id),\n })\n }\n if (perspective === 'published') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getPublishedId(sourceDocument._id),\n })\n }\n if (match) {\n return {...match, _id: getPublishedId(match._id), _originalId: match._id}\n }\n }\n return null\n }\n // define resolver that loops over source documents and perspectives\n return function resolveSourceDocument(\n sourceDocument: ContentSourceMapDocuments[number],\n ): MatchedDocument | null {\n return findDocument(sourceDocument)\n }\n}\n","import {createSourceDocumentResolver} from './createSourceDocumentResolver'\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\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 ) =>\n | (Partial<SanityDocument> & Required<Pick<SanityDocument, '_id' | '_type'>>)\n | null\n | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction,\n perspective: Exclude<ClientPerspective, 'raw'>,\n): Result {\n if (!resultSourceMap) return result\n\n const resolveDocument = createSourceDocumentResolver(getCachedDocument, perspective)\n const cachedDocuments = resultSourceMap.documents?.map?.(resolveDocument) || []\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\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 const cachedDocument = cachedDocuments[mapping.source.document]\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":["validateApiPerspective","getVersionId","getDraftId","getPublishedId","walkMap","resolveMapping","parseJsonPath","paths.toString","paths.get","jsonPath","studioPathToJsonPath","resolveEditInfo","createEditUrl"],"mappings":";;;AASO,SAAS,oBACd,aACmD;AAGnD,MAFAA,OAAuB,uBAAA,WAAW,GAE9B,MAAM,QAAQ,WAAW;AACtB,WAAA,YAAY,SAAS,WAAW,IAG9B,cAFE,CAAC,GAAG,aAAa,WAAW;AAIvC,UAAQ,aAAa;AAAA,IACnB,KAAK;AAAA,IACL,KAAK;AACI,aAAA,CAAC,UAAU,WAAW;AAAA,IAC/B,KAAK;AAAA,IACL;AACE,aAAO,CAAC,WAAW;AAAA,EAAA;AAEzB;ACfgB,SAAA,6BACd,mBAGA,cACA;AACM,QAAA,eAAe,oBAAoB,YAAY;AACrD,WAAS,aAAa,gBAAmD;AACvE,eAAW,eAAe,cAAc;AACtC,UAAI,QAA8C;AAmBlD,UAlBI,YAAY,WAAW,GAAG,MAC5B,QAAQ,kBAAkB;AAAA,QACxB,GAAG;AAAA,QACH,KAAKC,gBAAA,aAAa,eAAe,KAAK,WAAW;AAAA,MAClD,CAAA,IAEC,gBAAgB,aAClB,QAAQ,kBAAkB;AAAA,QACxB,GAAG;AAAA,QACH,KAAKC,gBAAAA,WAAW,eAAe,GAAG;AAAA,MACnC,CAAA,IAEC,gBAAgB,gBAClB,QAAQ,kBAAkB;AAAA,QACxB,GAAG;AAAA,QACH,KAAKC,gBAAAA,eAAe,eAAe,GAAG;AAAA,MACvC,CAAA,IAEC;AACK,eAAA,EAAC,GAAG,OAAO,KAAKA,gBAAA,eAAe,MAAM,GAAG,GAAG,aAAa,MAAM,IAAG;AAAA,IAAA;AAGrE,WAAA;AAAA,EAAA;AAGT,SAAO,SACL,gBACwB;AACxB,WAAO,aAAa,cAAc;AAAA,EACpC;AACF;ACjCO,SAAS,qBACd,QACA,iBACA,mBAMA,UACA,aACQ;AACJ,MAAA,CAAC,gBAAwB,QAAA;AAEv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Aa,IAAA,SAC/B,aAAaI,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.d.cts CHANGED
@@ -41,7 +41,7 @@ export declare type ClientPerspective =
41
41
  | 'published'
42
42
  | 'drafts'
43
43
  | 'raw'
44
- | ('published' | 'drafts' | ReleaseId)[]
44
+ | StackablePerspective[]
45
45
 
46
46
  /** @public */
47
47
  export declare interface ContentSourceMap {
@@ -258,9 +258,6 @@ export declare type PublishedId = Opaque<string, 'publishedId'>
258
258
  /** @internal */
259
259
  declare const reKeySegment: RegExp
260
260
 
261
- /** @public */
262
- declare type ReleaseId = `r${string}`
263
-
264
261
  /**
265
262
  * @internal
266
263
  */
@@ -326,6 +323,9 @@ export declare type SanityDocument<T extends Record<string, Any> = Record<string
326
323
  _originalId?: string
327
324
  }
328
325
 
326
+ /** @public */
327
+ declare type StackablePerspective = ('published' | 'drafts' | string) & {}
328
+
329
329
  /** @alpha */
330
330
  export declare type StudioBaseRoute = {
331
331
  baseUrl: StudioBaseUrl
package/dist/csm.d.ts CHANGED
@@ -41,7 +41,7 @@ export declare type ClientPerspective =
41
41
  | 'published'
42
42
  | 'drafts'
43
43
  | 'raw'
44
- | ('published' | 'drafts' | ReleaseId)[]
44
+ | StackablePerspective[]
45
45
 
46
46
  /** @public */
47
47
  export declare interface ContentSourceMap {
@@ -258,9 +258,6 @@ export declare type PublishedId = Opaque<string, 'publishedId'>
258
258
  /** @internal */
259
259
  declare const reKeySegment: RegExp
260
260
 
261
- /** @public */
262
- declare type ReleaseId = `r${string}`
263
-
264
261
  /**
265
262
  * @internal
266
263
  */
@@ -326,6 +323,9 @@ export declare type SanityDocument<T extends Record<string, Any> = Record<string
326
323
  _originalId?: string
327
324
  }
328
325
 
326
+ /** @public */
327
+ declare type StackablePerspective = ('published' | 'drafts' | string) & {}
328
+
329
329
  /** @alpha */
330
330
  export declare type StudioBaseRoute = {
331
331
  baseUrl: StudioBaseUrl
package/dist/csm.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"csm.js","sources":["../src/csm/resolvePerspectives.ts","../src/csm/createSourceDocumentResolver.ts","../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {validateApiPerspective} from '../config'\nimport type {ReleaseId} from '../types'\nimport type {ClientPerspective} from './types'\n\n/**\n * This resolves the perspectives to how documents should be resolved when applying optimistic updates,\n * like in `applySourceDocuments`.\n * @internal\n */\nexport function resolvePerspectives(\n perspective: Exclude<ClientPerspective, 'raw'>,\n): ('published' | 'drafts' | ReleaseId)[] {\n validateApiPerspective(perspective)\n\n if (Array.isArray(perspective)) {\n if (!perspective.includes('published')) {\n return [...perspective, 'published']\n }\n return perspective\n }\n switch (perspective) {\n case 'previewDrafts':\n case 'drafts':\n return ['drafts', 'published']\n case 'published':\n default:\n return ['published']\n }\n}\n","import {getDraftId, getPublishedId, getVersionId} from './draftUtils'\nimport {resolvePerspectives} from './resolvePerspectives'\nimport type {ClientPerspective, ContentSourceMapDocuments, SanityDocument} from './types'\n\n/** @internal */\nexport type ResolvedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type'>>\n\n/** @internal */\nexport type MatchedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type' | '_originalId'>>\n\n/** @internal */\nexport function createSourceDocumentResolver(\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => ResolvedDocument | null | undefined,\n _perspective: Exclude<ClientPerspective, 'raw'>,\n) {\n const perspectives = resolvePerspectives(_perspective)\n function findDocument(sourceDocument: ContentSourceMapDocuments[number]) {\n for (const perspective of perspectives) {\n let match: ReturnType<typeof getCachedDocument> = null\n if (perspective.startsWith('r')) {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getVersionId(sourceDocument._id, perspective),\n })\n }\n if (perspective === 'drafts') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getDraftId(sourceDocument._id),\n })\n }\n if (perspective === 'published') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getPublishedId(sourceDocument._id),\n })\n }\n if (match) {\n return {...match, _id: getPublishedId(match._id), _originalId: match._id}\n }\n }\n return null\n }\n // define resolver that loops over source documents and perspectives\n return function resolveSourceDocument(\n sourceDocument: ContentSourceMapDocuments[number],\n ): MatchedDocument | null {\n return findDocument(sourceDocument)\n }\n}\n","import {createSourceDocumentResolver} from './createSourceDocumentResolver'\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\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 ) =>\n | (Partial<SanityDocument> & Required<Pick<SanityDocument, '_id' | '_type'>>)\n | null\n | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction,\n perspective: Exclude<ClientPerspective, 'raw'>,\n): Result {\n if (!resultSourceMap) return result\n\n const resolveDocument = createSourceDocumentResolver(getCachedDocument, perspective)\n const cachedDocuments = resultSourceMap.documents?.map?.(resolveDocument) || []\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\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 const cachedDocument = cachedDocuments[mapping.source.document]\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(editInf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resolvePerspectives.ts","../src/csm/createSourceDocumentResolver.ts","../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {validateApiPerspective} from '../config'\nimport type {StackablePerspective} from '../types'\nimport type {ClientPerspective} from './types'\n\n/**\n * This resolves the perspectives to how documents should be resolved when applying optimistic updates,\n * like in `applySourceDocuments`.\n * @internal\n */\nexport function resolvePerspectives(\n perspective: Exclude<ClientPerspective, 'raw'>,\n): ('published' | 'drafts' | StackablePerspective)[] {\n validateApiPerspective(perspective)\n\n if (Array.isArray(perspective)) {\n if (!perspective.includes('published')) {\n return [...perspective, 'published']\n }\n return perspective\n }\n switch (perspective) {\n case 'previewDrafts':\n case 'drafts':\n return ['drafts', 'published']\n case 'published':\n default:\n return ['published']\n }\n}\n","import {getDraftId, getPublishedId, getVersionId} from './draftUtils'\nimport {resolvePerspectives} from './resolvePerspectives'\nimport type {ClientPerspective, ContentSourceMapDocuments, SanityDocument} from './types'\n\n/** @internal */\nexport type ResolvedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type'>>\n\n/** @internal */\nexport type MatchedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type' | '_originalId'>>\n\n/** @internal */\nexport function createSourceDocumentResolver(\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => ResolvedDocument | null | undefined,\n _perspective: Exclude<ClientPerspective, 'raw'>,\n) {\n const perspectives = resolvePerspectives(_perspective)\n function findDocument(sourceDocument: ContentSourceMapDocuments[number]) {\n for (const perspective of perspectives) {\n let match: ReturnType<typeof getCachedDocument> = null\n if (perspective.startsWith('r')) {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getVersionId(sourceDocument._id, perspective),\n })\n }\n if (perspective === 'drafts') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getDraftId(sourceDocument._id),\n })\n }\n if (perspective === 'published') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getPublishedId(sourceDocument._id),\n })\n }\n if (match) {\n return {...match, _id: getPublishedId(match._id), _originalId: match._id}\n }\n }\n return null\n }\n // define resolver that loops over source documents and perspectives\n return function resolveSourceDocument(\n sourceDocument: ContentSourceMapDocuments[number],\n ): MatchedDocument | null {\n return findDocument(sourceDocument)\n }\n}\n","import {createSourceDocumentResolver} from './createSourceDocumentResolver'\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\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 ) =>\n | (Partial<SanityDocument> & Required<Pick<SanityDocument, '_id' | '_type'>>)\n | null\n | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction,\n perspective: Exclude<ClientPerspective, 'raw'>,\n): Result {\n if (!resultSourceMap) return result\n\n const resolveDocument = createSourceDocumentResolver(getCachedDocument, perspective)\n const cachedDocuments = resultSourceMap.documents?.map?.(resolveDocument) || []\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\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 const cachedDocument = cachedDocuments[mapping.source.document]\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":";;;AASO,SAAS,oBACd,aACmD;AAGnD,MAFA,uBAAuB,WAAW,GAE9B,MAAM,QAAQ,WAAW;AACtB,WAAA,YAAY,SAAS,WAAW,IAG9B,cAFE,CAAC,GAAG,aAAa,WAAW;A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,SAAS;AACnB,aAAA;AAGT,UAAM,iBAAiB,gBAAgB,UAAU,QAAQ,OAAO,QAAQ,GAClE,aAAa,gBAAgB,MAAM,QAAQ,OAAO,IAAI;AAE5D,QAAI,gBAAgB;AAClB,YAAM,aAAa,cAAc,aAAa,UAAU,GAClD,kBAAkBA,SAAe,UAAkB,GACnD,iBAAiB,gBAAgB,QAAQ,OAAO,QAAQ;AAE9D,UAAI,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,IAAA;AAGA,WAAA;AAAA,EAAA,CACR;AACH;ACzEO,SAAS,wBAAwB,SAIT;AAC7B,QAAM,EAAC,iBAAiB,YAAY,eAAA,IAAkB,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;"}
@@ -212,25 +212,20 @@ function validateApiVersion(apiVersion) {
212
212
  if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
213
213
  throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
214
214
  }
215
+ const VALID_PERSPECTIVE = /^[a-z0-9_]+$/i;
215
216
  function validateApiPerspective(perspective) {
216
- if (Array.isArray(perspective)) {
217
- for (const perspectiveValue of perspective)
218
- if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
219
- throw new TypeError(
220
- "Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
221
- );
222
- return;
223
- }
224
- switch (perspective) {
225
- case "previewDrafts":
226
- case "drafts":
227
- case "published":
228
- case "raw":
229
- return;
230
- default:
231
- throw new TypeError(
232
- "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
233
- );
217
+ if (Array.isArray(perspective) && perspective.includes("raw"))
218
+ throw new TypeError(
219
+ 'Invalid API perspective value: "raw". The raw-perspective can not be combined with other perspectives'
220
+ );
221
+ const invalid = (Array.isArray(perspective) ? perspective : [perspective]).filter(
222
+ (perspectiveName) => typeof perspectiveName != "string" || !VALID_PERSPECTIVE.test(perspectiveName)
223
+ );
224
+ if (invalid.length > 0) {
225
+ const formatted = invalid.map((v) => JSON.stringify(v));
226
+ throw new TypeError(
227
+ `Invalid API perspective value${invalid.length === 1 ? "" : "s"}: ${formatted.join(", ")}, expected \`published\`, \`drafts\`, \`raw\` or a release identifier string`
228
+ );
234
229
  }
235
230
  }
236
231
  const initConfig = (config, prevConfig) => {
@@ -1044,6 +1039,28 @@ function _listen(query, params, opts = {}) {
1044
1039
  )
1045
1040
  );
1046
1041
  }
1042
+ function shareReplayLatest(configOrPredicate, config) {
1043
+ return _shareReplayLatest(
1044
+ typeof configOrPredicate == "function" ? { predicate: configOrPredicate, ...config } : configOrPredicate
1045
+ );
1046
+ }
1047
+ function _shareReplayLatest(config) {
1048
+ return (source) => {
1049
+ let latest, emitted = !1;
1050
+ const { predicate, ...shareConfig } = config, wrapped = source.pipe(
1051
+ rxjs.tap((value) => {
1052
+ config.predicate(value) && (emitted = !0, latest = value);
1053
+ }),
1054
+ rxjs.finalize(() => {
1055
+ emitted = !1, latest = void 0;
1056
+ }),
1057
+ rxjs.share(shareConfig)
1058
+ ), emitLatest = new rxjs.Observable((subscriber) => {
1059
+ emitted && subscriber.next(latest), subscriber.complete();
1060
+ });
1061
+ return rxjs.merge(wrapped, emitLatest);
1062
+ };
1063
+ }
1047
1064
  const requiredApiVersion = "2021-03-25";
1048
1065
  class LiveClient {
1049
1066
  #client;
@@ -1078,6 +1095,9 @@ class LiveClient {
1078
1095
  includeDrafts && token && (esOptions.headers = {
1079
1096
  Authorization: `Bearer ${token}`
1080
1097
  }), includeDrafts && withCredentials && (esOptions.withCredentials = !0);
1098
+ const key = `${url.href}::${JSON.stringify(esOptions)}`, existing = eventsCache.get(key);
1099
+ if (existing)
1100
+ return existing;
1081
1101
  const events = connectEventSource(() => (
1082
1102
  // use polyfill if there is no global EventSource or if we need to set headers
1083
1103
  (typeof EventSource > "u" || esOptions.headers ? eventSourcePolyfill : rxjs.of(EventSource)).pipe(operators.map((EventSource2) => new EventSource2(url.href, esOptions)))
@@ -1105,8 +1125,13 @@ class LiveClient {
1105
1125
  rxjs.catchError(() => {
1106
1126
  throw new CorsOriginError({ projectId: projectId2 });
1107
1127
  })
1128
+ ), observable = rxjs.concat(checkCors, events).pipe(
1129
+ operators.finalize(() => eventsCache.delete(key)),
1130
+ shareReplayLatest({
1131
+ predicate: (event) => event.type === "welcome"
1132
+ })
1108
1133
  );
1109
- return rxjs.concat(checkCors, events);
1134
+ return eventsCache.set(key, observable), observable;
1110
1135
  }
1111
1136
  }
1112
1137
  function fetchObservable(url, init) {
@@ -1122,6 +1147,7 @@ function fetchObservable(url, init) {
1122
1147
  ), () => controller.abort();
1123
1148
  });
1124
1149
  }
1150
+ const eventsCache = /* @__PURE__ */ new Map();
1125
1151
  class ObservableDatasetsClient {
1126
1152
  #client;
1127
1153
  #httpRequest;