@sanity/client 6.14.1 → 6.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/_chunks/browserMiddleware-BHXO2Lcy.cjs +1491 -0
  2. package/dist/_chunks/{browserMiddleware-FpdqDQ1o.cjs.map → browserMiddleware-BHXO2Lcy.cjs.map} +1 -1
  3. package/dist/_chunks/browserMiddleware-jPnXCUlp.js +1474 -0
  4. package/dist/_chunks/{browserMiddleware-DhUBf_19.js.map → browserMiddleware-jPnXCUlp.js.map} +1 -1
  5. package/dist/_chunks/nodeMiddleware-CrO2pNEp.js +1491 -0
  6. package/dist/_chunks/{nodeMiddleware-BSZoKrW0.js.map → nodeMiddleware-CrO2pNEp.js.map} +1 -1
  7. package/dist/_chunks/nodeMiddleware-JJNfI4Rf.cjs +1508 -0
  8. package/dist/_chunks/{nodeMiddleware-DmcqX3kz.cjs.map → nodeMiddleware-JJNfI4Rf.cjs.map} +1 -1
  9. package/dist/_chunks/resolveEditInfo-BNCwZySb.cjs +284 -0
  10. package/dist/_chunks/{resolveEditInfo-BB1WiUDY.cjs.map → resolveEditInfo-BNCwZySb.cjs.map} +1 -1
  11. package/dist/_chunks/resolveEditInfo-qA5twkfC.js +285 -0
  12. package/dist/_chunks/{resolveEditInfo-Cf8D1Agp.js.map → resolveEditInfo-qA5twkfC.js.map} +1 -1
  13. package/dist/_chunks/stegaEncodeSourceMap-B9_uz7Zb.cjs +166 -0
  14. package/dist/_chunks/{stegaEncodeSourceMap-8TjLXjYU.cjs.map → stegaEncodeSourceMap-B9_uz7Zb.cjs.map} +1 -1
  15. package/dist/_chunks/stegaEncodeSourceMap-BvBJpbrr.cjs +329 -0
  16. package/dist/_chunks/{stegaEncodeSourceMap-DIcuvN0P.cjs.map → stegaEncodeSourceMap-BvBJpbrr.cjs.map} +1 -1
  17. package/dist/_chunks/stegaEncodeSourceMap-De3F_oJN.js +330 -0
  18. package/dist/_chunks/{stegaEncodeSourceMap-DLon0Yls.js.map → stegaEncodeSourceMap-De3F_oJN.js.map} +1 -1
  19. package/dist/_chunks/stegaEncodeSourceMap-bRxIGJ-b.js +168 -0
  20. package/dist/_chunks/{stegaEncodeSourceMap-DU95idpa.js.map → stegaEncodeSourceMap-bRxIGJ-b.js.map} +1 -1
  21. package/dist/csm.cjs +22 -56
  22. package/dist/csm.cjs.map +1 -1
  23. package/dist/csm.js +36 -54
  24. package/dist/csm.js.map +1 -1
  25. package/dist/index.browser.cjs +15 -21
  26. package/dist/index.browser.cjs.map +1 -1
  27. package/dist/index.browser.js +24 -15
  28. package/dist/index.browser.js.map +1 -1
  29. package/dist/index.cjs +15 -21
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.js +24 -15
  32. package/dist/index.js.map +1 -1
  33. package/dist/stega.browser.cjs +12 -17
  34. package/dist/stega.browser.cjs.map +1 -1
  35. package/dist/stega.browser.js +26 -11
  36. package/dist/stega.browser.js.map +1 -1
  37. package/dist/stega.cjs +12 -17
  38. package/dist/stega.cjs.map +1 -1
  39. package/dist/stega.js +26 -11
  40. package/dist/stega.js.map +1 -1
  41. package/package.json +3 -3
  42. package/umd/sanityClient.js +2670 -3360
  43. package/umd/sanityClient.min.js +3 -3
  44. package/dist/_chunks/browserMiddleware-DhUBf_19.js +0 -1761
  45. package/dist/_chunks/browserMiddleware-FpdqDQ1o.cjs +0 -1777
  46. package/dist/_chunks/nodeMiddleware-BSZoKrW0.js +0 -1780
  47. package/dist/_chunks/nodeMiddleware-DmcqX3kz.cjs +0 -1796
  48. package/dist/_chunks/resolveEditInfo-BB1WiUDY.cjs +0 -422
  49. package/dist/_chunks/resolveEditInfo-Cf8D1Agp.js +0 -406
  50. package/dist/_chunks/stegaEncodeSourceMap-8TjLXjYU.cjs +0 -229
  51. package/dist/_chunks/stegaEncodeSourceMap-DIcuvN0P.cjs +0 -486
  52. package/dist/_chunks/stegaEncodeSourceMap-DLon0Yls.js +0 -482
  53. package/dist/_chunks/stegaEncodeSourceMap-DU95idpa.js +0 -225
@@ -0,0 +1,1491 @@
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
+ var getIt = require("get-it"), middleware = require("get-it/middleware"), rxjs = require("rxjs"), operators = require("rxjs/operators");
22
+ class ClientError extends Error {
23
+ constructor(res) {
24
+ const props = extractErrorProps(res);
25
+ super(props.message), this.statusCode = 400, Object.assign(this, props);
26
+ }
27
+ }
28
+ class ServerError extends Error {
29
+ constructor(res) {
30
+ const props = extractErrorProps(res);
31
+ super(props.message), this.statusCode = 500, Object.assign(this, props);
32
+ }
33
+ }
34
+ function extractErrorProps(res) {
35
+ const body = res.body, props = {
36
+ response: res,
37
+ statusCode: res.statusCode,
38
+ responseBody: stringifyBody(body, res),
39
+ message: "",
40
+ details: void 0
41
+ };
42
+ if (body.error && body.message)
43
+ return props.message = `${body.error} - ${body.message}`, props;
44
+ if (isMutationError(body)) {
45
+ const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => {
46
+ var _a;
47
+ return (_a = item.error) == null ? void 0 : _a.description;
48
+ }).filter(Boolean);
49
+ let itemsStr = items.length ? `:
50
+ - ${items.join(`
51
+ - `)}` : "";
52
+ return allItems.length > 5 && (itemsStr += `
53
+ ...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;
54
+ }
55
+ return body.error && body.error.description ? (props.message = body.error.description, props.details = body.error, props) : (props.message = body.error || body.message || httpErrorMessage(res), props);
56
+ }
57
+ function isMutationError(body) {
58
+ return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description == "string";
59
+ }
60
+ function isPlainObject(obj) {
61
+ return typeof obj == "object" && obj !== null && !Array.isArray(obj);
62
+ }
63
+ function httpErrorMessage(res) {
64
+ const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
65
+ return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;
66
+ }
67
+ function stringifyBody(body, res) {
68
+ return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? JSON.stringify(body, null, 2) : body;
69
+ }
70
+ const httpError = {
71
+ onResponse: (res) => {
72
+ if (res.statusCode >= 500)
73
+ throw new ServerError(res);
74
+ if (res.statusCode >= 400)
75
+ throw new ClientError(res);
76
+ return res;
77
+ }
78
+ }, printWarnings = {
79
+ onResponse: (res) => {
80
+ const warn = res.headers["x-sanity-warning"];
81
+ return (Array.isArray(warn) ? warn : [warn]).filter(Boolean).forEach((msg) => console.warn(msg)), res;
82
+ }
83
+ };
84
+ function defineHttpRequest(envMiddleware2, {
85
+ maxRetries = 5,
86
+ retryDelay
87
+ }) {
88
+ const request = getIt.getIt([
89
+ maxRetries > 0 ? middleware.retry({
90
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
91
+ retryDelay,
92
+ // This option is typed incorrectly in get-it.
93
+ maxRetries,
94
+ shouldRetry
95
+ }) : {},
96
+ ...envMiddleware2,
97
+ printWarnings,
98
+ middleware.jsonRequest(),
99
+ middleware.jsonResponse(),
100
+ middleware.progress(),
101
+ httpError,
102
+ middleware.observable({ implementation: rxjs.Observable })
103
+ ]);
104
+ function httpRequest(options, requester = request) {
105
+ return requester({ maxRedirects: 0, ...options });
106
+ }
107
+ return httpRequest.defaultRequester = request, httpRequest;
108
+ }
109
+ function shouldRetry(err, attempt, options) {
110
+ const isSafe = options.method === "GET" || options.method === "HEAD", isQuery = (options.uri || options.url).startsWith("/data/query"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);
111
+ return (isSafe || isQuery) && isRetriableResponse ? !0 : middleware.retry.shouldRetry(err, attempt, options);
112
+ }
113
+ function getSelection(sel) {
114
+ if (typeof sel == "string")
115
+ return { id: sel };
116
+ if (Array.isArray(sel))
117
+ return { query: "*[_id in $ids]", params: { ids: sel } };
118
+ if (typeof sel == "object" && sel !== null && "query" in sel && typeof sel.query == "string")
119
+ return "params" in sel && typeof sel.params == "object" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };
120
+ const selectionOpts = [
121
+ "* Document ID (<docId>)",
122
+ "* Array of document IDs",
123
+ "* Object containing `query`"
124
+ ].join(`
125
+ `);
126
+ throw new Error(`Unknown selection - must be one of:
127
+
128
+ ${selectionOpts}`);
129
+ }
130
+ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name) => {
131
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name))
132
+ throw new Error(
133
+ "Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
134
+ );
135
+ }, projectId = (id) => {
136
+ if (!/^[-a-z0-9]+$/i.test(id))
137
+ throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
138
+ }, validateAssetType = (type) => {
139
+ if (VALID_ASSET_TYPES.indexOf(type) === -1)
140
+ throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
141
+ }, validateObject = (op, val) => {
142
+ if (val === null || typeof val != "object" || Array.isArray(val))
143
+ throw new Error(`${op}() takes an object of properties`);
144
+ }, validateDocumentId = (op, id) => {
145
+ if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(".."))
146
+ throw new Error(`${op}(): "${id}" is not a valid document ID`);
147
+ }, requireDocumentId = (op, doc) => {
148
+ if (!doc._id)
149
+ throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
150
+ validateDocumentId(op, doc._id);
151
+ }, validateInsert = (at, selector, items) => {
152
+ const signature = "insert(at, selector, items)";
153
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
154
+ const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
155
+ throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
156
+ }
157
+ if (typeof selector != "string")
158
+ throw new Error(`${signature} takes a "selector"-argument which must be a string`);
159
+ if (!Array.isArray(items))
160
+ throw new Error(`${signature} takes an "items"-argument which must be an array`);
161
+ }, hasDataset = (config) => {
162
+ if (!config.dataset)
163
+ throw new Error("`dataset` must be provided to perform queries");
164
+ return config.dataset || "";
165
+ }, requestTag = (tag) => {
166
+ if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
167
+ throw new Error(
168
+ "Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long."
169
+ );
170
+ return tag;
171
+ };
172
+ var __accessCheck$6 = (obj, member, msg) => {
173
+ if (!member.has(obj))
174
+ throw TypeError("Cannot " + msg);
175
+ }, __privateGet$6 = (obj, member, getter) => (__accessCheck$6(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$6 = (obj, member, value) => {
176
+ if (member.has(obj))
177
+ throw TypeError("Cannot add the same private member more than once");
178
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
179
+ }, __privateSet$6 = (obj, member, value, setter) => (__accessCheck$6(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
180
+ class BasePatch {
181
+ constructor(selection, operations = {}) {
182
+ this.selection = selection, this.operations = operations;
183
+ }
184
+ /**
185
+ * Sets the given attributes to the document. Does NOT merge objects.
186
+ * The operation is added to the current patch, ready to be commited by `commit()`
187
+ *
188
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
189
+ */
190
+ set(attrs) {
191
+ return this._assign("set", attrs);
192
+ }
193
+ /**
194
+ * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
195
+ * The operation is added to the current patch, ready to be commited by `commit()`
196
+ *
197
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
198
+ */
199
+ setIfMissing(attrs) {
200
+ return this._assign("setIfMissing", attrs);
201
+ }
202
+ /**
203
+ * Performs a "diff-match-patch" operation on the string attributes provided.
204
+ * The operation is added to the current patch, ready to be commited by `commit()`
205
+ *
206
+ * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
207
+ */
208
+ diffMatchPatch(attrs) {
209
+ return validateObject("diffMatchPatch", attrs), this._assign("diffMatchPatch", attrs);
210
+ }
211
+ /**
212
+ * Unsets the attribute paths provided.
213
+ * The operation is added to the current patch, ready to be commited by `commit()`
214
+ *
215
+ * @param attrs - Attribute paths to unset.
216
+ */
217
+ unset(attrs) {
218
+ if (!Array.isArray(attrs))
219
+ throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
220
+ return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;
221
+ }
222
+ /**
223
+ * 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.
224
+ *
225
+ * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
226
+ */
227
+ inc(attrs) {
228
+ return this._assign("inc", attrs);
229
+ }
230
+ /**
231
+ * 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.
232
+ *
233
+ * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
234
+ */
235
+ dec(attrs) {
236
+ return this._assign("dec", attrs);
237
+ }
238
+ /**
239
+ * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
240
+ *
241
+ * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
242
+ * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
243
+ * @param items - Array of items to insert/replace
244
+ */
245
+ insert(at, selector, items) {
246
+ return validateInsert(at, selector, items), this._assign("insert", { [at]: selector, items });
247
+ }
248
+ /**
249
+ * Append the given items to the array at the given JSONPath
250
+ *
251
+ * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
252
+ * @param items - Array of items to append to the array
253
+ */
254
+ append(selector, items) {
255
+ return this.insert("after", `${selector}[-1]`, items);
256
+ }
257
+ /**
258
+ * Prepend the given items to the array at the given JSONPath
259
+ *
260
+ * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
261
+ * @param items - Array of items to prepend to the array
262
+ */
263
+ prepend(selector, items) {
264
+ return this.insert("before", `${selector}[0]`, items);
265
+ }
266
+ /**
267
+ * Change the contents of an array by removing existing elements and/or adding new elements.
268
+ *
269
+ * @param selector - Attribute or JSONPath expression for array
270
+ * @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
271
+ * @param deleteCount - An integer indicating the number of old array elements to remove.
272
+ * @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.
273
+ */
274
+ splice(selector, start, deleteCount, items) {
275
+ 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}]`;
276
+ return this.insert("replace", rangeSelector, items || []);
277
+ }
278
+ /**
279
+ * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
280
+ *
281
+ * @param rev - Revision to lock the patch to
282
+ */
283
+ ifRevisionId(rev) {
284
+ return this.operations.ifRevisionID = rev, this;
285
+ }
286
+ /**
287
+ * Return a plain JSON representation of the patch
288
+ */
289
+ serialize() {
290
+ return { ...getSelection(this.selection), ...this.operations };
291
+ }
292
+ /**
293
+ * Return a plain JSON representation of the patch
294
+ */
295
+ toJSON() {
296
+ return this.serialize();
297
+ }
298
+ /**
299
+ * Clears the patch of all operations
300
+ */
301
+ reset() {
302
+ return this.operations = {}, this;
303
+ }
304
+ _assign(op, props, merge = !0) {
305
+ return validateObject(op, props), this.operations = Object.assign({}, this.operations, {
306
+ [op]: Object.assign({}, merge && this.operations[op] || {}, props)
307
+ }), this;
308
+ }
309
+ _set(op, props) {
310
+ return this._assign(op, props, !1);
311
+ }
312
+ }
313
+ var _client$5;
314
+ const _ObservablePatch = class _ObservablePatch2 extends BasePatch {
315
+ constructor(selection, operations, client) {
316
+ super(selection, operations), __privateAdd$6(this, _client$5, void 0), __privateSet$6(this, _client$5, client);
317
+ }
318
+ /**
319
+ * Clones the patch
320
+ */
321
+ clone() {
322
+ return new _ObservablePatch2(this.selection, { ...this.operations }, __privateGet$6(this, _client$5));
323
+ }
324
+ commit(options) {
325
+ if (!__privateGet$6(this, _client$5))
326
+ throw new Error(
327
+ "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
328
+ );
329
+ const returnFirst = typeof this.selection == "string", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);
330
+ return __privateGet$6(this, _client$5).mutate({ patch: this.serialize() }, opts);
331
+ }
332
+ };
333
+ _client$5 = /* @__PURE__ */ new WeakMap();
334
+ let ObservablePatch = _ObservablePatch;
335
+ var _client2$5;
336
+ const _Patch = class _Patch2 extends BasePatch {
337
+ constructor(selection, operations, client) {
338
+ super(selection, operations), __privateAdd$6(this, _client2$5, void 0), __privateSet$6(this, _client2$5, client);
339
+ }
340
+ /**
341
+ * Clones the patch
342
+ */
343
+ clone() {
344
+ return new _Patch2(this.selection, { ...this.operations }, __privateGet$6(this, _client2$5));
345
+ }
346
+ commit(options) {
347
+ if (!__privateGet$6(this, _client2$5))
348
+ throw new Error(
349
+ "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
350
+ );
351
+ const returnFirst = typeof this.selection == "string", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);
352
+ return __privateGet$6(this, _client2$5).mutate({ patch: this.serialize() }, opts);
353
+ }
354
+ };
355
+ _client2$5 = /* @__PURE__ */ new WeakMap();
356
+ let Patch = _Patch;
357
+ var __accessCheck$5 = (obj, member, msg) => {
358
+ if (!member.has(obj))
359
+ throw TypeError("Cannot " + msg);
360
+ }, __privateGet$5 = (obj, member, getter) => (__accessCheck$5(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$5 = (obj, member, value) => {
361
+ if (member.has(obj))
362
+ throw TypeError("Cannot add the same private member more than once");
363
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
364
+ }, __privateSet$5 = (obj, member, value, setter) => (__accessCheck$5(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
365
+ const defaultMutateOptions = { returnDocuments: !1 };
366
+ class BaseTransaction {
367
+ constructor(operations = [], transactionId) {
368
+ this.operations = operations, this.trxId = transactionId;
369
+ }
370
+ /**
371
+ * 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.
372
+ * The operation is added to the current transaction, ready to be commited by `commit()`
373
+ *
374
+ * @param doc - Document to create. Requires a `_type` property.
375
+ */
376
+ create(doc) {
377
+ return validateObject("create", doc), this._add({ create: doc });
378
+ }
379
+ /**
380
+ * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
381
+ * The operation is added to the current transaction, ready to be commited by `commit()`
382
+ *
383
+ * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
384
+ */
385
+ createIfNotExists(doc) {
386
+ const op = "createIfNotExists";
387
+ return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
388
+ }
389
+ /**
390
+ * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
391
+ * The operation is added to the current transaction, ready to be commited by `commit()`
392
+ *
393
+ * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
394
+ */
395
+ createOrReplace(doc) {
396
+ const op = "createOrReplace";
397
+ return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
398
+ }
399
+ /**
400
+ * Deletes the document with the given document ID
401
+ * The operation is added to the current transaction, ready to be commited by `commit()`
402
+ *
403
+ * @param documentId - Document ID to delete
404
+ */
405
+ delete(documentId) {
406
+ return validateDocumentId("delete", documentId), this._add({ delete: { id: documentId } });
407
+ }
408
+ transactionId(id) {
409
+ return id ? (this.trxId = id, this) : this.trxId;
410
+ }
411
+ /**
412
+ * Return a plain JSON representation of the transaction
413
+ */
414
+ serialize() {
415
+ return [...this.operations];
416
+ }
417
+ /**
418
+ * Return a plain JSON representation of the transaction
419
+ */
420
+ toJSON() {
421
+ return this.serialize();
422
+ }
423
+ /**
424
+ * Clears the transaction of all operations
425
+ */
426
+ reset() {
427
+ return this.operations = [], this;
428
+ }
429
+ _add(mut) {
430
+ return this.operations.push(mut), this;
431
+ }
432
+ }
433
+ var _client$4;
434
+ const _Transaction = class _Transaction2 extends BaseTransaction {
435
+ constructor(operations, client, transactionId) {
436
+ super(operations, transactionId), __privateAdd$5(this, _client$4, void 0), __privateSet$5(this, _client$4, client);
437
+ }
438
+ /**
439
+ * Clones the transaction
440
+ */
441
+ clone() {
442
+ return new _Transaction2([...this.operations], __privateGet$5(this, _client$4), this.trxId);
443
+ }
444
+ commit(options) {
445
+ if (!__privateGet$5(this, _client$4))
446
+ throw new Error(
447
+ "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
448
+ );
449
+ return __privateGet$5(this, _client$4).mutate(
450
+ this.serialize(),
451
+ Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
452
+ );
453
+ }
454
+ patch(patchOrDocumentId, patchOps) {
455
+ const isBuilder = typeof patchOps == "function";
456
+ if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof Patch)
457
+ return this._add({ patch: patchOrDocumentId.serialize() });
458
+ if (isBuilder) {
459
+ const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$5(this, _client$4)));
460
+ if (!(patch instanceof Patch))
461
+ throw new Error("function passed to `patch()` must return the patch");
462
+ return this._add({ patch: patch.serialize() });
463
+ }
464
+ return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
465
+ }
466
+ };
467
+ _client$4 = /* @__PURE__ */ new WeakMap();
468
+ let Transaction = _Transaction;
469
+ var _client2$4;
470
+ const _ObservableTransaction = class _ObservableTransaction2 extends BaseTransaction {
471
+ constructor(operations, client, transactionId) {
472
+ super(operations, transactionId), __privateAdd$5(this, _client2$4, void 0), __privateSet$5(this, _client2$4, client);
473
+ }
474
+ /**
475
+ * Clones the transaction
476
+ */
477
+ clone() {
478
+ return new _ObservableTransaction2([...this.operations], __privateGet$5(this, _client2$4), this.trxId);
479
+ }
480
+ commit(options) {
481
+ if (!__privateGet$5(this, _client2$4))
482
+ throw new Error(
483
+ "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
484
+ );
485
+ return __privateGet$5(this, _client2$4).mutate(
486
+ this.serialize(),
487
+ Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
488
+ );
489
+ }
490
+ patch(patchOrDocumentId, patchOps) {
491
+ const isBuilder = typeof patchOps == "function";
492
+ if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof ObservablePatch)
493
+ return this._add({ patch: patchOrDocumentId.serialize() });
494
+ if (isBuilder) {
495
+ const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$5(this, _client2$4)));
496
+ if (!(patch instanceof ObservablePatch))
497
+ throw new Error("function passed to `patch()` must return the patch");
498
+ return this._add({ patch: patch.serialize() });
499
+ }
500
+ return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
501
+ }
502
+ };
503
+ _client2$4 = /* @__PURE__ */ new WeakMap();
504
+ let ObservableTransaction = _ObservableTransaction;
505
+ const BASE_URL = "https://www.sanity.io/help/";
506
+ function generateHelpUrl(slug) {
507
+ return BASE_URL + slug;
508
+ }
509
+ function once(fn) {
510
+ let didCall = !1, returnValue;
511
+ return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
512
+ }
513
+ const createWarningPrinter = (message) => (
514
+ // eslint-disable-next-line no-console
515
+ once((...args) => console.warn(message.join(" "), ...args))
516
+ ), printCdnWarning = createWarningPrinter([
517
+ "Since you haven't set a value for `useCdn`, we will deliver content using our",
518
+ "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
519
+ "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
520
+ ]), printCdnPreviewDraftsWarning = createWarningPrinter([
521
+ "The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
522
+ "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
523
+ ]), printBrowserTokenWarning = createWarningPrinter([
524
+ "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
525
+ `See ${generateHelpUrl(
526
+ "js-client-browser-token"
527
+ )} for more information and how to hide this warning.`
528
+ ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
529
+ "Using the Sanity client without specifying an API version is deprecated.",
530
+ `See ${generateHelpUrl("js-client-api-version")}`
531
+ ]), printNoDefaultExport = createWarningPrinter([
532
+ "The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
533
+ ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
534
+ apiHost: "https://api.sanity.io",
535
+ apiVersion: "1",
536
+ useProjectHostname: !0,
537
+ stega: { enabled: !1 }
538
+ }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1, validateApiVersion = function(apiVersion) {
539
+ if (apiVersion === "1" || apiVersion === "X")
540
+ return;
541
+ const apiDate = new Date(apiVersion);
542
+ if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
543
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
544
+ }, validateApiPerspective = function(perspective) {
545
+ switch (perspective) {
546
+ case "previewDrafts":
547
+ case "published":
548
+ case "raw":
549
+ return;
550
+ default:
551
+ throw new TypeError(
552
+ "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
553
+ );
554
+ }
555
+ }, initConfig = (config, prevConfig) => {
556
+ const specifiedConfig = {
557
+ ...prevConfig,
558
+ ...config,
559
+ stega: {
560
+ ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
561
+ ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
562
+ }
563
+ };
564
+ specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
565
+ const newConfig = {
566
+ ...defaultConfig,
567
+ ...specifiedConfig
568
+ }, projectBased = newConfig.useProjectHostname;
569
+ if (typeof Promise > "u") {
570
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
571
+ throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
572
+ }
573
+ if (projectBased && !newConfig.projectId)
574
+ throw new Error("Configuration must contain `projectId`");
575
+ if (typeof newConfig.perspective == "string" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
576
+ throw new Error(
577
+ "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?"
578
+ );
579
+ if ("encodeSourceMapAtPath" in newConfig)
580
+ throw new Error(
581
+ "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?"
582
+ );
583
+ if (typeof newConfig.stega.enabled != "boolean")
584
+ throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
585
+ if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
586
+ throw new Error("stega.studioUrl must be defined when stega.enabled is true");
587
+ if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
588
+ throw new Error(
589
+ `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
590
+ );
591
+ const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
592
+ isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > "u" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
593
+ const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
594
+ return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
595
+ }, projectHeader = "X-Sanity-Project-ID";
596
+ function requestOptions(config, overrides = {}) {
597
+ const headers = {}, token = overrides.token || config.token;
598
+ token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers[projectHeader] = config.projectId);
599
+ const withCredentials = !!(typeof overrides.withCredentials > "u" ? config.token || config.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > "u" ? config.timeout : overrides.timeout;
600
+ return Object.assign({}, overrides, {
601
+ headers: Object.assign({}, headers, overrides.headers || {}),
602
+ timeout: typeof timeout > "u" ? 5 * 60 * 1e3 : timeout,
603
+ proxy: overrides.proxy || config.proxy,
604
+ json: !0,
605
+ withCredentials,
606
+ fetch: typeof overrides.fetch == "object" && typeof config.fetch == "object" ? { ...config.fetch, ...overrides.fetch } : overrides.fetch || config.fetch
607
+ });
608
+ }
609
+ var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }, d = new Array(4).fill(String.fromCodePoint(c[0])).join("");
610
+ function E(t) {
611
+ let e = JSON.stringify(t);
612
+ return `${d}${Array.from(e).map((r) => {
613
+ let n = r.charCodeAt(0);
614
+ if (n > 255)
615
+ throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);
616
+ return Array.from(n.toString(4).padStart(4, "0")).map((o) => String.fromCodePoint(c[o])).join("");
617
+ }).join("")}`;
618
+ }
619
+ function I(t) {
620
+ return Number.isNaN(Number(t)) ? !!Date.parse(t) : !1;
621
+ }
622
+ function x(t) {
623
+ try {
624
+ new URL(t, t.startsWith("/") ? "https://acme.com" : void 0);
625
+ } catch {
626
+ return !1;
627
+ }
628
+ return !0;
629
+ }
630
+ function b(t, e, r = "auto") {
631
+ return r === !0 || r === "auto" && (I(t) || x(t)) ? t : `${t}${E(e)}`;
632
+ }
633
+ Object.fromEntries(Object.entries(c).map((t) => t.reverse()));
634
+ Object.fromEntries(Object.entries(s).map((t) => t.reverse()));
635
+ var S = `${Object.values(s).map((t) => `\\u{${t.toString(16)}}`).join("")}`, f = new RegExp(`[${S}]{4,}`, "gu");
636
+ function X(t) {
637
+ var e;
638
+ return { cleaned: t.replace(f, ""), encoded: ((e = t.match(f)) == null ? void 0 : e[0]) || "" };
639
+ }
640
+ function vercelStegaCleanAll(result) {
641
+ try {
642
+ return JSON.parse(
643
+ JSON.stringify(result, (key, value) => typeof value != "string" ? value : X(value).cleaned)
644
+ );
645
+ } catch {
646
+ return result;
647
+ }
648
+ }
649
+ const encodeQueryString = ({
650
+ query,
651
+ params = {},
652
+ options = {}
653
+ }) => {
654
+ const searchParams = new URLSearchParams(), { tag, returnQuery, ...opts } = options;
655
+ tag && searchParams.append("tag", tag), searchParams.append("query", query);
656
+ for (const [key, value] of Object.entries(params))
657
+ searchParams.append(`$${key}`, JSON.stringify(value));
658
+ for (const [key, value] of Object.entries(opts))
659
+ value && searchParams.append(key, `${value}`);
660
+ return returnQuery === !1 && searchParams.append("returnQuery", "false"), `?${searchParams}`;
661
+ }, excludeFalsey = (param, defValue) => param === !1 ? void 0 : typeof param > "u" ? defValue : param, getMutationQuery = (options = {}) => ({
662
+ dryRun: options.dryRun,
663
+ returnIds: !0,
664
+ returnDocuments: excludeFalsey(options.returnDocuments, !0),
665
+ visibility: options.visibility || "sync",
666
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
667
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
668
+ }), 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;
669
+ function _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {
670
+ const stega = "stega" in options ? {
671
+ ..._stega || {},
672
+ ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
673
+ } : _stega, params = stega.enabled ? vercelStegaCleanAll(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
674
+ // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.
675
+ // This is necessary in React Server Components to avoid opting out of Request Memoization.
676
+ useAbortSignal: typeof options.signal < "u",
677
+ // Set `resultSourceMap' when stega is enabled, as it's required for encoding.
678
+ resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
679
+ ...options,
680
+ // Default to not returning the query, unless `filterResponse` is `false`,
681
+ // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy
682
+ returnQuery: options.filterResponse === !1 && options.returnQuery !== !1
683
+ }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(client, httpRequest, "query", { query, params }, reqOpts);
684
+ return stega.enabled ? $request.pipe(
685
+ operators.combineLatestWith(
686
+ rxjs.from(
687
+ Promise.resolve().then(function() {
688
+ return require("./stegaEncodeSourceMap-BvBJpbrr.cjs");
689
+ }).then(function(n) {
690
+ return n.stegaEncodeSourceMap$1;
691
+ }).then(
692
+ ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap
693
+ )
694
+ )
695
+ ),
696
+ operators.map(
697
+ ([res, stegaEncodeSourceMap]) => {
698
+ const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
699
+ return mapResponse({ ...res, result });
700
+ }
701
+ )
702
+ ) : $request.pipe(operators.map(mapResponse));
703
+ }
704
+ function _getDocument(client, httpRequest, id, opts = {}) {
705
+ const options = { uri: _getDataUrl(client, "doc", id), json: !0, tag: opts.tag };
706
+ return _requestObservable(client, httpRequest, options).pipe(
707
+ operators.filter(isResponse),
708
+ operators.map((event) => event.body.documents && event.body.documents[0])
709
+ );
710
+ }
711
+ function _getDocuments(client, httpRequest, ids, opts = {}) {
712
+ const options = { uri: _getDataUrl(client, "doc", ids.join(",")), json: !0, tag: opts.tag };
713
+ return _requestObservable(client, httpRequest, options).pipe(
714
+ operators.filter(isResponse),
715
+ operators.map((event) => {
716
+ const indexed = indexBy(event.body.documents || [], (doc) => doc._id);
717
+ return ids.map((id) => indexed[id] || null);
718
+ })
719
+ );
720
+ }
721
+ function _createIfNotExists(client, httpRequest, doc, options) {
722
+ return requireDocumentId("createIfNotExists", doc), _create(client, httpRequest, doc, "createIfNotExists", options);
723
+ }
724
+ function _createOrReplace(client, httpRequest, doc, options) {
725
+ return requireDocumentId("createOrReplace", doc), _create(client, httpRequest, doc, "createOrReplace", options);
726
+ }
727
+ function _delete(client, httpRequest, selection, options) {
728
+ return _dataRequest(
729
+ client,
730
+ httpRequest,
731
+ "mutate",
732
+ { mutations: [{ delete: getSelection(selection) }] },
733
+ options
734
+ );
735
+ }
736
+ function _mutate(client, httpRequest, mutations, options) {
737
+ let mut;
738
+ mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;
739
+ const muts = Array.isArray(mut) ? mut : [mut], transactionId = options && options.transactionId || void 0;
740
+ return _dataRequest(client, httpRequest, "mutate", { mutations: muts, transactionId }, options);
741
+ }
742
+ function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
743
+ const isMutation = endpoint === "mutate", isQuery = endpoint === "query", strQuery = isMutation ? "" : encodeQueryString(body), useGet = !isMutation && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers, returnQuery } = options, uri = _getDataUrl(client, endpoint, stringQuery), reqOptions = {
744
+ method: useGet ? "GET" : "POST",
745
+ uri,
746
+ json: !0,
747
+ body: useGet ? void 0 : body,
748
+ query: isMutation && getMutationQuery(options),
749
+ timeout,
750
+ headers,
751
+ token,
752
+ tag,
753
+ returnQuery,
754
+ perspective: options.perspective,
755
+ resultSourceMap: options.resultSourceMap,
756
+ canUseCdn: isQuery,
757
+ signal: options.signal,
758
+ fetch: options.fetch,
759
+ useAbortSignal: options.useAbortSignal,
760
+ useCdn: options.useCdn
761
+ };
762
+ return _requestObservable(client, httpRequest, reqOptions).pipe(
763
+ operators.filter(isResponse),
764
+ operators.map(getBody),
765
+ operators.map((res) => {
766
+ if (!isMutation)
767
+ return res;
768
+ const results = res.results || [];
769
+ if (options.returnDocuments)
770
+ return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
771
+ const key = returnFirst ? "documentId" : "documentIds", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
772
+ return {
773
+ transactionId: res.transactionId,
774
+ results,
775
+ [key]: ids
776
+ };
777
+ })
778
+ );
779
+ }
780
+ function _create(client, httpRequest, doc, op, options = {}) {
781
+ const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);
782
+ return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
783
+ }
784
+ function _requestObservable(client, httpRequest, options) {
785
+ var _a, _b;
786
+ const uri = options.url || options.uri, config = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
787
+ let useCdn = ((_a = options.useCdn) != null ? _a : config.useCdn) && canUseCdn;
788
+ const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
789
+ if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/query/") === 0) {
790
+ const resultSourceMap = (_b = options.resultSourceMap) != null ? _b : config.resultSourceMap;
791
+ resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
792
+ const perspective = options.perspective || config.perspective;
793
+ typeof perspective == "string" && perspective !== "raw" && (validateApiPerspective(perspective), options.query = { perspective, ...options.query }, perspective === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query });
794
+ }
795
+ const reqOptions = requestOptions(
796
+ config,
797
+ Object.assign({}, options, {
798
+ url: _getUrl(client, uri, useCdn)
799
+ })
800
+ ), request = new rxjs.Observable(
801
+ (subscriber) => httpRequest(reqOptions, config.requester).subscribe(subscriber)
802
+ );
803
+ return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
804
+ }
805
+ function _request(client, httpRequest, options) {
806
+ return _requestObservable(client, httpRequest, options).pipe(
807
+ operators.filter((event) => event.type === "response"),
808
+ operators.map((event) => event.body)
809
+ );
810
+ }
811
+ function _getDataUrl(client, operation, path) {
812
+ const config = client.config(), catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;
813
+ return `/data${path ? `${baseUri}/${path}` : baseUri}`.replace(/\/($|\?)/, "$1");
814
+ }
815
+ function _getUrl(client, uri, canUseCdn = !1) {
816
+ const { url, cdnUrl } = client.config();
817
+ return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
818
+ }
819
+ function _withAbortSignal(signal) {
820
+ return (input) => new rxjs.Observable((observer) => {
821
+ const abort = () => observer.error(_createAbortError(signal));
822
+ if (signal && signal.aborted) {
823
+ abort();
824
+ return;
825
+ }
826
+ const subscription = input.subscribe(observer);
827
+ return signal.addEventListener("abort", abort), () => {
828
+ signal.removeEventListener("abort", abort), subscription.unsubscribe();
829
+ };
830
+ });
831
+ }
832
+ const isDomExceptionSupported = !!globalThis.DOMException;
833
+ function _createAbortError(signal) {
834
+ var _a, _b;
835
+ if (isDomExceptionSupported)
836
+ return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
837
+ const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
838
+ return error.name = "AbortError", error;
839
+ }
840
+ var __accessCheck$4 = (obj, member, msg) => {
841
+ if (!member.has(obj))
842
+ throw TypeError("Cannot " + msg);
843
+ }, __privateGet$4 = (obj, member, getter) => (__accessCheck$4(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$4 = (obj, member, value) => {
844
+ if (member.has(obj))
845
+ throw TypeError("Cannot add the same private member more than once");
846
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
847
+ }, __privateSet$4 = (obj, member, value, setter) => (__accessCheck$4(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client$3, _httpRequest$4;
848
+ class ObservableAssetsClient {
849
+ constructor(client, httpRequest) {
850
+ __privateAdd$4(this, _client$3, void 0), __privateAdd$4(this, _httpRequest$4, void 0), __privateSet$4(this, _client$3, client), __privateSet$4(this, _httpRequest$4, httpRequest);
851
+ }
852
+ upload(assetType, body, options) {
853
+ return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
854
+ }
855
+ }
856
+ _client$3 = /* @__PURE__ */ new WeakMap(), _httpRequest$4 = /* @__PURE__ */ new WeakMap();
857
+ var _client2$3, _httpRequest2$4;
858
+ class AssetsClient {
859
+ constructor(client, httpRequest) {
860
+ __privateAdd$4(this, _client2$3, void 0), __privateAdd$4(this, _httpRequest2$4, void 0), __privateSet$4(this, _client2$3, client), __privateSet$4(this, _httpRequest2$4, httpRequest);
861
+ }
862
+ upload(assetType, body, options) {
863
+ const observable = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
864
+ return rxjs.lastValueFrom(
865
+ observable.pipe(
866
+ operators.filter((event) => event.type === "response"),
867
+ operators.map(
868
+ (event) => event.body.document
869
+ )
870
+ )
871
+ );
872
+ }
873
+ }
874
+ _client2$3 = /* @__PURE__ */ new WeakMap(), _httpRequest2$4 = /* @__PURE__ */ new WeakMap();
875
+ function _upload(client, httpRequest, assetType, body, opts = {}) {
876
+ validateAssetType(assetType);
877
+ let meta = opts.extract || void 0;
878
+ meta && !meta.length && (meta = ["none"]);
879
+ const dataset2 = hasDataset(client.config()), assetEndpoint = assetType === "image" ? "images" : "files", options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {
880
+ label,
881
+ title,
882
+ description,
883
+ filename,
884
+ meta,
885
+ creditLine
886
+ };
887
+ return source && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {
888
+ tag,
889
+ method: "POST",
890
+ timeout: options.timeout || 0,
891
+ uri: `/assets/${assetEndpoint}/${dataset2}`,
892
+ headers: options.contentType ? { "Content-Type": options.contentType } : {},
893
+ query,
894
+ body
895
+ });
896
+ }
897
+ function optionsFromFile(opts, file) {
898
+ return typeof File > "u" || !(file instanceof File) ? opts : Object.assign(
899
+ {
900
+ filename: opts.preserveFilename === !1 ? void 0 : file.name,
901
+ contentType: file.type
902
+ },
903
+ opts
904
+ );
905
+ }
906
+ 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), {});
907
+ const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), MAX_URL_LENGTH = 14800, possibleOptions = [
908
+ "includePreviousRevision",
909
+ "includeResult",
910
+ "visibility",
911
+ "effectFormat",
912
+ "tag"
913
+ ], defaultOptions = {
914
+ includeResult: !0
915
+ };
916
+ function _listen(query, params, opts = {}) {
917
+ const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
918
+ if (uri.length > MAX_URL_LENGTH)
919
+ return new rxjs.Observable((observer) => observer.error(new Error("Query too large for listener")));
920
+ const listenFor = options.events ? options.events : ["mutation"], shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1, esOptions = {};
921
+ return (token || withCredentials) && (esOptions.withCredentials = !0), token && (esOptions.headers = {
922
+ Authorization: `Bearer ${token}`
923
+ }), new rxjs.Observable((observer) => {
924
+ let es;
925
+ getEventSource().then((eventSource) => {
926
+ es = eventSource;
927
+ }).catch((reason) => {
928
+ observer.error(reason), stop();
929
+ });
930
+ let reconnectTimer, stopped = !1;
931
+ function onError() {
932
+ stopped || (emitReconnect(), !stopped && es.readyState === es.CLOSED && (unsubscribe(), clearTimeout(reconnectTimer), reconnectTimer = setTimeout(open, 100)));
933
+ }
934
+ function onChannelError(err) {
935
+ observer.error(cooerceError(err));
936
+ }
937
+ function onMessage(evt) {
938
+ const event = parseEvent(evt);
939
+ return event instanceof Error ? observer.error(event) : observer.next(event);
940
+ }
941
+ function onDisconnect() {
942
+ stopped = !0, unsubscribe(), observer.complete();
943
+ }
944
+ function unsubscribe() {
945
+ es && (es.removeEventListener("error", onError), es.removeEventListener("channelError", onChannelError), es.removeEventListener("disconnect", onDisconnect), listenFor.forEach((type) => es.removeEventListener(type, onMessage)), es.close());
946
+ }
947
+ function emitReconnect() {
948
+ shouldEmitReconnect && observer.next({ type: "reconnect" });
949
+ }
950
+ async function getEventSource() {
951
+ const { default: EventSource } = await import("@sanity/eventsource"), evs = new EventSource(uri, esOptions);
952
+ return evs.addEventListener("error", onError), evs.addEventListener("channelError", onChannelError), evs.addEventListener("disconnect", onDisconnect), listenFor.forEach((type) => evs.addEventListener(type, onMessage)), evs;
953
+ }
954
+ function open() {
955
+ getEventSource().then((eventSource) => {
956
+ es = eventSource;
957
+ }).catch((reason) => {
958
+ observer.error(reason), stop();
959
+ });
960
+ }
961
+ function stop() {
962
+ stopped = !0, unsubscribe();
963
+ }
964
+ return stop;
965
+ });
966
+ }
967
+ function parseEvent(event) {
968
+ try {
969
+ const data = event.data && JSON.parse(event.data) || {};
970
+ return Object.assign({ type: event.type }, data);
971
+ } catch (err) {
972
+ return err;
973
+ }
974
+ }
975
+ function cooerceError(err) {
976
+ if (err instanceof Error)
977
+ return err;
978
+ const evt = parseEvent(err);
979
+ return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
980
+ }
981
+ function extractErrorMessage(err) {
982
+ return err.error ? err.error.description ? err.error.description : typeof err.error == "string" ? err.error : JSON.stringify(err.error, null, 2) : err.message || "Unknown listener error";
983
+ }
984
+ var __accessCheck$3 = (obj, member, msg) => {
985
+ if (!member.has(obj))
986
+ throw TypeError("Cannot " + msg);
987
+ }, __privateGet$3 = (obj, member, getter) => (__accessCheck$3(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$3 = (obj, member, value) => {
988
+ if (member.has(obj))
989
+ throw TypeError("Cannot add the same private member more than once");
990
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
991
+ }, __privateSet$3 = (obj, member, value, setter) => (__accessCheck$3(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client$2, _httpRequest$3;
992
+ class ObservableDatasetsClient {
993
+ constructor(client, httpRequest) {
994
+ __privateAdd$3(this, _client$2, void 0), __privateAdd$3(this, _httpRequest$3, void 0), __privateSet$3(this, _client$2, client), __privateSet$3(this, _httpRequest$3, httpRequest);
995
+ }
996
+ /**
997
+ * Create a new dataset with the given name
998
+ *
999
+ * @param name - Name of the dataset to create
1000
+ * @param options - Options for the dataset
1001
+ */
1002
+ create(name, options) {
1003
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name, options);
1004
+ }
1005
+ /**
1006
+ * Edit a dataset with the given name
1007
+ *
1008
+ * @param name - Name of the dataset to edit
1009
+ * @param options - New options for the dataset
1010
+ */
1011
+ edit(name, options) {
1012
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name, options);
1013
+ }
1014
+ /**
1015
+ * Delete a dataset with the given name
1016
+ *
1017
+ * @param name - Name of the dataset to delete
1018
+ */
1019
+ delete(name) {
1020
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name);
1021
+ }
1022
+ /**
1023
+ * Fetch a list of datasets for the configured project
1024
+ */
1025
+ list() {
1026
+ return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
1027
+ uri: "/datasets",
1028
+ tag: null
1029
+ });
1030
+ }
1031
+ }
1032
+ _client$2 = /* @__PURE__ */ new WeakMap(), _httpRequest$3 = /* @__PURE__ */ new WeakMap();
1033
+ var _client2$2, _httpRequest2$3;
1034
+ class DatasetsClient {
1035
+ constructor(client, httpRequest) {
1036
+ __privateAdd$3(this, _client2$2, void 0), __privateAdd$3(this, _httpRequest2$3, void 0), __privateSet$3(this, _client2$2, client), __privateSet$3(this, _httpRequest2$3, httpRequest);
1037
+ }
1038
+ /**
1039
+ * Create a new dataset with the given name
1040
+ *
1041
+ * @param name - Name of the dataset to create
1042
+ * @param options - Options for the dataset
1043
+ */
1044
+ create(name, options) {
1045
+ return rxjs.lastValueFrom(
1046
+ _modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name, options)
1047
+ );
1048
+ }
1049
+ /**
1050
+ * Edit a dataset with the given name
1051
+ *
1052
+ * @param name - Name of the dataset to edit
1053
+ * @param options - New options for the dataset
1054
+ */
1055
+ edit(name, options) {
1056
+ return rxjs.lastValueFrom(
1057
+ _modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name, options)
1058
+ );
1059
+ }
1060
+ /**
1061
+ * Delete a dataset with the given name
1062
+ *
1063
+ * @param name - Name of the dataset to delete
1064
+ */
1065
+ delete(name) {
1066
+ return rxjs.lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name));
1067
+ }
1068
+ /**
1069
+ * Fetch a list of datasets for the configured project
1070
+ */
1071
+ list() {
1072
+ return rxjs.lastValueFrom(
1073
+ _request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), { uri: "/datasets", tag: null })
1074
+ );
1075
+ }
1076
+ }
1077
+ _client2$2 = /* @__PURE__ */ new WeakMap(), _httpRequest2$3 = /* @__PURE__ */ new WeakMap();
1078
+ function _modify(client, httpRequest, method, name, options) {
1079
+ return dataset(name), _request(client, httpRequest, {
1080
+ method,
1081
+ uri: `/datasets/${name}`,
1082
+ body: options,
1083
+ tag: null
1084
+ });
1085
+ }
1086
+ var __accessCheck$2 = (obj, member, msg) => {
1087
+ if (!member.has(obj))
1088
+ throw TypeError("Cannot " + msg);
1089
+ }, __privateGet$2 = (obj, member, getter) => (__accessCheck$2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$2 = (obj, member, value) => {
1090
+ if (member.has(obj))
1091
+ throw TypeError("Cannot add the same private member more than once");
1092
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1093
+ }, __privateSet$2 = (obj, member, value, setter) => (__accessCheck$2(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client$1, _httpRequest$2;
1094
+ class ObservableProjectsClient {
1095
+ constructor(client, httpRequest) {
1096
+ __privateAdd$2(this, _client$1, void 0), __privateAdd$2(this, _httpRequest$2, void 0), __privateSet$2(this, _client$1, client), __privateSet$2(this, _httpRequest$2, httpRequest);
1097
+ }
1098
+ list(options) {
1099
+ const uri = (options == null ? void 0 : options.includeMembers) === !1 ? "/projects?includeMembers=false" : "/projects";
1100
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), { uri });
1101
+ }
1102
+ /**
1103
+ * Fetch a project by project ID
1104
+ *
1105
+ * @param projectId - ID of the project to fetch
1106
+ */
1107
+ getById(projectId2) {
1108
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), { uri: `/projects/${projectId2}` });
1109
+ }
1110
+ }
1111
+ _client$1 = /* @__PURE__ */ new WeakMap(), _httpRequest$2 = /* @__PURE__ */ new WeakMap();
1112
+ var _client2$1, _httpRequest2$2;
1113
+ class ProjectsClient {
1114
+ constructor(client, httpRequest) {
1115
+ __privateAdd$2(this, _client2$1, void 0), __privateAdd$2(this, _httpRequest2$2, void 0), __privateSet$2(this, _client2$1, client), __privateSet$2(this, _httpRequest2$2, httpRequest);
1116
+ }
1117
+ list(options) {
1118
+ const uri = (options == null ? void 0 : options.includeMembers) === !1 ? "/projects?includeMembers=false" : "/projects";
1119
+ return rxjs.lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), { uri }));
1120
+ }
1121
+ /**
1122
+ * Fetch a project by project ID
1123
+ *
1124
+ * @param projectId - ID of the project to fetch
1125
+ */
1126
+ getById(projectId2) {
1127
+ return rxjs.lastValueFrom(
1128
+ _request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), { uri: `/projects/${projectId2}` })
1129
+ );
1130
+ }
1131
+ }
1132
+ _client2$1 = /* @__PURE__ */ new WeakMap(), _httpRequest2$2 = /* @__PURE__ */ new WeakMap();
1133
+ var __accessCheck$1 = (obj, member, msg) => {
1134
+ if (!member.has(obj))
1135
+ throw TypeError("Cannot " + msg);
1136
+ }, __privateGet$1 = (obj, member, getter) => (__accessCheck$1(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$1 = (obj, member, value) => {
1137
+ if (member.has(obj))
1138
+ throw TypeError("Cannot add the same private member more than once");
1139
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1140
+ }, __privateSet$1 = (obj, member, value, setter) => (__accessCheck$1(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client, _httpRequest$1;
1141
+ class ObservableUsersClient {
1142
+ constructor(client, httpRequest) {
1143
+ __privateAdd$1(this, _client, void 0), __privateAdd$1(this, _httpRequest$1, void 0), __privateSet$1(this, _client, client), __privateSet$1(this, _httpRequest$1, httpRequest);
1144
+ }
1145
+ /**
1146
+ * Fetch a user by user ID
1147
+ *
1148
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
1149
+ */
1150
+ getById(id) {
1151
+ return _request(
1152
+ __privateGet$1(this, _client),
1153
+ __privateGet$1(this, _httpRequest$1),
1154
+ { uri: `/users/${id}` }
1155
+ );
1156
+ }
1157
+ }
1158
+ _client = /* @__PURE__ */ new WeakMap(), _httpRequest$1 = /* @__PURE__ */ new WeakMap();
1159
+ var _client2, _httpRequest2$1;
1160
+ class UsersClient {
1161
+ constructor(client, httpRequest) {
1162
+ __privateAdd$1(this, _client2, void 0), __privateAdd$1(this, _httpRequest2$1, void 0), __privateSet$1(this, _client2, client), __privateSet$1(this, _httpRequest2$1, httpRequest);
1163
+ }
1164
+ /**
1165
+ * Fetch a user by user ID
1166
+ *
1167
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
1168
+ */
1169
+ getById(id) {
1170
+ return rxjs.lastValueFrom(
1171
+ _request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
1172
+ uri: `/users/${id}`
1173
+ })
1174
+ );
1175
+ }
1176
+ }
1177
+ _client2 = /* @__PURE__ */ new WeakMap(), _httpRequest2$1 = /* @__PURE__ */ new WeakMap();
1178
+ var __accessCheck = (obj, member, msg) => {
1179
+ if (!member.has(obj))
1180
+ throw TypeError("Cannot " + msg);
1181
+ }, __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => {
1182
+ if (member.has(obj))
1183
+ throw TypeError("Cannot add the same private member more than once");
1184
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1185
+ }, __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _clientConfig, _httpRequest;
1186
+ const _ObservableSanityClient = class _ObservableSanityClient2 {
1187
+ constructor(httpRequest, config = defaultConfig) {
1188
+ __privateAdd(this, _clientConfig, void 0), __privateAdd(this, _httpRequest, void 0), this.listen = _listen, this.config(config), __privateSet(this, _httpRequest, httpRequest), this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest)), this.datasets = new ObservableDatasetsClient(this, __privateGet(this, _httpRequest)), this.projects = new ObservableProjectsClient(this, __privateGet(this, _httpRequest)), this.users = new ObservableUsersClient(this, __privateGet(this, _httpRequest));
1189
+ }
1190
+ /**
1191
+ * Clone the client - returns a new instance
1192
+ */
1193
+ clone() {
1194
+ return new _ObservableSanityClient2(__privateGet(this, _httpRequest), this.config());
1195
+ }
1196
+ config(newConfig) {
1197
+ if (newConfig === void 0)
1198
+ return { ...__privateGet(this, _clientConfig) };
1199
+ if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === !1)
1200
+ throw new Error(
1201
+ "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
1202
+ );
1203
+ return __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {})), this;
1204
+ }
1205
+ /**
1206
+ * Clone the client with a new (partial) configuration.
1207
+ *
1208
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1209
+ */
1210
+ withConfig(newConfig) {
1211
+ const thisConfig = this.config();
1212
+ return new _ObservableSanityClient2(__privateGet(this, _httpRequest), {
1213
+ ...thisConfig,
1214
+ ...newConfig,
1215
+ stega: {
1216
+ ...thisConfig.stega || {},
1217
+ ...typeof (newConfig == null ? void 0 : newConfig.stega) == "boolean" ? { enabled: newConfig.stega } : (newConfig == null ? void 0 : newConfig.stega) || {}
1218
+ }
1219
+ });
1220
+ }
1221
+ fetch(query, params, options) {
1222
+ return _fetch(
1223
+ this,
1224
+ __privateGet(this, _httpRequest),
1225
+ __privateGet(this, _clientConfig).stega,
1226
+ query,
1227
+ params,
1228
+ options
1229
+ );
1230
+ }
1231
+ /**
1232
+ * Fetch a single document with the given ID.
1233
+ *
1234
+ * @param id - Document ID to fetch
1235
+ * @param options - Request options
1236
+ */
1237
+ getDocument(id, options) {
1238
+ return _getDocument(this, __privateGet(this, _httpRequest), id, options);
1239
+ }
1240
+ /**
1241
+ * Fetch multiple documents in one request.
1242
+ * Should be used sparingly - performing a query is usually a better option.
1243
+ * The order/position of documents is preserved based on the original array of IDs.
1244
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
1245
+ *
1246
+ * @param ids - Document IDs to fetch
1247
+ * @param options - Request options
1248
+ */
1249
+ getDocuments(ids, options) {
1250
+ return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
1251
+ }
1252
+ create(document, options) {
1253
+ return _create(this, __privateGet(this, _httpRequest), document, "create", options);
1254
+ }
1255
+ createIfNotExists(document, options) {
1256
+ return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
1257
+ }
1258
+ createOrReplace(document, options) {
1259
+ return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
1260
+ }
1261
+ delete(selection, options) {
1262
+ return _delete(this, __privateGet(this, _httpRequest), selection, options);
1263
+ }
1264
+ mutate(operations, options) {
1265
+ return _mutate(this, __privateGet(this, _httpRequest), operations, options);
1266
+ }
1267
+ /**
1268
+ * Create a new buildable patch of operations to perform
1269
+ *
1270
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
1271
+ * @param operations - Optional object of patch operations to initialize the patch instance with
1272
+ * @returns Patch instance - call `.commit()` to perform the operations defined
1273
+ */
1274
+ patch(selection, operations) {
1275
+ return new ObservablePatch(selection, operations, this);
1276
+ }
1277
+ /**
1278
+ * Create a new transaction of mutations
1279
+ *
1280
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
1281
+ */
1282
+ transaction(operations) {
1283
+ return new ObservableTransaction(operations, this);
1284
+ }
1285
+ /**
1286
+ * Perform an HTTP request against the Sanity API
1287
+ *
1288
+ * @param options - Request options
1289
+ */
1290
+ request(options) {
1291
+ return _request(this, __privateGet(this, _httpRequest), options);
1292
+ }
1293
+ /**
1294
+ * Get a Sanity API URL for the URI provided
1295
+ *
1296
+ * @param uri - URI/path to build URL for
1297
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1298
+ */
1299
+ getUrl(uri, canUseCdn) {
1300
+ return _getUrl(this, uri, canUseCdn);
1301
+ }
1302
+ /**
1303
+ * Get a Sanity API URL for the data operation and path provided
1304
+ *
1305
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1306
+ * @param path - Path to append after the operation
1307
+ */
1308
+ getDataUrl(operation, path) {
1309
+ return _getDataUrl(this, operation, path);
1310
+ }
1311
+ };
1312
+ _clientConfig = /* @__PURE__ */ new WeakMap(), _httpRequest = /* @__PURE__ */ new WeakMap();
1313
+ let ObservableSanityClient = _ObservableSanityClient;
1314
+ var _clientConfig2, _httpRequest2;
1315
+ const _SanityClient = class _SanityClient2 {
1316
+ constructor(httpRequest, config = defaultConfig) {
1317
+ __privateAdd(this, _clientConfig2, void 0), __privateAdd(this, _httpRequest2, void 0), this.listen = _listen, this.config(config), __privateSet(this, _httpRequest2, httpRequest), this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2)), this.datasets = new DatasetsClient(this, __privateGet(this, _httpRequest2)), this.projects = new ProjectsClient(this, __privateGet(this, _httpRequest2)), this.users = new UsersClient(this, __privateGet(this, _httpRequest2)), this.observable = new ObservableSanityClient(httpRequest, config);
1318
+ }
1319
+ /**
1320
+ * Clone the client - returns a new instance
1321
+ */
1322
+ clone() {
1323
+ return new _SanityClient2(__privateGet(this, _httpRequest2), this.config());
1324
+ }
1325
+ config(newConfig) {
1326
+ if (newConfig === void 0)
1327
+ return { ...__privateGet(this, _clientConfig2) };
1328
+ if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === !1)
1329
+ throw new Error(
1330
+ "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
1331
+ );
1332
+ return this.observable && this.observable.config(newConfig), __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {})), this;
1333
+ }
1334
+ /**
1335
+ * Clone the client with a new (partial) configuration.
1336
+ *
1337
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1338
+ */
1339
+ withConfig(newConfig) {
1340
+ const thisConfig = this.config();
1341
+ return new _SanityClient2(__privateGet(this, _httpRequest2), {
1342
+ ...thisConfig,
1343
+ ...newConfig,
1344
+ stega: {
1345
+ ...thisConfig.stega || {},
1346
+ ...typeof (newConfig == null ? void 0 : newConfig.stega) == "boolean" ? { enabled: newConfig.stega } : (newConfig == null ? void 0 : newConfig.stega) || {}
1347
+ }
1348
+ });
1349
+ }
1350
+ fetch(query, params, options) {
1351
+ return rxjs.lastValueFrom(
1352
+ _fetch(
1353
+ this,
1354
+ __privateGet(this, _httpRequest2),
1355
+ __privateGet(this, _clientConfig2).stega,
1356
+ query,
1357
+ params,
1358
+ options
1359
+ )
1360
+ );
1361
+ }
1362
+ /**
1363
+ * Fetch a single document with the given ID.
1364
+ *
1365
+ * @param id - Document ID to fetch
1366
+ * @param options - Request options
1367
+ */
1368
+ getDocument(id, options) {
1369
+ return rxjs.lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
1370
+ }
1371
+ /**
1372
+ * Fetch multiple documents in one request.
1373
+ * Should be used sparingly - performing a query is usually a better option.
1374
+ * The order/position of documents is preserved based on the original array of IDs.
1375
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
1376
+ *
1377
+ * @param ids - Document IDs to fetch
1378
+ * @param options - Request options
1379
+ */
1380
+ getDocuments(ids, options) {
1381
+ return rxjs.lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
1382
+ }
1383
+ create(document, options) {
1384
+ return rxjs.lastValueFrom(
1385
+ _create(this, __privateGet(this, _httpRequest2), document, "create", options)
1386
+ );
1387
+ }
1388
+ createIfNotExists(document, options) {
1389
+ return rxjs.lastValueFrom(
1390
+ _createIfNotExists(this, __privateGet(this, _httpRequest2), document, options)
1391
+ );
1392
+ }
1393
+ createOrReplace(document, options) {
1394
+ return rxjs.lastValueFrom(
1395
+ _createOrReplace(this, __privateGet(this, _httpRequest2), document, options)
1396
+ );
1397
+ }
1398
+ delete(selection, options) {
1399
+ return rxjs.lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
1400
+ }
1401
+ mutate(operations, options) {
1402
+ return rxjs.lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
1403
+ }
1404
+ /**
1405
+ * Create a new buildable patch of operations to perform
1406
+ *
1407
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
1408
+ * @param operations - Optional object of patch operations to initialize the patch instance with
1409
+ * @returns Patch instance - call `.commit()` to perform the operations defined
1410
+ */
1411
+ patch(documentId, operations) {
1412
+ return new Patch(documentId, operations, this);
1413
+ }
1414
+ /**
1415
+ * Create a new transaction of mutations
1416
+ *
1417
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
1418
+ */
1419
+ transaction(operations) {
1420
+ return new Transaction(operations, this);
1421
+ }
1422
+ /**
1423
+ * Perform a request against the Sanity API
1424
+ * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
1425
+ *
1426
+ * @param options - Request options
1427
+ * @returns Promise resolving to the response body
1428
+ */
1429
+ request(options) {
1430
+ return rxjs.lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
1431
+ }
1432
+ /**
1433
+ * Perform an HTTP request a `/data` sub-endpoint
1434
+ * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
1435
+ *
1436
+ * @deprecated - Use `request()` or your own HTTP library instead
1437
+ * @param endpoint - Endpoint to hit (mutate, query etc)
1438
+ * @param body - Request body
1439
+ * @param options - Request options
1440
+ * @internal
1441
+ */
1442
+ dataRequest(endpoint, body, options) {
1443
+ return rxjs.lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
1444
+ }
1445
+ /**
1446
+ * Get a Sanity API URL for the URI provided
1447
+ *
1448
+ * @param uri - URI/path to build URL for
1449
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1450
+ */
1451
+ getUrl(uri, canUseCdn) {
1452
+ return _getUrl(this, uri, canUseCdn);
1453
+ }
1454
+ /**
1455
+ * Get a Sanity API URL for the data operation and path provided
1456
+ *
1457
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1458
+ * @param path - Path to append after the operation
1459
+ */
1460
+ getDataUrl(operation, path) {
1461
+ return _getDataUrl(this, operation, path);
1462
+ }
1463
+ };
1464
+ _clientConfig2 = /* @__PURE__ */ new WeakMap(), _httpRequest2 = /* @__PURE__ */ new WeakMap();
1465
+ let SanityClient = _SanityClient;
1466
+ function defineCreateClientExports(envMiddleware2, ClassConstructor) {
1467
+ return { requester: defineHttpRequest(envMiddleware2, {}).defaultRequester, createClient: (config) => new ClassConstructor(
1468
+ defineHttpRequest(envMiddleware2, {
1469
+ maxRetries: config.maxRetries,
1470
+ retryDelay: config.retryDelay
1471
+ }),
1472
+ config
1473
+ ) };
1474
+ }
1475
+ var envMiddleware = [];
1476
+ exports.BasePatch = BasePatch;
1477
+ exports.BaseTransaction = BaseTransaction;
1478
+ exports.ClientError = ClientError;
1479
+ exports.ObservablePatch = ObservablePatch;
1480
+ exports.ObservableSanityClient = ObservableSanityClient;
1481
+ exports.ObservableTransaction = ObservableTransaction;
1482
+ exports.Patch = Patch;
1483
+ exports.SanityClient = SanityClient;
1484
+ exports.ServerError = ServerError;
1485
+ exports.Transaction = Transaction;
1486
+ exports.b = b;
1487
+ exports.defineCreateClientExports = defineCreateClientExports;
1488
+ exports.envMiddleware = envMiddleware;
1489
+ exports.printNoDefaultExport = printNoDefaultExport;
1490
+ exports.vercelStegaCleanAll = vercelStegaCleanAll;
1491
+ //# sourceMappingURL=browserMiddleware-BHXO2Lcy.cjs.map