@sanity/client 6.14.1 → 6.14.2

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