@sanity/client 7.1.0-views.0 → 7.1.0-views.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.
Files changed (80) hide show
  1. package/README.md +668 -40
  2. package/dist/_chunks-cjs/config.cjs +14 -0
  3. package/dist/_chunks-cjs/config.cjs.map +1 -1
  4. package/dist/_chunks-cjs/dataMethods.cjs +197 -32
  5. package/dist/_chunks-cjs/dataMethods.cjs.map +1 -1
  6. package/dist/_chunks-cjs/isRecord.cjs +6 -0
  7. package/dist/_chunks-cjs/isRecord.cjs.map +1 -0
  8. package/dist/_chunks-cjs/resolveEditInfo.cjs +3 -5
  9. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +1 -1
  10. package/dist/_chunks-cjs/stegaClean.cjs +4 -0
  11. package/dist/_chunks-cjs/stegaClean.cjs.map +1 -1
  12. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +2 -5
  13. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
  14. package/dist/_chunks-es/config.js +15 -1
  15. package/dist/_chunks-es/config.js.map +1 -1
  16. package/dist/_chunks-es/dataMethods.js +200 -33
  17. package/dist/_chunks-es/dataMethods.js.map +1 -1
  18. package/dist/_chunks-es/isRecord.js +7 -0
  19. package/dist/_chunks-es/isRecord.js.map +1 -0
  20. package/dist/_chunks-es/resolveEditInfo.js +1 -3
  21. package/dist/_chunks-es/resolveEditInfo.js.map +1 -1
  22. package/dist/_chunks-es/stegaClean.js +4 -0
  23. package/dist/_chunks-es/stegaClean.js.map +1 -1
  24. package/dist/_chunks-es/stegaEncodeSourceMap.js +1 -4
  25. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
  26. package/dist/index.browser.cjs +1019 -59
  27. package/dist/index.browser.cjs.map +1 -1
  28. package/dist/index.browser.d.cts +1948 -149
  29. package/dist/index.browser.d.ts +1948 -149
  30. package/dist/index.browser.js +1021 -60
  31. package/dist/index.browser.js.map +1 -1
  32. package/dist/index.cjs +825 -29
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +1948 -149
  35. package/dist/index.d.ts +1948 -149
  36. package/dist/index.js +826 -31
  37. package/dist/index.js.map +1 -1
  38. package/dist/stega.browser.d.cts +1948 -149
  39. package/dist/stega.browser.d.ts +1948 -149
  40. package/dist/stega.d.cts +1948 -149
  41. package/dist/stega.d.ts +1948 -149
  42. package/dist/views.cjs +13 -5
  43. package/dist/views.cjs.map +1 -1
  44. package/dist/views.d.cts +51 -36
  45. package/dist/views.d.ts +51 -36
  46. package/dist/views.js +14 -5
  47. package/dist/views.js.map +1 -1
  48. package/package.json +2 -1
  49. package/src/SanityClient.ts +652 -12
  50. package/src/agent/actions/AgentActionsClient.ts +29 -2
  51. package/src/agent/actions/commonTypes.ts +57 -17
  52. package/src/agent/actions/generate.ts +36 -2
  53. package/src/agent/actions/patch.ts +136 -0
  54. package/src/agent/actions/prompt.ts +145 -0
  55. package/src/agent/actions/transform.ts +105 -7
  56. package/src/agent/actions/translate.ts +5 -2
  57. package/src/config.ts +3 -1
  58. package/src/csm/walkMap.ts +1 -1
  59. package/src/data/dataMethods.ts +170 -12
  60. package/src/data/encodeQueryString.ts +1 -1
  61. package/src/data/eventsource.ts +16 -7
  62. package/src/data/listen.ts +10 -4
  63. package/src/data/live.ts +13 -5
  64. package/src/datasets/DatasetsClient.ts +4 -1
  65. package/src/defineCreateClient.ts +7 -1
  66. package/src/http/errors.ts +92 -27
  67. package/src/http/request.ts +3 -3
  68. package/src/http/requestOptions.ts +4 -0
  69. package/src/projects/ProjectsClient.ts +6 -2
  70. package/src/releases/ReleasesClient.ts +693 -0
  71. package/src/releases/createRelease.ts +53 -0
  72. package/src/types.ts +291 -10
  73. package/src/users/UsersClient.ts +7 -3
  74. package/src/util/codeFrame.ts +174 -0
  75. package/src/util/createVersionId.ts +79 -0
  76. package/src/{csm → util}/isRecord.ts +1 -1
  77. package/src/validators.ts +23 -1
  78. package/src/views/index.ts +51 -15
  79. package/umd/sanityClient.js +1067 -61
  80. package/umd/sanityClient.min.js +2 -2
@@ -24,6 +24,18 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
24
24
  if (!doc._id)
25
25
  throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
26
26
  validateDocumentId(op, doc._id);
27
+ }, validateDocumentType = (op, type) => {
28
+ if (typeof type != "string")
29
+ throw new Error(`\`${op}()\`: \`${type}\` is not a valid document type`);
30
+ }, requireDocumentType = (op, doc) => {
31
+ if (!doc._type)
32
+ throw new Error(`\`${op}()\` requires that the document contains a type (\`_type\` property)`);
33
+ validateDocumentType(op, doc._type);
34
+ }, validateVersionIdMatch = (builtVersionId, document) => {
35
+ if (document._id && document._id !== builtVersionId)
36
+ throw new Error(
37
+ `The provided document ID (\`${document._id}\`) does not match the generated version ID (\`${builtVersionId}\`)`
38
+ );
27
39
  }, validateInsert = (at, selector, items) => {
28
40
  const signature = "insert(at, selector, items)";
29
41
  if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
@@ -167,6 +179,7 @@ exports.printNoDefaultExport = printNoDefaultExport;
167
179
  exports.printPreviewDraftsDeprecationWarning = printPreviewDraftsDeprecationWarning;
168
180
  exports.requestTag = requestTag;
169
181
  exports.requireDocumentId = requireDocumentId;
182
+ exports.requireDocumentType = requireDocumentType;
170
183
  exports.resourceConfig = resourceConfig;
171
184
  exports.resourceGuard = resourceGuard;
172
185
  exports.validateApiPerspective = validateApiPerspective;
@@ -174,4 +187,5 @@ exports.validateAssetType = validateAssetType;
174
187
  exports.validateDocumentId = validateDocumentId;
175
188
  exports.validateInsert = validateInsert;
176
189
  exports.validateObject = validateObject;
190
+ exports.validateVersionIdMatch = validateVersionIdMatch;
177
191
  //# sourceMappingURL=config.cjs.map
@@ -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\nexport const resourceConfig = (config: InitializedClientConfig): void => {\n if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_resource']\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"')\n }\n return\n }\n case 'dashboard':\n case 'media-library':\n case 'canvas':\n case 'view': {\n return\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n\nexport const resourceGuard = (service: string, config: InitializedClientConfig): void => {\n if (config['~experimental_resource']) {\n throw new Error(`\\`${service}\\` does not support resource-based operations`)\n }\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 \\`drafts\\` or \\`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 printPreviewDraftsDeprecationWarning = createWarningPrinter([\n `The \\`previewDrafts\\` perspective has been renamed to \\`drafts\\` and will be removed in a future API version`,\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 printCredentialedTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token, but also provided `withCredentials: true`.',\n 'This is no longer supported - only token will be used - remove `withCredentials: true`.',\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) && perspective.length > 1 && 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\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 && !newConfig['~experimental_resource']\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 (newConfig['~experimental_resource']) {\n validate.resourceConfig(newConfig)\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 const hasToken = Boolean(newConfig.token)\n if (newConfig.withCredentials && hasToken) {\n warnings.printCredentialedTokenWarning()\n newConfig.withCredentials = false\n }\n\n if (isBrowser && isLocalhost && hasToken && 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\n const cdnURL = newConfig.isDefaultApi ? `https://${defaultCdnHost}` : newConfig.apiCdnHost || newConfig.apiHost\n const cdnURLParts = cdnURL.split('://', 2)\n const cdnProtocol = cdnURLParts[0]\n const cdnHost = cdnURLParts[1]\n\n if (projectBased) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${cdnProtocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${cdnProtocol}://${cdnHost}/v${newConfig.apiVersion}`\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","validate.resourceConfig","warnings.printCredentialedTokenWarning","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,GAE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c,YAAY,CAAC,GAC3B,UAAU,YAAY,CAAC;AAEzB,SAAA,gBACF,UAAU,MAAM,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,WAAW,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE9F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,GAAG,WAAW,MAAM,OAAO,KAAK,UAAU,UAAU,KAGlE;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, SanityDocumentStub} 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 validateDocumentType = (op: string, type: string) => {\n if (typeof type !== 'string') {\n throw new Error(`\\`${op}()\\`: \\`${type}\\` is not a valid document type`)\n }\n}\n\nexport const requireDocumentType = (op: string, doc: Record<string, Any>) => {\n if (!doc._type) {\n throw new Error(`\\`${op}()\\` requires that the document contains a type (\\`_type\\` property)`)\n }\n\n validateDocumentType(op, doc._type)\n}\n\nexport const validateVersionIdMatch = (builtVersionId: string, document: SanityDocumentStub) => {\n if (document._id && document._id !== builtVersionId) {\n throw new Error(\n `The provided document ID (\\`${document._id}\\`) does not match the generated version ID (\\`${builtVersionId}\\`)`,\n )\n }\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\nexport const resourceConfig = (config: InitializedClientConfig): void => {\n if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_resource']\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"')\n }\n return\n }\n case 'dashboard':\n case 'media-library':\n case 'canvas':\n case 'view': {\n return\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n\nexport const resourceGuard = (service: string, config: InitializedClientConfig): void => {\n if (config['~experimental_resource']) {\n throw new Error(`\\`${service}\\` does not support resource-based operations`)\n }\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 \\`drafts\\` or \\`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 printPreviewDraftsDeprecationWarning = createWarningPrinter([\n `The \\`previewDrafts\\` perspective has been renamed to \\`drafts\\` and will be removed in a future API version`,\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 printCredentialedTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token, but also provided `withCredentials: true`.',\n 'This is no longer supported - only token will be used - remove `withCredentials: true`.',\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) && perspective.length > 1 && 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\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 && !newConfig['~experimental_resource']\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 (newConfig['~experimental_resource']) {\n validate.resourceConfig(newConfig)\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 const hasToken = Boolean(newConfig.token)\n if (newConfig.withCredentials && hasToken) {\n warnings.printCredentialedTokenWarning()\n newConfig.withCredentials = false\n }\n\n if (isBrowser && isLocalhost && hasToken && 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\n const cdnURL = newConfig.isDefaultApi\n ? `https://${defaultCdnHost}`\n : newConfig.apiCdnHost || newConfig.apiHost\n const cdnURLParts = cdnURL.split('://', 2)\n const cdnProtocol = cdnURLParts[0]\n const cdnHost = cdnURLParts[1]\n\n if (projectBased) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${cdnProtocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${cdnProtocol}://${cdnHost}/v${newConfig.apiVersion}`\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","validate.resourceConfig","warnings.printCredentialedTokenWarning","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,uBAAuB,CAAC,IAAY,SAAiB;AAChE,MAAI,O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,KACzB,UAAU,cAAc,UAAU,SACX,MAAM,OAAO,CAAC,GACnC,cAAc,YAAY,CAAC,GAC3B,UAAU,YAAY,CAAC;AAEzB,SAAA,gBACF,UAAU,MAAM,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,WAAW,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE9F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,GAAG,WAAW,MAAM,OAAO,KAAK,UAAU,UAAU,KAGlE;AACT;;;;;;;;;;;;;;;;;;;"}
@@ -1,12 +1,81 @@
1
1
  "use strict";
2
- var getIt = require("get-it"), middleware = require("get-it/middleware"), rxjs = require("rxjs"), operators = require("rxjs/operators"), config = require("./config.cjs"), stegaClean = require("./stegaClean.cjs");
2
+ var getIt = require("get-it"), middleware = require("get-it/middleware"), rxjs = require("rxjs"), isRecord = require("./isRecord.cjs"), csm = require("@sanity/client/csm"), operators = require("rxjs/operators"), config = require("./config.cjs"), stegaClean = require("./stegaClean.cjs");
3
+ const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
4
+ function codeFrame(query, location2, message) {
5
+ const lines = query.split(NEWLINE), loc = {
6
+ start: columnToLine(location2.start, lines),
7
+ end: location2.end ? columnToLine(location2.end, lines) : void 0
8
+ }, { start, end, markerLines } = getMarkerLines(loc, lines), numberMaxWidth = `${end}`.length;
9
+ return query.split(NEWLINE, end).slice(start, end).map((line, index) => {
10
+ const number = start + 1 + index, gutter = ` ${` ${number}`.slice(-numberMaxWidth)} |`, hasMarker = markerLines[number], lastMarkerLine = !markerLines[number + 1];
11
+ if (!hasMarker)
12
+ return ` ${gutter}${line.length > 0 ? ` ${line}` : ""}`;
13
+ let markerLine = "";
14
+ if (Array.isArray(hasMarker)) {
15
+ const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "), numberOfMarkers = hasMarker[1] || 1;
16
+ markerLine = [
17
+ `
18
+ `,
19
+ gutter.replace(/\d/g, " "),
20
+ " ",
21
+ markerSpacing,
22
+ "^".repeat(numberOfMarkers)
23
+ ].join(""), lastMarkerLine && message && (markerLine += " " + message);
24
+ }
25
+ return [">", gutter, line.length > 0 ? ` ${line}` : "", markerLine].join("");
26
+ }).join(`
27
+ `);
28
+ }
29
+ function getMarkerLines(loc, source) {
30
+ const startLoc = { ...loc.start }, endLoc = { ...startLoc, ...loc.end }, linesAbove = 2, linesBelow = 3, startLine = startLoc.line ?? -1, startColumn = startLoc.column ?? 0, endLine = endLoc.line, endColumn = endLoc.column;
31
+ let start = Math.max(startLine - (linesAbove + 1), 0), end = Math.min(source.length, endLine + linesBelow);
32
+ startLine === -1 && (start = 0), endLine === -1 && (end = source.length);
33
+ const lineDiff = endLine - startLine, markerLines = {};
34
+ if (lineDiff)
35
+ for (let i = 0; i <= lineDiff; i++) {
36
+ const lineNumber = i + startLine;
37
+ if (!startColumn)
38
+ markerLines[lineNumber] = !0;
39
+ else if (i === 0) {
40
+ const sourceLength = source[lineNumber - 1].length;
41
+ markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
42
+ } else if (i === lineDiff)
43
+ markerLines[lineNumber] = [0, endColumn];
44
+ else {
45
+ const sourceLength = source[lineNumber - i].length;
46
+ markerLines[lineNumber] = [0, sourceLength];
47
+ }
48
+ }
49
+ else
50
+ startColumn === endColumn ? startColumn ? markerLines[startLine] = [startColumn, 0] : markerLines[startLine] = !0 : markerLines[startLine] = [startColumn, endColumn - startColumn];
51
+ return { start, end, markerLines };
52
+ }
53
+ function columnToLine(column, lines) {
54
+ let offset = 0;
55
+ for (let i = 0; i < lines.length; i++) {
56
+ const lineLength = lines[i].length + 1;
57
+ if (offset + lineLength > column)
58
+ return {
59
+ line: i + 1,
60
+ // 1-based line
61
+ column: column - offset
62
+ // 0-based column
63
+ };
64
+ offset += lineLength;
65
+ }
66
+ return {
67
+ line: lines.length,
68
+ column: lines[lines.length - 1]?.length ?? 0
69
+ };
70
+ }
71
+ const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
3
72
  class ClientError extends Error {
4
73
  response;
5
74
  statusCode = 400;
6
75
  responseBody;
7
76
  details;
8
- constructor(res) {
9
- const props = extractErrorProps(res);
77
+ constructor(res, context) {
78
+ const props = extractErrorProps(res, context);
10
79
  super(props.message), Object.assign(this, props);
11
80
  }
12
81
  }
@@ -20,7 +89,7 @@ class ServerError extends Error {
20
89
  super(props.message), Object.assign(this, props);
21
90
  }
22
91
  }
23
- function extractErrorProps(res) {
92
+ function extractErrorProps(res, context) {
24
93
  const body = res.body, props = {
25
94
  response: res,
26
95
  statusCode: res.statusCode,
@@ -28,34 +97,56 @@ function extractErrorProps(res) {
28
97
  message: "",
29
98
  details: void 0
30
99
  };
31
- if (body.error && body.message)
32
- return props.message = `${body.error} - ${body.message}`, props;
33
- if (isMutationError(body) || isActionError(body)) {
34
- const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => item.error?.description).filter(Boolean);
100
+ if (!isRecord.isRecord(body))
101
+ return props.message = httpErrorMessage(res, body), props;
102
+ const error = body.error;
103
+ if (typeof error == "string" && typeof body.message == "string")
104
+ return props.message = `${error} - ${body.message}`, props;
105
+ if (typeof error != "object" || error === null)
106
+ return typeof error == "string" ? props.message = error : typeof body.message == "string" ? props.message = body.message : props.message = httpErrorMessage(res, body), props;
107
+ if (isMutationError(error) || isActionError(error)) {
108
+ const allItems = error.items || [], items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map((item) => item.error?.description).filter(Boolean);
35
109
  let itemsStr = items.length ? `:
36
110
  - ${items.join(`
37
111
  - `)}` : "";
38
- return allItems.length > 5 && (itemsStr += `
39
- ...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;
112
+ return allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE && (itemsStr += `
113
+ ...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`), props.message = `${error.description}${itemsStr}`, props.details = body.error, props;
114
+ }
115
+ if (isQueryParseError(error)) {
116
+ const tag = context?.options?.query?.tag;
117
+ return props.message = formatQueryParseError(error, tag), props.details = body.error, props;
40
118
  }
41
- return body.error && body.error.description ? (props.message = body.error.description, props.details = body.error, props) : (props.message = body.error || body.message || httpErrorMessage(res), props);
119
+ return "description" in error && typeof error.description == "string" ? (props.message = error.description, props.details = error, props) : (props.message = httpErrorMessage(res, body), props);
42
120
  }
43
- function isMutationError(body) {
44
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description == "string";
121
+ function isMutationError(error) {
122
+ return "type" in error && error.type === "mutationError" && "description" in error && typeof error.description == "string";
45
123
  }
46
- function isActionError(body) {
47
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "actionError" && typeof body.error.description == "string";
124
+ function isActionError(error) {
125
+ return "type" in error && error.type === "actionError" && "description" in error && typeof error.description == "string";
48
126
  }
49
- function isPlainObject(obj) {
50
- return typeof obj == "object" && obj !== null && !Array.isArray(obj);
127
+ function isQueryParseError(error) {
128
+ return isRecord.isRecord(error) && error.type === "queryParseError" && typeof error.query == "string" && typeof error.start == "number" && typeof error.end == "number";
51
129
  }
52
- function httpErrorMessage(res) {
53
- const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
54
- return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;
130
+ function formatQueryParseError(error, tag) {
131
+ const { query, start, end, description } = error;
132
+ if (!query || typeof start > "u")
133
+ return `GROQ query parse error: ${description}`;
134
+ const withTag = tag ? `
135
+
136
+ Tag: ${tag}` : "";
137
+ return `GROQ query parse error:
138
+ ${codeFrame(query, { start, end }, description)}${withTag}`;
139
+ }
140
+ function httpErrorMessage(res, body) {
141
+ const details = typeof body == "string" ? ` (${sliceWithEllipsis(body, 100)})` : "", statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
142
+ return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`;
55
143
  }
56
144
  function stringifyBody(body, res) {
57
145
  return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? JSON.stringify(body, null, 2) : body;
58
146
  }
147
+ function sliceWithEllipsis(str, max) {
148
+ return str.length > max ? `${str.slice(0, max)}\u2026` : str;
149
+ }
59
150
  class CorsOriginError extends Error {
60
151
  projectId;
61
152
  addOriginUrl;
@@ -70,11 +161,11 @@ class CorsOriginError extends Error {
70
161
  }
71
162
  }
72
163
  const httpError = {
73
- onResponse: (res) => {
164
+ onResponse: (res, context) => {
74
165
  if (res.statusCode >= 500)
75
166
  throw new ServerError(res);
76
167
  if (res.statusCode >= 400)
77
- throw new ClientError(res);
168
+ throw new ClientError(res, context);
78
169
  return res;
79
170
  }
80
171
  };
@@ -442,7 +533,9 @@ class ObservableTransaction extends BaseTransaction {
442
533
  }
443
534
  const projectHeader = "X-Sanity-Project-ID";
444
535
  function requestOptions(config2, overrides = {}) {
445
- const headers = {}, token = overrides.token || config2.token;
536
+ const headers = {};
537
+ config2.headers && Object.assign(headers, config2.headers);
538
+ const token = overrides.token || config2.token;
446
539
  token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config2.useProjectHostname && config2.projectId && (headers[projectHeader] = config2.projectId);
447
540
  const withCredentials = !!(typeof overrides.withCredentials > "u" ? config2.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > "u" ? config2.timeout : overrides.timeout;
448
541
  return Object.assign({}, overrides, {
@@ -462,7 +555,7 @@ const encodeQueryString = ({
462
555
  const searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;
463
556
  tag && searchParams.append("tag", tag), searchParams.append("query", query);
464
557
  for (const [key, value] of Object.entries(params))
465
- searchParams.append(`$${key}`, JSON.stringify(value));
558
+ value !== void 0 && searchParams.append(`$${key}`, JSON.stringify(value));
466
559
  for (const [key, value] of Object.entries(opts))
467
560
  value && searchParams.append(key, `${value}`);
468
561
  return returnQuery === !1 && searchParams.append("returnQuery", "false"), includeMutations === !1 && searchParams.append("includeMutations", "false"), `?${searchParams}`;
@@ -478,17 +571,25 @@ function _fetch(config2, httpRequest, _stega, query, _params = {}, options = {})
478
571
  const stega = "stega" in options ? {
479
572
  ..._stega || {},
480
573
  ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
481
- } : _stega, params = stega.enabled ? stegaClean.stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
574
+ } : _stega, params = stega.enabled ? stegaClean.stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, useEmulate, connections, ...opts } = {
482
575
  // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.
483
576
  // This is necessary in React Server Components to avoid opting out of Request Memoization.
484
577
  useAbortSignal: typeof options.signal < "u",
485
578
  // Set `resultSourceMap' when stega is enabled, as it's required for encoding.
486
579
  resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
580
+ // Only use emulate if explicitly asked for
581
+ useEmulate: !1,
582
+ // Having connections is a special case for views
583
+ connections: void 0,
487
584
  ...options,
488
585
  // Default to not returning the query, unless `filterResponse` is `false`,
489
586
  // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy
490
587
  returnQuery: options.filterResponse === !1 && options.returnQuery !== !1
491
- }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(config2, httpRequest, "query", { query, params }, reqOpts);
588
+ }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(config2, httpRequest, useEmulate ? "emulate" : "query", useEmulate ? {
589
+ query,
590
+ params,
591
+ connections
592
+ } : { query, params }, reqOpts);
492
593
  return stega.enabled ? $request.pipe(
493
594
  operators.combineLatestWith(
494
595
  rxjs.from(
@@ -510,8 +611,24 @@ function _fetch(config2, httpRequest, _stega, query, _params = {}, options = {})
510
611
  ) : $request.pipe(operators.map(mapResponse));
511
612
  }
512
613
  function _getDocument(config2, httpRequest, id, opts = {}) {
513
- const options = {
514
- uri: _getDataUrl(config2, "doc", id),
614
+ const docId = (() => {
615
+ if (!opts.releaseId)
616
+ return id;
617
+ const versionId = csm.getVersionFromId(id);
618
+ if (!versionId) {
619
+ if (csm.isDraftId(id))
620
+ throw new Error(
621
+ `The document ID (\`${id}\`) is a draft, but \`options.releaseId\` is set as \`${opts.releaseId}\``
622
+ );
623
+ return csm.getVersionId(id, opts.releaseId);
624
+ }
625
+ if (versionId !== opts.releaseId)
626
+ throw new Error(
627
+ `The document ID (\`${id}\`) is already a version of \`${versionId}\` release, but this does not match the provided \`options.releaseId\` (\`${opts.releaseId}\`)`
628
+ );
629
+ return id;
630
+ })(), options = {
631
+ uri: _getDataUrl(config2, "doc", docId),
515
632
  json: !0,
516
633
  tag: opts.tag,
517
634
  signal: opts.signal
@@ -536,12 +653,33 @@ function _getDocuments(config2, httpRequest, ids, opts = {}) {
536
653
  })
537
654
  );
538
655
  }
656
+ function _getReleaseDocuments(config2, httpRequest, releaseId, opts = {}) {
657
+ return _dataRequest(
658
+ config2,
659
+ httpRequest,
660
+ "query",
661
+ {
662
+ query: "*[sanity::partOfRelease($releaseId)]",
663
+ params: {
664
+ releaseId
665
+ }
666
+ },
667
+ opts
668
+ );
669
+ }
539
670
  function _createIfNotExists(config$1, httpRequest, doc, options) {
540
671
  return config.requireDocumentId("createIfNotExists", doc), _create(config$1, httpRequest, doc, "createIfNotExists", options);
541
672
  }
542
673
  function _createOrReplace(config$1, httpRequest, doc, options) {
543
674
  return config.requireDocumentId("createOrReplace", doc), _create(config$1, httpRequest, doc, "createOrReplace", options);
544
675
  }
676
+ function _createVersion(config$1, httpRequest, doc, publishedId, options) {
677
+ return config.requireDocumentId("createVersion", doc), config.requireDocumentType("createVersion", doc), _action(config$1, httpRequest, {
678
+ actionType: "sanity.action.document.version.create",
679
+ publishedId,
680
+ document: doc
681
+ }, options);
682
+ }
545
683
  function _delete(config2, httpRequest, selection, options) {
546
684
  return _dataRequest(
547
685
  config2,
@@ -551,6 +689,26 @@ function _delete(config2, httpRequest, selection, options) {
551
689
  options
552
690
  );
553
691
  }
692
+ function _discardVersion(config2, httpRequest, versionId, purge = !1, options) {
693
+ return _action(config2, httpRequest, {
694
+ actionType: "sanity.action.document.version.discard",
695
+ versionId,
696
+ purge
697
+ }, options);
698
+ }
699
+ function _replaceVersion(config$1, httpRequest, doc, options) {
700
+ return config.requireDocumentId("replaceVersion", doc), config.requireDocumentType("replaceVersion", doc), _action(config$1, httpRequest, {
701
+ actionType: "sanity.action.document.version.replace",
702
+ document: doc
703
+ }, options);
704
+ }
705
+ function _unpublishVersion(config2, httpRequest, versionId, publishedId, options) {
706
+ return _action(config2, httpRequest, {
707
+ actionType: "sanity.action.document.version.unpublish",
708
+ versionId,
709
+ publishedId
710
+ }, options);
711
+ }
554
712
  function _mutate(config2, httpRequest, mutations, options) {
555
713
  let mut;
556
714
  mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;
@@ -568,7 +726,7 @@ function _action(config2, httpRequest, actions, options) {
568
726
  );
569
727
  }
570
728
  function _dataRequest(config2, httpRequest, endpoint, body, options = {}) {
571
- const isMutation = endpoint === "mutate", isAction = endpoint === "actions", isQuery2 = endpoint === "query", strQuery = isMutation || isAction ? "" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode } = options, uri = _getDataUrl(config2, endpoint, stringQuery), reqOptions = {
729
+ const isMutation = endpoint === "mutate", isAction = endpoint === "actions", isQuery2 = endpoint === "query", isEmulate2 = endpoint === "emulate", strQuery = isMutation || isAction || isEmulate2 ? "" : encodeQueryString(body), useGet = !isMutation && !isAction && !isEmulate2 && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode } = options, uri = _getDataUrl(config2, endpoint, stringQuery), reqOptions = {
572
730
  method: useGet ? "GET" : "POST",
573
731
  uri,
574
732
  json: !0,
@@ -611,12 +769,12 @@ function _create(config2, httpRequest, doc, op, options = {}) {
611
769
  const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);
612
770
  return _dataRequest(config2, httpRequest, "mutate", { mutations: [mutation] }, opts);
613
771
  }
614
- const hasDataConfig = (config2) => config2.dataset !== void 0 && config2.projectId !== void 0 || config2["~experimental_resource"] !== void 0, isQuery = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "query")), isViewQuery = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "views")), isMutate = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "mutate")), isDoc = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "doc", "")), isListener = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "listen")), isHistory = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "history", "")), isData = (config2, uri) => uri.startsWith("/data/") || isQuery(config2, uri) || isMutate(config2, uri) || isDoc(config2, uri) || isListener(config2, uri) || isHistory(config2, uri) || isViewQuery(config2, uri);
772
+ const hasDataConfig = (config2) => config2.dataset !== void 0 && config2.projectId !== void 0 || config2["~experimental_resource"] !== void 0, isQuery = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "query")), isViewQuery = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "views")), isEmulate = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "emulate")), isMutate = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "mutate")), isDoc = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "doc", "")), isListener = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "listen")), isHistory = (config2, uri) => hasDataConfig(config2) && uri.startsWith(_getDataUrl(config2, "history", "")), isData = (config2, uri) => uri.startsWith("/data/") || isQuery(config2, uri) || isMutate(config2, uri) || isDoc(config2, uri) || isListener(config2, uri) || isHistory(config2, uri) || isViewQuery(config2, uri) || isEmulate(config2, uri);
615
773
  function _requestObservable(config$1, httpRequest, options) {
616
774
  const uri = options.url || options.uri, canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(config$1, uri) : options.canUseCdn;
617
775
  let useCdn = (options.useCdn ?? config$1.useCdn) && canUseCdn;
618
776
  const tag = options.tag && config$1.requestTagPrefix ? [config$1.requestTagPrefix, options.tag].join(".") : options.tag || config$1.requestTagPrefix;
619
- if (tag && options.tag !== null && (options.query = { tag: config.requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && isQuery(config$1, uri)) {
777
+ if (tag && options.tag !== null && (options.query = { tag: config.requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && (isQuery(config$1, uri) || isEmulate(config$1, uri))) {
620
778
  const resultSourceMap = options.resultSourceMap ?? config$1.resultSourceMap;
621
779
  resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
622
780
  const perspectiveOption = options.perspective || config$1.perspective;
@@ -651,7 +809,7 @@ function _getDataUrl(config$1, operation, path) {
651
809
  const catalog = config.hasDataset(config$1), baseUri = `/${operation}/${catalog}`;
652
810
  return `/data${path !== void 0 ? `${baseUri}/${path}` : baseUri}`.replace(/\/($|\?)/, "$1");
653
811
  }
654
- function _getUrl(config2, uri, canUseCdn = !1, options = {}) {
812
+ function _getUrl(config2, uri, canUseCdn = !1) {
655
813
  const { url, cdnUrl } = config2;
656
814
  return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
657
815
  }
@@ -711,16 +869,23 @@ exports._action = _action;
711
869
  exports._create = _create;
712
870
  exports._createIfNotExists = _createIfNotExists;
713
871
  exports._createOrReplace = _createOrReplace;
872
+ exports._createVersion = _createVersion;
714
873
  exports._dataRequest = _dataRequest;
715
874
  exports._delete = _delete;
875
+ exports._discardVersion = _discardVersion;
716
876
  exports._fetch = _fetch;
717
877
  exports._getDataUrl = _getDataUrl;
718
878
  exports._getDocument = _getDocument;
719
879
  exports._getDocuments = _getDocuments;
880
+ exports._getReleaseDocuments = _getReleaseDocuments;
720
881
  exports._getUrl = _getUrl;
721
882
  exports._mutate = _mutate;
883
+ exports._replaceVersion = _replaceVersion;
722
884
  exports._request = _request;
723
885
  exports._requestObservable = _requestObservable;
886
+ exports._unpublishVersion = _unpublishVersion;
724
887
  exports.defineHttpRequest = defineHttpRequest;
725
888
  exports.encodeQueryString = encodeQueryString;
889
+ exports.formatQueryParseError = formatQueryParseError;
890
+ exports.isQueryParseError = isQueryParseError;
726
891
  //# sourceMappingURL=dataMethods.cjs.map