@sanity/client 7.26.1 → 8.0.0

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 (128) hide show
  1. package/README.md +5 -377
  2. package/dist/browserUpload-CQgx9YYo.js +86 -0
  3. package/dist/browserUpload-CQgx9YYo.js.map +1 -0
  4. package/dist/browserUpload-icWlVP15.js +86 -0
  5. package/dist/browserUpload-icWlVP15.js.map +1 -0
  6. package/dist/config-a8VajuEY.js +126 -0
  7. package/dist/config-a8VajuEY.js.map +1 -0
  8. package/dist/csm.d.ts +122 -347
  9. package/dist/csm.js +79 -91
  10. package/dist/csm.js.map +1 -1
  11. package/dist/dist-C9ExSk2R.js +73 -0
  12. package/dist/dist-C9ExSk2R.js.map +1 -0
  13. package/dist/dist-Z8cIRxoB.js +69 -0
  14. package/dist/dist-Z8cIRxoB.js.map +1 -0
  15. package/dist/index.d.ts +107 -6758
  16. package/dist/index.js +2822 -2848
  17. package/dist/index.js.map +1 -1
  18. package/dist/{index.d.cts → index.node.d.ts} +4291 -5363
  19. package/dist/index.node.js +3131 -0
  20. package/dist/index.node.js.map +1 -0
  21. package/dist/isRecord-Kfmt-nk-.js +7 -0
  22. package/dist/isRecord-Kfmt-nk-.js.map +1 -0
  23. package/dist/media-library.d.ts +9 -100
  24. package/dist/media-library.js +36 -14
  25. package/dist/media-library.js.map +1 -1
  26. package/dist/request-CJxcN16k.js +372 -0
  27. package/dist/request-CJxcN16k.js.map +1 -0
  28. package/dist/request-k7VS_NnC.js +354 -0
  29. package/dist/request-k7VS_NnC.js.map +1 -0
  30. package/dist/resolveEditInfo-sq7yF78q.js +325 -0
  31. package/dist/resolveEditInfo-sq7yF78q.js.map +1 -0
  32. package/dist/rolldown-runtime-vyAXikos.js +9 -0
  33. package/dist/stega.d.ts +78 -7179
  34. package/dist/stega.js +27 -20
  35. package/dist/stega.js.map +1 -1
  36. package/dist/stegaClean-C18wLWau.js +21 -0
  37. package/dist/stegaClean-C18wLWau.js.map +1 -0
  38. package/dist/stegaEncodeSourceMap-B2fGArSf.js +163 -0
  39. package/dist/stegaEncodeSourceMap-B2fGArSf.js.map +1 -0
  40. package/dist/stegaEncodeSourceMap-DkoIlutY.js +367 -0
  41. package/dist/stegaEncodeSourceMap-DkoIlutY.js.map +1 -0
  42. package/dist/{index.browser.d.cts → types-CUxZSgB2.d.ts} +3956 -5295
  43. package/dist/types-CfGzbXrl.d.ts +108 -0
  44. package/package.json +69 -146
  45. package/src/SanityClient.ts +82 -117
  46. package/src/agent/actions/AgentActionsClient.ts +12 -12
  47. package/src/agent/actions/generate.ts +20 -3
  48. package/src/agent/actions/patch.ts +21 -4
  49. package/src/agent/actions/prompt.ts +17 -4
  50. package/src/agent/actions/transform.ts +21 -4
  51. package/src/agent/actions/translate.ts +21 -4
  52. package/src/assets/AssetsClient.ts +71 -23
  53. package/src/csm/createEditUrl.ts +1 -1
  54. package/src/csm/draftUtils.ts +0 -1
  55. package/src/csm/index.ts +2 -2
  56. package/src/csm/studioPath.ts +2 -1
  57. package/src/csm/types.ts +5 -1
  58. package/src/data/dataMethods.ts +801 -349
  59. package/src/data/eventsource.ts +13 -10
  60. package/src/data/listen.ts +16 -22
  61. package/src/data/live.ts +44 -27
  62. package/src/data/resolveEventSourceFetch.ts +96 -0
  63. package/src/datasets/DatasetsClient.ts +58 -41
  64. package/src/defineCreateClient.ts +35 -23
  65. package/src/http/browserMiddleware.ts +7 -1
  66. package/src/http/browserUpload.ts +162 -0
  67. package/src/http/errors.ts +60 -6
  68. package/src/http/nodeMiddleware.ts +94 -30
  69. package/src/http/request.ts +310 -87
  70. package/src/http/requestOptions.ts +131 -15
  71. package/src/{index.browser.ts → index.node.ts} +9 -4
  72. package/src/index.ts +4 -3
  73. package/src/mediaLibrary/MediaLibraryVideoClient.ts +26 -11
  74. package/src/projects/ProjectsClient.ts +18 -16
  75. package/src/releases/ReleasesClient.ts +34 -31
  76. package/src/stega/index.ts +1 -2
  77. package/src/stega/stegaEncodeSourceMap.ts +5 -0
  78. package/src/stega/types.ts +0 -1
  79. package/src/types.ts +110 -96
  80. package/src/users/UsersClient.ts +10 -14
  81. package/src/util/shareReplayLatest.ts +1 -1
  82. package/src/warnings.ts +6 -1
  83. package/dist/_chunks-cjs/config.cjs +0 -206
  84. package/dist/_chunks-cjs/config.cjs.map +0 -1
  85. package/dist/_chunks-cjs/isRecord.cjs +0 -6
  86. package/dist/_chunks-cjs/isRecord.cjs.map +0 -1
  87. package/dist/_chunks-cjs/resolveEditInfo.cjs +0 -334
  88. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +0 -1
  89. package/dist/_chunks-cjs/stegaClean.cjs +0 -46
  90. package/dist/_chunks-cjs/stegaClean.cjs.map +0 -1
  91. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +0 -388
  92. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +0 -1
  93. package/dist/_chunks-es/config.js +0 -207
  94. package/dist/_chunks-es/config.js.map +0 -1
  95. package/dist/_chunks-es/isRecord.js +0 -7
  96. package/dist/_chunks-es/isRecord.js.map +0 -1
  97. package/dist/_chunks-es/resolveEditInfo.js +0 -335
  98. package/dist/_chunks-es/resolveEditInfo.js.map +0 -1
  99. package/dist/_chunks-es/stegaClean.js +0 -47
  100. package/dist/_chunks-es/stegaClean.js.map +0 -1
  101. package/dist/_chunks-es/stegaEncodeSourceMap.js +0 -389
  102. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +0 -1
  103. package/dist/csm.cjs +0 -99
  104. package/dist/csm.cjs.map +0 -1
  105. package/dist/csm.d.cts +0 -403
  106. package/dist/index.browser.cjs +0 -3106
  107. package/dist/index.browser.cjs.map +0 -1
  108. package/dist/index.browser.d.ts +0 -6841
  109. package/dist/index.browser.js +0 -3082
  110. package/dist/index.browser.js.map +0 -1
  111. package/dist/index.cjs +0 -2947
  112. package/dist/index.cjs.map +0 -1
  113. package/dist/media-library.cjs +0 -20
  114. package/dist/media-library.cjs.map +0 -1
  115. package/dist/media-library.d.cts +0 -117
  116. package/dist/stega.browser.cjs +0 -29
  117. package/dist/stega.browser.cjs.map +0 -1
  118. package/dist/stega.browser.d.cts +0 -7242
  119. package/dist/stega.browser.d.ts +0 -7242
  120. package/dist/stega.browser.js +0 -24
  121. package/dist/stega.browser.js.map +0 -1
  122. package/dist/stega.cjs +0 -29
  123. package/dist/stega.cjs.map +0 -1
  124. package/dist/stega.d.cts +0 -7242
  125. package/src/data/eventsourcePolyfill.ts +0 -7
  126. package/umd/.gitkeep +0 -1
  127. package/umd/sanityClient.js +0 -6536
  128. package/umd/sanityClient.min.js +0 -6
package/dist/index.cjs DELETED
@@ -1,2947 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __copyProps = (to, from, except, desc) => {
8
- if (from && typeof from == "object" || typeof from == "function")
9
- for (let key of __getOwnPropNames(from))
10
- !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- return to;
12
- };
13
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
14
- // If the importer is in node compatibility mode or this is not an ESM
15
- // file that has been converted to a CommonJS file using a Babel-
16
- // compatible transform (i.e. "__esModule" has not been set), then set
17
- // "default" to the CommonJS "module.exports" for node compatibility.
18
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
19
- mod
20
- ));
21
- Object.defineProperty(exports, "__esModule", { value: !0 });
22
- var getIt = require("get-it"), middleware$1 = require("get-it/middleware"), rxjs = require("rxjs"), isRecord = require("./_chunks-cjs/isRecord.cjs"), stegaClean = require("./_chunks-cjs/stegaClean.cjs"), operators = require("rxjs/operators"), csm = require("@sanity/client/csm"), nanoid = require("nanoid"), config = require("./_chunks-cjs/config.cjs");
23
- const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
24
- function codeFrame(query, location2, message) {
25
- const lines = query.split(NEWLINE), loc = {
26
- start: columnToLine(location2.start, lines),
27
- end: location2.end ? columnToLine(location2.end, lines) : void 0
28
- }, { start, end, markerLines } = getMarkerLines(loc, lines), numberMaxWidth = `${end}`.length;
29
- return query.split(NEWLINE, end).slice(start, end).map((line, index) => {
30
- const number = start + 1 + index, gutter = ` ${` ${number}`.slice(-numberMaxWidth)} |`, hasMarker = markerLines[number], lastMarkerLine = !markerLines[number + 1];
31
- if (!hasMarker)
32
- return ` ${gutter}${line.length > 0 ? ` ${line}` : ""}`;
33
- let markerLine = "";
34
- if (Array.isArray(hasMarker)) {
35
- const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "), numberOfMarkers = hasMarker[1] || 1;
36
- markerLine = [
37
- `
38
- `,
39
- gutter.replace(/\d/g, " "),
40
- " ",
41
- markerSpacing,
42
- "^".repeat(numberOfMarkers)
43
- ].join(""), lastMarkerLine && message && (markerLine += " " + message);
44
- }
45
- return [">", gutter, line.length > 0 ? ` ${line}` : "", markerLine].join("");
46
- }).join(`
47
- `);
48
- }
49
- function getMarkerLines(loc, source) {
50
- 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;
51
- let start = Math.max(startLine - (linesAbove + 1), 0), end = Math.min(source.length, endLine + linesBelow);
52
- startLine === -1 && (start = 0), endLine === -1 && (end = source.length);
53
- const lineDiff = endLine - startLine, markerLines = {};
54
- if (lineDiff)
55
- for (let i = 0; i <= lineDiff; i++) {
56
- const lineNumber = i + startLine;
57
- if (!startColumn)
58
- markerLines[lineNumber] = !0;
59
- else if (i === 0) {
60
- const sourceLength = source[lineNumber - 1].length;
61
- markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
62
- } else if (i === lineDiff)
63
- markerLines[lineNumber] = [0, endColumn];
64
- else {
65
- const sourceLength = source[lineNumber - i].length;
66
- markerLines[lineNumber] = [0, sourceLength];
67
- }
68
- }
69
- else
70
- startColumn === endColumn ? startColumn ? markerLines[startLine] = [startColumn, 0] : markerLines[startLine] = !0 : markerLines[startLine] = [startColumn, endColumn - startColumn];
71
- return { start, end, markerLines };
72
- }
73
- function columnToLine(column, lines) {
74
- let offset = 0;
75
- for (let i = 0; i < lines.length; i++) {
76
- const lineLength = lines[i].length + 1;
77
- if (offset + lineLength > column)
78
- return {
79
- line: i + 1,
80
- // 1-based line
81
- column: column - offset
82
- // 0-based column
83
- };
84
- offset += lineLength;
85
- }
86
- return {
87
- line: lines.length,
88
- column: lines[lines.length - 1]?.length ?? 0
89
- };
90
- }
91
- const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
92
- function isHttpError(error) {
93
- if (!isRecord.isRecord(error))
94
- return !1;
95
- const response = error.response;
96
- return !(typeof error.statusCode != "number" || typeof error.message != "string" || !isRecord.isRecord(response) || typeof response.body > "u" || typeof response.url != "string" || typeof response.method != "string" || typeof response.headers != "object" || typeof response.statusCode != "number");
97
- }
98
- class ClientError extends Error {
99
- response;
100
- statusCode = 400;
101
- responseBody;
102
- traceId;
103
- details;
104
- constructor(res, context) {
105
- const props = extractErrorProps(res, context);
106
- super(props.message), Object.assign(this, props);
107
- }
108
- }
109
- class ServerError extends Error {
110
- response;
111
- statusCode = 500;
112
- responseBody;
113
- traceId;
114
- details;
115
- constructor(res) {
116
- const props = extractErrorProps(res);
117
- super(props.message), Object.assign(this, props);
118
- }
119
- }
120
- function extractErrorProps(res, context) {
121
- const body = res.body, props = {
122
- response: res,
123
- statusCode: res.statusCode,
124
- responseBody: stringifyBody(body, res),
125
- traceId: extractTraceId(res),
126
- message: "",
127
- details: void 0
128
- };
129
- if (!isRecord.isRecord(body))
130
- return props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`, props;
131
- const error = body.error;
132
- if (typeof error == "string" && typeof body.message == "string")
133
- return props.message = `${error} - ${body.message}${formatTraceId(props.traceId)}`, props;
134
- if (typeof error != "object" || error === null)
135
- return typeof error == "string" ? props.message = `${error}${formatTraceId(props.traceId)}` : typeof body.message == "string" ? props.message = `${body.message}${formatTraceId(props.traceId)}` : props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`, props;
136
- if (isMutationError(error) || isActionError(error)) {
137
- const allItems = error.items || [], items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map((item) => item.error?.description).filter(Boolean);
138
- let itemsStr = items.length ? `:
139
- - ${items.join(`
140
- - `)}` : "";
141
- return allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE && (itemsStr += `
142
- ...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`), props.message = `${error.description}${formatTraceId(props.traceId)}${itemsStr}`, props.details = body.error, props;
143
- }
144
- if (isQueryParseError(error)) {
145
- const tag = context?.options?.query?.tag;
146
- return props.message = formatQueryParseError(error, tag, props.traceId), props.details = body.error, props;
147
- }
148
- return "description" in error && typeof error.description == "string" ? (props.message = `${error.description}${formatTraceId(props.traceId)}`, props.details = error, props) : (props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`, props);
149
- }
150
- function isMutationError(error) {
151
- return "type" in error && error.type === "mutationError" && "description" in error && typeof error.description == "string";
152
- }
153
- function isActionError(error) {
154
- return "type" in error && error.type === "actionError" && "description" in error && typeof error.description == "string";
155
- }
156
- function isQueryParseError(error) {
157
- return isRecord.isRecord(error) && error.type === "queryParseError" && typeof error.query == "string" && typeof error.start == "number" && typeof error.end == "number";
158
- }
159
- function formatQueryParseError(error, tag, traceId) {
160
- const { query, start, end, description } = error, withTraceId = traceId ? `
161
- (traceId: ${traceId})` : "";
162
- if (!query || typeof start > "u")
163
- return `GROQ query parse error: ${description}${withTraceId}`;
164
- const withTag = tag ? `
165
-
166
- Tag: ${tag}` : "";
167
- return `GROQ query parse error:
168
- ${codeFrame(query, { start, end }, description)}${withTag}${withTraceId}`;
169
- }
170
- function httpErrorMessage(res, body) {
171
- const details = typeof body == "string" ? ` (${sliceWithEllipsis(body, 100)})` : "", statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
172
- return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`;
173
- }
174
- function extractTraceId(res) {
175
- const traceparent = res?.headers?.traceparent;
176
- if (traceparent)
177
- return traceparent.split("-")[1];
178
- }
179
- function stringifyBody(body, res) {
180
- return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? JSON.stringify(body, null, 2) : body;
181
- }
182
- function formatTraceId(traceId) {
183
- return traceId ? ` (traceId: ${traceId})` : "";
184
- }
185
- function sliceWithEllipsis(str, max) {
186
- return str.length > max ? `${str.slice(0, max)}\u2026` : str;
187
- }
188
- class CorsOriginError extends Error {
189
- projectId;
190
- addOriginUrl;
191
- constructor({ projectId, credentials } = {}) {
192
- if (super("CorsOriginError"), this.name = "CorsOriginError", this.projectId = projectId, projectId && typeof location < "u") {
193
- const url = new URL(`https://sanity.io/manage/project/${projectId}/api`), { origin } = location;
194
- url.searchParams.set("cors", "add"), url.searchParams.set("origin", origin), credentials && url.searchParams.set("credentials", ""), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;
195
- } else projectId ? this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: https://sanity.io/manage/project/${projectId}/api` : this.message = "The current origin is not allowed to connect to the Live Content API.";
196
- }
197
- }
198
- const httpError = {
199
- onResponse: (res, context) => {
200
- if (res.statusCode >= 500)
201
- throw new ServerError(res);
202
- if (res.statusCode >= 400)
203
- throw new ClientError(res, context);
204
- return res;
205
- }
206
- };
207
- function printWarnings(config2 = {}) {
208
- const seen = {}, shouldIgnoreWarning = (message) => config2.ignoreWarnings === void 0 ? !1 : (Array.isArray(config2.ignoreWarnings) ? config2.ignoreWarnings : [config2.ignoreWarnings]).some((pattern) => typeof pattern == "string" ? message.includes(pattern) : pattern instanceof RegExp ? pattern.test(message) : !1);
209
- return {
210
- onResponse: (res) => {
211
- const warn = res.headers["x-sanity-warning"], warnings = Array.isArray(warn) ? warn : [warn];
212
- for (const msg of warnings)
213
- !msg || seen[msg] || shouldIgnoreWarning(msg) || (seen[msg] = !0, console.warn(msg));
214
- return res;
215
- }
216
- };
217
- }
218
- function defineHttpRequest(envMiddleware, config2 = {}) {
219
- return getIt.getIt([
220
- middleware$1.retry({ shouldRetry }),
221
- ...envMiddleware,
222
- printWarnings(config2),
223
- middleware$1.jsonRequest(),
224
- middleware$1.jsonResponse(),
225
- middleware$1.progress(),
226
- httpError,
227
- middleware$1.observable({ implementation: rxjs.Observable })
228
- ]);
229
- }
230
- function shouldRetry(err, attempt, options) {
231
- if (options.maxRetries === 0) return !1;
232
- const isSafe = options.method === "GET" || options.method === "HEAD", isQuery2 = (options.uri || options.url).startsWith("/data/query"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);
233
- return (isSafe || isQuery2) && isRetriableResponse ? !0 : middleware$1.retry.shouldRetry(err, attempt, options);
234
- }
235
- const EXPERIMENTAL_API_WARNING = "This is an experimental API version";
236
- class ConnectionFailedError extends Error {
237
- name = "ConnectionFailedError";
238
- /**
239
- * HTTP status code of the rejected connection attempt, if known.
240
- * Only set when the EventSource implementation exposes it — the polyfill used in
241
- * Node.js and when custom headers (eg authorization) are required does, while
242
- * native EventSource implementations (browser and Node.js) do not.
243
- */
244
- status;
245
- constructor(message, options = {}) {
246
- const { status, ...errorOptions } = options;
247
- super(message, errorOptions), this.status = status;
248
- }
249
- }
250
- class DisconnectError extends Error {
251
- name = "DisconnectError";
252
- reason;
253
- constructor(message, reason, options = {}) {
254
- super(message, options), this.reason = reason;
255
- }
256
- }
257
- class ChannelError extends Error {
258
- name = "ChannelError";
259
- data;
260
- constructor(message, data) {
261
- super(message), this.data = data;
262
- }
263
- }
264
- class MessageError extends Error {
265
- name = "MessageError";
266
- data;
267
- constructor(message, data, options = {}) {
268
- super(message, options), this.data = data;
269
- }
270
- }
271
- class MessageParseError extends Error {
272
- name = "MessageParseError";
273
- }
274
- const REQUIRED_EVENTS = ["channelError", "disconnect"];
275
- function connectEventSource(initEventSource, events) {
276
- return rxjs.defer(() => {
277
- const es = initEventSource();
278
- return rxjs.isObservable(es) ? es : rxjs.of(es);
279
- }).pipe(rxjs.mergeMap((es) => connectWithESInstance(es, events)));
280
- }
281
- function connectWithESInstance(es, events) {
282
- return new rxjs.Observable((observer) => {
283
- const emitOpen = events.includes("open"), emitReconnect = events.includes("reconnect");
284
- function onError(evt) {
285
- if ("data" in evt) {
286
- const [parseError, event] = parseEvent(evt);
287
- observer.error(
288
- parseError ? new MessageParseError("Unable to parse EventSource error message", { cause: event }) : new MessageError((event?.data).message, event)
289
- );
290
- return;
291
- }
292
- const rawStatus = evt.status, status = typeof rawStatus == "number" ? rawStatus : void 0;
293
- if (status !== void 0) {
294
- observer.error(new ConnectionFailedError("EventSource connection failed", { status }));
295
- return;
296
- }
297
- es.readyState === es.CLOSED ? observer.error(new ConnectionFailedError("EventSource connection failed")) : emitReconnect && observer.next({ type: "reconnect" });
298
- }
299
- function onOpen() {
300
- observer.next({ type: "open" });
301
- }
302
- function onMessage(message) {
303
- const [parseError, event] = parseEvent(message);
304
- if (parseError) {
305
- observer.error(
306
- new MessageParseError("Unable to parse EventSource message", { cause: parseError })
307
- );
308
- return;
309
- }
310
- if (message.type === "channelError") {
311
- const tag = new URL(es.url).searchParams.get("tag");
312
- observer.error(new ChannelError(extractErrorMessage(event?.data, tag), event.data));
313
- return;
314
- }
315
- if (message.type === "disconnect") {
316
- observer.error(
317
- new DisconnectError(
318
- `Server disconnected client: ${event.data?.reason || "unknown error"}`
319
- )
320
- );
321
- return;
322
- }
323
- observer.next({
324
- type: message.type,
325
- id: message.lastEventId,
326
- ...event.data ? { data: event.data } : {}
327
- });
328
- }
329
- es.addEventListener("error", onError), emitOpen && es.addEventListener("open", onOpen);
330
- const cleanedEvents = [.../* @__PURE__ */ new Set([...REQUIRED_EVENTS, ...events])].filter((type) => type !== "error" && type !== "open" && type !== "reconnect");
331
- return cleanedEvents.forEach((type) => es.addEventListener(type, onMessage)), () => {
332
- es.removeEventListener("error", onError), emitOpen && es.removeEventListener("open", onOpen), cleanedEvents.forEach((type) => es.removeEventListener(type, onMessage)), es.close();
333
- };
334
- });
335
- }
336
- function parseEvent(message) {
337
- try {
338
- const data = typeof message.data == "string" && JSON.parse(message.data);
339
- return [
340
- null,
341
- {
342
- type: message.type,
343
- id: message.lastEventId,
344
- ...isEmptyObject(data) ? {} : { data }
345
- }
346
- ];
347
- } catch (err) {
348
- return [err, null];
349
- }
350
- }
351
- function extractErrorMessage(err, tag) {
352
- const error = err.error;
353
- 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";
354
- }
355
- function isEmptyObject(data) {
356
- for (const _ in data)
357
- return !1;
358
- return !0;
359
- }
360
- function getSelection(sel) {
361
- if (typeof sel == "string")
362
- return { id: sel };
363
- if (Array.isArray(sel))
364
- return { query: "*[_id in $ids]", params: { ids: sel } };
365
- if (typeof sel == "object" && sel !== null && "query" in sel && typeof sel.query == "string")
366
- return "params" in sel && typeof sel.params == "object" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };
367
- const selectionOpts = [
368
- "* Document ID (<docId>)",
369
- "* Array of document IDs",
370
- "* Object containing `query`"
371
- ].join(`
372
- `);
373
- throw new Error(`Unknown selection - must be one of:
374
-
375
- ${selectionOpts}`);
376
- }
377
- class BasePatch {
378
- selection;
379
- operations;
380
- constructor(selection, operations = {}) {
381
- this.selection = selection, this.operations = operations;
382
- }
383
- /**
384
- * Sets the given attributes to the document. Does NOT merge objects.
385
- * The operation is added to the current patch, ready to be commited by `commit()`
386
- *
387
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
388
- */
389
- set(attrs) {
390
- return this._assign("set", attrs);
391
- }
392
- /**
393
- * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
394
- * The operation is added to the current patch, ready to be commited by `commit()`
395
- *
396
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
397
- */
398
- setIfMissing(attrs) {
399
- return this._assign("setIfMissing", attrs);
400
- }
401
- /**
402
- * Performs a "diff-match-patch" operation on the string attributes provided.
403
- * The operation is added to the current patch, ready to be commited by `commit()`
404
- *
405
- * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
406
- */
407
- diffMatchPatch(attrs) {
408
- return config.validateObject("diffMatchPatch", attrs), this._assign("diffMatchPatch", attrs);
409
- }
410
- /**
411
- * Unsets the attribute paths provided.
412
- * The operation is added to the current patch, ready to be commited by `commit()`
413
- *
414
- * @param attrs - Attribute paths to unset.
415
- */
416
- unset(attrs) {
417
- if (!Array.isArray(attrs))
418
- throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
419
- return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;
420
- }
421
- /**
422
- * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
423
- *
424
- * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
425
- */
426
- inc(attrs) {
427
- return this._assign("inc", attrs);
428
- }
429
- /**
430
- * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
431
- *
432
- * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
433
- */
434
- dec(attrs) {
435
- return this._assign("dec", attrs);
436
- }
437
- /**
438
- * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
439
- *
440
- * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
441
- * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
442
- * @param items - Array of items to insert/replace
443
- */
444
- insert(at, selector, items) {
445
- return config.validateInsert(at, selector, items), this._assign("insert", { [at]: selector, items });
446
- }
447
- /**
448
- * Append the given items to the array at the given JSONPath
449
- *
450
- * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
451
- * @param items - Array of items to append to the array
452
- */
453
- append(selector, items) {
454
- return this.insert("after", `${selector}[-1]`, items);
455
- }
456
- /**
457
- * Prepend the given items to the array at the given JSONPath
458
- *
459
- * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
460
- * @param items - Array of items to prepend to the array
461
- */
462
- prepend(selector, items) {
463
- return this.insert("before", `${selector}[0]`, items);
464
- }
465
- /**
466
- * Change the contents of an array by removing existing elements and/or adding new elements.
467
- *
468
- * @param selector - Attribute or JSONPath expression for array
469
- * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x
470
- * @param deleteCount - An integer indicating the number of old array elements to remove.
471
- * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.
472
- */
473
- splice(selector, start, deleteCount, items) {
474
- const delAll = typeof deleteCount > "u" || deleteCount === -1, startIndex = start < 0 ? start - 1 : start, delCount = delAll ? -1 : Math.max(0, start + deleteCount), delRange = startIndex < 0 && delCount >= 0 ? "" : delCount, rangeSelector = `${selector}[${startIndex}:${delRange}]`;
475
- return this.insert("replace", rangeSelector, items || []);
476
- }
477
- /**
478
- * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
479
- *
480
- * @param rev - Revision to lock the patch to
481
- */
482
- ifRevisionId(rev) {
483
- return this.operations.ifRevisionID = rev, this;
484
- }
485
- /**
486
- * Return a plain JSON representation of the patch
487
- */
488
- serialize() {
489
- return { ...getSelection(this.selection), ...this.operations };
490
- }
491
- /**
492
- * Return a plain JSON representation of the patch
493
- */
494
- toJSON() {
495
- return this.serialize();
496
- }
497
- /**
498
- * Clears the patch of all operations
499
- */
500
- reset() {
501
- return this.operations = {}, this;
502
- }
503
- _assign(op, props, merge = !0) {
504
- return config.validateObject(op, props), this.operations = Object.assign({}, this.operations, {
505
- [op]: Object.assign({}, merge && this.operations[op] || {}, props)
506
- }), this;
507
- }
508
- _set(op, props) {
509
- return this._assign(op, props, !1);
510
- }
511
- }
512
- class ObservablePatch extends BasePatch {
513
- #client;
514
- constructor(selection, operations, client) {
515
- super(selection, operations), this.#client = client;
516
- }
517
- /**
518
- * Clones the patch
519
- */
520
- clone() {
521
- return new ObservablePatch(this.selection, { ...this.operations }, this.#client);
522
- }
523
- commit(options) {
524
- if (!this.#client)
525
- throw new Error(
526
- "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
527
- );
528
- const returnFirst = typeof this.selection == "string", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);
529
- return this.#client.mutate({ patch: this.serialize() }, opts);
530
- }
531
- }
532
- class Patch extends BasePatch {
533
- #client;
534
- constructor(selection, operations, client) {
535
- super(selection, operations), this.#client = client;
536
- }
537
- /**
538
- * Clones the patch
539
- */
540
- clone() {
541
- return new Patch(this.selection, { ...this.operations }, this.#client);
542
- }
543
- commit(options) {
544
- if (!this.#client)
545
- throw new Error(
546
- "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
547
- );
548
- const returnFirst = typeof this.selection == "string", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);
549
- return this.#client.mutate({ patch: this.serialize() }, opts);
550
- }
551
- }
552
- const defaultMutateOptions = { returnDocuments: !1 };
553
- class BaseTransaction {
554
- operations;
555
- trxId;
556
- constructor(operations = [], transactionId) {
557
- this.operations = operations, this.trxId = transactionId;
558
- }
559
- /**
560
- * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.
561
- * The operation is added to the current transaction, ready to be commited by `commit()`
562
- *
563
- * @param doc - Document to create. Requires a `_type` property.
564
- */
565
- create(doc) {
566
- return config.validateObject("create", doc), this._add({ create: doc });
567
- }
568
- /**
569
- * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
570
- * The operation is added to the current transaction, ready to be commited by `commit()`
571
- *
572
- * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
573
- */
574
- createIfNotExists(doc) {
575
- const op = "createIfNotExists";
576
- return config.validateObject(op, doc), config.requireDocumentId(op, doc), this._add({ [op]: doc });
577
- }
578
- /**
579
- * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
580
- * The operation is added to the current transaction, ready to be commited by `commit()`
581
- *
582
- * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
583
- */
584
- createOrReplace(doc) {
585
- const op = "createOrReplace";
586
- return config.validateObject(op, doc), config.requireDocumentId(op, doc), this._add({ [op]: doc });
587
- }
588
- /**
589
- * Deletes the document with the given document ID
590
- * The operation is added to the current transaction, ready to be commited by `commit()`
591
- *
592
- * @param documentId - Document ID to delete
593
- */
594
- delete(documentId) {
595
- return config.validateDocumentId("delete", documentId), this._add({ delete: { id: documentId } });
596
- }
597
- transactionId(id) {
598
- return id ? (this.trxId = id, this) : this.trxId;
599
- }
600
- /**
601
- * Return a plain JSON representation of the transaction
602
- */
603
- serialize() {
604
- return [...this.operations];
605
- }
606
- /**
607
- * Return a plain JSON representation of the transaction
608
- */
609
- toJSON() {
610
- return this.serialize();
611
- }
612
- /**
613
- * Clears the transaction of all operations
614
- */
615
- reset() {
616
- return this.operations = [], this;
617
- }
618
- _add(mut) {
619
- return this.operations.push(mut), this;
620
- }
621
- }
622
- class Transaction extends BaseTransaction {
623
- #client;
624
- constructor(operations, client, transactionId) {
625
- super(operations, transactionId), this.#client = client;
626
- }
627
- /**
628
- * Clones the transaction
629
- */
630
- clone() {
631
- return new Transaction([...this.operations], this.#client, this.trxId);
632
- }
633
- commit(options) {
634
- if (!this.#client)
635
- throw new Error(
636
- "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
637
- );
638
- return this.#client.mutate(
639
- this.serialize(),
640
- Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
641
- );
642
- }
643
- patch(patchOrDocumentId, patchOps) {
644
- const isBuilder = typeof patchOps == "function", isPatch = typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof Patch, isMutationSelection = typeof patchOrDocumentId == "object" && ("query" in patchOrDocumentId || "id" in patchOrDocumentId);
645
- if (isPatch)
646
- return this._add({ patch: patchOrDocumentId.serialize() });
647
- if (isBuilder) {
648
- const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client));
649
- if (!(patch instanceof Patch))
650
- throw new Error("function passed to `patch()` must return the patch");
651
- return this._add({ patch: patch.serialize() });
652
- }
653
- if (isMutationSelection) {
654
- const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client);
655
- return this._add({ patch: patch.serialize() });
656
- }
657
- return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
658
- }
659
- }
660
- class ObservableTransaction extends BaseTransaction {
661
- #client;
662
- constructor(operations, client, transactionId) {
663
- super(operations, transactionId), this.#client = client;
664
- }
665
- /**
666
- * Clones the transaction
667
- */
668
- clone() {
669
- return new ObservableTransaction([...this.operations], this.#client, this.trxId);
670
- }
671
- commit(options) {
672
- if (!this.#client)
673
- throw new Error(
674
- "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
675
- );
676
- return this.#client.mutate(
677
- this.serialize(),
678
- Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
679
- );
680
- }
681
- patch(patchOrDocumentId, patchOps) {
682
- const isBuilder = typeof patchOps == "function";
683
- if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof ObservablePatch)
684
- return this._add({ patch: patchOrDocumentId.serialize() });
685
- if (isBuilder) {
686
- const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client));
687
- if (!(patch instanceof ObservablePatch))
688
- throw new Error("function passed to `patch()` must return the patch");
689
- return this._add({ patch: patch.serialize() });
690
- }
691
- return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
692
- }
693
- }
694
- const projectHeader = "X-Sanity-Project-ID";
695
- function requestOptions(config2, overrides = {}) {
696
- const headers = {};
697
- config2.headers && Object.assign(headers, config2.headers);
698
- const token = overrides.token || config2.token;
699
- token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config2.useProjectHostname && config2.projectId && (headers[projectHeader] = config2.projectId);
700
- const withCredentials = !!(typeof overrides.withCredentials > "u" ? config2.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > "u" ? config2.timeout : overrides.timeout;
701
- return Object.assign({}, overrides, {
702
- headers: Object.assign({}, headers, overrides.headers || {}),
703
- timeout: typeof timeout > "u" ? 5 * 60 * 1e3 : timeout,
704
- proxy: overrides.proxy || config2.proxy,
705
- json: !0,
706
- withCredentials,
707
- fetch: typeof overrides.fetch == "object" && typeof config2.fetch == "object" ? { ...config2.fetch, ...overrides.fetch } : overrides.fetch || config2.fetch
708
- });
709
- }
710
- const encodeQueryString = ({
711
- query,
712
- params = {},
713
- options = {}
714
- }) => {
715
- const searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;
716
- tag && searchParams.append("tag", tag), searchParams.append("query", query);
717
- for (const [key, value] of Object.entries(params))
718
- value !== void 0 && searchParams.append(`$${key}`, JSON.stringify(value));
719
- for (const [key, value] of Object.entries(opts))
720
- value && searchParams.append(key, `${value}`);
721
- return returnQuery === !1 && searchParams.append("returnQuery", "false"), includeMutations === !1 && searchParams.append("includeMutations", "false"), `?${searchParams}`;
722
- }, excludeFalsey = (param, defValue) => param === !1 ? void 0 : typeof param > "u" ? defValue : param, getMutationQuery = (options = {}) => ({
723
- dryRun: options.dryRun,
724
- returnIds: !0,
725
- returnDocuments: excludeFalsey(options.returnDocuments, !0),
726
- visibility: options.visibility || "sync",
727
- autoGenerateArrayKeys: options.autoGenerateArrayKeys,
728
- skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
729
- }), isResponse = (event) => event.type === "response", getBody = (event) => event.body, indexBy = (docs, attr) => docs.reduce((indexed, doc) => (indexed[attr(doc)] = doc, indexed), /* @__PURE__ */ Object.create(null)), getQuerySizeLimit = 11264;
730
- function _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {
731
- const stega = "stega" in options ? {
732
- ..._stega || {},
733
- ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
734
- } : _stega, params = stega.enabled ? stegaClean.stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
735
- // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.
736
- // This is necessary in React Server Components to avoid opting out of Request Memoization.
737
- useAbortSignal: typeof options.signal < "u",
738
- // Set `resultSourceMap' when stega is enabled, as it's required for encoding.
739
- resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
740
- ...options,
741
- // Default to not returning the query, unless `filterResponse` is `false`,
742
- // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy
743
- returnQuery: options.filterResponse === !1 && options.returnQuery !== !1
744
- }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(client, httpRequest, "query", { query, params }, reqOpts);
745
- return stega.enabled ? $request.pipe(
746
- operators.combineLatestWith(
747
- rxjs.from(
748
- Promise.resolve().then(function() {
749
- return require("./_chunks-cjs/stegaEncodeSourceMap.cjs");
750
- }).then(function(n) {
751
- return n.stegaEncodeSourceMap$1;
752
- }).then(
753
- ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap
754
- )
755
- )
756
- ),
757
- operators.map(
758
- ([res, stegaEncodeSourceMap]) => {
759
- const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
760
- return mapResponse({ ...res, result });
761
- }
762
- )
763
- ) : $request.pipe(operators.map(mapResponse));
764
- }
765
- function _getDocument(client, httpRequest, id, opts = {}) {
766
- const docId = (() => {
767
- if (!opts.releaseId)
768
- return id;
769
- const versionId = csm.getVersionFromId(id);
770
- if (!versionId) {
771
- if (csm.isDraftId(id))
772
- throw new Error(
773
- `The document ID (\`${id}\`) is a draft, but \`options.releaseId\` is set as \`${opts.releaseId}\``
774
- );
775
- return csm.getVersionId(id, opts.releaseId);
776
- }
777
- if (versionId !== opts.releaseId)
778
- throw new Error(
779
- `The document ID (\`${id}\`) is already a version of \`${versionId}\` release, but this does not match the provided \`options.releaseId\` (\`${opts.releaseId}\`)`
780
- );
781
- return id;
782
- })(), options = {
783
- uri: _getDataUrl(client, "doc", docId),
784
- json: !0,
785
- tag: opts.tag,
786
- signal: opts.signal,
787
- query: opts.includeAllVersions !== void 0 ? { includeAllVersions: opts.includeAllVersions } : void 0
788
- };
789
- return _requestObservable(
790
- client,
791
- httpRequest,
792
- options
793
- ).pipe(
794
- operators.filter(isResponse),
795
- operators.map((event) => {
796
- const documents = event.body.documents;
797
- return documents ? opts.includeAllVersions ? documents : documents[0] : opts.includeAllVersions ? [] : void 0;
798
- })
799
- );
800
- }
801
- function _getDocuments(client, httpRequest, ids, opts = {}) {
802
- const options = {
803
- uri: _getDataUrl(client, "doc", ids.join(",")),
804
- json: !0,
805
- tag: opts.tag,
806
- signal: opts.signal
807
- };
808
- return _requestObservable(client, httpRequest, options).pipe(
809
- operators.filter(isResponse),
810
- operators.map((event) => {
811
- const indexed = indexBy(event.body.documents || [], (doc) => doc._id);
812
- return ids.map((id) => indexed[id] || null);
813
- })
814
- );
815
- }
816
- const DOCUMENTS_EXISTS_BATCH_SIZE = 100;
817
- function _documentsExists(client, httpRequest, ids, opts = {}) {
818
- if (ids.length === 0)
819
- return rxjs.of(/* @__PURE__ */ new Set());
820
- const batches = [];
821
- for (let i = 0; i < ids.length; i += DOCUMENTS_EXISTS_BATCH_SIZE)
822
- batches.push(ids.slice(i, i + DOCUMENTS_EXISTS_BATCH_SIZE));
823
- const fetchBatch = (batchIds) => _requestObservable(client, httpRequest, {
824
- uri: _getDataUrl(client, "doc", batchIds.map(encodeURIComponent).join(",")),
825
- tag: opts.tag,
826
- signal: opts.signal,
827
- query: { excludeContent: !0 }
828
- }).pipe(
829
- operators.filter(isResponse),
830
- operators.map((event) => {
831
- const missing = /* @__PURE__ */ new Set();
832
- for (const omitted of event.body.omitted || [])
833
- omitted.reason === "existence" && missing.add(omitted.id);
834
- return new Set(batchIds.filter((id) => !missing.has(id)));
835
- })
836
- );
837
- return rxjs.from(batches).pipe(
838
- operators.concatMap(fetchBatch),
839
- operators.reduce((acc, set) => {
840
- for (const id of set) acc.add(id);
841
- return acc;
842
- }, /* @__PURE__ */ new Set())
843
- );
844
- }
845
- function _getReleaseDocuments(client, httpRequest, releaseId, opts = {}) {
846
- return _dataRequest(
847
- client,
848
- httpRequest,
849
- "query",
850
- {
851
- query: "*[sanity::partOfRelease($releaseId)]",
852
- params: {
853
- releaseId
854
- }
855
- },
856
- opts
857
- );
858
- }
859
- function _createIfNotExists(client, httpRequest, doc, options) {
860
- return config.requireDocumentId("createIfNotExists", doc), _create(client, httpRequest, doc, "createIfNotExists", options);
861
- }
862
- function _createOrReplace(client, httpRequest, doc, options) {
863
- return config.requireDocumentId("createOrReplace", doc), _create(client, httpRequest, doc, "createOrReplace", options);
864
- }
865
- function _createVersion(client, httpRequest, doc, publishedId, options) {
866
- return config.requireDocumentId("createVersion", doc), config.requireDocumentType("createVersion", doc), config.printCreateVersionWithBaseIdWarning(), _action(client, httpRequest, {
867
- actionType: "sanity.action.document.version.create",
868
- publishedId,
869
- document: doc
870
- }, options);
871
- }
872
- function _createVersionFromBase(client, httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options) {
873
- if (!baseId)
874
- throw new Error("`createVersion()` requires `baseId` when no `document` is provided");
875
- if (!publishedId)
876
- throw new Error("`createVersion()` requires `publishedId` when `baseId` is provided");
877
- config.validateDocumentId("createVersion", baseId), config.validateDocumentId("createVersion", publishedId);
878
- const createVersionAction = {
879
- actionType: "sanity.action.document.version.create",
880
- publishedId,
881
- baseId,
882
- versionId: releaseId ? csm.getVersionId(publishedId, releaseId) : csm.getDraftId(publishedId),
883
- ifBaseRevisionId
884
- };
885
- return _action(client, httpRequest, createVersionAction, options);
886
- }
887
- function _delete(client, httpRequest, selection, options) {
888
- return _dataRequest(
889
- client,
890
- httpRequest,
891
- "mutate",
892
- { mutations: [{ delete: getSelection(selection) }] },
893
- options
894
- );
895
- }
896
- function _discardVersion(client, httpRequest, versionId, purge = !1, options) {
897
- return _action(client, httpRequest, {
898
- actionType: "sanity.action.document.version.discard",
899
- versionId,
900
- purge
901
- }, options);
902
- }
903
- function _replaceVersion(client, httpRequest, doc, options) {
904
- return config.requireDocumentId("replaceVersion", doc), config.requireDocumentType("replaceVersion", doc), _action(client, httpRequest, {
905
- actionType: "sanity.action.document.version.replace",
906
- document: doc
907
- }, options);
908
- }
909
- function _unpublishVersion(client, httpRequest, versionId, publishedId, options) {
910
- return _action(client, httpRequest, {
911
- actionType: "sanity.action.document.version.unpublish",
912
- versionId,
913
- publishedId
914
- }, options);
915
- }
916
- function _mutate(client, httpRequest, mutations, options) {
917
- let mut;
918
- mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;
919
- const muts = Array.isArray(mut) ? mut : [mut], transactionId = options && options.transactionId || void 0;
920
- return _dataRequest(client, httpRequest, "mutate", { mutations: muts, transactionId }, options);
921
- }
922
- function _action(client, httpRequest, actions, options) {
923
- const acts = Array.isArray(actions) ? actions : [actions], transactionId = options && options.transactionId || void 0, skipCrossDatasetReferenceValidation = options && options.skipCrossDatasetReferenceValidation || void 0, dryRun = options && options.dryRun || void 0;
924
- return _dataRequest(
925
- client,
926
- httpRequest,
927
- "actions",
928
- { actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun },
929
- options
930
- );
931
- }
932
- function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
933
- 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(client, endpoint, stringQuery), reqOptions = {
934
- method: useGet ? "GET" : "POST",
935
- uri,
936
- json: !0,
937
- body: useGet ? void 0 : body,
938
- query: isMutation && getMutationQuery(options),
939
- timeout,
940
- headers,
941
- token,
942
- tag,
943
- returnQuery,
944
- perspective: options.perspective,
945
- variant: options.variant,
946
- resultSourceMap: options.resultSourceMap,
947
- lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,
948
- cacheMode,
949
- canUseCdn: isQuery2,
950
- signal: options.signal,
951
- fetch: options.fetch,
952
- useAbortSignal: options.useAbortSignal,
953
- useCdn: options.useCdn
954
- };
955
- return _requestObservable(client, httpRequest, reqOptions).pipe(
956
- operators.filter(isResponse),
957
- operators.map(getBody),
958
- operators.map((res) => {
959
- if (!isMutation)
960
- return res;
961
- const results = res.results || [];
962
- if (options.returnDocuments)
963
- return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
964
- const key = returnFirst ? "documentId" : "documentIds", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
965
- return {
966
- transactionId: res.transactionId,
967
- results,
968
- [key]: ids
969
- };
970
- })
971
- );
972
- }
973
- function _create(client, httpRequest, doc, op, options = {}) {
974
- const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);
975
- return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
976
- }
977
- const hasDataConfig = (client) => {
978
- const config2 = client.config();
979
- return config2.dataset !== void 0 && config2.projectId !== void 0 || config2.resource !== void 0;
980
- }, isQuery = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "query")), isMutate = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "mutate")), isDoc = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "doc", "")), isListener = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "listen")), isHistory = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "history", "")), isData = (client, uri) => uri.startsWith("/data/") || isQuery(client, uri) || isMutate(client, uri) || isDoc(client, uri) || isListener(client, uri) || isHistory(client, uri);
981
- function _requestObservable(client, httpRequest, options) {
982
- const callSiteStack = new Error(), uri = options.url || options.uri, config$1 = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(client, uri) : options.canUseCdn;
983
- let useCdn = (options.useCdn ?? config$1.useCdn) && canUseCdn;
984
- const tag = options.tag && config$1.requestTagPrefix ? [config$1.requestTagPrefix, options.tag].join(".") : options.tag || config$1.requestTagPrefix;
985
- if (tag && options.tag !== null && (options.query = { tag: config.requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && isQuery(client, uri)) {
986
- const resultSourceMap = options.resultSourceMap ?? config$1.resultSourceMap;
987
- resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
988
- const perspectiveOption = options.perspective || config$1.perspective;
989
- typeof perspectiveOption < "u" && (perspectiveOption === "previewDrafts" && config.printPreviewDraftsDeprecationWarning(), config.validateApiPerspective(perspectiveOption), options.query = {
990
- perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption,
991
- ...options.query
992
- }, (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || // previewDrafts was renamed to drafts, but keep for backwards compat
993
- perspectiveOption === "previewDrafts" || perspectiveOption === "drafts") && useCdn && (useCdn = !1, config.printCdnPreviewDraftsWarning()));
994
- const variantOption = options.variant || config$1.variant;
995
- typeof variantOption == "string" && (options.query = {
996
- variant: variantOption,
997
- ...options.query
998
- }), typeof variantOption == "object" && (options.query = {
999
- variantCondition: variantConditionsToQueryArray(variantOption),
1000
- ...options.query
1001
- }), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query }), useCdn && options.cacheMode == "noStale" && (options.query = { cacheMode: "noStale", ...options.query });
1002
- }
1003
- const reqOptions = requestOptions(
1004
- config$1,
1005
- Object.assign({}, options, {
1006
- url: _getUrl(client, uri, useCdn),
1007
- callSiteStack
1008
- })
1009
- ), request = new rxjs.Observable(
1010
- (subscriber) => httpRequest(reqOptions, config$1.requester).subscribe(subscriber)
1011
- );
1012
- return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
1013
- }
1014
- function _request(client, httpRequest, options) {
1015
- return _requestObservable(client, httpRequest, options).pipe(
1016
- operators.filter((event) => event.type === "response"),
1017
- operators.map((event) => event.body)
1018
- );
1019
- }
1020
- function _getDataUrl(client, operation, path) {
1021
- const config$1 = client.config();
1022
- if (config$1.resource) {
1023
- config.resourceConfig(config$1);
1024
- const resourceBase = resourceDataBase(config$1), uri2 = path !== void 0 ? `${operation}/${path}` : operation;
1025
- return `${resourceBase}/${uri2}`.replace(/\/($|\?)/, "$1");
1026
- }
1027
- const catalog = config.hasDataset(config$1), baseUri = `/${operation}/${catalog}`;
1028
- return `/data${path !== void 0 ? `${baseUri}/${path}` : baseUri}`.replace(/\/($|\?)/, "$1");
1029
- }
1030
- function _getUrl(client, uri, canUseCdn = !1) {
1031
- const { url, cdnUrl } = client.config();
1032
- return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
1033
- }
1034
- function _withAbortSignal(signal) {
1035
- return (input) => new rxjs.Observable((observer) => {
1036
- const abort = () => observer.error(_createAbortError(signal));
1037
- if (signal && signal.aborted) {
1038
- abort();
1039
- return;
1040
- }
1041
- const subscription = input.subscribe(observer);
1042
- return signal.addEventListener("abort", abort), () => {
1043
- signal.removeEventListener("abort", abort), subscription.unsubscribe();
1044
- };
1045
- });
1046
- }
1047
- const isDomExceptionSupported = !!globalThis.DOMException;
1048
- function _createAbortError(signal) {
1049
- if (isDomExceptionSupported)
1050
- return new DOMException(signal?.reason ?? "The operation was aborted.", "AbortError");
1051
- const error = new Error(signal?.reason ?? "The operation was aborted.");
1052
- return error.name = "AbortError", error;
1053
- }
1054
- const resourceDataBase = (config2) => {
1055
- const resource = config2.resource;
1056
- if (!resource)
1057
- throw new Error("`resource` must be provided to perform resource queries");
1058
- const { type, id } = resource;
1059
- switch (type) {
1060
- case "dataset": {
1061
- const segments = id.split(".");
1062
- if (segments.length !== 2)
1063
- throw new Error('Dataset ID must be in the format "project.dataset"');
1064
- return `/projects/${segments[0]}/datasets/${segments[1]}`;
1065
- }
1066
- case "canvas":
1067
- return `/canvases/${id}`;
1068
- case "media-library":
1069
- return `/media-libraries/${id}`;
1070
- case "dashboard":
1071
- return `/dashboards/${id}`;
1072
- default:
1073
- throw new Error(`Unsupported resource type: ${type.toString()}`);
1074
- }
1075
- };
1076
- function variantConditionsToQueryArray(variantConditions) {
1077
- return Object.entries(variantConditions).map(([condition, value]) => `${condition}:${value}`).toSorted();
1078
- }
1079
- function _generate(client, httpRequest, request) {
1080
- const dataset = config.hasDataset(client.config());
1081
- return _request(client, httpRequest, {
1082
- method: "POST",
1083
- uri: `/agent/action/generate/${dataset}`,
1084
- body: request
1085
- });
1086
- }
1087
- function _patch(client, httpRequest, request) {
1088
- const dataset = config.hasDataset(client.config());
1089
- return _request(client, httpRequest, {
1090
- method: "POST",
1091
- uri: `/agent/action/patch/${dataset}`,
1092
- body: request
1093
- });
1094
- }
1095
- function _prompt(client, httpRequest, request) {
1096
- const dataset = config.hasDataset(client.config());
1097
- return _request(client, httpRequest, {
1098
- method: "POST",
1099
- uri: `/agent/action/prompt/${dataset}`,
1100
- body: request
1101
- });
1102
- }
1103
- function _transform(client, httpRequest, request) {
1104
- const dataset = config.hasDataset(client.config());
1105
- return _request(client, httpRequest, {
1106
- method: "POST",
1107
- uri: `/agent/action/transform/${dataset}`,
1108
- body: request
1109
- });
1110
- }
1111
- function _translate(client, httpRequest, request) {
1112
- const dataset = config.hasDataset(client.config());
1113
- return _request(client, httpRequest, {
1114
- method: "POST",
1115
- uri: `/agent/action/translate/${dataset}`,
1116
- body: request
1117
- });
1118
- }
1119
- class ObservableAgentsActionClient {
1120
- #client;
1121
- #httpRequest;
1122
- constructor(client, httpRequest) {
1123
- this.#client = client, this.#httpRequest = httpRequest;
1124
- }
1125
- /**
1126
- * Run an instruction to generate content in a target document.
1127
- * @param request - instruction request
1128
- */
1129
- generate(request) {
1130
- return _generate(this.#client, this.#httpRequest, request);
1131
- }
1132
- /**
1133
- * Transform a target document based on a source.
1134
- * @param request - translation request
1135
- */
1136
- transform(request) {
1137
- return _transform(this.#client, this.#httpRequest, request);
1138
- }
1139
- /**
1140
- * Translate a target document based on a source.
1141
- * @param request - translation request
1142
- */
1143
- translate(request) {
1144
- return _translate(this.#client, this.#httpRequest, request);
1145
- }
1146
- }
1147
- class AgentActionsClient {
1148
- #client;
1149
- #httpRequest;
1150
- constructor(client, httpRequest) {
1151
- this.#client = client, this.#httpRequest = httpRequest;
1152
- }
1153
- /**
1154
- * Run an instruction to generate content in a target document.
1155
- * @param request - instruction request
1156
- */
1157
- generate(request) {
1158
- return rxjs.lastValueFrom(_generate(this.#client, this.#httpRequest, request));
1159
- }
1160
- /**
1161
- * Transform a target document based on a source.
1162
- * @param request - translation request
1163
- */
1164
- transform(request) {
1165
- return rxjs.lastValueFrom(_transform(this.#client, this.#httpRequest, request));
1166
- }
1167
- /**
1168
- * Translate a target document based on a source.
1169
- * @param request - translation request
1170
- */
1171
- translate(request) {
1172
- return rxjs.lastValueFrom(_translate(this.#client, this.#httpRequest, request));
1173
- }
1174
- /**
1175
- * Run a raw instruction and return the result either as text or json
1176
- * @param request - prompt request
1177
- */
1178
- prompt(request) {
1179
- return rxjs.lastValueFrom(_prompt(this.#client, this.#httpRequest, request));
1180
- }
1181
- /**
1182
- * Patch a document using a schema aware API.
1183
- * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.
1184
- * @param request - instruction request
1185
- */
1186
- patch(request) {
1187
- return rxjs.lastValueFrom(_patch(this.#client, this.#httpRequest, request));
1188
- }
1189
- }
1190
- class ObservableAssetsClient {
1191
- #client;
1192
- #httpRequest;
1193
- constructor(client, httpRequest) {
1194
- this.#client = client, this.#httpRequest = httpRequest;
1195
- }
1196
- upload(assetType, body, options) {
1197
- return _upload(this.#client, this.#httpRequest, assetType, body, options);
1198
- }
1199
- }
1200
- class AssetsClient {
1201
- #client;
1202
- #httpRequest;
1203
- constructor(client, httpRequest) {
1204
- this.#client = client, this.#httpRequest = httpRequest;
1205
- }
1206
- upload(assetType, body, options) {
1207
- const observable = _upload(this.#client, this.#httpRequest, assetType, body, options);
1208
- return rxjs.lastValueFrom(
1209
- observable.pipe(
1210
- operators.filter((event) => event.type === "response"),
1211
- operators.map(
1212
- (event) => event.body.document
1213
- )
1214
- )
1215
- );
1216
- }
1217
- }
1218
- function _upload(client, httpRequest, assetType, body, opts = {}) {
1219
- config.validateAssetType(assetType);
1220
- let meta = opts.extract || void 0;
1221
- meta && !meta.length && (meta = ["none"]);
1222
- const config$1 = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, isMediaLibrary = config$1.resource?.type === "media-library", query = isMediaLibrary ? {
1223
- // Media Library only supports basic parameters
1224
- title,
1225
- filename
1226
- } : {
1227
- // Content Lake supports full set of parameters
1228
- label,
1229
- title,
1230
- description,
1231
- filename,
1232
- meta,
1233
- creditLine
1234
- };
1235
- return source && !isMediaLibrary && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {
1236
- tag,
1237
- method: "POST",
1238
- timeout: options.timeout || 0,
1239
- uri: buildAssetUploadUrl(config$1, assetType),
1240
- headers: options.contentType ? { "Content-Type": options.contentType } : {},
1241
- query,
1242
- body
1243
- });
1244
- }
1245
- function buildAssetUploadUrl(config$1, assetType) {
1246
- const assetTypeEndpoint = assetType === "image" ? "images" : "files", resource = config$1.resource;
1247
- if (resource) {
1248
- const { type, id } = resource;
1249
- switch (type) {
1250
- case "dataset":
1251
- throw new Error(
1252
- "Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead."
1253
- );
1254
- case "canvas":
1255
- return `/canvases/${id}/assets/${assetTypeEndpoint}`;
1256
- case "media-library":
1257
- return `/media-libraries/${id}/upload`;
1258
- case "dashboard":
1259
- return `/dashboards/${id}/assets/${assetTypeEndpoint}`;
1260
- default:
1261
- throw new Error(`Unsupported resource type: ${type.toString()}`);
1262
- }
1263
- }
1264
- const dataset = config.hasDataset(config$1);
1265
- return `assets/${assetTypeEndpoint}/${dataset}`;
1266
- }
1267
- function optionsFromFile(opts, file) {
1268
- return typeof File > "u" || !(file instanceof File) ? opts : Object.assign(
1269
- {
1270
- filename: opts.preserveFilename === !1 ? void 0 : file.name,
1271
- contentType: file.type
1272
- },
1273
- opts
1274
- );
1275
- }
1276
- var defaults = (obj, defaults2) => Object.keys(defaults2).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = typeof obj[prop] > "u" ? defaults2[prop] : obj[prop], target), {});
1277
- const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), eventSourcePolyfill = rxjs.defer(() => import("@sanity/eventsource")).pipe(
1278
- operators.map(({ default: EventSource2 }) => EventSource2),
1279
- rxjs.shareReplay(1)
1280
- ), RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429]);
1281
- function reconnectOnConnectionFailure() {
1282
- return function(source) {
1283
- return source.pipe(
1284
- rxjs.catchError((err, caught) => err instanceof ConnectionFailedError && (typeof err.status != "number" || err.status < 400 || err.status >= 500 || RETRYABLE_STATUSES.has(err.status)) ? rxjs.concat(rxjs.of({ type: "reconnect" }), rxjs.timer(1e3).pipe(rxjs.mergeMap(() => caught))) : rxjs.throwError(() => err))
1285
- );
1286
- };
1287
- }
1288
- const MAX_URL_LENGTH = 14800, possibleOptions = [
1289
- "includePreviousRevision",
1290
- "includeResult",
1291
- "includeMutations",
1292
- "includeAllVersions",
1293
- "visibility",
1294
- "effectFormat",
1295
- "enableResume",
1296
- "tag"
1297
- ], defaultOptions = {
1298
- includeResult: !0
1299
- };
1300
- function _listen(query, params, opts = {}) {
1301
- 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, "listen", qs)}`;
1302
- if (uri.length > MAX_URL_LENGTH)
1303
- return rxjs.throwError(() => new Error("Query too large for listener"));
1304
- const listenFor = options.events ? options.events : ["mutation"], esOptions = {};
1305
- return withCredentials && (esOptions.withCredentials = !0), (token || configHeaders) && (esOptions.headers = {}, token && (esOptions.headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(esOptions.headers, configHeaders)), connectEventSource(() => (
1306
- // use polyfill if there is no global EventSource or if we need to set headers
1307
- (typeof EventSource > "u" || esOptions.headers ? eventSourcePolyfill : rxjs.of(EventSource)).pipe(operators.map((EventSource2) => new EventSource2(uri, esOptions)))
1308
- ), listenFor).pipe(
1309
- reconnectOnConnectionFailure(),
1310
- operators.filter((event) => listenFor.includes(event.type)),
1311
- operators.map((event) => ({
1312
- type: event.type,
1313
- ..."data" in event ? event.data : {}
1314
- }))
1315
- );
1316
- }
1317
- function shareReplayLatest(configOrPredicate, config2) {
1318
- return _shareReplayLatest(
1319
- typeof configOrPredicate == "function" ? { predicate: configOrPredicate, ...config2 } : configOrPredicate
1320
- );
1321
- }
1322
- function _shareReplayLatest(config2) {
1323
- return (source) => {
1324
- let latest, emitted = !1;
1325
- const { predicate, ...shareConfig } = config2, wrapped = source.pipe(
1326
- rxjs.tap((value) => {
1327
- config2.predicate(value) && (emitted = !0, latest = value);
1328
- }),
1329
- rxjs.finalize(() => {
1330
- emitted = !1, latest = void 0;
1331
- }),
1332
- rxjs.share(shareConfig)
1333
- ), emitLatest = new rxjs.Observable((subscriber) => {
1334
- emitted && subscriber.next(
1335
- // this cast is safe because of the emitted check which asserts that we got T from the source
1336
- latest
1337
- ), subscriber.complete();
1338
- });
1339
- return rxjs.merge(wrapped, emitLatest);
1340
- };
1341
- }
1342
- const requiredApiVersion = "2021-03-25";
1343
- class LiveClient {
1344
- #client;
1345
- constructor(client) {
1346
- this.#client = client;
1347
- }
1348
- /**
1349
- * Requires `apiVersion` to be `2021-03-25` or later.
1350
- */
1351
- events({
1352
- includeDrafts = !1,
1353
- tag: _tag,
1354
- waitFor
1355
- } = {}) {
1356
- const {
1357
- projectId,
1358
- apiVersion: _apiVersion,
1359
- token,
1360
- withCredentials,
1361
- requestTagPrefix,
1362
- headers: configHeaders
1363
- } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, "");
1364
- if (apiVersion !== "X" && apiVersion < requiredApiVersion)
1365
- throw new Error(
1366
- `The live events API requires API version ${requiredApiVersion} or later. The current API version is ${apiVersion}. Please update your API version to use this feature.`
1367
- );
1368
- if (includeDrafts && !token && !withCredentials)
1369
- throw new Error(
1370
- "The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role."
1371
- );
1372
- const path = _getDataUrl(this.#client, "live/events"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(".") : _tag;
1373
- tag && url.searchParams.set("tag", tag), includeDrafts && url.searchParams.set("includeDrafts", "true"), waitFor && url.searchParams.set("waitFor", waitFor);
1374
- const esOptions = {};
1375
- includeDrafts && withCredentials && (esOptions.withCredentials = !0), (includeDrafts && token || configHeaders) && (esOptions.headers = {}, includeDrafts && token && (esOptions.headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(esOptions.headers, configHeaders));
1376
- const key = `${url.href}::${JSON.stringify(esOptions)}`, existing = eventsCache.get(key);
1377
- if (existing)
1378
- return existing;
1379
- const events = connectEventSource(() => (
1380
- // use polyfill if there is no global EventSource or if we need to set headers
1381
- (typeof EventSource > "u" || esOptions.headers ? eventSourcePolyfill : rxjs.of(EventSource)).pipe(operators.map((EventSource2) => new EventSource2(url.href, esOptions)))
1382
- ), [
1383
- "message",
1384
- "restart",
1385
- "welcome",
1386
- "reconnect",
1387
- "goaway"
1388
- ]), checkCors = checkCorsObservable(
1389
- new URL(this.#client.getUrl("/check/cors", !1)),
1390
- projectId,
1391
- esOptions.withCredentials === !0
1392
- ), observable = events.pipe(
1393
- reconnectOnConnectionFailure(),
1394
- rxjs.mergeMap((event) => event.type === "reconnect" ? checkCors.pipe(rxjs.mergeMap(() => rxjs.of(event))) : rxjs.of(event)),
1395
- rxjs.catchError((err) => err instanceof CorsOriginError ? rxjs.throwError(() => err) : checkCors.pipe(
1396
- rxjs.mergeMap(() => {
1397
- throw err;
1398
- })
1399
- )),
1400
- operators.map((event) => {
1401
- if (event.type === "message") {
1402
- const { data, ...rest } = event;
1403
- return { ...rest, tags: data.tags };
1404
- }
1405
- return event;
1406
- })
1407
- ).pipe(
1408
- operators.finalize(() => eventsCache.delete(key)),
1409
- shareReplayLatest({
1410
- predicate: (event) => event.type === "welcome"
1411
- })
1412
- );
1413
- return eventsCache.set(key, observable), observable;
1414
- }
1415
- }
1416
- function checkCorsObservable(url, projectId, requireCredentials) {
1417
- return new rxjs.Observable((observer) => {
1418
- const controller = new AbortController(), { signal } = controller;
1419
- return fetch(url, { method: "GET", mode: "cors", credentials: "omit", signal }).then((response) => {
1420
- if (!(signal.aborted || !response.ok))
1421
- return response.json();
1422
- }).then((body) => {
1423
- if (!signal.aborted) {
1424
- if (requireCredentials && body?.result?.withCredentials === !1) {
1425
- observer.error(new CorsOriginError({ projectId, credentials: !0 }));
1426
- return;
1427
- }
1428
- if (body?.result?.allowed === !1) {
1429
- observer.error(new CorsOriginError({ projectId, credentials: requireCredentials }));
1430
- return;
1431
- }
1432
- observer.next(), observer.complete();
1433
- }
1434
- }).catch(() => {
1435
- signal.aborted || observer.closed || (observer.next(), observer.complete());
1436
- }), () => controller.abort();
1437
- });
1438
- }
1439
- const eventsCache = /* @__PURE__ */ new Map();
1440
- class ObservableDatasetsClient {
1441
- #client;
1442
- #httpRequest;
1443
- constructor(client, httpRequest) {
1444
- this.#client = client, this.#httpRequest = httpRequest;
1445
- }
1446
- /**
1447
- * Create a new dataset with the given name
1448
- *
1449
- * @param name - Name of the dataset to create
1450
- * @param options - Options for the dataset, including optional embeddings configuration
1451
- */
1452
- create(name2, options) {
1453
- return _modify(this.#client, this.#httpRequest, "PUT", name2, options);
1454
- }
1455
- /**
1456
- * Edit a dataset with the given name
1457
- *
1458
- * @param name - Name of the dataset to edit
1459
- * @param options - New options for the dataset
1460
- */
1461
- edit(name2, options) {
1462
- return _modify(this.#client, this.#httpRequest, "PATCH", name2, options);
1463
- }
1464
- /**
1465
- * Delete a dataset with the given name
1466
- *
1467
- * @param name - Name of the dataset to delete
1468
- */
1469
- delete(name2) {
1470
- return _modify(this.#client, this.#httpRequest, "DELETE", name2);
1471
- }
1472
- /**
1473
- * Fetch a list of datasets for the configured project
1474
- */
1475
- list() {
1476
- config.resourceGuard("dataset", this.#client.config());
1477
- const config$1 = this.#client.config(), projectId = config$1.projectId;
1478
- let uri = "/datasets";
1479
- return config$1.useProjectHostname === !1 && (uri = `/projects/${projectId}/datasets`), _request(this.#client, this.#httpRequest, {
1480
- uri,
1481
- tag: null
1482
- });
1483
- }
1484
- /**
1485
- * Get embeddings settings for a dataset
1486
- *
1487
- * @param name - Name of the dataset
1488
- */
1489
- getEmbeddingsSettings(name2) {
1490
- return config.resourceGuard("dataset", this.#client.config()), config.dataset(name2), _request(this.#client, this.#httpRequest, {
1491
- uri: _embeddingsSettingsUri(this.#client, name2),
1492
- tag: null
1493
- });
1494
- }
1495
- /**
1496
- * Edit embeddings settings for a dataset
1497
- *
1498
- * @param name - Name of the dataset
1499
- * @param settings - Embeddings settings to apply
1500
- */
1501
- editEmbeddingsSettings(name2, settings) {
1502
- return config.resourceGuard("dataset", this.#client.config()), config.dataset(name2), _request(this.#client, this.#httpRequest, {
1503
- method: "PUT",
1504
- uri: _embeddingsSettingsUri(this.#client, name2),
1505
- body: settings,
1506
- tag: null
1507
- });
1508
- }
1509
- }
1510
- class DatasetsClient {
1511
- #client;
1512
- #httpRequest;
1513
- constructor(client, httpRequest) {
1514
- this.#client = client, this.#httpRequest = httpRequest;
1515
- }
1516
- /**
1517
- * Create a new dataset with the given name
1518
- *
1519
- * @param name - Name of the dataset to create
1520
- * @param options - Options for the dataset, including optional embeddings configuration
1521
- */
1522
- create(name2, options) {
1523
- return config.resourceGuard("dataset", this.#client.config()), rxjs.lastValueFrom(
1524
- _modify(this.#client, this.#httpRequest, "PUT", name2, options)
1525
- );
1526
- }
1527
- /**
1528
- * Edit a dataset with the given name
1529
- *
1530
- * @param name - Name of the dataset to edit
1531
- * @param options - New options for the dataset
1532
- */
1533
- edit(name2, options) {
1534
- return config.resourceGuard("dataset", this.#client.config()), rxjs.lastValueFrom(
1535
- _modify(this.#client, this.#httpRequest, "PATCH", name2, options)
1536
- );
1537
- }
1538
- /**
1539
- * Delete a dataset with the given name
1540
- *
1541
- * @param name - Name of the dataset to delete
1542
- */
1543
- delete(name2) {
1544
- return config.resourceGuard("dataset", this.#client.config()), rxjs.lastValueFrom(_modify(this.#client, this.#httpRequest, "DELETE", name2));
1545
- }
1546
- /**
1547
- * Fetch a list of datasets for the configured project
1548
- */
1549
- list() {
1550
- config.resourceGuard("dataset", this.#client.config());
1551
- const config$1 = this.#client.config(), projectId = config$1.projectId;
1552
- let uri = "/datasets";
1553
- return config$1.useProjectHostname === !1 && (uri = `/projects/${projectId}/datasets`), rxjs.lastValueFrom(
1554
- _request(this.#client, this.#httpRequest, { uri, tag: null })
1555
- );
1556
- }
1557
- /**
1558
- * Get embeddings settings for a dataset
1559
- *
1560
- * @param name - Name of the dataset
1561
- */
1562
- getEmbeddingsSettings(name2) {
1563
- return config.resourceGuard("dataset", this.#client.config()), config.dataset(name2), rxjs.lastValueFrom(
1564
- _request(this.#client, this.#httpRequest, {
1565
- uri: _embeddingsSettingsUri(this.#client, name2),
1566
- tag: null
1567
- })
1568
- );
1569
- }
1570
- /**
1571
- * Edit embeddings settings for a dataset
1572
- *
1573
- * @param name - Name of the dataset
1574
- * @param settings - Embeddings settings to apply
1575
- */
1576
- editEmbeddingsSettings(name2, settings) {
1577
- return config.resourceGuard("dataset", this.#client.config()), config.dataset(name2), rxjs.lastValueFrom(
1578
- _request(this.#client, this.#httpRequest, {
1579
- method: "PUT",
1580
- uri: _embeddingsSettingsUri(this.#client, name2),
1581
- body: settings,
1582
- tag: null
1583
- })
1584
- );
1585
- }
1586
- }
1587
- function _embeddingsSettingsUri(client, name2) {
1588
- const config2 = client.config();
1589
- return config2.useProjectHostname === !1 ? `/projects/${config2.projectId}/datasets/${name2}/settings/embeddings` : `/datasets/${name2}/settings/embeddings`;
1590
- }
1591
- function _modify(client, httpRequest, method, name2, options) {
1592
- return config.resourceGuard("dataset", client.config()), config.dataset(name2), _request(client, httpRequest, {
1593
- method,
1594
- uri: `/datasets/${name2}`,
1595
- body: options,
1596
- tag: null
1597
- });
1598
- }
1599
- class ObservableMediaLibraryVideoClient {
1600
- #client;
1601
- #httpRequest;
1602
- constructor(client, httpRequest) {
1603
- this.#client = client, this.#httpRequest = httpRequest;
1604
- }
1605
- /**
1606
- * Get video playback information for a media library asset
1607
- *
1608
- * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
1609
- * @param options - Options for transformations and expiration
1610
- */
1611
- getPlaybackInfo(assetIdentifier, options = {}) {
1612
- const config2 = this.#client.config(), configMediaLibraryId = (config2.resource || config2["~experimental_resource"])?.id, { instanceId, libraryId } = parseAssetInstanceId(assetIdentifier), effectiveLibraryId = libraryId || configMediaLibraryId;
1613
- if (!effectiveLibraryId)
1614
- throw new Error(
1615
- "Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR"
1616
- );
1617
- const uri = buildVideoPlaybackInfoUrl(instanceId, effectiveLibraryId), queryParams = buildQueryParams(options);
1618
- return _request(this.#client, this.#httpRequest, {
1619
- method: "GET",
1620
- uri,
1621
- query: queryParams
1622
- });
1623
- }
1624
- }
1625
- class MediaLibraryVideoClient {
1626
- #client;
1627
- #httpRequest;
1628
- constructor(client, httpRequest) {
1629
- this.#client = client, this.#httpRequest = httpRequest;
1630
- }
1631
- /**
1632
- * Get video playback information for a media library asset
1633
- *
1634
- * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
1635
- * @param options - Options for transformations and expiration
1636
- */
1637
- getPlaybackInfo(assetIdentifier, options = {}) {
1638
- return rxjs.lastValueFrom(
1639
- new ObservableMediaLibraryVideoClient(
1640
- this.#client.observable,
1641
- this.#httpRequest
1642
- ).getPlaybackInfo(assetIdentifier, options)
1643
- );
1644
- }
1645
- }
1646
- const ML_GDR_PATTERN = /^media-library:(ml[^:]+):([^:]+)$/;
1647
- function isSanityReference(assetIdentifier) {
1648
- return typeof assetIdentifier == "object" && "_ref" in assetIdentifier;
1649
- }
1650
- function parseAssetInstanceId(assetIdentifier) {
1651
- const ref = isSanityReference(assetIdentifier) ? assetIdentifier._ref : assetIdentifier, match = ML_GDR_PATTERN.exec(ref);
1652
- if (match) {
1653
- const [, libraryId, instanceId] = match;
1654
- return { libraryId, instanceId };
1655
- }
1656
- if (typeof assetIdentifier == "string" && assetIdentifier.startsWith("video-"))
1657
- return { instanceId: assetIdentifier };
1658
- throw new Error(
1659
- `Invalid video asset instance identifier "${ref}": must be a valid video instance id or a Global Dataset Reference (GDR) to the video asset in the Media Library`
1660
- );
1661
- }
1662
- function buildVideoPlaybackInfoUrl(instanceId, libraryId) {
1663
- return `/media-libraries/${libraryId}/video/${instanceId}/playback-info`;
1664
- }
1665
- function buildQueryParams(options) {
1666
- const params = {};
1667
- if (options.transformations) {
1668
- const { thumbnail, animated, storyboard } = options.transformations;
1669
- thumbnail && (thumbnail.width && (params.thumbnailWidth = thumbnail.width), thumbnail.height && (params.thumbnailHeight = thumbnail.height), thumbnail.time !== void 0 && (params.thumbnailTime = thumbnail.time), thumbnail.fit && (params.thumbnailFit = thumbnail.fit), thumbnail.format && (params.thumbnailFormat = thumbnail.format)), animated && (animated.width && (params.animatedWidth = animated.width), animated.height && (params.animatedHeight = animated.height), animated.start !== void 0 && (params.animatedStart = animated.start), animated.end !== void 0 && (params.animatedEnd = animated.end), animated.fps && (params.animatedFps = animated.fps), animated.format && (params.animatedFormat = animated.format)), storyboard && storyboard.format && (params.storyboardFormat = storyboard.format);
1670
- }
1671
- return options.expiration && (params.expiration = options.expiration), params;
1672
- }
1673
- class ObservableProjectsClient {
1674
- #client;
1675
- #httpRequest;
1676
- constructor(client, httpRequest) {
1677
- this.#client = client, this.#httpRequest = httpRequest;
1678
- }
1679
- /**
1680
- * Fetch a list of projects the authenticated user has access to.
1681
- *
1682
- * @param options - Options for the list request
1683
- * - `includeMembers` - Whether to include members in the response (default: true)
1684
- * - `includeFeatures` - Whether to include features in the response (default: true)
1685
- * - `organizationId` - ID of the organization to fetch projects for
1686
- * - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
1687
- */
1688
- list(options) {
1689
- const query = {}, uri = "/projects";
1690
- return options?.includeMembers === !1 && (query.includeMembers = "false"), options?.includeFeatures === !1 && (query.includeFeatures = "false"), options?.organizationId && (query.organizationId = options.organizationId), options?.onlyExplicitMembership && (query.onlyExplicitMembership = "true"), _request(this.#client, this.#httpRequest, { uri, query });
1691
- }
1692
- /**
1693
- * Fetch a project by project ID
1694
- *
1695
- * @param projectId - ID of the project to fetch
1696
- */
1697
- getById(projectId) {
1698
- return _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` });
1699
- }
1700
- }
1701
- class ProjectsClient {
1702
- #client;
1703
- #httpRequest;
1704
- constructor(client, httpRequest) {
1705
- this.#client = client, this.#httpRequest = httpRequest;
1706
- }
1707
- /**
1708
- * Fetch a list of projects the authenticated user has access to.
1709
- *
1710
- * @param options - Options for the list request
1711
- * - `includeMembers` - Whether to include members in the response (default: true)
1712
- * - `includeFeatures` - Whether to include features in the response (default: true)
1713
- * - `organizationId` - ID of the organization to fetch projects for
1714
- * - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
1715
- */
1716
- list(options) {
1717
- const query = {}, uri = "/projects";
1718
- return options?.includeMembers === !1 && (query.includeMembers = "false"), options?.includeFeatures === !1 && (query.includeFeatures = "false"), options?.organizationId && (query.organizationId = options.organizationId), options?.onlyExplicitMembership && (query.onlyExplicitMembership = "true"), rxjs.lastValueFrom(
1719
- _request(this.#client, this.#httpRequest, { uri, query })
1720
- );
1721
- }
1722
- /**
1723
- * Fetch a project by project ID
1724
- *
1725
- * @param projectId - ID of the project to fetch
1726
- */
1727
- getById(projectId) {
1728
- return rxjs.lastValueFrom(
1729
- _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` })
1730
- );
1731
- }
1732
- }
1733
- const generateReleaseId = nanoid.customAlphabet(
1734
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
1735
- 8
1736
- ), getDocumentVersionId = (publishedId, releaseId) => releaseId ? csm.getVersionId(publishedId, releaseId) : csm.getDraftId(publishedId);
1737
- function deriveDocumentVersionId(op, {
1738
- releaseId,
1739
- publishedId,
1740
- document
1741
- }) {
1742
- if (publishedId && document._id) {
1743
- const versionId = getDocumentVersionId(publishedId, releaseId);
1744
- return config.validateVersionIdMatch(versionId, document), versionId;
1745
- }
1746
- if (document._id) {
1747
- const isDraft = csm.isDraftId(document._id), isVersion = csm.isVersionId(document._id);
1748
- if (!isDraft && !isVersion)
1749
- throw new Error(
1750
- `\`${op}()\` requires a document with an \`_id\` that is a version or draft ID`
1751
- );
1752
- if (releaseId) {
1753
- if (isDraft)
1754
- throw new Error(
1755
- `\`${op}()\` was called with a document ID (\`${document._id}\`) that is a draft ID, but a release ID (\`${releaseId}\`) was also provided.`
1756
- );
1757
- const builtVersionId = csm.getVersionFromId(document._id);
1758
- if (builtVersionId !== releaseId)
1759
- throw new Error(
1760
- `\`${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}\`).`
1761
- );
1762
- }
1763
- return document._id;
1764
- }
1765
- if (publishedId)
1766
- return getDocumentVersionId(publishedId, releaseId);
1767
- throw new Error(`\`${op}()\` requires either a publishedId or a document with an \`_id\``);
1768
- }
1769
- const getArgs = (releaseOrOptions, maybeOptions) => {
1770
- if (typeof releaseOrOptions == "object" && releaseOrOptions !== null && ("releaseId" in releaseOrOptions || "metadata" in releaseOrOptions)) {
1771
- const { releaseId = generateReleaseId(), metadata = {} } = releaseOrOptions;
1772
- return [releaseId, metadata, maybeOptions];
1773
- }
1774
- return [generateReleaseId(), {}, releaseOrOptions];
1775
- }, createRelease = (releaseOrOptions, maybeOptions) => {
1776
- const [releaseId, metadata, options] = getArgs(releaseOrOptions, maybeOptions), finalMetadata = {
1777
- ...metadata,
1778
- releaseType: metadata.releaseType || "undecided"
1779
- };
1780
- return { action: {
1781
- actionType: "sanity.action.release.create",
1782
- releaseId,
1783
- metadata: finalMetadata
1784
- }, options };
1785
- };
1786
- class ObservableReleasesClient {
1787
- #client;
1788
- #httpRequest;
1789
- constructor(client, httpRequest) {
1790
- this.#client = client, this.#httpRequest = httpRequest;
1791
- }
1792
- /**
1793
- * @public
1794
- *
1795
- * Retrieve a release by id.
1796
- *
1797
- * @category Releases
1798
- *
1799
- * @param params - Release action parameters:
1800
- * - `releaseId` - The id of the release to retrieve.
1801
- * @param options - Additional query options including abort signal and query tag.
1802
- * @returns An observable that resolves to the release document {@link ReleaseDocument}.
1803
- *
1804
- * @example Retrieving a release by id
1805
- * ```ts
1806
- * client.observable.releases.get({releaseId: 'my-release'}).pipe(
1807
- * tap((release) => console.log(release)),
1808
- * // {
1809
- * // _id: '_.releases.my-release',
1810
- * // name: 'my-release'
1811
- * // _type: 'system.release',
1812
- * // metadata: {releaseType: 'asap'},
1813
- * // _createdAt: '2021-01-01T00:00:00.000Z',
1814
- * // ...
1815
- * // }
1816
- * ).subscribe()
1817
- * ```
1818
- */
1819
- get({ releaseId }, options) {
1820
- return _getDocument(
1821
- this.#client,
1822
- this.#httpRequest,
1823
- `_.releases.${releaseId}`,
1824
- options
1825
- );
1826
- }
1827
- create(releaseOrOptions, maybeOptions) {
1828
- const { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
1829
- return _action(this.#client, this.#httpRequest, action, options).pipe(
1830
- rxjs.map((actionResult) => ({
1831
- ...actionResult,
1832
- releaseId,
1833
- metadata
1834
- }))
1835
- );
1836
- }
1837
- /**
1838
- * @public
1839
- *
1840
- * Edits an existing release, updating the metadata.
1841
- *
1842
- * @category Releases
1843
- *
1844
- * @param params - Release action parameters:
1845
- * - `releaseId` - The id of the release to edit.
1846
- * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
1847
- * @param options - Additional action options.
1848
- * @returns An observable that resolves to the `transactionId`.
1849
- */
1850
- edit({ releaseId, patch }, options) {
1851
- const editAction = {
1852
- actionType: "sanity.action.release.edit",
1853
- releaseId,
1854
- patch
1855
- };
1856
- return _action(this.#client, this.#httpRequest, editAction, options);
1857
- }
1858
- /**
1859
- * @public
1860
- *
1861
- * Publishes all documents in a release at once. For larger releases the effect of the publish
1862
- * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
1863
- * documents and creation of the corresponding published documents with the new content may
1864
- * take some time.
1865
- *
1866
- * During this period both the source and target documents are locked and cannot be
1867
- * modified through any other means.
1868
- *
1869
- * @category Releases
1870
- *
1871
- * @param params - Release action parameters:
1872
- * - `releaseId` - The id of the release to publish.
1873
- * @param options - Additional action options.
1874
- * @returns An observable that resolves to the `transactionId`.
1875
- */
1876
- publish({ releaseId }, options) {
1877
- const publishAction = {
1878
- actionType: "sanity.action.release.publish",
1879
- releaseId
1880
- };
1881
- return _action(this.#client, this.#httpRequest, publishAction, options);
1882
- }
1883
- /**
1884
- * @public
1885
- *
1886
- * An archive action removes an active release. The documents that comprise the release
1887
- * are deleted and therefore no longer queryable.
1888
- *
1889
- * While the documents remain in retention the last version can still be accessed using document history endpoint.
1890
- *
1891
- * @category Releases
1892
- *
1893
- * @param params - Release action parameters:
1894
- * - `releaseId` - The id of the release to archive.
1895
- * @param options - Additional action options.
1896
- * @returns An observable that resolves to the `transactionId`.
1897
- */
1898
- archive({ releaseId }, options) {
1899
- const archiveAction = {
1900
- actionType: "sanity.action.release.archive",
1901
- releaseId
1902
- };
1903
- return _action(this.#client, this.#httpRequest, archiveAction, options);
1904
- }
1905
- /**
1906
- * @public
1907
- *
1908
- * An unarchive action restores an archived release and all documents
1909
- * with the content they had just prior to archiving.
1910
- *
1911
- * @category Releases
1912
- *
1913
- * @param params - Release action parameters:
1914
- * - `releaseId` - The id of the release to unarchive.
1915
- * @param options - Additional action options.
1916
- * @returns An observable that resolves to the `transactionId`.
1917
- */
1918
- unarchive({ releaseId }, options) {
1919
- const unarchiveAction = {
1920
- actionType: "sanity.action.release.unarchive",
1921
- releaseId
1922
- };
1923
- return _action(this.#client, this.#httpRequest, unarchiveAction, options);
1924
- }
1925
- /**
1926
- * @public
1927
- *
1928
- * A schedule action queues a release for publishing at the given future time.
1929
- * The release is locked such that no documents in the release can be modified and
1930
- * no documents that it references can be deleted as this would make the publish fail.
1931
- * At the given time, the same logic as for the publish action is triggered.
1932
- *
1933
- * @category Releases
1934
- *
1935
- * @param params - Release action parameters:
1936
- * - `releaseId` - The id of the release to schedule.
1937
- * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
1938
- * @param options - Additional action options.
1939
- * @returns An observable that resolves to the `transactionId`.
1940
- */
1941
- schedule({ releaseId, publishAt }, options) {
1942
- const scheduleAction = {
1943
- actionType: "sanity.action.release.schedule",
1944
- releaseId,
1945
- publishAt
1946
- };
1947
- return _action(this.#client, this.#httpRequest, scheduleAction, options);
1948
- }
1949
- /**
1950
- * @public
1951
- *
1952
- * An unschedule action stops a release from being published.
1953
- * The documents in the release are considered unlocked and can be edited again.
1954
- * This may fail if another release is scheduled to be published after this one and
1955
- * has a reference to a document created by this one.
1956
- *
1957
- * @category Releases
1958
- *
1959
- * @param params - Release action parameters:
1960
- * - `releaseId` - The id of the release to unschedule.
1961
- * @param options - Additional action options.
1962
- * @returns An observable that resolves to the `transactionId`.
1963
- */
1964
- unschedule({ releaseId }, options) {
1965
- const unscheduleAction = {
1966
- actionType: "sanity.action.release.unschedule",
1967
- releaseId
1968
- };
1969
- return _action(this.#client, this.#httpRequest, unscheduleAction, options);
1970
- }
1971
- /**
1972
- * @public
1973
- *
1974
- * A delete action removes a published or archived release.
1975
- * The backing system document will be removed from the dataset.
1976
- *
1977
- * @category Releases
1978
- *
1979
- * @param params - Release action parameters:
1980
- * - `releaseId` - The id of the release to delete.
1981
- * @param options - Additional action options.
1982
- * @returns An observable that resolves to the `transactionId`.
1983
- */
1984
- delete({ releaseId }, options) {
1985
- const deleteAction = {
1986
- actionType: "sanity.action.release.delete",
1987
- releaseId
1988
- };
1989
- return _action(this.#client, this.#httpRequest, deleteAction, options);
1990
- }
1991
- /**
1992
- * @public
1993
- *
1994
- * Fetch the documents in a release by release id.
1995
- *
1996
- * @category Releases
1997
- *
1998
- * @param params - Release action parameters:
1999
- * - `releaseId` - The id of the release to fetch documents for.
2000
- * @param options - Additional mutation options {@link BaseMutationOptions}.
2001
- * @returns An observable that resolves to the documents in the release.
2002
- */
2003
- fetchDocuments({ releaseId }, options) {
2004
- return _getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options);
2005
- }
2006
- }
2007
- class ReleasesClient {
2008
- #client;
2009
- #httpRequest;
2010
- constructor(client, httpRequest) {
2011
- this.#client = client, this.#httpRequest = httpRequest;
2012
- }
2013
- /**
2014
- * @public
2015
- *
2016
- * Retrieve a release by id.
2017
- *
2018
- * @category Releases
2019
- *
2020
- * @param params - Release action parameters:
2021
- * - `releaseId` - The id of the release to retrieve.
2022
- * @param options - Additional query options including abort signal and query tag.
2023
- * @returns A promise that resolves to the release document {@link ReleaseDocument}.
2024
- *
2025
- * @example Retrieving a release by id
2026
- * ```ts
2027
- * const release = await client.releases.get({releaseId: 'my-release'})
2028
- * console.log(release)
2029
- * // {
2030
- * // _id: '_.releases.my-release',
2031
- * // name: 'my-release'
2032
- * // _type: 'system.release',
2033
- * // metadata: {releaseType: 'asap'},
2034
- * // _createdAt: '2021-01-01T00:00:00.000Z',
2035
- * // ...
2036
- * // }
2037
- * ```
2038
- */
2039
- get({ releaseId }, options) {
2040
- return rxjs.lastValueFrom(
2041
- _getDocument(
2042
- this.#client,
2043
- this.#httpRequest,
2044
- `_.releases.${releaseId}`,
2045
- options
2046
- )
2047
- );
2048
- }
2049
- async create(releaseOrOptions, maybeOptions) {
2050
- const { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
2051
- return { ...await rxjs.lastValueFrom(
2052
- _action(this.#client, this.#httpRequest, action, options)
2053
- ), releaseId, metadata };
2054
- }
2055
- /**
2056
- * @public
2057
- *
2058
- * Edits an existing release, updating the metadata.
2059
- *
2060
- * @category Releases
2061
- *
2062
- * @param params - Release action parameters:
2063
- * - `releaseId` - The id of the release to edit.
2064
- * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
2065
- * @param options - Additional action options.
2066
- * @returns A promise that resolves to the `transactionId`.
2067
- */
2068
- edit({ releaseId, patch }, options) {
2069
- const editAction = {
2070
- actionType: "sanity.action.release.edit",
2071
- releaseId,
2072
- patch
2073
- };
2074
- return rxjs.lastValueFrom(_action(this.#client, this.#httpRequest, editAction, options));
2075
- }
2076
- /**
2077
- * @public
2078
- *
2079
- * Publishes all documents in a release at once. For larger releases the effect of the publish
2080
- * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
2081
- * documents and creation of the corresponding published documents with the new content may
2082
- * take some time.
2083
- *
2084
- * During this period both the source and target documents are locked and cannot be
2085
- * modified through any other means.
2086
- *
2087
- * @category Releases
2088
- *
2089
- * @param params - Release action parameters:
2090
- * - `releaseId` - The id of the release to publish.
2091
- * @param options - Additional action options.
2092
- * @returns A promise that resolves to the `transactionId`.
2093
- */
2094
- publish({ releaseId }, options) {
2095
- const publishAction = {
2096
- actionType: "sanity.action.release.publish",
2097
- releaseId
2098
- };
2099
- return rxjs.lastValueFrom(_action(this.#client, this.#httpRequest, publishAction, options));
2100
- }
2101
- /**
2102
- * @public
2103
- *
2104
- * An archive action removes an active release. The documents that comprise the release
2105
- * are deleted and therefore no longer queryable.
2106
- *
2107
- * While the documents remain in retention the last version can still be accessed using document history endpoint.
2108
- *
2109
- * @category Releases
2110
- *
2111
- * @param params - Release action parameters:
2112
- * - `releaseId` - The id of the release to archive.
2113
- * @param options - Additional action options.
2114
- * @returns A promise that resolves to the `transactionId`.
2115
- */
2116
- archive({ releaseId }, options) {
2117
- const archiveAction = {
2118
- actionType: "sanity.action.release.archive",
2119
- releaseId
2120
- };
2121
- return rxjs.lastValueFrom(_action(this.#client, this.#httpRequest, archiveAction, options));
2122
- }
2123
- /**
2124
- * @public
2125
- *
2126
- * An unarchive action restores an archived release and all documents
2127
- * with the content they had just prior to archiving.
2128
- *
2129
- * @category Releases
2130
- *
2131
- * @param params - Release action parameters:
2132
- * - `releaseId` - The id of the release to unarchive.
2133
- * @param options - Additional action options.
2134
- * @returns A promise that resolves to the `transactionId`.
2135
- */
2136
- unarchive({ releaseId }, options) {
2137
- const unarchiveAction = {
2138
- actionType: "sanity.action.release.unarchive",
2139
- releaseId
2140
- };
2141
- return rxjs.lastValueFrom(_action(this.#client, this.#httpRequest, unarchiveAction, options));
2142
- }
2143
- /**
2144
- * @public
2145
- *
2146
- * A schedule action queues a release for publishing at the given future time.
2147
- * The release is locked such that no documents in the release can be modified and
2148
- * no documents that it references can be deleted as this would make the publish fail.
2149
- * At the given time, the same logic as for the publish action is triggered.
2150
- *
2151
- * @category Releases
2152
- *
2153
- * @param params - Release action parameters:
2154
- * - `releaseId` - The id of the release to schedule.
2155
- * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
2156
- * @param options - Additional action options.
2157
- * @returns A promise that resolves to the `transactionId`.
2158
- */
2159
- schedule({ releaseId, publishAt }, options) {
2160
- const scheduleAction = {
2161
- actionType: "sanity.action.release.schedule",
2162
- releaseId,
2163
- publishAt
2164
- };
2165
- return rxjs.lastValueFrom(_action(this.#client, this.#httpRequest, scheduleAction, options));
2166
- }
2167
- /**
2168
- * @public
2169
- *
2170
- * An unschedule action stops a release from being published.
2171
- * The documents in the release are considered unlocked and can be edited again.
2172
- * This may fail if another release is scheduled to be published after this one and
2173
- * has a reference to a document created by this one.
2174
- *
2175
- * @category Releases
2176
- *
2177
- * @param params - Release action parameters:
2178
- * - `releaseId` - The id of the release to unschedule.
2179
- * @param options - Additional action options.
2180
- * @returns A promise that resolves to the `transactionId`.
2181
- */
2182
- unschedule({ releaseId }, options) {
2183
- const unscheduleAction = {
2184
- actionType: "sanity.action.release.unschedule",
2185
- releaseId
2186
- };
2187
- return rxjs.lastValueFrom(_action(this.#client, this.#httpRequest, unscheduleAction, options));
2188
- }
2189
- /**
2190
- * @public
2191
- *
2192
- * A delete action removes a published or archived release.
2193
- * The backing system document will be removed from the dataset.
2194
- *
2195
- * @category Releases
2196
- *
2197
- * @param params - Release action parameters:
2198
- * - `releaseId` - The id of the release to delete.
2199
- * @param options - Additional action options.
2200
- * @returns A promise that resolves to the `transactionId`.
2201
- */
2202
- delete({ releaseId }, options) {
2203
- const deleteAction = {
2204
- actionType: "sanity.action.release.delete",
2205
- releaseId
2206
- };
2207
- return rxjs.lastValueFrom(_action(this.#client, this.#httpRequest, deleteAction, options));
2208
- }
2209
- /**
2210
- * @public
2211
- *
2212
- * Fetch the documents in a release by release id.
2213
- *
2214
- * @category Releases
2215
- *
2216
- * @param params - Release action parameters:
2217
- * - `releaseId` - The id of the release to fetch documents for.
2218
- * @param options - Additional mutation options {@link BaseMutationOptions}.
2219
- * @returns A promise that resolves to the documents in the release.
2220
- */
2221
- fetchDocuments({ releaseId }, options) {
2222
- return rxjs.lastValueFrom(_getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options));
2223
- }
2224
- }
2225
- class ObservableUsersClient {
2226
- #client;
2227
- #httpRequest;
2228
- constructor(client, httpRequest) {
2229
- this.#client = client, this.#httpRequest = httpRequest;
2230
- }
2231
- /**
2232
- * Fetch a user by user ID
2233
- *
2234
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2235
- */
2236
- getById(id) {
2237
- return _request(
2238
- this.#client,
2239
- this.#httpRequest,
2240
- { uri: `/users/${id}` }
2241
- );
2242
- }
2243
- }
2244
- class UsersClient {
2245
- #client;
2246
- #httpRequest;
2247
- constructor(client, httpRequest) {
2248
- this.#client = client, this.#httpRequest = httpRequest;
2249
- }
2250
- /**
2251
- * Fetch a user by user ID
2252
- *
2253
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2254
- */
2255
- getById(id) {
2256
- return rxjs.lastValueFrom(
2257
- _request(this.#client, this.#httpRequest, {
2258
- uri: `/users/${id}`
2259
- })
2260
- );
2261
- }
2262
- }
2263
- class ObservableSanityClient {
2264
- assets;
2265
- datasets;
2266
- live;
2267
- mediaLibrary;
2268
- projects;
2269
- users;
2270
- agent;
2271
- releases;
2272
- /**
2273
- * Private properties
2274
- */
2275
- #clientConfig;
2276
- #originalHttpRequest;
2277
- #httpRequest;
2278
- /**
2279
- * Instance properties
2280
- */
2281
- listen = _listen;
2282
- constructor(httpRequest, config$1 = config.defaultConfig) {
2283
- this.config(config$1), this.#originalHttpRequest = httpRequest;
2284
- const requestHandler = config$1._requestHandler;
2285
- this.#httpRequest = requestHandler ? /* @__PURE__ */ (() => {
2286
- let bareClient;
2287
- return (options, requester2) => {
2288
- const opts = options;
2289
- return bareClient || (bareClient = new SanityClient(httpRequest, { ...config$1, _requestHandler: void 0 })), requestHandler(opts, (o) => httpRequest(o, requester2), bareClient);
2290
- };
2291
- })() : httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = {
2292
- video: new ObservableMediaLibraryVideoClient(this, this.#httpRequest)
2293
- }, this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest), this.agent = {
2294
- action: new ObservableAgentsActionClient(this, this.#httpRequest)
2295
- }, this.releases = new ObservableReleasesClient(this, this.#httpRequest);
2296
- }
2297
- /**
2298
- * Clone the client - returns a new instance
2299
- */
2300
- clone() {
2301
- return new ObservableSanityClient(this.#originalHttpRequest, this.config());
2302
- }
2303
- config(newConfig) {
2304
- if (newConfig === void 0)
2305
- return { ...this.#clientConfig };
2306
- if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)
2307
- throw new Error(
2308
- "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
2309
- );
2310
- return this.#clientConfig = config.initConfig(newConfig, this.#clientConfig || {}), this;
2311
- }
2312
- /**
2313
- * Clone the client with a new (partial) configuration.
2314
- *
2315
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2316
- */
2317
- withConfig(newConfig) {
2318
- const thisConfig = this.config();
2319
- return new ObservableSanityClient(this.#originalHttpRequest, {
2320
- ...thisConfig,
2321
- ...newConfig,
2322
- stega: {
2323
- ...thisConfig.stega || {},
2324
- ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2325
- }
2326
- });
2327
- }
2328
- fetch(query, params, options) {
2329
- return _fetch(
2330
- this,
2331
- this.#httpRequest,
2332
- this.#clientConfig.stega,
2333
- query,
2334
- params,
2335
- options
2336
- );
2337
- }
2338
- getDocument(id, options) {
2339
- if (options?.includeAllVersions === !0)
2340
- return _getDocument(this, this.#httpRequest, id, {
2341
- ...options,
2342
- includeAllVersions: !0
2343
- });
2344
- const opts = {
2345
- signal: options?.signal,
2346
- tag: options?.tag,
2347
- releaseId: options?.releaseId,
2348
- ...options && "includeAllVersions" in options ? { includeAllVersions: !1 } : {}
2349
- };
2350
- return _getDocument(this, this.#httpRequest, id, opts);
2351
- }
2352
- /**
2353
- * Fetch multiple documents in one request.
2354
- * Should be used sparingly - performing a query is usually a better option.
2355
- * The order/position of documents is preserved based on the original array of IDs.
2356
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2357
- *
2358
- * @param ids - Document IDs to fetch
2359
- * @param options - Request options
2360
- */
2361
- getDocuments(ids, options) {
2362
- return _getDocuments(this, this.#httpRequest, ids, options);
2363
- }
2364
- /**
2365
- * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
2366
- * Returns a set of the IDs that exist.
2367
- *
2368
- * @param ids - Document IDs to check
2369
- * @param options - Request options
2370
- */
2371
- documentsExists(ids, options) {
2372
- return _documentsExists(this, this.#httpRequest, ids, options);
2373
- }
2374
- create(document, options) {
2375
- return _create(this, this.#httpRequest, document, "create", options);
2376
- }
2377
- createIfNotExists(document, options) {
2378
- return _createIfNotExists(this, this.#httpRequest, document, options);
2379
- }
2380
- createOrReplace(document, options) {
2381
- return _createOrReplace(this, this.#httpRequest, document, options);
2382
- }
2383
- createVersion({
2384
- document,
2385
- publishedId,
2386
- releaseId,
2387
- baseId,
2388
- ifBaseRevisionId
2389
- }, options) {
2390
- if (!document)
2391
- return _createVersionFromBase(
2392
- this,
2393
- this.#httpRequest,
2394
- publishedId,
2395
- baseId,
2396
- releaseId,
2397
- ifBaseRevisionId,
2398
- options
2399
- );
2400
- const documentVersionId = deriveDocumentVersionId("createVersion", {
2401
- document,
2402
- publishedId,
2403
- releaseId
2404
- }), documentVersion = { ...document, _id: documentVersionId }, versionPublishedId = publishedId || csm.getPublishedId(document._id);
2405
- return _createVersion(
2406
- this,
2407
- this.#httpRequest,
2408
- documentVersion,
2409
- versionPublishedId,
2410
- options
2411
- );
2412
- }
2413
- delete(selection, options) {
2414
- return _delete(this, this.#httpRequest, selection, options);
2415
- }
2416
- /**
2417
- * @public
2418
- *
2419
- * Deletes the draft or release version of a document.
2420
- *
2421
- * @remarks
2422
- * * Discarding a version with no `releaseId` will discard the draft version of the published document.
2423
- * * If the draft or release version does not exist, any error will throw.
2424
- *
2425
- * @param params - Version action parameters:
2426
- * - `releaseId` - The ID of the release to discard the document from.
2427
- * - `publishedId` - The published ID of the document to discard.
2428
- * @param purge - if `true` the document history is also discarded.
2429
- * @param options - Additional action options.
2430
- * @returns an observable that resolves to the `transactionId`.
2431
- *
2432
- * @example Discarding a release version of a document
2433
- * ```ts
2434
- * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2435
- * // The document with the ID `versions.myRelease.myDocument` will be discarded.
2436
- * ```
2437
- *
2438
- * @example Discarding a draft version of a document
2439
- * ```ts
2440
- * client.observable.discardVersion({publishedId: 'myDocument'})
2441
- * // The document with the ID `drafts.myDocument` will be discarded.
2442
- * ```
2443
- */
2444
- discardVersion({ releaseId, publishedId }, purge, options) {
2445
- const documentVersionId = getDocumentVersionId(publishedId, releaseId);
2446
- return _discardVersion(this, this.#httpRequest, documentVersionId, purge, options);
2447
- }
2448
- replaceVersion({
2449
- document,
2450
- publishedId,
2451
- releaseId
2452
- }, options) {
2453
- const documentVersionId = deriveDocumentVersionId("replaceVersion", {
2454
- document,
2455
- publishedId,
2456
- releaseId
2457
- }), documentVersion = { ...document, _id: documentVersionId };
2458
- return _replaceVersion(this, this.#httpRequest, documentVersion, options);
2459
- }
2460
- /**
2461
- * @public
2462
- *
2463
- * Used to indicate when a document within a release should be unpublished when
2464
- * the release is run.
2465
- *
2466
- * @remarks
2467
- * * If the published document does not exist, an error will be thrown.
2468
- *
2469
- * @param params - Version action parameters:
2470
- * - `releaseId` - The ID of the release to unpublish the document from.
2471
- * - `publishedId` - The published ID of the document to unpublish.
2472
- * @param options - Additional action options.
2473
- * @returns an observable that resolves to the `transactionId`.
2474
- *
2475
- * @example Unpublishing a release version of a published document
2476
- * ```ts
2477
- * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2478
- * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
2479
- * ```
2480
- */
2481
- unpublishVersion({ releaseId, publishedId }, options) {
2482
- const versionId = csm.getVersionId(publishedId, releaseId);
2483
- return _unpublishVersion(this, this.#httpRequest, versionId, publishedId, options);
2484
- }
2485
- mutate(operations, options) {
2486
- return _mutate(this, this.#httpRequest, operations, options);
2487
- }
2488
- /**
2489
- * Create a new buildable patch of operations to perform
2490
- *
2491
- * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
2492
- * @param operations - Optional object of patch operations to initialize the patch instance with
2493
- * @returns Patch instance - call `.commit()` to perform the operations defined
2494
- */
2495
- patch(selection, operations) {
2496
- return new ObservablePatch(selection, operations, this);
2497
- }
2498
- /**
2499
- * Create a new transaction of mutations
2500
- *
2501
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
2502
- */
2503
- transaction(operations) {
2504
- return new ObservableTransaction(operations, this);
2505
- }
2506
- /**
2507
- * Perform action operations against the configured dataset
2508
- *
2509
- * @param operations - Action operation(s) to execute
2510
- * @param options - Action options
2511
- */
2512
- action(operations, options) {
2513
- return _action(this, this.#httpRequest, operations, options);
2514
- }
2515
- /**
2516
- * Perform an HTTP request against the Sanity API
2517
- *
2518
- * @param options - Request options
2519
- */
2520
- request(options) {
2521
- return _request(this, this.#httpRequest, options);
2522
- }
2523
- /**
2524
- * Get a Sanity API URL for the URI provided
2525
- *
2526
- * @param uri - URI/path to build URL for
2527
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
2528
- */
2529
- getUrl(uri, canUseCdn) {
2530
- return _getUrl(this, uri, canUseCdn);
2531
- }
2532
- /**
2533
- * Get a Sanity API URL for the data operation and path provided
2534
- *
2535
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
2536
- * @param path - Path to append after the operation
2537
- */
2538
- getDataUrl(operation, path) {
2539
- return _getDataUrl(this, operation, path);
2540
- }
2541
- }
2542
- class SanityClient {
2543
- assets;
2544
- datasets;
2545
- live;
2546
- mediaLibrary;
2547
- projects;
2548
- users;
2549
- agent;
2550
- releases;
2551
- /**
2552
- * Observable version of the Sanity client, with the same configuration as the promise-based one
2553
- */
2554
- observable;
2555
- /**
2556
- * Private properties
2557
- */
2558
- #clientConfig;
2559
- #originalHttpRequest;
2560
- #httpRequest;
2561
- /**
2562
- * Instance properties
2563
- */
2564
- listen = _listen;
2565
- constructor(httpRequest, config$1 = config.defaultConfig) {
2566
- this.config(config$1), this.#originalHttpRequest = httpRequest;
2567
- const requestHandler = config$1._requestHandler;
2568
- this.#httpRequest = requestHandler ? /* @__PURE__ */ (() => {
2569
- let bareClient;
2570
- return (options, requester2) => {
2571
- const opts = options;
2572
- return bareClient || (bareClient = new SanityClient(httpRequest, { ...config$1, _requestHandler: void 0 })), requestHandler(opts, (o) => httpRequest(o, requester2), bareClient);
2573
- };
2574
- })() : httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = {
2575
- video: new MediaLibraryVideoClient(this, this.#httpRequest)
2576
- }, this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.agent = {
2577
- action: new AgentActionsClient(this, this.#httpRequest)
2578
- }, this.releases = new ReleasesClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config$1);
2579
- }
2580
- /**
2581
- * Clone the client - returns a new instance
2582
- */
2583
- clone() {
2584
- return new SanityClient(this.#originalHttpRequest, this.config());
2585
- }
2586
- config(newConfig) {
2587
- if (newConfig === void 0)
2588
- return { ...this.#clientConfig };
2589
- if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)
2590
- throw new Error(
2591
- "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
2592
- );
2593
- return this.observable && this.observable.config(newConfig), this.#clientConfig = config.initConfig(newConfig, this.#clientConfig || {}), this;
2594
- }
2595
- /**
2596
- * Clone the client with a new (partial) configuration.
2597
- *
2598
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2599
- */
2600
- withConfig(newConfig) {
2601
- const thisConfig = this.config();
2602
- return new SanityClient(this.#originalHttpRequest, {
2603
- ...thisConfig,
2604
- ...newConfig,
2605
- stega: {
2606
- ...thisConfig.stega || {},
2607
- ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2608
- }
2609
- });
2610
- }
2611
- fetch(query, params, options) {
2612
- return rxjs.lastValueFrom(
2613
- _fetch(
2614
- this,
2615
- this.#httpRequest,
2616
- this.#clientConfig.stega,
2617
- query,
2618
- params,
2619
- options
2620
- )
2621
- );
2622
- }
2623
- getDocument(id, options) {
2624
- if (options?.includeAllVersions === !0)
2625
- return rxjs.lastValueFrom(
2626
- _getDocument(this, this.#httpRequest, id, {
2627
- ...options,
2628
- includeAllVersions: !0
2629
- })
2630
- );
2631
- const opts = {
2632
- signal: options?.signal,
2633
- tag: options?.tag,
2634
- releaseId: options?.releaseId,
2635
- ...options && "includeAllVersions" in options ? { includeAllVersions: !1 } : {}
2636
- };
2637
- return rxjs.lastValueFrom(_getDocument(this, this.#httpRequest, id, opts));
2638
- }
2639
- /**
2640
- * Fetch multiple documents in one request.
2641
- * Should be used sparingly - performing a query is usually a better option.
2642
- * The order/position of documents is preserved based on the original array of IDs.
2643
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2644
- *
2645
- * @param ids - Document IDs to fetch
2646
- * @param options - Request options
2647
- */
2648
- getDocuments(ids, options) {
2649
- return rxjs.lastValueFrom(_getDocuments(this, this.#httpRequest, ids, options));
2650
- }
2651
- /**
2652
- * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
2653
- * Returns a set of the IDs that exist.
2654
- *
2655
- * @param ids - Document IDs to check
2656
- * @param options - Request options
2657
- */
2658
- documentsExists(ids, options) {
2659
- return rxjs.lastValueFrom(_documentsExists(this, this.#httpRequest, ids, options));
2660
- }
2661
- create(document, options) {
2662
- return rxjs.lastValueFrom(
2663
- _create(this, this.#httpRequest, document, "create", options)
2664
- );
2665
- }
2666
- createIfNotExists(document, options) {
2667
- return rxjs.lastValueFrom(
2668
- _createIfNotExists(this, this.#httpRequest, document, options)
2669
- );
2670
- }
2671
- createOrReplace(document, options) {
2672
- return rxjs.lastValueFrom(
2673
- _createOrReplace(this, this.#httpRequest, document, options)
2674
- );
2675
- }
2676
- createVersion({
2677
- document,
2678
- publishedId,
2679
- releaseId,
2680
- baseId,
2681
- ifBaseRevisionId
2682
- }, options) {
2683
- if (!document)
2684
- return rxjs.firstValueFrom(
2685
- _createVersionFromBase(
2686
- this,
2687
- this.#httpRequest,
2688
- publishedId,
2689
- baseId,
2690
- releaseId,
2691
- ifBaseRevisionId,
2692
- options
2693
- )
2694
- );
2695
- const documentVersionId = deriveDocumentVersionId("createVersion", {
2696
- document,
2697
- publishedId,
2698
- releaseId
2699
- }), documentVersion = { ...document, _id: documentVersionId }, versionPublishedId = publishedId || csm.getPublishedId(document._id);
2700
- return rxjs.firstValueFrom(
2701
- _createVersion(
2702
- this,
2703
- this.#httpRequest,
2704
- documentVersion,
2705
- versionPublishedId,
2706
- options
2707
- )
2708
- );
2709
- }
2710
- delete(selection, options) {
2711
- return rxjs.lastValueFrom(_delete(this, this.#httpRequest, selection, options));
2712
- }
2713
- /**
2714
- * @public
2715
- *
2716
- * Deletes the draft or release version of a document.
2717
- *
2718
- * @remarks
2719
- * * Discarding a version with no `releaseId` will discard the draft version of the published document.
2720
- * * If the draft or release version does not exist, any error will throw.
2721
- *
2722
- * @param params - Version action parameters:
2723
- * - `releaseId` - The ID of the release to discard the document from.
2724
- * - `publishedId` - The published ID of the document to discard.
2725
- * @param purge - if `true` the document history is also discarded.
2726
- * @param options - Additional action options.
2727
- * @returns a promise that resolves to the `transactionId`.
2728
- *
2729
- * @example Discarding a release version of a document
2730
- * ```ts
2731
- * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2732
- * // The document with the ID `versions.myRelease.myDocument` will be discarded.
2733
- * ```
2734
- *
2735
- * @example Discarding a draft version of a document
2736
- * ```ts
2737
- * client.discardVersion({publishedId: 'myDocument'})
2738
- * // The document with the ID `drafts.myDocument` will be discarded.
2739
- * ```
2740
- */
2741
- discardVersion({ releaseId, publishedId }, purge, options) {
2742
- const documentVersionId = getDocumentVersionId(publishedId, releaseId);
2743
- return rxjs.lastValueFrom(
2744
- _discardVersion(this, this.#httpRequest, documentVersionId, purge, options)
2745
- );
2746
- }
2747
- replaceVersion({
2748
- document,
2749
- publishedId,
2750
- releaseId
2751
- }, options) {
2752
- const documentVersionId = deriveDocumentVersionId("replaceVersion", {
2753
- document,
2754
- publishedId,
2755
- releaseId
2756
- }), documentVersion = { ...document, _id: documentVersionId };
2757
- return rxjs.firstValueFrom(
2758
- _replaceVersion(this, this.#httpRequest, documentVersion, options)
2759
- );
2760
- }
2761
- /**
2762
- * @public
2763
- *
2764
- * Used to indicate when a document within a release should be unpublished when
2765
- * the release is run.
2766
- *
2767
- * @remarks
2768
- * * If the published document does not exist, an error will be thrown.
2769
- *
2770
- * @param params - Version action parameters:
2771
- * - `releaseId` - The ID of the release to unpublish the document from.
2772
- * - `publishedId` - The published ID of the document to unpublish.
2773
- * @param options - Additional action options.
2774
- * @returns a promise that resolves to the `transactionId`.
2775
- *
2776
- * @example Unpublishing a release version of a published document
2777
- * ```ts
2778
- * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2779
- * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
2780
- * ```
2781
- */
2782
- unpublishVersion({ releaseId, publishedId }, options) {
2783
- const versionId = csm.getVersionId(publishedId, releaseId);
2784
- return rxjs.lastValueFrom(
2785
- _unpublishVersion(this, this.#httpRequest, versionId, publishedId, options)
2786
- );
2787
- }
2788
- mutate(operations, options) {
2789
- return rxjs.lastValueFrom(_mutate(this, this.#httpRequest, operations, options));
2790
- }
2791
- /**
2792
- * Create a new buildable patch of operations to perform
2793
- *
2794
- * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
2795
- * @param operations - Optional object of patch operations to initialize the patch instance with
2796
- * @returns Patch instance - call `.commit()` to perform the operations defined
2797
- */
2798
- patch(documentId, operations) {
2799
- return new Patch(documentId, operations, this);
2800
- }
2801
- /**
2802
- * Create a new transaction of mutations
2803
- *
2804
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
2805
- */
2806
- transaction(operations) {
2807
- return new Transaction(operations, this);
2808
- }
2809
- /**
2810
- * Perform action operations against the configured dataset
2811
- * Returns a promise that resolves to the transaction result
2812
- *
2813
- * @param operations - Action operation(s) to execute
2814
- * @param options - Action options
2815
- */
2816
- action(operations, options) {
2817
- return rxjs.lastValueFrom(_action(this, this.#httpRequest, operations, options));
2818
- }
2819
- /**
2820
- * Perform a request against the Sanity API
2821
- * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
2822
- *
2823
- * @param options - Request options
2824
- * @returns Promise resolving to the response body
2825
- */
2826
- request(options) {
2827
- return rxjs.lastValueFrom(_request(this, this.#httpRequest, options));
2828
- }
2829
- /**
2830
- * Perform an HTTP request a `/data` sub-endpoint
2831
- * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
2832
- *
2833
- * @deprecated - Use `request()` or your own HTTP library instead
2834
- * @param endpoint - Endpoint to hit (mutate, query etc)
2835
- * @param body - Request body
2836
- * @param options - Request options
2837
- * @internal
2838
- */
2839
- dataRequest(endpoint, body, options) {
2840
- return rxjs.lastValueFrom(_dataRequest(this, this.#httpRequest, endpoint, body, options));
2841
- }
2842
- /**
2843
- * Get a Sanity API URL for the URI provided
2844
- *
2845
- * @param uri - URI/path to build URL for
2846
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
2847
- */
2848
- getUrl(uri, canUseCdn) {
2849
- return _getUrl(this, uri, canUseCdn);
2850
- }
2851
- /**
2852
- * Get a Sanity API URL for the data operation and path provided
2853
- *
2854
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
2855
- * @param path - Path to append after the operation
2856
- */
2857
- getDataUrl(operation, path) {
2858
- return _getDataUrl(this, operation, path);
2859
- }
2860
- }
2861
- function defineCreateClientExports(envMiddleware, ClassConstructor) {
2862
- return { requester: defineHttpRequest(envMiddleware), createClient: (config2) => {
2863
- const clientRequester = defineHttpRequest(envMiddleware, {
2864
- ignoreWarnings: config2.ignoreWarnings
2865
- });
2866
- return new ClassConstructor(
2867
- (options, requester2) => (requester2 || clientRequester)({
2868
- maxRedirects: 0,
2869
- maxRetries: config2.maxRetries,
2870
- retryDelay: config2.retryDelay,
2871
- lineage: config2.lineage,
2872
- ...options
2873
- }),
2874
- config2
2875
- );
2876
- } };
2877
- }
2878
- function defineDeprecatedCreateClient(createClient2) {
2879
- return function(config$1) {
2880
- return config.printNoDefaultExport(), createClient2(config$1);
2881
- };
2882
- }
2883
- var name = "@sanity/client", version = "7.26.1";
2884
- const middleware = [
2885
- middleware$1.debug({ verbose: !0, namespace: "sanity:client" }),
2886
- middleware$1.headers({ "User-Agent": `${name} ${version}` }),
2887
- // Lineage is used for recursion control/tracing and can be passed either through
2888
- // client constructor or through environent variable.
2889
- // Not used in browser environments.
2890
- {
2891
- processOptions(opts) {
2892
- const lineage = typeof process < "u" && process.env.X_SANITY_LINEAGE || opts.lineage;
2893
- return lineage && (opts.headers = opts.headers || {}, opts.headers["x-sanity-lineage"] = lineage), opts;
2894
- }
2895
- },
2896
- // Enable keep-alive, and in addition limit the number of sockets that can be opened.
2897
- // This avoids opening too many connections to the server if someone tries to execute
2898
- // a bunch of requests in parallel. It's recommended to have a concurrency limit
2899
- // at a "higher limit" (i.e. you shouldn't actually execute hundreds of requests in parallel),
2900
- // and this is mainly to minimize the impact for the network and server.
2901
- //
2902
- // We're currently matching the same defaults as browsers:
2903
- // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op
2904
- middleware$1.agent({
2905
- keepAlive: !0,
2906
- maxSockets: 30,
2907
- maxTotalSockets: 256
2908
- })
2909
- ], exp = defineCreateClientExports(middleware, SanityClient), requester = exp.requester, createClient = exp.createClient, deprecatedCreateClient = defineDeprecatedCreateClient(createClient);
2910
- Object.defineProperty(exports, "unstable__adapter", {
2911
- enumerable: !0,
2912
- get: function() {
2913
- return getIt.adapter;
2914
- }
2915
- });
2916
- Object.defineProperty(exports, "unstable__environment", {
2917
- enumerable: !0,
2918
- get: function() {
2919
- return getIt.environment;
2920
- }
2921
- });
2922
- exports.validateApiPerspective = config.validateApiPerspective;
2923
- exports.BasePatch = BasePatch;
2924
- exports.BaseTransaction = BaseTransaction;
2925
- exports.ChannelError = ChannelError;
2926
- exports.ClientError = ClientError;
2927
- exports.ConnectionFailedError = ConnectionFailedError;
2928
- exports.CorsOriginError = CorsOriginError;
2929
- exports.DisconnectError = DisconnectError;
2930
- exports.EXPERIMENTAL_API_WARNING = EXPERIMENTAL_API_WARNING;
2931
- exports.MessageError = MessageError;
2932
- exports.MessageParseError = MessageParseError;
2933
- exports.ObservablePatch = ObservablePatch;
2934
- exports.ObservableSanityClient = ObservableSanityClient;
2935
- exports.ObservableTransaction = ObservableTransaction;
2936
- exports.Patch = Patch;
2937
- exports.SanityClient = SanityClient;
2938
- exports.ServerError = ServerError;
2939
- exports.Transaction = Transaction;
2940
- exports.connectEventSource = connectEventSource;
2941
- exports.createClient = createClient;
2942
- exports.default = deprecatedCreateClient;
2943
- exports.formatQueryParseError = formatQueryParseError;
2944
- exports.isHttpError = isHttpError;
2945
- exports.isQueryParseError = isQueryParseError;
2946
- exports.requester = requester;
2947
- //# sourceMappingURL=index.cjs.map