@sanity/client 6.7.1 → 6.8.0-pink-lizard.1

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