@sanity/client 7.1.0-views.0 → 7.1.0-views.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +810 -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 +1950 -149
  29. package/dist/index.browser.d.ts +1950 -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 +1950 -149
  35. package/dist/index.d.ts +1950 -149
  36. package/dist/index.js +826 -31
  37. package/dist/index.js.map +1 -1
  38. package/dist/stega.browser.d.cts +1950 -149
  39. package/dist/stega.browser.d.ts +1950 -149
  40. package/dist/stega.d.cts +1950 -149
  41. package/dist/stega.d.ts +1950 -149
  42. package/dist/views.cjs +21 -5
  43. package/dist/views.cjs.map +1 -1
  44. package/dist/views.d.cts +54 -36
  45. package/dist/views.d.ts +54 -36
  46. package/dist/views.js +22 -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 +293 -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 +65 -15
  79. package/umd/sanityClient.js +1067 -61
  80. package/umd/sanityClient.min.js +2 -2
@@ -1495,6 +1495,24 @@
1495
1495
  });
1496
1496
  }
1497
1497
 
1498
+ function firstValueFrom(source, config) {
1499
+ return new Promise(function (resolve, reject) {
1500
+ var subscriber = new SafeSubscriber({
1501
+ next: function (value) {
1502
+ resolve(value);
1503
+ subscriber.unsubscribe();
1504
+ },
1505
+ error: reject,
1506
+ complete: function () {
1507
+ {
1508
+ reject(new EmptyError());
1509
+ }
1510
+ },
1511
+ });
1512
+ source.subscribe(subscriber);
1513
+ });
1514
+ }
1515
+
1498
1516
  function isValidDate$1(value) {
1499
1517
  return value instanceof Date && !isNaN(value);
1500
1518
  }
@@ -1875,6 +1893,9 @@
1875
1893
  identity;
1876
1894
  }
1877
1895
 
1896
+ function isRecord(value) {
1897
+ return typeof value == "object" && value !== null && !Array.isArray(value);
1898
+ }
1878
1899
  var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }, u = new Array(4).fill(String.fromCodePoint(c[0])).join("");
1879
1900
  function E(t) {
1880
1901
  let e = JSON.stringify(t);
@@ -1912,13 +1933,110 @@
1912
1933
  return O(result);
1913
1934
  }
1914
1935
 
1936
+ const DRAFTS_FOLDER$1 = "drafts", VERSION_FOLDER$1 = "versions", PATH_SEPARATOR$1 = ".", DRAFTS_PREFIX$1 = `${DRAFTS_FOLDER$1}${PATH_SEPARATOR$1}`, VERSION_PREFIX$1 = `${VERSION_FOLDER$1}${PATH_SEPARATOR$1}`;
1937
+ function isDraftId$1(id) {
1938
+ return id.startsWith(DRAFTS_PREFIX$1);
1939
+ }
1940
+ function isVersionId$1(id) {
1941
+ return id.startsWith(VERSION_PREFIX$1);
1942
+ }
1943
+ function getDraftId(id) {
1944
+ if (isVersionId$1(id)) {
1945
+ const publishedId = getPublishedId$1(id);
1946
+ return DRAFTS_PREFIX$1 + publishedId;
1947
+ }
1948
+ return isDraftId$1(id) ? id : DRAFTS_PREFIX$1 + id;
1949
+ }
1950
+ function getVersionId(id, version) {
1951
+ if (version === "drafts" || version === "published")
1952
+ throw new Error('Version can not be "published" or "drafts"');
1953
+ return `${VERSION_PREFIX$1}${version}${PATH_SEPARATOR$1}${getPublishedId$1(id)}`;
1954
+ }
1955
+ function getVersionFromId$1(id) {
1956
+ if (!isVersionId$1(id)) return;
1957
+ const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR$1);
1958
+ return versionId;
1959
+ }
1960
+ function getPublishedId$1(id) {
1961
+ return isVersionId$1(id) ? id.split(PATH_SEPARATOR$1).slice(2).join(PATH_SEPARATOR$1) : isDraftId$1(id) ? id.slice(DRAFTS_PREFIX$1.length) : id;
1962
+ }
1963
+
1964
+ const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
1965
+ function codeFrame(query, location2, message) {
1966
+ const lines = query.split(NEWLINE), loc = {
1967
+ start: columnToLine(location2.start, lines),
1968
+ end: location2.end ? columnToLine(location2.end, lines) : void 0
1969
+ }, { start, end, markerLines } = getMarkerLines(loc, lines), numberMaxWidth = `${end}`.length;
1970
+ return query.split(NEWLINE, end).slice(start, end).map((line, index) => {
1971
+ const number = start + 1 + index, gutter = ` ${` ${number}`.slice(-numberMaxWidth)} |`, hasMarker = markerLines[number], lastMarkerLine = !markerLines[number + 1];
1972
+ if (!hasMarker)
1973
+ return ` ${gutter}${line.length > 0 ? ` ${line}` : ""}`;
1974
+ let markerLine = "";
1975
+ if (Array.isArray(hasMarker)) {
1976
+ const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "), numberOfMarkers = hasMarker[1] || 1;
1977
+ markerLine = [
1978
+ `
1979
+ `,
1980
+ gutter.replace(/\d/g, " "),
1981
+ " ",
1982
+ markerSpacing,
1983
+ "^".repeat(numberOfMarkers)
1984
+ ].join(""), lastMarkerLine && message && (markerLine += " " + message);
1985
+ }
1986
+ return [">", gutter, line.length > 0 ? ` ${line}` : "", markerLine].join("");
1987
+ }).join(`
1988
+ `);
1989
+ }
1990
+ function getMarkerLines(loc, source) {
1991
+ 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;
1992
+ let start = Math.max(startLine - (linesAbove + 1), 0), end = Math.min(source.length, endLine + linesBelow);
1993
+ startLine === -1 && (start = 0), endLine === -1 && (end = source.length);
1994
+ const lineDiff = endLine - startLine, markerLines = {};
1995
+ if (lineDiff)
1996
+ for (let i = 0; i <= lineDiff; i++) {
1997
+ const lineNumber = i + startLine;
1998
+ if (!startColumn)
1999
+ markerLines[lineNumber] = true;
2000
+ else if (i === 0) {
2001
+ const sourceLength = source[lineNumber - 1].length;
2002
+ markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
2003
+ } else if (i === lineDiff)
2004
+ markerLines[lineNumber] = [0, endColumn];
2005
+ else {
2006
+ const sourceLength = source[lineNumber - i].length;
2007
+ markerLines[lineNumber] = [0, sourceLength];
2008
+ }
2009
+ }
2010
+ else
2011
+ startColumn === endColumn ? startColumn ? markerLines[startLine] = [startColumn, 0] : markerLines[startLine] = true : markerLines[startLine] = [startColumn, endColumn - startColumn];
2012
+ return { start, end, markerLines };
2013
+ }
2014
+ function columnToLine(column, lines) {
2015
+ let offset = 0;
2016
+ for (let i = 0; i < lines.length; i++) {
2017
+ const lineLength = lines[i].length + 1;
2018
+ if (offset + lineLength > column)
2019
+ return {
2020
+ line: i + 1,
2021
+ // 1-based line
2022
+ column: column - offset
2023
+ // 0-based column
2024
+ };
2025
+ offset += lineLength;
2026
+ }
2027
+ return {
2028
+ line: lines.length,
2029
+ column: lines[lines.length - 1]?.length ?? 0
2030
+ };
2031
+ }
2032
+ const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
1915
2033
  class ClientError extends Error {
1916
2034
  response;
1917
2035
  statusCode = 400;
1918
2036
  responseBody;
1919
2037
  details;
1920
- constructor(res) {
1921
- const props = extractErrorProps(res);
2038
+ constructor(res, context) {
2039
+ const props = extractErrorProps(res, context);
1922
2040
  super(props.message), Object.assign(this, props);
1923
2041
  }
1924
2042
  }
@@ -1932,7 +2050,7 @@
1932
2050
  super(props.message), Object.assign(this, props);
1933
2051
  }
1934
2052
  }
1935
- function extractErrorProps(res) {
2053
+ function extractErrorProps(res, context) {
1936
2054
  const body = res.body, props = {
1937
2055
  response: res,
1938
2056
  statusCode: res.statusCode,
@@ -1940,34 +2058,56 @@
1940
2058
  message: "",
1941
2059
  details: void 0
1942
2060
  };
1943
- if (body.error && body.message)
1944
- return props.message = `${body.error} - ${body.message}`, props;
1945
- if (isMutationError(body) || isActionError(body)) {
1946
- const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => item.error?.description).filter(Boolean);
2061
+ if (!isRecord(body))
2062
+ return props.message = httpErrorMessage(res, body), props;
2063
+ const error = body.error;
2064
+ if (typeof error == "string" && typeof body.message == "string")
2065
+ return props.message = `${error} - ${body.message}`, props;
2066
+ if (typeof error != "object" || error === null)
2067
+ return typeof error == "string" ? props.message = error : typeof body.message == "string" ? props.message = body.message : props.message = httpErrorMessage(res, body), props;
2068
+ if (isMutationError(error) || isActionError(error)) {
2069
+ const allItems = error.items || [], items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map((item) => item.error?.description).filter(Boolean);
1947
2070
  let itemsStr = items.length ? `:
1948
2071
  - ${items.join(`
1949
2072
  - `)}` : "";
1950
- return allItems.length > 5 && (itemsStr += `
1951
- ...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;
2073
+ return allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE && (itemsStr += `
2074
+ ...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`), props.message = `${error.description}${itemsStr}`, props.details = body.error, props;
2075
+ }
2076
+ if (isQueryParseError(error)) {
2077
+ const tag = context?.options?.query?.tag;
2078
+ return props.message = formatQueryParseError(error, tag), props.details = body.error, props;
1952
2079
  }
1953
- 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);
2080
+ return "description" in error && typeof error.description == "string" ? (props.message = error.description, props.details = error, props) : (props.message = httpErrorMessage(res, body), props);
1954
2081
  }
1955
- function isMutationError(body) {
1956
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description == "string";
2082
+ function isMutationError(error) {
2083
+ return "type" in error && error.type === "mutationError" && "description" in error && typeof error.description == "string";
1957
2084
  }
1958
- function isActionError(body) {
1959
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "actionError" && typeof body.error.description == "string";
2085
+ function isActionError(error) {
2086
+ return "type" in error && error.type === "actionError" && "description" in error && typeof error.description == "string";
1960
2087
  }
1961
- function isPlainObject(obj) {
1962
- return typeof obj == "object" && obj !== null && !Array.isArray(obj);
2088
+ function isQueryParseError(error) {
2089
+ return isRecord(error) && error.type === "queryParseError" && typeof error.query == "string" && typeof error.start == "number" && typeof error.end == "number";
1963
2090
  }
1964
- function httpErrorMessage(res) {
1965
- const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
1966
- return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;
2091
+ function formatQueryParseError(error, tag) {
2092
+ const { query, start, end, description } = error;
2093
+ if (!query || typeof start > "u")
2094
+ return `GROQ query parse error: ${description}`;
2095
+ const withTag = tag ? `
2096
+
2097
+ Tag: ${tag}` : "";
2098
+ return `GROQ query parse error:
2099
+ ${codeFrame(query, { start, end }, description)}${withTag}`;
2100
+ }
2101
+ function httpErrorMessage(res, body) {
2102
+ const details = typeof body == "string" ? ` (${sliceWithEllipsis(body, 100)})` : "", statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
2103
+ return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`;
1967
2104
  }
1968
2105
  function stringifyBody(body, res) {
1969
2106
  return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? JSON.stringify(body, null, 2) : body;
1970
2107
  }
2108
+ function sliceWithEllipsis(str, max) {
2109
+ return str.length > max ? `${str.slice(0, max)}\u2026` : str;
2110
+ }
1971
2111
  class CorsOriginError extends Error {
1972
2112
  projectId;
1973
2113
  addOriginUrl;
@@ -1982,11 +2122,11 @@
1982
2122
  }
1983
2123
  }
1984
2124
  const httpError = {
1985
- onResponse: (res) => {
2125
+ onResponse: (res, context) => {
1986
2126
  if (res.statusCode >= 500)
1987
2127
  throw new ServerError(res);
1988
2128
  if (res.statusCode >= 400)
1989
- throw new ClientError(res);
2129
+ throw new ClientError(res, context);
1990
2130
  return res;
1991
2131
  }
1992
2132
  };
@@ -2043,6 +2183,18 @@
2043
2183
  if (!doc._id)
2044
2184
  throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
2045
2185
  validateDocumentId(op, doc._id);
2186
+ }, validateDocumentType = (op, type) => {
2187
+ if (typeof type != "string")
2188
+ throw new Error(`\`${op}()\`: \`${type}\` is not a valid document type`);
2189
+ }, requireDocumentType = (op, doc) => {
2190
+ if (!doc._type)
2191
+ throw new Error(`\`${op}()\` requires that the document contains a type (\`_type\` property)`);
2192
+ validateDocumentType(op, doc._type);
2193
+ }, validateVersionIdMatch = (builtVersionId, document) => {
2194
+ if (document._id && document._id !== builtVersionId)
2195
+ throw new Error(
2196
+ `The provided document ID (\`${document._id}\`) does not match the generated version ID (\`${builtVersionId}\`)`
2197
+ );
2046
2198
  }, validateInsert = (at, selector, items) => {
2047
2199
  const signature = "insert(at, selector, items)";
2048
2200
  if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
@@ -2085,6 +2237,7 @@
2085
2237
  if (config["~experimental_resource"])
2086
2238
  throw new Error(`\`${service}\` does not support resource-based operations`);
2087
2239
  };
2240
+ var ViewResourceType = /* @__PURE__ */ ((ViewResourceType2) => (ViewResourceType2.Dataset = "dataset", ViewResourceType2.View = "view", ViewResourceType2))(ViewResourceType || {});
2088
2241
  function once(fn) {
2089
2242
  let didCall = false, returnValue;
2090
2243
  return (...args) => (didCall || (returnValue = fn(...args), didCall = true), returnValue);
@@ -2236,7 +2389,8 @@
2236
2389
  return;
2237
2390
  }
2238
2391
  if (message.type === "channelError") {
2239
- observer.error(new ChannelError(extractErrorMessage(event?.data), event.data));
2392
+ const tag = new URL(es.url).searchParams.get("tag");
2393
+ observer.error(new ChannelError(extractErrorMessage(event?.data, tag), event.data));
2240
2394
  return;
2241
2395
  }
2242
2396
  if (message.type === "disconnect") {
@@ -2275,8 +2429,9 @@
2275
2429
  return [err, null];
2276
2430
  }
2277
2431
  }
2278
- function extractErrorMessage(err) {
2279
- return err.error ? err.error.description ? err.error.description : typeof err.error == "string" ? err.error : JSON.stringify(err.error, null, 2) : err.message || "Unknown listener error";
2432
+ function extractErrorMessage(err, tag) {
2433
+ const error = err.error;
2434
+ return error ? isQueryParseError(error) ? formatQueryParseError(error, tag) : error.description ? error.description : typeof error == "string" ? error : JSON.stringify(error, null, 2) : err.message || "Unknown listener error";
2280
2435
  }
2281
2436
  function isEmptyObject(data) {
2282
2437
  for (const _ in data)
@@ -2619,7 +2774,9 @@ ${selectionOpts}`);
2619
2774
  }
2620
2775
  const projectHeader = "X-Sanity-Project-ID";
2621
2776
  function requestOptions(config, overrides = {}) {
2622
- const headers = {}, token = overrides.token || config.token;
2777
+ const headers = {};
2778
+ config.headers && Object.assign(headers, config.headers);
2779
+ const token = overrides.token || config.token;
2623
2780
  token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers[projectHeader] = config.projectId);
2624
2781
  const withCredentials = !!(typeof overrides.withCredentials > "u" ? config.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > "u" ? config.timeout : overrides.timeout;
2625
2782
  return Object.assign({}, overrides, {
@@ -2639,7 +2796,7 @@ ${selectionOpts}`);
2639
2796
  const searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;
2640
2797
  tag && searchParams.append("tag", tag), searchParams.append("query", query);
2641
2798
  for (const [key, value] of Object.entries(params))
2642
- searchParams.append(`$${key}`, JSON.stringify(value));
2799
+ value !== void 0 && searchParams.append(`$${key}`, JSON.stringify(value));
2643
2800
  for (const [key, value] of Object.entries(opts))
2644
2801
  value && searchParams.append(key, `${value}`);
2645
2802
  return returnQuery === false && searchParams.append("returnQuery", "false"), includeMutations === false && searchParams.append("includeMutations", "false"), `?${searchParams}`;
@@ -2655,17 +2812,25 @@ ${selectionOpts}`);
2655
2812
  const stega = "stega" in options ? {
2656
2813
  ..._stega || {},
2657
2814
  ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
2658
- } : _stega, params = stega.enabled ? stegaClean(_params) : _params, mapResponse = options.filterResponse === false ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
2815
+ } : _stega, params = stega.enabled ? stegaClean(_params) : _params, mapResponse = options.filterResponse === false ? (res) => res : (res) => res.result, { cache, next, useEmulate, connections, ...opts } = {
2659
2816
  // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.
2660
2817
  // This is necessary in React Server Components to avoid opting out of Request Memoization.
2661
2818
  useAbortSignal: typeof options.signal < "u",
2662
2819
  // Set `resultSourceMap' when stega is enabled, as it's required for encoding.
2663
2820
  resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
2821
+ // Only use emulate if explicitly asked for
2822
+ useEmulate: false,
2823
+ // Having connections is a special case for views
2824
+ connections: void 0,
2664
2825
  ...options,
2665
2826
  // Default to not returning the query, unless `filterResponse` is `false`,
2666
2827
  // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy
2667
2828
  returnQuery: options.filterResponse === false && options.returnQuery !== false
2668
- }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(config, httpRequest, "query", { query, params }, reqOpts);
2829
+ }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(config, httpRequest, useEmulate ? "emulate" : "query", useEmulate ? {
2830
+ query,
2831
+ params,
2832
+ connections
2833
+ } : { query, params }, reqOpts);
2669
2834
  return stega.enabled ? $request.pipe(
2670
2835
  combineLatestWith(
2671
2836
  from(
@@ -2685,8 +2850,24 @@ ${selectionOpts}`);
2685
2850
  ) : $request.pipe(map(mapResponse));
2686
2851
  }
2687
2852
  function _getDocument(config, httpRequest, id, opts = {}) {
2688
- const options = {
2689
- uri: _getDataUrl(config, "doc", id),
2853
+ const docId = (() => {
2854
+ if (!opts.releaseId)
2855
+ return id;
2856
+ const versionId = getVersionFromId$1(id);
2857
+ if (!versionId) {
2858
+ if (isDraftId$1(id))
2859
+ throw new Error(
2860
+ `The document ID (\`${id}\`) is a draft, but \`options.releaseId\` is set as \`${opts.releaseId}\``
2861
+ );
2862
+ return getVersionId(id, opts.releaseId);
2863
+ }
2864
+ if (versionId !== opts.releaseId)
2865
+ throw new Error(
2866
+ `The document ID (\`${id}\`) is already a version of \`${versionId}\` release, but this does not match the provided \`options.releaseId\` (\`${opts.releaseId}\`)`
2867
+ );
2868
+ return id;
2869
+ })(), options = {
2870
+ uri: _getDataUrl(config, "doc", docId),
2690
2871
  json: true,
2691
2872
  tag: opts.tag,
2692
2873
  signal: opts.signal
@@ -2711,12 +2892,33 @@ ${selectionOpts}`);
2711
2892
  })
2712
2893
  );
2713
2894
  }
2895
+ function _getReleaseDocuments(config, httpRequest, releaseId, opts = {}) {
2896
+ return _dataRequest(
2897
+ config,
2898
+ httpRequest,
2899
+ "query",
2900
+ {
2901
+ query: "*[sanity::partOfRelease($releaseId)]",
2902
+ params: {
2903
+ releaseId
2904
+ }
2905
+ },
2906
+ opts
2907
+ );
2908
+ }
2714
2909
  function _createIfNotExists(config, httpRequest, doc, options) {
2715
2910
  return requireDocumentId("createIfNotExists", doc), _create(config, httpRequest, doc, "createIfNotExists", options);
2716
2911
  }
2717
2912
  function _createOrReplace(config, httpRequest, doc, options) {
2718
2913
  return requireDocumentId("createOrReplace", doc), _create(config, httpRequest, doc, "createOrReplace", options);
2719
2914
  }
2915
+ function _createVersion(config, httpRequest, doc, publishedId, options) {
2916
+ return requireDocumentId("createVersion", doc), requireDocumentType("createVersion", doc), _action(config, httpRequest, {
2917
+ actionType: "sanity.action.document.version.create",
2918
+ publishedId,
2919
+ document: doc
2920
+ }, options);
2921
+ }
2720
2922
  function _delete(config, httpRequest, selection, options) {
2721
2923
  return _dataRequest(
2722
2924
  config,
@@ -2726,6 +2928,26 @@ ${selectionOpts}`);
2726
2928
  options
2727
2929
  );
2728
2930
  }
2931
+ function _discardVersion(config, httpRequest, versionId, purge = false, options) {
2932
+ return _action(config, httpRequest, {
2933
+ actionType: "sanity.action.document.version.discard",
2934
+ versionId,
2935
+ purge
2936
+ }, options);
2937
+ }
2938
+ function _replaceVersion(config, httpRequest, doc, options) {
2939
+ return requireDocumentId("replaceVersion", doc), requireDocumentType("replaceVersion", doc), _action(config, httpRequest, {
2940
+ actionType: "sanity.action.document.version.replace",
2941
+ document: doc
2942
+ }, options);
2943
+ }
2944
+ function _unpublishVersion(config, httpRequest, versionId, publishedId, options) {
2945
+ return _action(config, httpRequest, {
2946
+ actionType: "sanity.action.document.version.unpublish",
2947
+ versionId,
2948
+ publishedId
2949
+ }, options);
2950
+ }
2729
2951
  function _mutate(config, httpRequest, mutations, options) {
2730
2952
  let mut;
2731
2953
  mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;
@@ -2743,7 +2965,7 @@ ${selectionOpts}`);
2743
2965
  );
2744
2966
  }
2745
2967
  function _dataRequest(config, httpRequest, endpoint, body, options = {}) {
2746
- 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(config, endpoint, stringQuery), reqOptions = {
2968
+ 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(config, endpoint, stringQuery), reqOptions = {
2747
2969
  method: useGet ? "GET" : "POST",
2748
2970
  uri,
2749
2971
  json: true,
@@ -2786,12 +3008,12 @@ ${selectionOpts}`);
2786
3008
  const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: true, returnDocuments: true }, options);
2787
3009
  return _dataRequest(config, httpRequest, "mutate", { mutations: [mutation] }, opts);
2788
3010
  }
2789
- const hasDataConfig = (config) => config.dataset !== void 0 && config.projectId !== void 0 || config["~experimental_resource"] !== void 0, isQuery = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "query")), isViewQuery = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "views")), isMutate = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "mutate")), isDoc = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "doc", "")), isListener = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "listen")), isHistory = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "history", "")), isData = (config, uri) => uri.startsWith("/data/") || isQuery(config, uri) || isMutate(config, uri) || isDoc(config, uri) || isListener(config, uri) || isHistory(config, uri) || isViewQuery(config, uri);
3011
+ const hasDataConfig = (config) => config.dataset !== void 0 && config.projectId !== void 0 || config["~experimental_resource"] !== void 0, isQuery = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "query")), isViewQuery = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "views")), isEmulate = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "emulate")), isMutate = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "mutate")), isDoc = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "doc", "")), isListener = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "listen")), isHistory = (config, uri) => hasDataConfig(config) && uri.startsWith(_getDataUrl(config, "history", "")), isData = (config, uri) => uri.startsWith("/data/") || isQuery(config, uri) || isMutate(config, uri) || isDoc(config, uri) || isListener(config, uri) || isHistory(config, uri) || isViewQuery(config, uri) || isEmulate(config, uri);
2790
3012
  function _requestObservable(config, httpRequest, options) {
2791
3013
  const uri = options.url || options.uri, canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(config, uri) : options.canUseCdn;
2792
3014
  let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn;
2793
3015
  const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
2794
- if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && isQuery(config, uri)) {
3016
+ if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && (isQuery(config, uri) || isEmulate(config, uri))) {
2795
3017
  const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;
2796
3018
  resultSourceMap !== void 0 && resultSourceMap !== false && (options.query = { resultSourceMap, ...options.query });
2797
3019
  const perspectiveOption = options.perspective || config.perspective;
@@ -2826,7 +3048,7 @@ ${selectionOpts}`);
2826
3048
  const catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;
2827
3049
  return `/data${path !== void 0 ? `${baseUri}/${path}` : baseUri}`.replace(/\/($|\?)/, "$1");
2828
3050
  }
2829
- function _getUrl(config, uri, canUseCdn = false, options = {}) {
3051
+ function _getUrl(config, uri, canUseCdn = false) {
2830
3052
  const { url, cdnUrl } = config;
2831
3053
  return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
2832
3054
  }
@@ -2881,6 +3103,22 @@ ${selectionOpts}`);
2881
3103
  body: request
2882
3104
  });
2883
3105
  }
3106
+ function _patch(client, httpRequest, request) {
3107
+ const dataset2 = hasDataset(client.config());
3108
+ return _request(client.config(), httpRequest, {
3109
+ method: "POST",
3110
+ uri: `/agent/action/patch/${dataset2}`,
3111
+ body: request
3112
+ });
3113
+ }
3114
+ function _prompt(client, httpRequest, request) {
3115
+ const dataset2 = hasDataset(client.config());
3116
+ return _request(client.config(), httpRequest, {
3117
+ method: "POST",
3118
+ uri: `/agent/action/prompt/${dataset2}`,
3119
+ body: request
3120
+ });
3121
+ }
2884
3122
  function _transform(client, httpRequest, request) {
2885
3123
  const dataset2 = hasDataset(client.config());
2886
3124
  return _request(client.config(), httpRequest, {
@@ -2952,6 +3190,21 @@ ${selectionOpts}`);
2952
3190
  translate(request) {
2953
3191
  return lastValueFrom(_translate(this.#client, this.#httpRequest, request));
2954
3192
  }
3193
+ /**
3194
+ * Run a raw instruction and return the result either as text or json
3195
+ * @param request - prompt request
3196
+ */
3197
+ prompt(request) {
3198
+ return lastValueFrom(_prompt(this.#client, this.#httpRequest, request));
3199
+ }
3200
+ /**
3201
+ * Patch a document using a schema aware API.
3202
+ * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.
3203
+ * @param request - instruction request
3204
+ */
3205
+ patch(request) {
3206
+ return lastValueFrom(_patch(this.#client, this.#httpRequest, request));
3207
+ }
2955
3208
  }
2956
3209
  class ObservableAssetsClient {
2957
3210
  #client;
@@ -3060,13 +3313,11 @@ ${selectionOpts}`);
3060
3313
  includeResult: true
3061
3314
  };
3062
3315
  function _listen(query, params, opts = {}) {
3063
- const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this.config(), "listen", qs)}`;
3316
+ const { url, token, withCredentials, requestTagPrefix, headers: configHeaders } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this.config(), "listen", qs)}`;
3064
3317
  if (uri.length > MAX_URL_LENGTH)
3065
3318
  return throwError(() => new Error("Query too large for listener"));
3066
3319
  const listenFor = options.events ? options.events : ["mutation"], esOptions = {};
3067
- return withCredentials && (esOptions.withCredentials = true), token && (esOptions.headers = {
3068
- Authorization: `Bearer ${token}`
3069
- }), connectEventSource(() => (
3320
+ return withCredentials && (esOptions.withCredentials = true), (token || configHeaders) && (esOptions.headers = {}, token && (esOptions.headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(esOptions.headers, configHeaders)), connectEventSource(() => (
3070
3321
  // use polyfill if there is no global EventSource or if we need to set headers
3071
3322
  (typeof EventSource > "u" || esOptions.headers ? eventSourcePolyfill : of(EventSource)).pipe(map((EventSource2) => new EventSource2(uri, esOptions)))
3072
3323
  ), listenFor).pipe(
@@ -3124,7 +3375,8 @@ ${selectionOpts}`);
3124
3375
  apiVersion: _apiVersion,
3125
3376
  token,
3126
3377
  withCredentials,
3127
- requestTagPrefix
3378
+ requestTagPrefix,
3379
+ headers: configHeaders
3128
3380
  } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, "");
3129
3381
  if (apiVersion !== "X" && apiVersion < requiredApiVersion)
3130
3382
  throw new Error(
@@ -3137,9 +3389,7 @@ ${selectionOpts}`);
3137
3389
  const path = _getDataUrl(this.#client.config(), "live/events"), url = new URL(this.#client.getUrl(path, false)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(".") : _tag;
3138
3390
  tag && url.searchParams.set("tag", tag), includeDrafts && url.searchParams.set("includeDrafts", "true");
3139
3391
  const esOptions = {};
3140
- includeDrafts && token && (esOptions.headers = {
3141
- Authorization: `Bearer ${token}`
3142
- }), includeDrafts && withCredentials && (esOptions.withCredentials = true);
3392
+ includeDrafts && withCredentials && (esOptions.withCredentials = true), (includeDrafts && token || configHeaders) && (esOptions.headers = {}, includeDrafts && token && (esOptions.headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(esOptions.headers, configHeaders));
3143
3393
  const key = `${url.href}::${JSON.stringify(esOptions)}`, existing = eventsCache.get(key);
3144
3394
  if (existing)
3145
3395
  return existing;
@@ -3277,7 +3527,10 @@ ${selectionOpts}`);
3277
3527
  */
3278
3528
  list() {
3279
3529
  return resourceGuard("dataset", this.#client.config()), lastValueFrom(
3280
- _request(this.#client.config(), this.#httpRequest, { uri: "/datasets", tag: null })
3530
+ _request(this.#client.config(), this.#httpRequest, {
3531
+ uri: "/datasets",
3532
+ tag: null
3533
+ })
3281
3534
  );
3282
3535
  }
3283
3536
  }
@@ -3306,7 +3559,9 @@ ${selectionOpts}`);
3306
3559
  * @param projectId - ID of the project to fetch
3307
3560
  */
3308
3561
  getById(projectId2) {
3309
- return resourceGuard("projects", this.#client.config()), _request(this.#client.config(), this.#httpRequest, { uri: `/projects/${projectId2}` });
3562
+ return resourceGuard("projects", this.#client.config()), _request(this.#client.config(), this.#httpRequest, {
3563
+ uri: `/projects/${projectId2}`
3564
+ });
3310
3565
  }
3311
3566
  }
3312
3567
  class ProjectsClient {
@@ -3327,7 +3582,518 @@ ${selectionOpts}`);
3327
3582
  */
3328
3583
  getById(projectId2) {
3329
3584
  return resourceGuard("projects", this.#client.config()), lastValueFrom(
3330
- _request(this.#client.config(), this.#httpRequest, { uri: `/projects/${projectId2}` })
3585
+ _request(this.#client.config(), this.#httpRequest, {
3586
+ uri: `/projects/${projectId2}`
3587
+ })
3588
+ );
3589
+ }
3590
+ }
3591
+ let random = (bytes) => crypto.getRandomValues(new Uint8Array(bytes)), customRandom = (alphabet, defaultSize, getRandom) => {
3592
+ let mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 1, step = -~(1.6 * mask * defaultSize / alphabet.length);
3593
+ return (size = defaultSize) => {
3594
+ let id = "";
3595
+ for (; ; ) {
3596
+ let bytes = getRandom(step), j = step | 0;
3597
+ for (; j--; )
3598
+ if (id += alphabet[bytes[j] & mask] || "", id.length === size) return id;
3599
+ }
3600
+ };
3601
+ }, customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size, random);
3602
+ const generateReleaseId = customAlphabet(
3603
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
3604
+ 8
3605
+ ), getDocumentVersionId = (publishedId, releaseId) => releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId);
3606
+ function deriveDocumentVersionId(op, {
3607
+ releaseId,
3608
+ publishedId,
3609
+ document
3610
+ }) {
3611
+ if (publishedId && document._id) {
3612
+ const versionId = getDocumentVersionId(publishedId, releaseId);
3613
+ return validateVersionIdMatch(versionId, document), versionId;
3614
+ }
3615
+ if (document._id) {
3616
+ const isDraft = isDraftId$1(document._id), isVersion = isVersionId$1(document._id);
3617
+ if (!isDraft && !isVersion)
3618
+ throw new Error(
3619
+ `\`${op}()\` requires a document with an \`_id\` that is a version or draft ID`
3620
+ );
3621
+ if (releaseId) {
3622
+ if (isDraft)
3623
+ throw new Error(
3624
+ `\`${op}()\` was called with a document ID (\`${document._id}\`) that is a draft ID, but a release ID (\`${releaseId}\`) was also provided.`
3625
+ );
3626
+ const builtVersionId = getVersionFromId$1(document._id);
3627
+ if (builtVersionId !== releaseId)
3628
+ throw new Error(
3629
+ `\`${op}()\` was called with a document ID (\`${document._id}\`) that is a version ID, but the release ID (\`${releaseId}\`) does not match the document's version ID (\`${builtVersionId}\`).`
3630
+ );
3631
+ }
3632
+ return document._id;
3633
+ }
3634
+ if (publishedId)
3635
+ return getDocumentVersionId(publishedId, releaseId);
3636
+ throw new Error(`\`${op}()\` requires either a publishedId or a document with an \`_id\``);
3637
+ }
3638
+ const getArgs = (releaseOrOptions, maybeOptions) => {
3639
+ if (typeof releaseOrOptions == "object" && releaseOrOptions !== null && ("releaseId" in releaseOrOptions || "metadata" in releaseOrOptions)) {
3640
+ const { releaseId = generateReleaseId(), metadata = {} } = releaseOrOptions;
3641
+ return [releaseId, metadata, maybeOptions];
3642
+ }
3643
+ return [generateReleaseId(), {}, releaseOrOptions];
3644
+ }, createRelease = (releaseOrOptions, maybeOptions) => {
3645
+ const [releaseId, metadata, options] = getArgs(releaseOrOptions, maybeOptions), finalMetadata = {
3646
+ ...metadata,
3647
+ releaseType: metadata.releaseType || "undecided"
3648
+ };
3649
+ return { action: {
3650
+ actionType: "sanity.action.release.create",
3651
+ releaseId,
3652
+ metadata: finalMetadata
3653
+ }, options };
3654
+ };
3655
+ class ObservableReleasesClient {
3656
+ #client;
3657
+ #httpRequest;
3658
+ constructor(client, httpRequest) {
3659
+ this.#client = client, this.#httpRequest = httpRequest;
3660
+ }
3661
+ /**
3662
+ * @public
3663
+ *
3664
+ * Retrieve a release by id.
3665
+ *
3666
+ * @category Releases
3667
+ *
3668
+ * @param params - Release action parameters:
3669
+ * - `releaseId` - The id of the release to retrieve.
3670
+ * @param options - Additional query options including abort signal and query tag.
3671
+ * @returns An observable that resolves to the release document {@link ReleaseDocument}.
3672
+ *
3673
+ * @example Retrieving a release by id
3674
+ * ```ts
3675
+ * client.observable.releases.get({releaseId: 'my-release'}).pipe(
3676
+ * tap((release) => console.log(release)),
3677
+ * // {
3678
+ * // _id: '_.releases.my-release',
3679
+ * // name: 'my-release'
3680
+ * // _type: 'system.release',
3681
+ * // metadata: {releaseType: 'asap'},
3682
+ * // _createdAt: '2021-01-01T00:00:00.000Z',
3683
+ * // ...
3684
+ * // }
3685
+ * ).subscribe()
3686
+ * ```
3687
+ */
3688
+ get({ releaseId }, options) {
3689
+ return _getDocument(
3690
+ this.#client.config(),
3691
+ this.#httpRequest,
3692
+ `_.releases.${releaseId}`,
3693
+ options
3694
+ );
3695
+ }
3696
+ create(releaseOrOptions, maybeOptions) {
3697
+ const { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
3698
+ return _action(this.#client.config(), this.#httpRequest, action, options).pipe(
3699
+ map((actionResult) => ({
3700
+ ...actionResult,
3701
+ releaseId,
3702
+ metadata
3703
+ }))
3704
+ );
3705
+ }
3706
+ /**
3707
+ * @public
3708
+ *
3709
+ * Edits an existing release, updating the metadata.
3710
+ *
3711
+ * @category Releases
3712
+ *
3713
+ * @param params - Release action parameters:
3714
+ * - `releaseId` - The id of the release to edit.
3715
+ * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
3716
+ * @param options - Additional action options.
3717
+ * @returns An observable that resolves to the `transactionId`.
3718
+ */
3719
+ edit({ releaseId, patch }, options) {
3720
+ const editAction = {
3721
+ actionType: "sanity.action.release.edit",
3722
+ releaseId,
3723
+ patch
3724
+ };
3725
+ return _action(this.#client.config(), this.#httpRequest, editAction, options);
3726
+ }
3727
+ /**
3728
+ * @public
3729
+ *
3730
+ * Publishes all documents in a release at once. For larger releases the effect of the publish
3731
+ * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
3732
+ * documents and creation of the corresponding published documents with the new content may
3733
+ * take some time.
3734
+ *
3735
+ * During this period both the source and target documents are locked and cannot be
3736
+ * modified through any other means.
3737
+ *
3738
+ * @category Releases
3739
+ *
3740
+ * @param params - Release action parameters:
3741
+ * - `releaseId` - The id of the release to publish.
3742
+ * @param options - Additional action options.
3743
+ * @returns An observable that resolves to the `transactionId`.
3744
+ */
3745
+ publish({ releaseId }, options) {
3746
+ const publishAction = {
3747
+ actionType: "sanity.action.release.publish",
3748
+ releaseId
3749
+ };
3750
+ return _action(this.#client.config(), this.#httpRequest, publishAction, options);
3751
+ }
3752
+ /**
3753
+ * @public
3754
+ *
3755
+ * An archive action removes an active release. The documents that comprise the release
3756
+ * are deleted and therefore no longer queryable.
3757
+ *
3758
+ * While the documents remain in retention the last version can still be accessed using document history endpoint.
3759
+ *
3760
+ * @category Releases
3761
+ *
3762
+ * @param params - Release action parameters:
3763
+ * - `releaseId` - The id of the release to archive.
3764
+ * @param options - Additional action options.
3765
+ * @returns An observable that resolves to the `transactionId`.
3766
+ */
3767
+ archive({ releaseId }, options) {
3768
+ const archiveAction = {
3769
+ actionType: "sanity.action.release.archive",
3770
+ releaseId
3771
+ };
3772
+ return _action(this.#client.config(), this.#httpRequest, archiveAction, options);
3773
+ }
3774
+ /**
3775
+ * @public
3776
+ *
3777
+ * An unarchive action restores an archived release and all documents
3778
+ * with the content they had just prior to archiving.
3779
+ *
3780
+ * @category Releases
3781
+ *
3782
+ * @param params - Release action parameters:
3783
+ * - `releaseId` - The id of the release to unarchive.
3784
+ * @param options - Additional action options.
3785
+ * @returns An observable that resolves to the `transactionId`.
3786
+ */
3787
+ unarchive({ releaseId }, options) {
3788
+ const unarchiveAction = {
3789
+ actionType: "sanity.action.release.unarchive",
3790
+ releaseId
3791
+ };
3792
+ return _action(this.#client.config(), this.#httpRequest, unarchiveAction, options);
3793
+ }
3794
+ /**
3795
+ * @public
3796
+ *
3797
+ * A schedule action queues a release for publishing at the given future time.
3798
+ * The release is locked such that no documents in the release can be modified and
3799
+ * no documents that it references can be deleted as this would make the publish fail.
3800
+ * At the given time, the same logic as for the publish action is triggered.
3801
+ *
3802
+ * @category Releases
3803
+ *
3804
+ * @param params - Release action parameters:
3805
+ * - `releaseId` - The id of the release to schedule.
3806
+ * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
3807
+ * @param options - Additional action options.
3808
+ * @returns An observable that resolves to the `transactionId`.
3809
+ */
3810
+ schedule({ releaseId, publishAt }, options) {
3811
+ const scheduleAction = {
3812
+ actionType: "sanity.action.release.schedule",
3813
+ releaseId,
3814
+ publishAt
3815
+ };
3816
+ return _action(this.#client.config(), this.#httpRequest, scheduleAction, options);
3817
+ }
3818
+ /**
3819
+ * @public
3820
+ *
3821
+ * An unschedule action stops a release from being published.
3822
+ * The documents in the release are considered unlocked and can be edited again.
3823
+ * This may fail if another release is scheduled to be published after this one and
3824
+ * has a reference to a document created by this one.
3825
+ *
3826
+ * @category Releases
3827
+ *
3828
+ * @param params - Release action parameters:
3829
+ * - `releaseId` - The id of the release to unschedule.
3830
+ * @param options - Additional action options.
3831
+ * @returns An observable that resolves to the `transactionId`.
3832
+ */
3833
+ unschedule({ releaseId }, options) {
3834
+ const unscheduleAction = {
3835
+ actionType: "sanity.action.release.unschedule",
3836
+ releaseId
3837
+ };
3838
+ return _action(this.#client.config(), this.#httpRequest, unscheduleAction, options);
3839
+ }
3840
+ /**
3841
+ * @public
3842
+ *
3843
+ * A delete action removes a published or archived release.
3844
+ * The backing system document will be removed from the dataset.
3845
+ *
3846
+ * @category Releases
3847
+ *
3848
+ * @param params - Release action parameters:
3849
+ * - `releaseId` - The id of the release to delete.
3850
+ * @param options - Additional action options.
3851
+ * @returns An observable that resolves to the `transactionId`.
3852
+ */
3853
+ delete({ releaseId }, options) {
3854
+ const deleteAction = {
3855
+ actionType: "sanity.action.release.delete",
3856
+ releaseId
3857
+ };
3858
+ return _action(this.#client.config(), this.#httpRequest, deleteAction, options);
3859
+ }
3860
+ /**
3861
+ * @public
3862
+ *
3863
+ * Fetch the documents in a release by release id.
3864
+ *
3865
+ * @category Releases
3866
+ *
3867
+ * @param params - Release action parameters:
3868
+ * - `releaseId` - The id of the release to fetch documents for.
3869
+ * @param options - Additional mutation options {@link BaseMutationOptions}.
3870
+ * @returns An observable that resolves to the documents in the release.
3871
+ */
3872
+ fetchDocuments({ releaseId }, options) {
3873
+ return _getReleaseDocuments(this.#client.config(), this.#httpRequest, releaseId, options);
3874
+ }
3875
+ }
3876
+ class ReleasesClient {
3877
+ #client;
3878
+ #httpRequest;
3879
+ constructor(client, httpRequest) {
3880
+ this.#client = client, this.#httpRequest = httpRequest;
3881
+ }
3882
+ /**
3883
+ * @public
3884
+ *
3885
+ * Retrieve a release by id.
3886
+ *
3887
+ * @category Releases
3888
+ *
3889
+ * @param params - Release action parameters:
3890
+ * - `releaseId` - The id of the release to retrieve.
3891
+ * @param options - Additional query options including abort signal and query tag.
3892
+ * @returns A promise that resolves to the release document {@link ReleaseDocument}.
3893
+ *
3894
+ * @example Retrieving a release by id
3895
+ * ```ts
3896
+ * const release = await client.releases.get({releaseId: 'my-release'})
3897
+ * console.log(release)
3898
+ * // {
3899
+ * // _id: '_.releases.my-release',
3900
+ * // name: 'my-release'
3901
+ * // _type: 'system.release',
3902
+ * // metadata: {releaseType: 'asap'},
3903
+ * // _createdAt: '2021-01-01T00:00:00.000Z',
3904
+ * // ...
3905
+ * // }
3906
+ * ```
3907
+ */
3908
+ get({ releaseId }, options) {
3909
+ return lastValueFrom(
3910
+ _getDocument(
3911
+ this.#client.config(),
3912
+ this.#httpRequest,
3913
+ `_.releases.${releaseId}`,
3914
+ options
3915
+ )
3916
+ );
3917
+ }
3918
+ async create(releaseOrOptions, maybeOptions) {
3919
+ const { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
3920
+ return { ...await lastValueFrom(
3921
+ _action(this.#client.config(), this.#httpRequest, action, options)
3922
+ ), releaseId, metadata };
3923
+ }
3924
+ /**
3925
+ * @public
3926
+ *
3927
+ * Edits an existing release, updating the metadata.
3928
+ *
3929
+ * @category Releases
3930
+ *
3931
+ * @param params - Release action parameters:
3932
+ * - `releaseId` - The id of the release to edit.
3933
+ * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
3934
+ * @param options - Additional action options.
3935
+ * @returns A promise that resolves to the `transactionId`.
3936
+ */
3937
+ edit({ releaseId, patch }, options) {
3938
+ const editAction = {
3939
+ actionType: "sanity.action.release.edit",
3940
+ releaseId,
3941
+ patch
3942
+ };
3943
+ return lastValueFrom(_action(this.#client.config(), this.#httpRequest, editAction, options));
3944
+ }
3945
+ /**
3946
+ * @public
3947
+ *
3948
+ * Publishes all documents in a release at once. For larger releases the effect of the publish
3949
+ * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
3950
+ * documents and creation of the corresponding published documents with the new content may
3951
+ * take some time.
3952
+ *
3953
+ * During this period both the source and target documents are locked and cannot be
3954
+ * modified through any other means.
3955
+ *
3956
+ * @category Releases
3957
+ *
3958
+ * @param params - Release action parameters:
3959
+ * - `releaseId` - The id of the release to publish.
3960
+ * @param options - Additional action options.
3961
+ * @returns A promise that resolves to the `transactionId`.
3962
+ */
3963
+ publish({ releaseId }, options) {
3964
+ const publishAction = {
3965
+ actionType: "sanity.action.release.publish",
3966
+ releaseId
3967
+ };
3968
+ return lastValueFrom(_action(this.#client.config(), this.#httpRequest, publishAction, options));
3969
+ }
3970
+ /**
3971
+ * @public
3972
+ *
3973
+ * An archive action removes an active release. The documents that comprise the release
3974
+ * are deleted and therefore no longer queryable.
3975
+ *
3976
+ * While the documents remain in retention the last version can still be accessed using document history endpoint.
3977
+ *
3978
+ * @category Releases
3979
+ *
3980
+ * @param params - Release action parameters:
3981
+ * - `releaseId` - The id of the release to archive.
3982
+ * @param options - Additional action options.
3983
+ * @returns A promise that resolves to the `transactionId`.
3984
+ */
3985
+ archive({ releaseId }, options) {
3986
+ const archiveAction = {
3987
+ actionType: "sanity.action.release.archive",
3988
+ releaseId
3989
+ };
3990
+ return lastValueFrom(_action(this.#client.config(), this.#httpRequest, archiveAction, options));
3991
+ }
3992
+ /**
3993
+ * @public
3994
+ *
3995
+ * An unarchive action restores an archived release and all documents
3996
+ * with the content they had just prior to archiving.
3997
+ *
3998
+ * @category Releases
3999
+ *
4000
+ * @param params - Release action parameters:
4001
+ * - `releaseId` - The id of the release to unarchive.
4002
+ * @param options - Additional action options.
4003
+ * @returns A promise that resolves to the `transactionId`.
4004
+ */
4005
+ unarchive({ releaseId }, options) {
4006
+ const unarchiveAction = {
4007
+ actionType: "sanity.action.release.unarchive",
4008
+ releaseId
4009
+ };
4010
+ return lastValueFrom(
4011
+ _action(this.#client.config(), this.#httpRequest, unarchiveAction, options)
4012
+ );
4013
+ }
4014
+ /**
4015
+ * @public
4016
+ *
4017
+ * A schedule action queues a release for publishing at the given future time.
4018
+ * The release is locked such that no documents in the release can be modified and
4019
+ * no documents that it references can be deleted as this would make the publish fail.
4020
+ * At the given time, the same logic as for the publish action is triggered.
4021
+ *
4022
+ * @category Releases
4023
+ *
4024
+ * @param params - Release action parameters:
4025
+ * - `releaseId` - The id of the release to schedule.
4026
+ * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
4027
+ * @param options - Additional action options.
4028
+ * @returns A promise that resolves to the `transactionId`.
4029
+ */
4030
+ schedule({ releaseId, publishAt }, options) {
4031
+ const scheduleAction = {
4032
+ actionType: "sanity.action.release.schedule",
4033
+ releaseId,
4034
+ publishAt
4035
+ };
4036
+ return lastValueFrom(_action(this.#client.config(), this.#httpRequest, scheduleAction, options));
4037
+ }
4038
+ /**
4039
+ * @public
4040
+ *
4041
+ * An unschedule action stops a release from being published.
4042
+ * The documents in the release are considered unlocked and can be edited again.
4043
+ * This may fail if another release is scheduled to be published after this one and
4044
+ * has a reference to a document created by this one.
4045
+ *
4046
+ * @category Releases
4047
+ *
4048
+ * @param params - Release action parameters:
4049
+ * - `releaseId` - The id of the release to unschedule.
4050
+ * @param options - Additional action options.
4051
+ * @returns A promise that resolves to the `transactionId`.
4052
+ */
4053
+ unschedule({ releaseId }, options) {
4054
+ const unscheduleAction = {
4055
+ actionType: "sanity.action.release.unschedule",
4056
+ releaseId
4057
+ };
4058
+ return lastValueFrom(
4059
+ _action(this.#client.config(), this.#httpRequest, unscheduleAction, options)
4060
+ );
4061
+ }
4062
+ /**
4063
+ * @public
4064
+ *
4065
+ * A delete action removes a published or archived release.
4066
+ * The backing system document will be removed from the dataset.
4067
+ *
4068
+ * @category Releases
4069
+ *
4070
+ * @param params - Release action parameters:
4071
+ * - `releaseId` - The id of the release to delete.
4072
+ * @param options - Additional action options.
4073
+ * @returns A promise that resolves to the `transactionId`.
4074
+ */
4075
+ delete({ releaseId }, options) {
4076
+ const deleteAction = {
4077
+ actionType: "sanity.action.release.delete",
4078
+ releaseId
4079
+ };
4080
+ return lastValueFrom(_action(this.#client.config(), this.#httpRequest, deleteAction, options));
4081
+ }
4082
+ /**
4083
+ * @public
4084
+ *
4085
+ * Fetch the documents in a release by release id.
4086
+ *
4087
+ * @category Releases
4088
+ *
4089
+ * @param params - Release action parameters:
4090
+ * - `releaseId` - The id of the release to fetch documents for.
4091
+ * @param options - Additional mutation options {@link BaseMutationOptions}.
4092
+ * @returns A promise that resolves to the documents in the release.
4093
+ */
4094
+ fetchDocuments({ releaseId }, options) {
4095
+ return lastValueFrom(
4096
+ _getReleaseDocuments(this.#client.config(), this.#httpRequest, releaseId, options)
3331
4097
  );
3332
4098
  }
3333
4099
  }
@@ -3363,9 +4129,13 @@ ${selectionOpts}`);
3363
4129
  */
3364
4130
  getById(id) {
3365
4131
  return lastValueFrom(
3366
- _request(this.#client.config(), this.#httpRequest, {
3367
- uri: `/users/${id}`
3368
- })
4132
+ _request(
4133
+ this.#client.config(),
4134
+ this.#httpRequest,
4135
+ {
4136
+ uri: `/users/${id}`
4137
+ }
4138
+ )
3369
4139
  );
3370
4140
  }
3371
4141
  }
@@ -3376,6 +4146,7 @@ ${selectionOpts}`);
3376
4146
  projects;
3377
4147
  users;
3378
4148
  agent;
4149
+ releases;
3379
4150
  /**
3380
4151
  * Private properties
3381
4152
  */
@@ -3388,7 +4159,7 @@ ${selectionOpts}`);
3388
4159
  constructor(httpRequest, config = defaultConfig) {
3389
4160
  this.config(config), this.#httpRequest = httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest), this.agent = {
3390
4161
  action: new ObservableAgentsActionClient(this, this.#httpRequest)
3391
- };
4162
+ }, this.releases = new ObservableReleasesClient(this, this.#httpRequest);
3392
4163
  }
3393
4164
  /**
3394
4165
  * Clone the client - returns a new instance
@@ -3453,17 +4224,132 @@ ${selectionOpts}`);
3453
4224
  return _getDocuments(this.#clientConfig, this.#httpRequest, ids, options);
3454
4225
  }
3455
4226
  create(document, options) {
3456
- return _create(this.#clientConfig, this.#httpRequest, document, "create", options);
4227
+ return _create(
4228
+ this.#clientConfig,
4229
+ this.#httpRequest,
4230
+ document,
4231
+ "create",
4232
+ options
4233
+ );
3457
4234
  }
3458
4235
  createIfNotExists(document, options) {
3459
- return _createIfNotExists(this.#clientConfig, this.#httpRequest, document, options);
4236
+ return _createIfNotExists(
4237
+ this.#clientConfig,
4238
+ this.#httpRequest,
4239
+ document,
4240
+ options
4241
+ );
3460
4242
  }
3461
4243
  createOrReplace(document, options) {
3462
4244
  return _createOrReplace(this.#clientConfig, this.#httpRequest, document, options);
3463
4245
  }
4246
+ createVersion({
4247
+ document,
4248
+ publishedId,
4249
+ releaseId
4250
+ }, options) {
4251
+ const documentVersionId = deriveDocumentVersionId("createVersion", {
4252
+ document,
4253
+ publishedId,
4254
+ releaseId
4255
+ }), documentVersion = { ...document, _id: documentVersionId }, versionPublishedId = publishedId || getPublishedId$1(document._id);
4256
+ return _createVersion(
4257
+ this.config(),
4258
+ this.#httpRequest,
4259
+ documentVersion,
4260
+ versionPublishedId,
4261
+ options
4262
+ );
4263
+ }
3464
4264
  delete(selection, options) {
3465
4265
  return _delete(this.#clientConfig, this.#httpRequest, selection, options);
3466
4266
  }
4267
+ /**
4268
+ * @public
4269
+ *
4270
+ * Deletes the draft or release version of a document.
4271
+ *
4272
+ * @remarks
4273
+ * * Discarding a version with no `releaseId` will discard the draft version of the published document.
4274
+ * * If the draft or release version does not exist, any error will throw.
4275
+ *
4276
+ * @param params - Version action parameters:
4277
+ * - `releaseId` - The ID of the release to discard the document from.
4278
+ * - `publishedId` - The published ID of the document to discard.
4279
+ * @param purge - if `true` the document history is also discarded.
4280
+ * @param options - Additional action options.
4281
+ * @returns an observable that resolves to the `transactionId`.
4282
+ *
4283
+ * @example Discarding a release version of a document
4284
+ * ```ts
4285
+ * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
4286
+ * // The document with the ID `versions.myRelease.myDocument` will be discarded.
4287
+ * ```
4288
+ *
4289
+ * @example Discarding a draft version of a document
4290
+ * ```ts
4291
+ * client.observable.discardVersion({publishedId: 'myDocument'})
4292
+ * // The document with the ID `drafts.myDocument` will be discarded.
4293
+ * ```
4294
+ */
4295
+ discardVersion({ releaseId, publishedId }, purge, options) {
4296
+ const documentVersionId = getDocumentVersionId(publishedId, releaseId);
4297
+ return _discardVersion(
4298
+ this.config(),
4299
+ this.#httpRequest,
4300
+ documentVersionId,
4301
+ purge,
4302
+ options
4303
+ );
4304
+ }
4305
+ replaceVersion({
4306
+ document,
4307
+ publishedId,
4308
+ releaseId
4309
+ }, options) {
4310
+ const documentVersionId = deriveDocumentVersionId("replaceVersion", {
4311
+ document,
4312
+ publishedId,
4313
+ releaseId
4314
+ }), documentVersion = { ...document, _id: documentVersionId };
4315
+ return _replaceVersion(
4316
+ this.config(),
4317
+ this.#httpRequest,
4318
+ documentVersion,
4319
+ options
4320
+ );
4321
+ }
4322
+ /**
4323
+ * @public
4324
+ *
4325
+ * Used to indicate when a document within a release should be unpublished when
4326
+ * the release is run.
4327
+ *
4328
+ * @remarks
4329
+ * * If the published document does not exist, an error will be thrown.
4330
+ *
4331
+ * @param params - Version action parameters:
4332
+ * - `releaseId` - The ID of the release to unpublish the document from.
4333
+ * - `publishedId` - The published ID of the document to unpublish.
4334
+ * @param options - Additional action options.
4335
+ * @returns an observable that resolves to the `transactionId`.
4336
+ *
4337
+ * @example Unpublishing a release version of a published document
4338
+ * ```ts
4339
+ * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
4340
+ * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
4341
+ * ```
4342
+ */
4343
+ unpublishVersion({ releaseId, publishedId }, options) {
4344
+ const versionId = getVersionId(publishedId, releaseId);
4345
+ return _unpublishVersion(
4346
+ this.config(),
4347
+ this.#httpRequest,
4348
+ versionId,
4349
+ publishedId,
4350
+ options
4351
+ );
4352
+ }
3467
4353
  mutate(operations, options) {
3468
4354
  return _mutate(this.#clientConfig, this.#httpRequest, operations, options);
3469
4355
  }
@@ -3528,6 +4414,7 @@ ${selectionOpts}`);
3528
4414
  projects;
3529
4415
  users;
3530
4416
  agent;
4417
+ releases;
3531
4418
  /**
3532
4419
  * Observable version of the Sanity client, with the same configuration as the promise-based one
3533
4420
  */
@@ -3544,7 +4431,7 @@ ${selectionOpts}`);
3544
4431
  constructor(httpRequest, config = defaultConfig) {
3545
4432
  this.config(config), this.#httpRequest = httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.agent = {
3546
4433
  action: new AgentActionsClient(this, this.#httpRequest)
3547
- }, this.observable = new ObservableSanityClient(httpRequest, config);
4434
+ }, this.releases = new ReleasesClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config);
3548
4435
  }
3549
4436
  /**
3550
4437
  * Clone the client - returns a new instance
@@ -3596,7 +4483,9 @@ ${selectionOpts}`);
3596
4483
  * @param options - Request options
3597
4484
  */
3598
4485
  getDocument(id, options) {
3599
- return lastValueFrom(_getDocument(this.#clientConfig, this.#httpRequest, id, options));
4486
+ return lastValueFrom(
4487
+ _getDocument(this.#clientConfig, this.#httpRequest, id, options)
4488
+ );
3600
4489
  }
3601
4490
  /**
3602
4491
  * Fetch multiple documents in one request.
@@ -3608,7 +4497,9 @@ ${selectionOpts}`);
3608
4497
  * @param options - Request options
3609
4498
  */
3610
4499
  getDocuments(ids, options) {
3611
- return lastValueFrom(_getDocuments(this.#clientConfig, this.#httpRequest, ids, options));
4500
+ return lastValueFrom(
4501
+ _getDocuments(this.#clientConfig, this.#httpRequest, ids, options)
4502
+ );
3612
4503
  }
3613
4504
  create(document, options) {
3614
4505
  return lastValueFrom(
@@ -3625,11 +4516,122 @@ ${selectionOpts}`);
3625
4516
  _createOrReplace(this.#clientConfig, this.#httpRequest, document, options)
3626
4517
  );
3627
4518
  }
4519
+ createVersion({
4520
+ document,
4521
+ publishedId,
4522
+ releaseId
4523
+ }, options) {
4524
+ const documentVersionId = deriveDocumentVersionId("createVersion", {
4525
+ document,
4526
+ publishedId,
4527
+ releaseId
4528
+ }), documentVersion = { ...document, _id: documentVersionId }, versionPublishedId = publishedId || getPublishedId$1(document._id);
4529
+ return firstValueFrom(
4530
+ _createVersion(
4531
+ this.config(),
4532
+ this.#httpRequest,
4533
+ documentVersion,
4534
+ versionPublishedId,
4535
+ options
4536
+ )
4537
+ );
4538
+ }
3628
4539
  delete(selection, options) {
3629
- return lastValueFrom(_delete(this.#clientConfig, this.#httpRequest, selection, options));
4540
+ return lastValueFrom(
4541
+ _delete(this.#clientConfig, this.#httpRequest, selection, options)
4542
+ );
4543
+ }
4544
+ /**
4545
+ * @public
4546
+ *
4547
+ * Deletes the draft or release version of a document.
4548
+ *
4549
+ * @remarks
4550
+ * * Discarding a version with no `releaseId` will discard the draft version of the published document.
4551
+ * * If the draft or release version does not exist, any error will throw.
4552
+ *
4553
+ * @param params - Version action parameters:
4554
+ * - `releaseId` - The ID of the release to discard the document from.
4555
+ * - `publishedId` - The published ID of the document to discard.
4556
+ * @param purge - if `true` the document history is also discarded.
4557
+ * @param options - Additional action options.
4558
+ * @returns a promise that resolves to the `transactionId`.
4559
+ *
4560
+ * @example Discarding a release version of a document
4561
+ * ```ts
4562
+ * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
4563
+ * // The document with the ID `versions.myRelease.myDocument` will be discarded.
4564
+ * ```
4565
+ *
4566
+ * @example Discarding a draft version of a document
4567
+ * ```ts
4568
+ * client.discardVersion({publishedId: 'myDocument'})
4569
+ * // The document with the ID `drafts.myDocument` will be discarded.
4570
+ * ```
4571
+ */
4572
+ discardVersion({ releaseId, publishedId }, purge, options) {
4573
+ const documentVersionId = getDocumentVersionId(publishedId, releaseId);
4574
+ return lastValueFrom(
4575
+ _discardVersion(
4576
+ this.config(),
4577
+ this.#httpRequest,
4578
+ documentVersionId,
4579
+ purge,
4580
+ options
4581
+ )
4582
+ );
4583
+ }
4584
+ replaceVersion({
4585
+ document,
4586
+ publishedId,
4587
+ releaseId
4588
+ }, options) {
4589
+ const documentVersionId = deriveDocumentVersionId("replaceVersion", {
4590
+ document,
4591
+ publishedId,
4592
+ releaseId
4593
+ }), documentVersion = { ...document, _id: documentVersionId };
4594
+ return firstValueFrom(
4595
+ _replaceVersion(this.config(), this.#httpRequest, documentVersion, options)
4596
+ );
4597
+ }
4598
+ /**
4599
+ * @public
4600
+ *
4601
+ * Used to indicate when a document within a release should be unpublished when
4602
+ * the release is run.
4603
+ *
4604
+ * @remarks
4605
+ * * If the published document does not exist, an error will be thrown.
4606
+ *
4607
+ * @param params - Version action parameters:
4608
+ * - `releaseId` - The ID of the release to unpublish the document from.
4609
+ * - `publishedId` - The published ID of the document to unpublish.
4610
+ * @param options - Additional action options.
4611
+ * @returns a promise that resolves to the `transactionId`.
4612
+ *
4613
+ * @example Unpublishing a release version of a published document
4614
+ * ```ts
4615
+ * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
4616
+ * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
4617
+ * ```
4618
+ */
4619
+ unpublishVersion({ releaseId, publishedId }, options) {
4620
+ const versionId = getVersionId(publishedId, releaseId);
4621
+ return lastValueFrom(
4622
+ _unpublishVersion(
4623
+ this.config(),
4624
+ this.#httpRequest,
4625
+ versionId,
4626
+ publishedId,
4627
+ options
4628
+ )
4629
+ );
3630
4630
  }
3631
4631
  mutate(operations, options) {
3632
- return lastValueFrom(_mutate(this.#clientConfig, this.#httpRequest, operations, options));
4632
+ return lastValueFrom(
4633
+ _mutate(this.#clientConfig, this.#httpRequest, operations, options)
4634
+ );
3633
4635
  }
3634
4636
  /**
3635
4637
  * Create a new buildable patch of operations to perform
@@ -3657,7 +4659,9 @@ ${selectionOpts}`);
3657
4659
  * @param options - Action options
3658
4660
  */
3659
4661
  action(operations, options) {
3660
- return lastValueFrom(_action(this.#clientConfig, this.#httpRequest, operations, options));
4662
+ return lastValueFrom(
4663
+ _action(this.#clientConfig, this.#httpRequest, operations, options)
4664
+ );
3661
4665
  }
3662
4666
  /**
3663
4667
  * Perform a request against the Sanity API
@@ -3680,7 +4684,9 @@ ${selectionOpts}`);
3680
4684
  * @internal
3681
4685
  */
3682
4686
  dataRequest(endpoint, body, options) {
3683
- return lastValueFrom(_dataRequest(this.#clientConfig, this.#httpRequest, endpoint, body, options));
4687
+ return lastValueFrom(
4688
+ _dataRequest(this.#clientConfig, this.#httpRequest, endpoint, body, options)
4689
+ );
3684
4690
  }
3685
4691
  /**
3686
4692
  * Get a Sanity API URL for the URI provided
@@ -3827,9 +4833,6 @@ ${selectionOpts}`);
3827
4833
  function isArray(value) {
3828
4834
  return value !== null && Array.isArray(value);
3829
4835
  }
3830
- function isRecord(value) {
3831
- return typeof value == "object" && value !== null;
3832
- }
3833
4836
  function walkMap(value, mappingFn, path = []) {
3834
4837
  if (isArray(value))
3835
4838
  return value.map((v, idx) => {
@@ -5175,9 +6178,12 @@ ${selectionOpts}`);
5175
6178
  exports.SanityClient = SanityClient;
5176
6179
  exports.ServerError = ServerError;
5177
6180
  exports.Transaction = Transaction;
6181
+ exports.ViewResourceType = ViewResourceType;
5178
6182
  exports.connectEventSource = connectEventSource;
5179
6183
  exports.createClient = createClient;
5180
6184
  exports.default = deprecatedCreateClient;
6185
+ exports.formatQueryParseError = formatQueryParseError;
6186
+ exports.isQueryParseError = isQueryParseError;
5181
6187
  exports.requester = requester;
5182
6188
  exports.unstable__adapter = c$2;
5183
6189
  exports.unstable__environment = f$1;