@sanity/client 6.14.1 → 6.14.3

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 (61) hide show
  1. package/dist/_chunks/browserMiddleware-B_0VHs-S.js +1476 -0
  2. package/dist/_chunks/browserMiddleware-B_0VHs-S.js.map +1 -0
  3. package/dist/_chunks/browserMiddleware-wr3kZwY7.cjs +1493 -0
  4. package/dist/_chunks/browserMiddleware-wr3kZwY7.cjs.map +1 -0
  5. package/dist/_chunks/nodeMiddleware-C0pzwo72.js +1493 -0
  6. package/dist/_chunks/nodeMiddleware-C0pzwo72.js.map +1 -0
  7. package/dist/_chunks/nodeMiddleware-SsjaLQfQ.cjs +1510 -0
  8. package/dist/_chunks/nodeMiddleware-SsjaLQfQ.cjs.map +1 -0
  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-C01qsbyy.js +285 -0
  12. package/dist/_chunks/{resolveEditInfo-Cf8D1Agp.js.map → resolveEditInfo-C01qsbyy.js.map} +1 -1
  13. package/dist/_chunks/stegaEncodeSourceMap-BbnAw_7a.js +168 -0
  14. package/dist/_chunks/{stegaEncodeSourceMap-DU95idpa.js.map → stegaEncodeSourceMap-BbnAw_7a.js.map} +1 -1
  15. package/dist/_chunks/stegaEncodeSourceMap-D5HvcZ8_.cjs +329 -0
  16. package/dist/_chunks/{stegaEncodeSourceMap-DIcuvN0P.cjs.map → stegaEncodeSourceMap-D5HvcZ8_.cjs.map} +1 -1
  17. package/dist/_chunks/stegaEncodeSourceMap-SLOvEWQZ.cjs +166 -0
  18. package/dist/_chunks/{stegaEncodeSourceMap-8TjLXjYU.cjs.map → stegaEncodeSourceMap-SLOvEWQZ.cjs.map} +1 -1
  19. package/dist/_chunks/stegaEncodeSourceMap-Z_1_DmND.js +330 -0
  20. package/dist/_chunks/{stegaEncodeSourceMap-DLon0Yls.js.map → stegaEncodeSourceMap-Z_1_DmND.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.d.ts +6 -0
  32. package/dist/index.js +24 -15
  33. package/dist/index.js.map +1 -1
  34. package/dist/stega.browser.cjs +12 -17
  35. package/dist/stega.browser.cjs.map +1 -1
  36. package/dist/stega.browser.js +26 -11
  37. package/dist/stega.browser.js.map +1 -1
  38. package/dist/stega.cjs +12 -17
  39. package/dist/stega.cjs.map +1 -1
  40. package/dist/stega.d.ts +6 -0
  41. package/dist/stega.js +26 -11
  42. package/dist/stega.js.map +1 -1
  43. package/package.json +4 -4
  44. package/src/config.ts +1 -1
  45. package/src/types.ts +10 -1
  46. package/umd/sanityClient.js +2676 -3364
  47. package/umd/sanityClient.min.js +3 -3
  48. package/dist/_chunks/browserMiddleware-DhUBf_19.js +0 -1761
  49. package/dist/_chunks/browserMiddleware-DhUBf_19.js.map +0 -1
  50. package/dist/_chunks/browserMiddleware-FpdqDQ1o.cjs +0 -1777
  51. package/dist/_chunks/browserMiddleware-FpdqDQ1o.cjs.map +0 -1
  52. package/dist/_chunks/nodeMiddleware-BSZoKrW0.js +0 -1780
  53. package/dist/_chunks/nodeMiddleware-BSZoKrW0.js.map +0 -1
  54. package/dist/_chunks/nodeMiddleware-DmcqX3kz.cjs +0 -1796
  55. package/dist/_chunks/nodeMiddleware-DmcqX3kz.cjs.map +0 -1
  56. package/dist/_chunks/resolveEditInfo-BB1WiUDY.cjs +0 -422
  57. package/dist/_chunks/resolveEditInfo-Cf8D1Agp.js +0 -406
  58. package/dist/_chunks/stegaEncodeSourceMap-8TjLXjYU.cjs +0 -229
  59. package/dist/_chunks/stegaEncodeSourceMap-DIcuvN0P.cjs +0 -486
  60. package/dist/_chunks/stegaEncodeSourceMap-DLon0Yls.js +0 -482
  61. package/dist/_chunks/stegaEncodeSourceMap-DU95idpa.js +0 -225
@@ -0,0 +1,1510 @@
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$1 = 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(envMiddleware, {
85
+ maxRetries = 5,
86
+ retryDelay
87
+ }) {
88
+ const request = getIt.getIt([
89
+ maxRetries > 0 ? middleware$1.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
+ ...envMiddleware,
97
+ printWarnings,
98
+ middleware$1.jsonRequest(),
99
+ middleware$1.jsonResponse(),
100
+ middleware$1.progress(),
101
+ httpError,
102
+ middleware$1.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$1.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 = (name2) => {
131
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name2))
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;
539
+ function validateApiVersion(apiVersion) {
540
+ if (apiVersion === "1" || apiVersion === "X")
541
+ return;
542
+ const apiDate = new Date(apiVersion);
543
+ if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
544
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
545
+ }
546
+ const validateApiPerspective = function(perspective) {
547
+ switch (perspective) {
548
+ case "previewDrafts":
549
+ case "published":
550
+ case "raw":
551
+ return;
552
+ default:
553
+ throw new TypeError(
554
+ "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
555
+ );
556
+ }
557
+ }, initConfig = (config, prevConfig) => {
558
+ const specifiedConfig = {
559
+ ...prevConfig,
560
+ ...config,
561
+ stega: {
562
+ ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
563
+ ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
564
+ }
565
+ };
566
+ specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
567
+ const newConfig = {
568
+ ...defaultConfig,
569
+ ...specifiedConfig
570
+ }, projectBased = newConfig.useProjectHostname;
571
+ if (typeof Promise > "u") {
572
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
573
+ throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
574
+ }
575
+ if (projectBased && !newConfig.projectId)
576
+ throw new Error("Configuration must contain `projectId`");
577
+ if (typeof newConfig.perspective == "string" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
578
+ throw new Error(
579
+ "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'?"
580
+ );
581
+ if ("encodeSourceMapAtPath" in newConfig)
582
+ throw new Error(
583
+ "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'?"
584
+ );
585
+ if (typeof newConfig.stega.enabled != "boolean")
586
+ throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
587
+ if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
588
+ throw new Error("stega.studioUrl must be defined when stega.enabled is true");
589
+ if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
590
+ throw new Error(
591
+ `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
592
+ );
593
+ const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
594
+ 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);
595
+ const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
596
+ 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;
597
+ }, projectHeader = "X-Sanity-Project-ID";
598
+ function requestOptions(config, overrides = {}) {
599
+ const headers = {}, token = overrides.token || config.token;
600
+ token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers[projectHeader] = config.projectId);
601
+ const withCredentials = !!(typeof overrides.withCredentials > "u" ? config.token || config.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > "u" ? config.timeout : overrides.timeout;
602
+ return Object.assign({}, overrides, {
603
+ headers: Object.assign({}, headers, overrides.headers || {}),
604
+ timeout: typeof timeout > "u" ? 5 * 60 * 1e3 : timeout,
605
+ proxy: overrides.proxy || config.proxy,
606
+ json: !0,
607
+ withCredentials,
608
+ fetch: typeof overrides.fetch == "object" && typeof config.fetch == "object" ? { ...config.fetch, ...overrides.fetch } : overrides.fetch || config.fetch
609
+ });
610
+ }
611
+ 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("");
612
+ function E(t) {
613
+ let e = JSON.stringify(t);
614
+ return `${d}${Array.from(e).map((r) => {
615
+ let n = r.charCodeAt(0);
616
+ if (n > 255)
617
+ throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);
618
+ return Array.from(n.toString(4).padStart(4, "0")).map((o) => String.fromCodePoint(c[o])).join("");
619
+ }).join("")}`;
620
+ }
621
+ function I(t) {
622
+ return Number.isNaN(Number(t)) ? !!Date.parse(t) : !1;
623
+ }
624
+ function x(t) {
625
+ try {
626
+ new URL(t, t.startsWith("/") ? "https://acme.com" : void 0);
627
+ } catch {
628
+ return !1;
629
+ }
630
+ return !0;
631
+ }
632
+ function b(t, e, r = "auto") {
633
+ return r === !0 || r === "auto" && (I(t) || x(t)) ? t : `${t}${E(e)}`;
634
+ }
635
+ Object.fromEntries(Object.entries(c).map((t) => t.reverse()));
636
+ Object.fromEntries(Object.entries(s).map((t) => t.reverse()));
637
+ var S = `${Object.values(s).map((t) => `\\u{${t.toString(16)}}`).join("")}`, f = new RegExp(`[${S}]{4,}`, "gu");
638
+ function X(t) {
639
+ var e;
640
+ return { cleaned: t.replace(f, ""), encoded: ((e = t.match(f)) == null ? void 0 : e[0]) || "" };
641
+ }
642
+ function vercelStegaCleanAll(result) {
643
+ try {
644
+ return JSON.parse(
645
+ JSON.stringify(result, (key, value) => typeof value != "string" ? value : X(value).cleaned)
646
+ );
647
+ } catch {
648
+ return result;
649
+ }
650
+ }
651
+ const encodeQueryString = ({
652
+ query,
653
+ params = {},
654
+ options = {}
655
+ }) => {
656
+ const searchParams = new URLSearchParams(), { tag, returnQuery, ...opts } = options;
657
+ tag && searchParams.append("tag", tag), searchParams.append("query", query);
658
+ for (const [key, value] of Object.entries(params))
659
+ searchParams.append(`$${key}`, JSON.stringify(value));
660
+ for (const [key, value] of Object.entries(opts))
661
+ value && searchParams.append(key, `${value}`);
662
+ return returnQuery === !1 && searchParams.append("returnQuery", "false"), `?${searchParams}`;
663
+ }, excludeFalsey = (param, defValue) => param === !1 ? void 0 : typeof param > "u" ? defValue : param, getMutationQuery = (options = {}) => ({
664
+ dryRun: options.dryRun,
665
+ returnIds: !0,
666
+ returnDocuments: excludeFalsey(options.returnDocuments, !0),
667
+ visibility: options.visibility || "sync",
668
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
669
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
670
+ }), 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;
671
+ function _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {
672
+ const stega = "stega" in options ? {
673
+ ..._stega || {},
674
+ ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
675
+ } : _stega, params = stega.enabled ? vercelStegaCleanAll(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
676
+ // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.
677
+ // This is necessary in React Server Components to avoid opting out of Request Memoization.
678
+ useAbortSignal: typeof options.signal < "u",
679
+ // Set `resultSourceMap' when stega is enabled, as it's required for encoding.
680
+ resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
681
+ ...options,
682
+ // Default to not returning the query, unless `filterResponse` is `false`,
683
+ // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy
684
+ returnQuery: options.filterResponse === !1 && options.returnQuery !== !1
685
+ }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(client, httpRequest, "query", { query, params }, reqOpts);
686
+ return stega.enabled ? $request.pipe(
687
+ operators.combineLatestWith(
688
+ rxjs.from(
689
+ Promise.resolve().then(function() {
690
+ return require("./stegaEncodeSourceMap-SLOvEWQZ.cjs");
691
+ }).then(function(n) {
692
+ return n.stegaEncodeSourceMap$1;
693
+ }).then(
694
+ ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap
695
+ )
696
+ )
697
+ ),
698
+ operators.map(
699
+ ([res, stegaEncodeSourceMap]) => {
700
+ const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
701
+ return mapResponse({ ...res, result });
702
+ }
703
+ )
704
+ ) : $request.pipe(operators.map(mapResponse));
705
+ }
706
+ function _getDocument(client, httpRequest, id, opts = {}) {
707
+ const options = { uri: _getDataUrl(client, "doc", id), json: !0, tag: opts.tag };
708
+ return _requestObservable(client, httpRequest, options).pipe(
709
+ operators.filter(isResponse),
710
+ operators.map((event) => event.body.documents && event.body.documents[0])
711
+ );
712
+ }
713
+ function _getDocuments(client, httpRequest, ids, opts = {}) {
714
+ const options = { uri: _getDataUrl(client, "doc", ids.join(",")), json: !0, tag: opts.tag };
715
+ return _requestObservable(client, httpRequest, options).pipe(
716
+ operators.filter(isResponse),
717
+ operators.map((event) => {
718
+ const indexed = indexBy(event.body.documents || [], (doc) => doc._id);
719
+ return ids.map((id) => indexed[id] || null);
720
+ })
721
+ );
722
+ }
723
+ function _createIfNotExists(client, httpRequest, doc, options) {
724
+ return requireDocumentId("createIfNotExists", doc), _create(client, httpRequest, doc, "createIfNotExists", options);
725
+ }
726
+ function _createOrReplace(client, httpRequest, doc, options) {
727
+ return requireDocumentId("createOrReplace", doc), _create(client, httpRequest, doc, "createOrReplace", options);
728
+ }
729
+ function _delete(client, httpRequest, selection, options) {
730
+ return _dataRequest(
731
+ client,
732
+ httpRequest,
733
+ "mutate",
734
+ { mutations: [{ delete: getSelection(selection) }] },
735
+ options
736
+ );
737
+ }
738
+ function _mutate(client, httpRequest, mutations, options) {
739
+ let mut;
740
+ mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;
741
+ const muts = Array.isArray(mut) ? mut : [mut], transactionId = options && options.transactionId || void 0;
742
+ return _dataRequest(client, httpRequest, "mutate", { mutations: muts, transactionId }, options);
743
+ }
744
+ function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
745
+ 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 = {
746
+ method: useGet ? "GET" : "POST",
747
+ uri,
748
+ json: !0,
749
+ body: useGet ? void 0 : body,
750
+ query: isMutation && getMutationQuery(options),
751
+ timeout,
752
+ headers,
753
+ token,
754
+ tag,
755
+ returnQuery,
756
+ perspective: options.perspective,
757
+ resultSourceMap: options.resultSourceMap,
758
+ canUseCdn: isQuery,
759
+ signal: options.signal,
760
+ fetch: options.fetch,
761
+ useAbortSignal: options.useAbortSignal,
762
+ useCdn: options.useCdn
763
+ };
764
+ return _requestObservable(client, httpRequest, reqOptions).pipe(
765
+ operators.filter(isResponse),
766
+ operators.map(getBody),
767
+ operators.map((res) => {
768
+ if (!isMutation)
769
+ return res;
770
+ const results = res.results || [];
771
+ if (options.returnDocuments)
772
+ return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
773
+ const key = returnFirst ? "documentId" : "documentIds", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
774
+ return {
775
+ transactionId: res.transactionId,
776
+ results,
777
+ [key]: ids
778
+ };
779
+ })
780
+ );
781
+ }
782
+ function _create(client, httpRequest, doc, op, options = {}) {
783
+ const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);
784
+ return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
785
+ }
786
+ function _requestObservable(client, httpRequest, options) {
787
+ var _a, _b;
788
+ 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;
789
+ let useCdn = ((_a = options.useCdn) != null ? _a : config.useCdn) && canUseCdn;
790
+ const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
791
+ 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) {
792
+ const resultSourceMap = (_b = options.resultSourceMap) != null ? _b : config.resultSourceMap;
793
+ resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
794
+ const perspective = options.perspective || config.perspective;
795
+ 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 });
796
+ }
797
+ const reqOptions = requestOptions(
798
+ config,
799
+ Object.assign({}, options, {
800
+ url: _getUrl(client, uri, useCdn)
801
+ })
802
+ ), request = new rxjs.Observable(
803
+ (subscriber) => httpRequest(reqOptions, config.requester).subscribe(subscriber)
804
+ );
805
+ return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
806
+ }
807
+ function _request(client, httpRequest, options) {
808
+ return _requestObservable(client, httpRequest, options).pipe(
809
+ operators.filter((event) => event.type === "response"),
810
+ operators.map((event) => event.body)
811
+ );
812
+ }
813
+ function _getDataUrl(client, operation, path) {
814
+ const config = client.config(), catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;
815
+ return `/data${path ? `${baseUri}/${path}` : baseUri}`.replace(/\/($|\?)/, "$1");
816
+ }
817
+ function _getUrl(client, uri, canUseCdn = !1) {
818
+ const { url, cdnUrl } = client.config();
819
+ return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
820
+ }
821
+ function _withAbortSignal(signal) {
822
+ return (input) => new rxjs.Observable((observer) => {
823
+ const abort = () => observer.error(_createAbortError(signal));
824
+ if (signal && signal.aborted) {
825
+ abort();
826
+ return;
827
+ }
828
+ const subscription = input.subscribe(observer);
829
+ return signal.addEventListener("abort", abort), () => {
830
+ signal.removeEventListener("abort", abort), subscription.unsubscribe();
831
+ };
832
+ });
833
+ }
834
+ const isDomExceptionSupported = !!globalThis.DOMException;
835
+ function _createAbortError(signal) {
836
+ var _a, _b;
837
+ if (isDomExceptionSupported)
838
+ return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
839
+ const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
840
+ return error.name = "AbortError", error;
841
+ }
842
+ var __accessCheck$4 = (obj, member, msg) => {
843
+ if (!member.has(obj))
844
+ throw TypeError("Cannot " + msg);
845
+ }, __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) => {
846
+ if (member.has(obj))
847
+ throw TypeError("Cannot add the same private member more than once");
848
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
849
+ }, __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;
850
+ class ObservableAssetsClient {
851
+ constructor(client, httpRequest) {
852
+ __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);
853
+ }
854
+ upload(assetType, body, options) {
855
+ return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
856
+ }
857
+ }
858
+ _client$3 = /* @__PURE__ */ new WeakMap(), _httpRequest$4 = /* @__PURE__ */ new WeakMap();
859
+ var _client2$3, _httpRequest2$4;
860
+ class AssetsClient {
861
+ constructor(client, httpRequest) {
862
+ __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);
863
+ }
864
+ upload(assetType, body, options) {
865
+ const observable = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
866
+ return rxjs.lastValueFrom(
867
+ observable.pipe(
868
+ operators.filter((event) => event.type === "response"),
869
+ operators.map(
870
+ (event) => event.body.document
871
+ )
872
+ )
873
+ );
874
+ }
875
+ }
876
+ _client2$3 = /* @__PURE__ */ new WeakMap(), _httpRequest2$4 = /* @__PURE__ */ new WeakMap();
877
+ function _upload(client, httpRequest, assetType, body, opts = {}) {
878
+ validateAssetType(assetType);
879
+ let meta = opts.extract || void 0;
880
+ meta && !meta.length && (meta = ["none"]);
881
+ const dataset2 = hasDataset(client.config()), assetEndpoint = assetType === "image" ? "images" : "files", options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {
882
+ label,
883
+ title,
884
+ description,
885
+ filename,
886
+ meta,
887
+ creditLine
888
+ };
889
+ return source && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {
890
+ tag,
891
+ method: "POST",
892
+ timeout: options.timeout || 0,
893
+ uri: `/assets/${assetEndpoint}/${dataset2}`,
894
+ headers: options.contentType ? { "Content-Type": options.contentType } : {},
895
+ query,
896
+ body
897
+ });
898
+ }
899
+ function optionsFromFile(opts, file) {
900
+ return typeof File > "u" || !(file instanceof File) ? opts : Object.assign(
901
+ {
902
+ filename: opts.preserveFilename === !1 ? void 0 : file.name,
903
+ contentType: file.type
904
+ },
905
+ opts
906
+ );
907
+ }
908
+ 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), {});
909
+ const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), MAX_URL_LENGTH = 14800, possibleOptions = [
910
+ "includePreviousRevision",
911
+ "includeResult",
912
+ "visibility",
913
+ "effectFormat",
914
+ "tag"
915
+ ], defaultOptions = {
916
+ includeResult: !0
917
+ };
918
+ function _listen(query, params, opts = {}) {
919
+ 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)}`;
920
+ if (uri.length > MAX_URL_LENGTH)
921
+ return new rxjs.Observable((observer) => observer.error(new Error("Query too large for listener")));
922
+ const listenFor = options.events ? options.events : ["mutation"], shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1, esOptions = {};
923
+ return (token || withCredentials) && (esOptions.withCredentials = !0), token && (esOptions.headers = {
924
+ Authorization: `Bearer ${token}`
925
+ }), new rxjs.Observable((observer) => {
926
+ let es;
927
+ getEventSource().then((eventSource) => {
928
+ es = eventSource;
929
+ }).catch((reason) => {
930
+ observer.error(reason), stop();
931
+ });
932
+ let reconnectTimer, stopped = !1;
933
+ function onError() {
934
+ stopped || (emitReconnect(), !stopped && es.readyState === es.CLOSED && (unsubscribe(), clearTimeout(reconnectTimer), reconnectTimer = setTimeout(open, 100)));
935
+ }
936
+ function onChannelError(err) {
937
+ observer.error(cooerceError(err));
938
+ }
939
+ function onMessage(evt) {
940
+ const event = parseEvent(evt);
941
+ return event instanceof Error ? observer.error(event) : observer.next(event);
942
+ }
943
+ function onDisconnect() {
944
+ stopped = !0, unsubscribe(), observer.complete();
945
+ }
946
+ function unsubscribe() {
947
+ es && (es.removeEventListener("error", onError), es.removeEventListener("channelError", onChannelError), es.removeEventListener("disconnect", onDisconnect), listenFor.forEach((type) => es.removeEventListener(type, onMessage)), es.close());
948
+ }
949
+ function emitReconnect() {
950
+ shouldEmitReconnect && observer.next({ type: "reconnect" });
951
+ }
952
+ async function getEventSource() {
953
+ const { default: EventSource } = await import("@sanity/eventsource"), evs = new EventSource(uri, esOptions);
954
+ return evs.addEventListener("error", onError), evs.addEventListener("channelError", onChannelError), evs.addEventListener("disconnect", onDisconnect), listenFor.forEach((type) => evs.addEventListener(type, onMessage)), evs;
955
+ }
956
+ function open() {
957
+ getEventSource().then((eventSource) => {
958
+ es = eventSource;
959
+ }).catch((reason) => {
960
+ observer.error(reason), stop();
961
+ });
962
+ }
963
+ function stop() {
964
+ stopped = !0, unsubscribe();
965
+ }
966
+ return stop;
967
+ });
968
+ }
969
+ function parseEvent(event) {
970
+ try {
971
+ const data = event.data && JSON.parse(event.data) || {};
972
+ return Object.assign({ type: event.type }, data);
973
+ } catch (err) {
974
+ return err;
975
+ }
976
+ }
977
+ function cooerceError(err) {
978
+ if (err instanceof Error)
979
+ return err;
980
+ const evt = parseEvent(err);
981
+ return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
982
+ }
983
+ function extractErrorMessage(err) {
984
+ 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";
985
+ }
986
+ var __accessCheck$3 = (obj, member, msg) => {
987
+ if (!member.has(obj))
988
+ throw TypeError("Cannot " + msg);
989
+ }, __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) => {
990
+ if (member.has(obj))
991
+ throw TypeError("Cannot add the same private member more than once");
992
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
993
+ }, __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;
994
+ class ObservableDatasetsClient {
995
+ constructor(client, httpRequest) {
996
+ __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);
997
+ }
998
+ /**
999
+ * Create a new dataset with the given name
1000
+ *
1001
+ * @param name - Name of the dataset to create
1002
+ * @param options - Options for the dataset
1003
+ */
1004
+ create(name2, options) {
1005
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name2, options);
1006
+ }
1007
+ /**
1008
+ * Edit a dataset with the given name
1009
+ *
1010
+ * @param name - Name of the dataset to edit
1011
+ * @param options - New options for the dataset
1012
+ */
1013
+ edit(name2, options) {
1014
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name2, options);
1015
+ }
1016
+ /**
1017
+ * Delete a dataset with the given name
1018
+ *
1019
+ * @param name - Name of the dataset to delete
1020
+ */
1021
+ delete(name2) {
1022
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name2);
1023
+ }
1024
+ /**
1025
+ * Fetch a list of datasets for the configured project
1026
+ */
1027
+ list() {
1028
+ return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
1029
+ uri: "/datasets",
1030
+ tag: null
1031
+ });
1032
+ }
1033
+ }
1034
+ _client$2 = /* @__PURE__ */ new WeakMap(), _httpRequest$3 = /* @__PURE__ */ new WeakMap();
1035
+ var _client2$2, _httpRequest2$3;
1036
+ class DatasetsClient {
1037
+ constructor(client, httpRequest) {
1038
+ __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);
1039
+ }
1040
+ /**
1041
+ * Create a new dataset with the given name
1042
+ *
1043
+ * @param name - Name of the dataset to create
1044
+ * @param options - Options for the dataset
1045
+ */
1046
+ create(name2, options) {
1047
+ return rxjs.lastValueFrom(
1048
+ _modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name2, options)
1049
+ );
1050
+ }
1051
+ /**
1052
+ * Edit a dataset with the given name
1053
+ *
1054
+ * @param name - Name of the dataset to edit
1055
+ * @param options - New options for the dataset
1056
+ */
1057
+ edit(name2, options) {
1058
+ return rxjs.lastValueFrom(
1059
+ _modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name2, options)
1060
+ );
1061
+ }
1062
+ /**
1063
+ * Delete a dataset with the given name
1064
+ *
1065
+ * @param name - Name of the dataset to delete
1066
+ */
1067
+ delete(name2) {
1068
+ return rxjs.lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name2));
1069
+ }
1070
+ /**
1071
+ * Fetch a list of datasets for the configured project
1072
+ */
1073
+ list() {
1074
+ return rxjs.lastValueFrom(
1075
+ _request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), { uri: "/datasets", tag: null })
1076
+ );
1077
+ }
1078
+ }
1079
+ _client2$2 = /* @__PURE__ */ new WeakMap(), _httpRequest2$3 = /* @__PURE__ */ new WeakMap();
1080
+ function _modify(client, httpRequest, method, name2, options) {
1081
+ return dataset(name2), _request(client, httpRequest, {
1082
+ method,
1083
+ uri: `/datasets/${name2}`,
1084
+ body: options,
1085
+ tag: null
1086
+ });
1087
+ }
1088
+ var __accessCheck$2 = (obj, member, msg) => {
1089
+ if (!member.has(obj))
1090
+ throw TypeError("Cannot " + msg);
1091
+ }, __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) => {
1092
+ if (member.has(obj))
1093
+ throw TypeError("Cannot add the same private member more than once");
1094
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1095
+ }, __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;
1096
+ class ObservableProjectsClient {
1097
+ constructor(client, httpRequest) {
1098
+ __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);
1099
+ }
1100
+ list(options) {
1101
+ const uri = (options == null ? void 0 : options.includeMembers) === !1 ? "/projects?includeMembers=false" : "/projects";
1102
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), { uri });
1103
+ }
1104
+ /**
1105
+ * Fetch a project by project ID
1106
+ *
1107
+ * @param projectId - ID of the project to fetch
1108
+ */
1109
+ getById(projectId2) {
1110
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), { uri: `/projects/${projectId2}` });
1111
+ }
1112
+ }
1113
+ _client$1 = /* @__PURE__ */ new WeakMap(), _httpRequest$2 = /* @__PURE__ */ new WeakMap();
1114
+ var _client2$1, _httpRequest2$2;
1115
+ class ProjectsClient {
1116
+ constructor(client, httpRequest) {
1117
+ __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);
1118
+ }
1119
+ list(options) {
1120
+ const uri = (options == null ? void 0 : options.includeMembers) === !1 ? "/projects?includeMembers=false" : "/projects";
1121
+ return rxjs.lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), { uri }));
1122
+ }
1123
+ /**
1124
+ * Fetch a project by project ID
1125
+ *
1126
+ * @param projectId - ID of the project to fetch
1127
+ */
1128
+ getById(projectId2) {
1129
+ return rxjs.lastValueFrom(
1130
+ _request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), { uri: `/projects/${projectId2}` })
1131
+ );
1132
+ }
1133
+ }
1134
+ _client2$1 = /* @__PURE__ */ new WeakMap(), _httpRequest2$2 = /* @__PURE__ */ new WeakMap();
1135
+ var __accessCheck$1 = (obj, member, msg) => {
1136
+ if (!member.has(obj))
1137
+ throw TypeError("Cannot " + msg);
1138
+ }, __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) => {
1139
+ if (member.has(obj))
1140
+ throw TypeError("Cannot add the same private member more than once");
1141
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1142
+ }, __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;
1143
+ class ObservableUsersClient {
1144
+ constructor(client, httpRequest) {
1145
+ __privateAdd$1(this, _client, void 0), __privateAdd$1(this, _httpRequest$1, void 0), __privateSet$1(this, _client, client), __privateSet$1(this, _httpRequest$1, httpRequest);
1146
+ }
1147
+ /**
1148
+ * Fetch a user by user ID
1149
+ *
1150
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
1151
+ */
1152
+ getById(id) {
1153
+ return _request(
1154
+ __privateGet$1(this, _client),
1155
+ __privateGet$1(this, _httpRequest$1),
1156
+ { uri: `/users/${id}` }
1157
+ );
1158
+ }
1159
+ }
1160
+ _client = /* @__PURE__ */ new WeakMap(), _httpRequest$1 = /* @__PURE__ */ new WeakMap();
1161
+ var _client2, _httpRequest2$1;
1162
+ class UsersClient {
1163
+ constructor(client, httpRequest) {
1164
+ __privateAdd$1(this, _client2, void 0), __privateAdd$1(this, _httpRequest2$1, void 0), __privateSet$1(this, _client2, client), __privateSet$1(this, _httpRequest2$1, httpRequest);
1165
+ }
1166
+ /**
1167
+ * Fetch a user by user ID
1168
+ *
1169
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
1170
+ */
1171
+ getById(id) {
1172
+ return rxjs.lastValueFrom(
1173
+ _request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
1174
+ uri: `/users/${id}`
1175
+ })
1176
+ );
1177
+ }
1178
+ }
1179
+ _client2 = /* @__PURE__ */ new WeakMap(), _httpRequest2$1 = /* @__PURE__ */ new WeakMap();
1180
+ var __accessCheck = (obj, member, msg) => {
1181
+ if (!member.has(obj))
1182
+ throw TypeError("Cannot " + msg);
1183
+ }, __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => {
1184
+ if (member.has(obj))
1185
+ throw TypeError("Cannot add the same private member more than once");
1186
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1187
+ }, __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _clientConfig, _httpRequest;
1188
+ const _ObservableSanityClient = class _ObservableSanityClient2 {
1189
+ constructor(httpRequest, config = defaultConfig) {
1190
+ __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));
1191
+ }
1192
+ /**
1193
+ * Clone the client - returns a new instance
1194
+ */
1195
+ clone() {
1196
+ return new _ObservableSanityClient2(__privateGet(this, _httpRequest), this.config());
1197
+ }
1198
+ config(newConfig) {
1199
+ if (newConfig === void 0)
1200
+ return { ...__privateGet(this, _clientConfig) };
1201
+ if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === !1)
1202
+ throw new Error(
1203
+ "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
1204
+ );
1205
+ return __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {})), this;
1206
+ }
1207
+ /**
1208
+ * Clone the client with a new (partial) configuration.
1209
+ *
1210
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1211
+ */
1212
+ withConfig(newConfig) {
1213
+ const thisConfig = this.config();
1214
+ return new _ObservableSanityClient2(__privateGet(this, _httpRequest), {
1215
+ ...thisConfig,
1216
+ ...newConfig,
1217
+ stega: {
1218
+ ...thisConfig.stega || {},
1219
+ ...typeof (newConfig == null ? void 0 : newConfig.stega) == "boolean" ? { enabled: newConfig.stega } : (newConfig == null ? void 0 : newConfig.stega) || {}
1220
+ }
1221
+ });
1222
+ }
1223
+ fetch(query, params, options) {
1224
+ return _fetch(
1225
+ this,
1226
+ __privateGet(this, _httpRequest),
1227
+ __privateGet(this, _clientConfig).stega,
1228
+ query,
1229
+ params,
1230
+ options
1231
+ );
1232
+ }
1233
+ /**
1234
+ * Fetch a single document with the given ID.
1235
+ *
1236
+ * @param id - Document ID to fetch
1237
+ * @param options - Request options
1238
+ */
1239
+ getDocument(id, options) {
1240
+ return _getDocument(this, __privateGet(this, _httpRequest), id, options);
1241
+ }
1242
+ /**
1243
+ * Fetch multiple documents in one request.
1244
+ * Should be used sparingly - performing a query is usually a better option.
1245
+ * The order/position of documents is preserved based on the original array of IDs.
1246
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
1247
+ *
1248
+ * @param ids - Document IDs to fetch
1249
+ * @param options - Request options
1250
+ */
1251
+ getDocuments(ids, options) {
1252
+ return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
1253
+ }
1254
+ create(document, options) {
1255
+ return _create(this, __privateGet(this, _httpRequest), document, "create", options);
1256
+ }
1257
+ createIfNotExists(document, options) {
1258
+ return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
1259
+ }
1260
+ createOrReplace(document, options) {
1261
+ return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
1262
+ }
1263
+ delete(selection, options) {
1264
+ return _delete(this, __privateGet(this, _httpRequest), selection, options);
1265
+ }
1266
+ mutate(operations, options) {
1267
+ return _mutate(this, __privateGet(this, _httpRequest), operations, options);
1268
+ }
1269
+ /**
1270
+ * Create a new buildable patch of operations to perform
1271
+ *
1272
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
1273
+ * @param operations - Optional object of patch operations to initialize the patch instance with
1274
+ * @returns Patch instance - call `.commit()` to perform the operations defined
1275
+ */
1276
+ patch(selection, operations) {
1277
+ return new ObservablePatch(selection, operations, this);
1278
+ }
1279
+ /**
1280
+ * Create a new transaction of mutations
1281
+ *
1282
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
1283
+ */
1284
+ transaction(operations) {
1285
+ return new ObservableTransaction(operations, this);
1286
+ }
1287
+ /**
1288
+ * Perform an HTTP request against the Sanity API
1289
+ *
1290
+ * @param options - Request options
1291
+ */
1292
+ request(options) {
1293
+ return _request(this, __privateGet(this, _httpRequest), options);
1294
+ }
1295
+ /**
1296
+ * Get a Sanity API URL for the URI provided
1297
+ *
1298
+ * @param uri - URI/path to build URL for
1299
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1300
+ */
1301
+ getUrl(uri, canUseCdn) {
1302
+ return _getUrl(this, uri, canUseCdn);
1303
+ }
1304
+ /**
1305
+ * Get a Sanity API URL for the data operation and path provided
1306
+ *
1307
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1308
+ * @param path - Path to append after the operation
1309
+ */
1310
+ getDataUrl(operation, path) {
1311
+ return _getDataUrl(this, operation, path);
1312
+ }
1313
+ };
1314
+ _clientConfig = /* @__PURE__ */ new WeakMap(), _httpRequest = /* @__PURE__ */ new WeakMap();
1315
+ let ObservableSanityClient = _ObservableSanityClient;
1316
+ var _clientConfig2, _httpRequest2;
1317
+ const _SanityClient = class _SanityClient2 {
1318
+ constructor(httpRequest, config = defaultConfig) {
1319
+ __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);
1320
+ }
1321
+ /**
1322
+ * Clone the client - returns a new instance
1323
+ */
1324
+ clone() {
1325
+ return new _SanityClient2(__privateGet(this, _httpRequest2), this.config());
1326
+ }
1327
+ config(newConfig) {
1328
+ if (newConfig === void 0)
1329
+ return { ...__privateGet(this, _clientConfig2) };
1330
+ if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === !1)
1331
+ throw new Error(
1332
+ "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
1333
+ );
1334
+ return this.observable && this.observable.config(newConfig), __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {})), this;
1335
+ }
1336
+ /**
1337
+ * Clone the client with a new (partial) configuration.
1338
+ *
1339
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1340
+ */
1341
+ withConfig(newConfig) {
1342
+ const thisConfig = this.config();
1343
+ return new _SanityClient2(__privateGet(this, _httpRequest2), {
1344
+ ...thisConfig,
1345
+ ...newConfig,
1346
+ stega: {
1347
+ ...thisConfig.stega || {},
1348
+ ...typeof (newConfig == null ? void 0 : newConfig.stega) == "boolean" ? { enabled: newConfig.stega } : (newConfig == null ? void 0 : newConfig.stega) || {}
1349
+ }
1350
+ });
1351
+ }
1352
+ fetch(query, params, options) {
1353
+ return rxjs.lastValueFrom(
1354
+ _fetch(
1355
+ this,
1356
+ __privateGet(this, _httpRequest2),
1357
+ __privateGet(this, _clientConfig2).stega,
1358
+ query,
1359
+ params,
1360
+ options
1361
+ )
1362
+ );
1363
+ }
1364
+ /**
1365
+ * Fetch a single document with the given ID.
1366
+ *
1367
+ * @param id - Document ID to fetch
1368
+ * @param options - Request options
1369
+ */
1370
+ getDocument(id, options) {
1371
+ return rxjs.lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
1372
+ }
1373
+ /**
1374
+ * Fetch multiple documents in one request.
1375
+ * Should be used sparingly - performing a query is usually a better option.
1376
+ * The order/position of documents is preserved based on the original array of IDs.
1377
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
1378
+ *
1379
+ * @param ids - Document IDs to fetch
1380
+ * @param options - Request options
1381
+ */
1382
+ getDocuments(ids, options) {
1383
+ return rxjs.lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
1384
+ }
1385
+ create(document, options) {
1386
+ return rxjs.lastValueFrom(
1387
+ _create(this, __privateGet(this, _httpRequest2), document, "create", options)
1388
+ );
1389
+ }
1390
+ createIfNotExists(document, options) {
1391
+ return rxjs.lastValueFrom(
1392
+ _createIfNotExists(this, __privateGet(this, _httpRequest2), document, options)
1393
+ );
1394
+ }
1395
+ createOrReplace(document, options) {
1396
+ return rxjs.lastValueFrom(
1397
+ _createOrReplace(this, __privateGet(this, _httpRequest2), document, options)
1398
+ );
1399
+ }
1400
+ delete(selection, options) {
1401
+ return rxjs.lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
1402
+ }
1403
+ mutate(operations, options) {
1404
+ return rxjs.lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
1405
+ }
1406
+ /**
1407
+ * Create a new buildable patch of operations to perform
1408
+ *
1409
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
1410
+ * @param operations - Optional object of patch operations to initialize the patch instance with
1411
+ * @returns Patch instance - call `.commit()` to perform the operations defined
1412
+ */
1413
+ patch(documentId, operations) {
1414
+ return new Patch(documentId, operations, this);
1415
+ }
1416
+ /**
1417
+ * Create a new transaction of mutations
1418
+ *
1419
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
1420
+ */
1421
+ transaction(operations) {
1422
+ return new Transaction(operations, this);
1423
+ }
1424
+ /**
1425
+ * Perform a request against the Sanity API
1426
+ * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
1427
+ *
1428
+ * @param options - Request options
1429
+ * @returns Promise resolving to the response body
1430
+ */
1431
+ request(options) {
1432
+ return rxjs.lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
1433
+ }
1434
+ /**
1435
+ * Perform an HTTP request a `/data` sub-endpoint
1436
+ * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
1437
+ *
1438
+ * @deprecated - Use `request()` or your own HTTP library instead
1439
+ * @param endpoint - Endpoint to hit (mutate, query etc)
1440
+ * @param body - Request body
1441
+ * @param options - Request options
1442
+ * @internal
1443
+ */
1444
+ dataRequest(endpoint, body, options) {
1445
+ return rxjs.lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
1446
+ }
1447
+ /**
1448
+ * Get a Sanity API URL for the URI provided
1449
+ *
1450
+ * @param uri - URI/path to build URL for
1451
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1452
+ */
1453
+ getUrl(uri, canUseCdn) {
1454
+ return _getUrl(this, uri, canUseCdn);
1455
+ }
1456
+ /**
1457
+ * Get a Sanity API URL for the data operation and path provided
1458
+ *
1459
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1460
+ * @param path - Path to append after the operation
1461
+ */
1462
+ getDataUrl(operation, path) {
1463
+ return _getDataUrl(this, operation, path);
1464
+ }
1465
+ };
1466
+ _clientConfig2 = /* @__PURE__ */ new WeakMap(), _httpRequest2 = /* @__PURE__ */ new WeakMap();
1467
+ let SanityClient = _SanityClient;
1468
+ function defineCreateClientExports(envMiddleware, ClassConstructor) {
1469
+ return { requester: defineHttpRequest(envMiddleware, {}).defaultRequester, createClient: (config) => new ClassConstructor(
1470
+ defineHttpRequest(envMiddleware, {
1471
+ maxRetries: config.maxRetries,
1472
+ retryDelay: config.retryDelay
1473
+ }),
1474
+ config
1475
+ ) };
1476
+ }
1477
+ var name = "@sanity/client", version = "6.14.3";
1478
+ const middleware = [
1479
+ middleware$1.debug({ verbose: !0, namespace: "sanity:client" }),
1480
+ middleware$1.headers({ "User-Agent": `${name} ${version}` }),
1481
+ // Enable keep-alive, and in addition limit the number of sockets that can be opened.
1482
+ // This avoids opening too many connections to the server if someone tries to execute
1483
+ // a bunch of requests in parallel. It's recommended to have a concurrency limit
1484
+ // at a "higher limit" (i.e. you shouldn't actually execute hundreds of requests in parallel),
1485
+ // and this is mainly to minimize the impact for the network and server.
1486
+ //
1487
+ // We're currently matching the same defaults as browsers:
1488
+ // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op
1489
+ middleware$1.agent({
1490
+ keepAlive: !0,
1491
+ maxSockets: 30,
1492
+ maxTotalSockets: 256
1493
+ })
1494
+ ];
1495
+ exports.BasePatch = BasePatch;
1496
+ exports.BaseTransaction = BaseTransaction;
1497
+ exports.ClientError = ClientError;
1498
+ exports.ObservablePatch = ObservablePatch;
1499
+ exports.ObservableSanityClient = ObservableSanityClient;
1500
+ exports.ObservableTransaction = ObservableTransaction;
1501
+ exports.Patch = Patch;
1502
+ exports.SanityClient = SanityClient;
1503
+ exports.ServerError = ServerError;
1504
+ exports.Transaction = Transaction;
1505
+ exports.b = b;
1506
+ exports.defineCreateClientExports = defineCreateClientExports;
1507
+ exports.middleware = middleware;
1508
+ exports.printNoDefaultExport = printNoDefaultExport;
1509
+ exports.vercelStegaCleanAll = vercelStegaCleanAll;
1510
+ //# sourceMappingURL=nodeMiddleware-SsjaLQfQ.cjs.map