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