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