@sanity/client 4.0.1-1 → 5.0.0-esm.0

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 (68) hide show
  1. package/dist/index.browser.cjs +1335 -0
  2. package/dist/index.browser.cjs.map +1 -0
  3. package/dist/index.browser.js +1312 -0
  4. package/dist/index.browser.js.map +1 -0
  5. package/dist/index.cjs +1344 -0
  6. package/dist/index.cjs.js +15 -0
  7. package/dist/index.cjs.map +1 -0
  8. package/{sanityClient.d.ts → dist/index.d.ts} +991 -1117
  9. package/dist/index.js +1321 -0
  10. package/dist/index.js.map +1 -0
  11. package/package.json +81 -73
  12. package/src/SanityClient.ts +1261 -0
  13. package/src/assets/AssetsClient.ts +164 -0
  14. package/src/auth/AuthClient.ts +43 -0
  15. package/src/config.ts +95 -0
  16. package/src/data/dataMethods.ts +328 -0
  17. package/src/data/encodeQueryString.ts +28 -0
  18. package/src/data/listen.ts +195 -0
  19. package/src/data/patch.ts +353 -0
  20. package/src/data/transaction.ts +352 -0
  21. package/src/datasets/DatasetsClient.ts +97 -0
  22. package/src/generateHelpUrl.ts +5 -0
  23. package/src/http/browserMiddleware.ts +1 -0
  24. package/src/http/errors.ts +68 -0
  25. package/src/http/nodeMiddleware.ts +11 -0
  26. package/src/http/request.ts +50 -0
  27. package/src/http/requestOptions.ts +31 -0
  28. package/src/index.browser.ts +18 -0
  29. package/src/index.ts +57 -0
  30. package/src/projects/ProjectsClient.ts +45 -0
  31. package/src/types.ts +502 -0
  32. package/src/users/UsersClient.ts +46 -0
  33. package/src/util/defaults.ts +8 -0
  34. package/src/util/getSelection.ts +21 -0
  35. package/src/util/once.ts +12 -0
  36. package/src/util/pick.ts +9 -0
  37. package/src/validators.ts +76 -0
  38. package/src/warnings.ts +25 -0
  39. package/umd/sanityClient.js +5199 -5302
  40. package/umd/sanityClient.min.js +13 -13
  41. package/dist/sanityClient.browser.mjs +0 -2806
  42. package/dist/sanityClient.browser.mjs.map +0 -7
  43. package/index.js +0 -7
  44. package/lib/assets/assetsClient.js +0 -145
  45. package/lib/auth/authClient.js +0 -26
  46. package/lib/config.js +0 -88
  47. package/lib/data/dataMethods.js +0 -205
  48. package/lib/data/encodeQueryString.js +0 -31
  49. package/lib/data/listen.js +0 -164
  50. package/lib/data/patch.js +0 -121
  51. package/lib/data/transaction.js +0 -117
  52. package/lib/datasets/datasetsClient.js +0 -41
  53. package/lib/generateHelpUrl.js +0 -11
  54. package/lib/http/browserMiddleware.js +0 -9
  55. package/lib/http/errors.js +0 -56
  56. package/lib/http/nodeMiddleware.js +0 -22
  57. package/lib/http/queryString.js +0 -17
  58. package/lib/http/request.js +0 -52
  59. package/lib/http/requestOptions.js +0 -30
  60. package/lib/projects/projectsClient.js +0 -25
  61. package/lib/sanityClient.js +0 -118
  62. package/lib/users/usersClient.js +0 -20
  63. package/lib/util/defaults.js +0 -14
  64. package/lib/util/getSelection.js +0 -24
  65. package/lib/util/once.js +0 -20
  66. package/lib/util/pick.js +0 -17
  67. package/lib/validators.js +0 -76
  68. package/lib/warnings.js +0 -27
@@ -0,0 +1,1335 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', {
4
+ value: true
5
+ });
6
+ var getIt = require('get-it');
7
+ var middleware = require('get-it/middleware');
8
+ var rxjs = require('rxjs');
9
+ var makeError = require('make-error');
10
+ var operators = require('rxjs/operators');
11
+ var polyfilledEventSource = require('@sanity/eventsource');
12
+ function _interopDefaultCompat(e) {
13
+ return e && typeof e === 'object' && 'default' in e ? e : {
14
+ default: e
15
+ };
16
+ }
17
+ var polyfilledEventSource__default = /*#__PURE__*/_interopDefaultCompat(polyfilledEventSource);
18
+ var envMiddleware = [];
19
+ class ClientError extends makeError.BaseError {
20
+ constructor(res) {
21
+ const props = extractErrorProps(res);
22
+ super(props.message);
23
+ this.statusCode = 400;
24
+ Object.assign(this, props);
25
+ }
26
+ }
27
+ class ServerError extends makeError.BaseError {
28
+ constructor(res) {
29
+ const props = extractErrorProps(res);
30
+ super(props.message);
31
+ this.statusCode = 500;
32
+ Object.assign(this, props);
33
+ }
34
+ }
35
+ function extractErrorProps(res) {
36
+ const body = res.body;
37
+ const props = {
38
+ response: res,
39
+ statusCode: res.statusCode,
40
+ responseBody: stringifyBody(body, res),
41
+ message: "",
42
+ details: void 0
43
+ };
44
+ if (body.error && body.message) {
45
+ props.message = "".concat(body.error, " - ").concat(body.message);
46
+ return props;
47
+ }
48
+ if (body.error && body.error.description) {
49
+ props.message = body.error.description;
50
+ props.details = body.error;
51
+ return props;
52
+ }
53
+ props.message = body.error || body.message || httpErrorMessage(res);
54
+ return props;
55
+ }
56
+ function httpErrorMessage(res) {
57
+ const statusMessage = res.statusMessage ? " ".concat(res.statusMessage) : "";
58
+ return "".concat(res.method, "-request to ").concat(res.url, " resulted in HTTP ").concat(res.statusCode).concat(statusMessage);
59
+ }
60
+ function stringifyBody(body, res) {
61
+ const contentType = (res.headers["content-type"] || "").toLowerCase();
62
+ const isJson = contentType.indexOf("application/json") !== -1;
63
+ return isJson ? JSON.stringify(body, null, 2) : body;
64
+ }
65
+ const httpError = {
66
+ onResponse: res => {
67
+ if (res.statusCode >= 500) {
68
+ throw new ServerError(res);
69
+ } else if (res.statusCode >= 400) {
70
+ throw new ClientError(res);
71
+ }
72
+ return res;
73
+ }
74
+ };
75
+ const printWarnings = {
76
+ onResponse: res => {
77
+ const warn = res.headers["x-sanity-warning"];
78
+ const warnings = Array.isArray(warn) ? warn : [warn];
79
+ warnings.filter(Boolean).forEach(msg => console.warn(msg));
80
+ return res;
81
+ }
82
+ };
83
+ function defineHttpRequest(envMiddleware) {
84
+ const request = getIt.getIt([...envMiddleware, printWarnings, middleware.jsonRequest(), middleware.jsonResponse(), middleware.progress(), httpError, middleware.observable({
85
+ implementation: rxjs.Observable
86
+ })]);
87
+ function httpRequest(options) {
88
+ let requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : request;
89
+ return requester({
90
+ maxRedirects: 0,
91
+ ...options
92
+ });
93
+ }
94
+ httpRequest.defaultRequester = request;
95
+ return httpRequest;
96
+ }
97
+ const projectHeader = "X-Sanity-Project-ID";
98
+ var getRequestOptions = function (config) {
99
+ let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
100
+ const headers = {};
101
+ const token = overrides.token || config.token;
102
+ if (token) {
103
+ headers.Authorization = "Bearer ".concat(token);
104
+ }
105
+ if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
106
+ headers[projectHeader] = config.projectId;
107
+ }
108
+ const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
109
+ const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
110
+ return Object.assign({}, overrides, {
111
+ headers: Object.assign({}, headers, overrides.headers || {}),
112
+ timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
113
+ proxy: overrides.proxy || config.proxy,
114
+ json: true,
115
+ withCredentials
116
+ });
117
+ };
118
+ function getSelection(sel) {
119
+ if (typeof sel === "string" || Array.isArray(sel)) {
120
+ return {
121
+ id: sel
122
+ };
123
+ }
124
+ if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
125
+ return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
126
+ query: sel.query,
127
+ params: sel.params
128
+ } : {
129
+ query: sel.query
130
+ };
131
+ }
132
+ const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
133
+ throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
134
+ }
135
+ const VALID_ASSET_TYPES = ["image", "file"];
136
+ const VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
137
+ const dataset = name => {
138
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
139
+ throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
140
+ }
141
+ };
142
+ const projectId = id => {
143
+ if (!/^[-a-z0-9]+$/i.test(id)) {
144
+ throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
145
+ }
146
+ };
147
+ const validateAssetType = type => {
148
+ if (VALID_ASSET_TYPES.indexOf(type) === -1) {
149
+ throw new Error("Invalid asset type: ".concat(type, ". Must be one of ").concat(VALID_ASSET_TYPES.join(", ")));
150
+ }
151
+ };
152
+ const validateObject = (op, val) => {
153
+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
154
+ throw new Error("".concat(op, "() takes an object of properties"));
155
+ }
156
+ };
157
+ const validateDocumentId = (op, id) => {
158
+ if (typeof id !== "string" || !/^[a-z0-9_.-]+$/i.test(id)) {
159
+ throw new Error("".concat(op, "(): \"").concat(id, "\" is not a valid document ID"));
160
+ }
161
+ };
162
+ const requireDocumentId = (op, doc) => {
163
+ if (!doc._id) {
164
+ throw new Error("".concat(op, "() requires that the document contains an ID (\"_id\" property)"));
165
+ }
166
+ validateDocumentId(op, doc._id);
167
+ };
168
+ const validateInsert = (at, selector, items) => {
169
+ const signature = "insert(at, selector, items)";
170
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
171
+ const valid = VALID_INSERT_LOCATIONS.map(loc => "\"".concat(loc, "\"")).join(", ");
172
+ throw new Error("".concat(signature, " takes an \"at\"-argument which is one of: ").concat(valid));
173
+ }
174
+ if (typeof selector !== "string") {
175
+ throw new Error("".concat(signature, " takes a \"selector\"-argument which must be a string"));
176
+ }
177
+ if (!Array.isArray(items)) {
178
+ throw new Error("".concat(signature, " takes an \"items\"-argument which must be an array"));
179
+ }
180
+ };
181
+ const hasDataset = config => {
182
+ if (!config.dataset) {
183
+ throw new Error("`dataset` must be provided to perform queries");
184
+ }
185
+ return config.dataset || "";
186
+ };
187
+ const requestTag = tag => {
188
+ if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
189
+ throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
190
+ }
191
+ return tag;
192
+ };
193
+ const enc = encodeURIComponent;
194
+ var encodeQueryString = _ref => {
195
+ let {
196
+ query,
197
+ params = {},
198
+ options = {}
199
+ } = _ref;
200
+ const {
201
+ tag,
202
+ ...opts
203
+ } = options;
204
+ const q = "query=".concat(enc(query));
205
+ const base = tag ? "?tag=".concat(enc(tag), "&").concat(q) : "?".concat(q);
206
+ const qString = Object.keys(params).reduce((qs, param) => "".concat(qs, "&").concat(enc("$".concat(param)), "=").concat(enc(JSON.stringify(params[param]))), base);
207
+ return Object.keys(opts).reduce((qs, option) => {
208
+ return options[option] ? "".concat(qs, "&").concat(enc(option), "=").concat(enc(options[option])) : qs;
209
+ }, qString);
210
+ };
211
+ var __accessCheck$4 = (obj, member, msg) => {
212
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
213
+ };
214
+ var __privateGet$3 = (obj, member, getter) => {
215
+ __accessCheck$4(obj, member, "read from private field");
216
+ return getter ? getter.call(obj) : member.get(obj);
217
+ };
218
+ var __privateAdd$4 = (obj, member, value) => {
219
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
220
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
221
+ };
222
+ var __privateSet$3 = (obj, member, value, setter) => {
223
+ __accessCheck$4(obj, member, "write to private field");
224
+ setter ? setter.call(obj, value) : member.set(obj, value);
225
+ return value;
226
+ };
227
+ var _client$2, _client2$2;
228
+ class BasePatch {
229
+ constructor(selection) {
230
+ let operations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
231
+ this.selection = selection;
232
+ this.operations = operations;
233
+ }
234
+ replace(attrs) {
235
+ validateObject("replace", attrs);
236
+ return this._set("set", {
237
+ $: attrs
238
+ });
239
+ }
240
+ set(attrs) {
241
+ return this._assign("set", attrs);
242
+ }
243
+ setIfMissing(attrs) {
244
+ return this._assign("setIfMissing", attrs);
245
+ }
246
+ diffMatchPatch(attrs) {
247
+ validateObject("diffMatchPatch", attrs);
248
+ return this._assign("diffMatchPatch", attrs);
249
+ }
250
+ unset(attrs) {
251
+ if (!Array.isArray(attrs)) {
252
+ throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
253
+ }
254
+ this.operations = Object.assign({}, this.operations, {
255
+ unset: attrs
256
+ });
257
+ return this;
258
+ }
259
+ inc(attrs) {
260
+ return this._assign("inc", attrs);
261
+ }
262
+ dec(attrs) {
263
+ return this._assign("dec", attrs);
264
+ }
265
+ insert(at, selector, items) {
266
+ validateInsert(at, selector, items);
267
+ return this._assign("insert", {
268
+ [at]: selector,
269
+ items
270
+ });
271
+ }
272
+ append(selector, items) {
273
+ return this.insert("after", "".concat(selector, "[-1]"), items);
274
+ }
275
+ prepend(selector, items) {
276
+ return this.insert("before", "".concat(selector, "[0]"), items);
277
+ }
278
+ splice(selector, start, deleteCount, items) {
279
+ const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
280
+ const startIndex = start < 0 ? start - 1 : start;
281
+ const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
282
+ const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
283
+ const rangeSelector = "".concat(selector, "[").concat(startIndex, ":").concat(delRange, "]");
284
+ return this.insert("replace", rangeSelector, items || []);
285
+ }
286
+ ifRevisionId(rev) {
287
+ this.operations.ifRevisionID = rev;
288
+ return this;
289
+ }
290
+ serialize() {
291
+ return {
292
+ ...getSelection(this.selection),
293
+ ...this.operations
294
+ };
295
+ }
296
+ toJSON() {
297
+ return this.serialize();
298
+ }
299
+ reset() {
300
+ this.operations = {};
301
+ return this;
302
+ }
303
+ _assign(op, props) {
304
+ let merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
305
+ validateObject(op, props);
306
+ this.operations = Object.assign({}, this.operations, {
307
+ [op]: Object.assign({}, merge && this.operations[op] || {}, props)
308
+ });
309
+ return this;
310
+ }
311
+ _set(op, props) {
312
+ return this._assign(op, props, false);
313
+ }
314
+ }
315
+ const _ObservablePatch = class extends BasePatch {
316
+ constructor(selection, operations, client) {
317
+ super(selection, operations);
318
+ __privateAdd$4(this, _client$2, void 0);
319
+ __privateSet$3(this, _client$2, client);
320
+ }
321
+ clone() {
322
+ return new _ObservablePatch(this.selection, {
323
+ ...this.operations
324
+ }, __privateGet$3(this, _client$2));
325
+ }
326
+ commit(options) {
327
+ if (!__privateGet$3(this, _client$2)) {
328
+ throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
329
+ }
330
+ const returnFirst = typeof this.selection === "string";
331
+ const opts = Object.assign({
332
+ returnFirst,
333
+ returnDocuments: true
334
+ }, options);
335
+ return __privateGet$3(this, _client$2).mutate({
336
+ patch: this.serialize()
337
+ }, opts);
338
+ }
339
+ };
340
+ let ObservablePatch = _ObservablePatch;
341
+ _client$2 = new WeakMap();
342
+ const _Patch = class extends BasePatch {
343
+ constructor(selection, operations, client) {
344
+ super(selection, operations);
345
+ __privateAdd$4(this, _client2$2, void 0);
346
+ __privateSet$3(this, _client2$2, client);
347
+ }
348
+ clone() {
349
+ return new _Patch(this.selection, {
350
+ ...this.operations
351
+ }, __privateGet$3(this, _client2$2));
352
+ }
353
+ commit(options) {
354
+ if (!__privateGet$3(this, _client2$2)) {
355
+ throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
356
+ }
357
+ const returnFirst = typeof this.selection === "string";
358
+ const opts = Object.assign({
359
+ returnFirst,
360
+ returnDocuments: true
361
+ }, options);
362
+ return __privateGet$3(this, _client2$2).mutate({
363
+ patch: this.serialize()
364
+ }, opts);
365
+ }
366
+ };
367
+ let Patch = _Patch;
368
+ _client2$2 = new WeakMap();
369
+ var __accessCheck$3 = (obj, member, msg) => {
370
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
371
+ };
372
+ var __privateGet$2 = (obj, member, getter) => {
373
+ __accessCheck$3(obj, member, "read from private field");
374
+ return getter ? getter.call(obj) : member.get(obj);
375
+ };
376
+ var __privateAdd$3 = (obj, member, value) => {
377
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
378
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
379
+ };
380
+ var __privateSet$2 = (obj, member, value, setter) => {
381
+ __accessCheck$3(obj, member, "write to private field");
382
+ setter ? setter.call(obj, value) : member.set(obj, value);
383
+ return value;
384
+ };
385
+ var _client$1, _client2$1;
386
+ const defaultMutateOptions = {
387
+ returnDocuments: false
388
+ };
389
+ class BaseTransaction {
390
+ constructor() {
391
+ let operations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
392
+ let transactionId = arguments.length > 1 ? arguments[1] : undefined;
393
+ this.operations = operations;
394
+ this.trxId = transactionId;
395
+ }
396
+ create(doc) {
397
+ validateObject("create", doc);
398
+ return this._add({
399
+ create: doc
400
+ });
401
+ }
402
+ createIfNotExists(doc) {
403
+ const op = "createIfNotExists";
404
+ validateObject(op, doc);
405
+ requireDocumentId(op, doc);
406
+ return this._add({
407
+ [op]: doc
408
+ });
409
+ }
410
+ createOrReplace(doc) {
411
+ const op = "createOrReplace";
412
+ validateObject(op, doc);
413
+ requireDocumentId(op, doc);
414
+ return this._add({
415
+ [op]: doc
416
+ });
417
+ }
418
+ delete(documentId) {
419
+ validateDocumentId("delete", documentId);
420
+ return this._add({
421
+ delete: {
422
+ id: documentId
423
+ }
424
+ });
425
+ }
426
+ transactionId(id) {
427
+ if (!id) {
428
+ return this.trxId;
429
+ }
430
+ this.trxId = id;
431
+ return this;
432
+ }
433
+ serialize() {
434
+ return [...this.operations];
435
+ }
436
+ toJSON() {
437
+ return this.serialize();
438
+ }
439
+ reset() {
440
+ this.operations = [];
441
+ return this;
442
+ }
443
+ _add(mut) {
444
+ this.operations.push(mut);
445
+ return this;
446
+ }
447
+ }
448
+ const _Transaction = class extends BaseTransaction {
449
+ constructor(operations, client, transactionId) {
450
+ super(operations, transactionId);
451
+ __privateAdd$3(this, _client$1, void 0);
452
+ __privateSet$2(this, _client$1, client);
453
+ }
454
+ clone() {
455
+ return new _Transaction([...this.operations], __privateGet$2(this, _client$1), this.trxId);
456
+ }
457
+ commit(options) {
458
+ if (!__privateGet$2(this, _client$1)) {
459
+ throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
460
+ }
461
+ return __privateGet$2(this, _client$1).mutate(this.serialize(), Object.assign({
462
+ transactionId: this.trxId
463
+ }, defaultMutateOptions, options || {}));
464
+ }
465
+ patch(patchOrDocumentId, patchOps) {
466
+ const isBuilder = typeof patchOps === "function";
467
+ const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof Patch;
468
+ if (isPatch) {
469
+ return this._add({
470
+ patch: patchOrDocumentId.serialize()
471
+ });
472
+ }
473
+ if (isBuilder) {
474
+ const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$2(this, _client$1)));
475
+ if (!(patch instanceof Patch)) {
476
+ throw new Error("function passed to `patch()` must return the patch");
477
+ }
478
+ return this._add({
479
+ patch: patch.serialize()
480
+ });
481
+ }
482
+ return this._add({
483
+ patch: {
484
+ id: patchOrDocumentId,
485
+ ...patchOps
486
+ }
487
+ });
488
+ }
489
+ };
490
+ let Transaction = _Transaction;
491
+ _client$1 = new WeakMap();
492
+ const _ObservableTransaction = class extends BaseTransaction {
493
+ constructor(operations, client, transactionId) {
494
+ super(operations, transactionId);
495
+ __privateAdd$3(this, _client2$1, void 0);
496
+ __privateSet$2(this, _client2$1, client);
497
+ }
498
+ clone() {
499
+ return new _ObservableTransaction([...this.operations], __privateGet$2(this, _client2$1), this.trxId);
500
+ }
501
+ commit(options) {
502
+ if (!__privateGet$2(this, _client2$1)) {
503
+ throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
504
+ }
505
+ return __privateGet$2(this, _client2$1).mutate(this.serialize(), Object.assign({
506
+ transactionId: this.trxId
507
+ }, defaultMutateOptions, options || {}));
508
+ }
509
+ patch(patchOrDocumentId, patchOps) {
510
+ const isBuilder = typeof patchOps === "function";
511
+ const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof ObservablePatch;
512
+ if (isPatch) {
513
+ return this._add({
514
+ patch: patchOrDocumentId.serialize()
515
+ });
516
+ }
517
+ if (isBuilder) {
518
+ const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$2(this, _client2$1)));
519
+ if (!(patch instanceof ObservablePatch)) {
520
+ throw new Error("function passed to `patch()` must return the patch");
521
+ }
522
+ return this._add({
523
+ patch: patch.serialize()
524
+ });
525
+ }
526
+ return this._add({
527
+ patch: {
528
+ id: patchOrDocumentId,
529
+ ...patchOps
530
+ }
531
+ });
532
+ }
533
+ };
534
+ let ObservableTransaction = _ObservableTransaction;
535
+ _client2$1 = new WeakMap();
536
+ const excludeFalsey = (param, defValue) => {
537
+ const value = typeof param === "undefined" ? defValue : param;
538
+ return param === false ? void 0 : value;
539
+ };
540
+ const getMutationQuery = function () {
541
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
542
+ return {
543
+ dryRun: options.dryRun,
544
+ returnIds: true,
545
+ returnDocuments: excludeFalsey(options.returnDocuments, true),
546
+ visibility: options.visibility || "sync",
547
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
548
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
549
+ };
550
+ };
551
+ const isResponse = event => event.type === "response";
552
+ const getBody = event => event.body;
553
+ const indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
554
+ indexed[attr(doc)] = doc;
555
+ return indexed;
556
+ }, /* @__PURE__ */Object.create(null));
557
+ const getQuerySizeLimit = 11264;
558
+ function _fetch(client, httpRequest, query, params) {
559
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
560
+ const mapResponse = options.filterResponse === false ? res => res : res => res.result;
561
+ return _dataRequest(client, httpRequest, "query", {
562
+ query,
563
+ params
564
+ }, options).pipe(operators.map(mapResponse));
565
+ }
566
+ function _getDocument(client, httpRequest, id) {
567
+ let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
568
+ const options = {
569
+ uri: client.getDataUrl("doc", id),
570
+ json: true,
571
+ tag: opts.tag
572
+ };
573
+ return _requestObservable(client, httpRequest, options).pipe(operators.filter(isResponse), operators.map(event => event.body.documents && event.body.documents[0]));
574
+ }
575
+ function _getDocuments(client, httpRequest, ids) {
576
+ let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
577
+ const options = {
578
+ uri: client.getDataUrl("doc", ids.join(",")),
579
+ json: true,
580
+ tag: opts.tag
581
+ };
582
+ return _requestObservable(client, httpRequest, options).pipe(operators.filter(isResponse), operators.map(event => {
583
+ const indexed = indexBy(event.body.documents || [], doc => doc._id);
584
+ return ids.map(id => indexed[id] || null);
585
+ }));
586
+ }
587
+ function _createIfNotExists(client, httpRequest, doc, options) {
588
+ requireDocumentId("createIfNotExists", doc);
589
+ return _create(client, httpRequest, doc, "createIfNotExists", options);
590
+ }
591
+ function _createOrReplace(client, httpRequest, doc, options) {
592
+ requireDocumentId("createOrReplace", doc);
593
+ return _create(client, httpRequest, doc, "createOrReplace", options);
594
+ }
595
+ function _delete(client, httpRequest, selection, options) {
596
+ return _dataRequest(client, httpRequest, "mutate", {
597
+ mutations: [{
598
+ delete: getSelection(selection)
599
+ }]
600
+ }, options);
601
+ }
602
+ function _mutate(client, httpRequest, mutations, options) {
603
+ const mut = mutations instanceof Patch || mutations instanceof ObservablePatch || mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mutations.serialize() : mutations;
604
+ const muts = Array.isArray(mut) ? mut : [mut];
605
+ const transactionId = options && options.transactionId;
606
+ return _dataRequest(client, httpRequest, "mutate", {
607
+ mutations: muts,
608
+ transactionId
609
+ }, options);
610
+ }
611
+ function _dataRequest(client, httpRequest, endpoint, body) {
612
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
613
+ const isMutation = endpoint === "mutate";
614
+ const isQuery = endpoint === "query";
615
+ const strQuery = isMutation ? "" : encodeQueryString(body);
616
+ const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
617
+ const stringQuery = useGet ? strQuery : "";
618
+ const returnFirst = options.returnFirst;
619
+ const {
620
+ timeout,
621
+ token,
622
+ tag,
623
+ headers
624
+ } = options;
625
+ const uri = client.getDataUrl(endpoint, stringQuery);
626
+ const reqOptions = {
627
+ method: useGet ? "GET" : "POST",
628
+ uri,
629
+ json: true,
630
+ body: useGet ? void 0 : body,
631
+ query: isMutation && getMutationQuery(options),
632
+ timeout,
633
+ headers,
634
+ token,
635
+ tag,
636
+ canUseCdn: isQuery
637
+ };
638
+ return _requestObservable(client, httpRequest, reqOptions).pipe(operators.filter(isResponse), operators.map(getBody), operators.map(res => {
639
+ if (!isMutation) {
640
+ return res;
641
+ }
642
+ const results = res.results || [];
643
+ if (options.returnDocuments) {
644
+ return returnFirst ? results[0] && results[0].document : results.map(mut => mut.document);
645
+ }
646
+ const key = returnFirst ? "documentId" : "documentIds";
647
+ const ids = returnFirst ? results[0] && results[0].id : results.map(mut => mut.id);
648
+ return {
649
+ transactionId: res.transactionId,
650
+ results,
651
+ [key]: ids
652
+ };
653
+ }));
654
+ }
655
+ function _create(client, httpRequest, doc, op) {
656
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
657
+ const mutation = {
658
+ [op]: doc
659
+ };
660
+ const opts = Object.assign({
661
+ returnFirst: true,
662
+ returnDocuments: true
663
+ }, options);
664
+ return _dataRequest(client, httpRequest, "mutate", {
665
+ mutations: [mutation]
666
+ }, opts);
667
+ }
668
+ function _requestObservable(client, httpRequest, options) {
669
+ const uri = options.url || options.uri;
670
+ const config = client.config();
671
+ const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
672
+ const useCdn = config.useCdn && canUseCdn;
673
+ const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
674
+ if (tag) {
675
+ options.query = {
676
+ tag: requestTag(tag),
677
+ ...options.query
678
+ };
679
+ }
680
+ const reqOptions = getRequestOptions(config, Object.assign({}, options, {
681
+ url: client.getUrl(uri, useCdn)
682
+ }));
683
+ return new rxjs.Observable(subscriber => httpRequest(reqOptions, config.requester).subscribe(subscriber));
684
+ }
685
+ function _request(client, httpRequest, options) {
686
+ const observable = _requestObservable(client, httpRequest, options).pipe(operators.filter(event => event.type === "response"), operators.map(event => event.body));
687
+ return observable;
688
+ }
689
+ var __accessCheck$2 = (obj, member, msg) => {
690
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
691
+ };
692
+ var __privateGet$1 = (obj, member, getter) => {
693
+ __accessCheck$2(obj, member, "read from private field");
694
+ return getter ? getter.call(obj) : member.get(obj);
695
+ };
696
+ var __privateAdd$2 = (obj, member, value) => {
697
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
698
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
699
+ };
700
+ var __privateSet$1 = (obj, member, value, setter) => {
701
+ __accessCheck$2(obj, member, "write to private field");
702
+ setter ? setter.call(obj, value) : member.set(obj, value);
703
+ return value;
704
+ };
705
+ var _client, _httpRequest$1, _client2, _httpRequest2$1;
706
+ class ObservableAssetsClient {
707
+ constructor(client, httpRequest) {
708
+ __privateAdd$2(this, _client, void 0);
709
+ __privateAdd$2(this, _httpRequest$1, void 0);
710
+ __privateSet$1(this, _client, client);
711
+ __privateSet$1(this, _httpRequest$1, httpRequest);
712
+ }
713
+ upload(assetType, body, options) {
714
+ return _upload(__privateGet$1(this, _client), __privateGet$1(this, _httpRequest$1), assetType, body, options);
715
+ }
716
+ }
717
+ _client = new WeakMap();
718
+ _httpRequest$1 = new WeakMap();
719
+ class AssetsClient {
720
+ constructor(client, httpRequest) {
721
+ __privateAdd$2(this, _client2, void 0);
722
+ __privateAdd$2(this, _httpRequest2$1, void 0);
723
+ __privateSet$1(this, _client2, client);
724
+ __privateSet$1(this, _httpRequest2$1, httpRequest);
725
+ }
726
+ upload(assetType, body, options) {
727
+ const observable = _upload(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), assetType, body, options);
728
+ return rxjs.lastValueFrom(observable.pipe(operators.filter(event => event.type === "response"), operators.map(event => event.body.document)));
729
+ }
730
+ }
731
+ _client2 = new WeakMap();
732
+ _httpRequest2$1 = new WeakMap();
733
+ function _upload(client, httpRequest, assetType, body) {
734
+ let opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
735
+ validateAssetType(assetType);
736
+ let meta = opts.extract || void 0;
737
+ if (meta && !meta.length) {
738
+ meta = ["none"];
739
+ }
740
+ const dataset = hasDataset(client.config());
741
+ const assetEndpoint = assetType === "image" ? "images" : "files";
742
+ const options = optionsFromFile(opts, body);
743
+ const {
744
+ tag,
745
+ label,
746
+ title,
747
+ description,
748
+ creditLine,
749
+ filename,
750
+ source
751
+ } = options;
752
+ const query = {
753
+ label,
754
+ title,
755
+ description,
756
+ filename,
757
+ meta,
758
+ creditLine
759
+ };
760
+ if (source) {
761
+ query.sourceId = source.id;
762
+ query.sourceName = source.name;
763
+ query.sourceUrl = source.url;
764
+ }
765
+ return _requestObservable(client, httpRequest, {
766
+ tag,
767
+ method: "POST",
768
+ timeout: options.timeout || 0,
769
+ uri: "/assets/".concat(assetEndpoint, "/").concat(dataset),
770
+ headers: options.contentType ? {
771
+ "Content-Type": options.contentType
772
+ } : {},
773
+ query,
774
+ body
775
+ });
776
+ }
777
+ function optionsFromFile(opts, file) {
778
+ if (typeof window === "undefined" || !(file instanceof window.File)) {
779
+ return opts;
780
+ }
781
+ return Object.assign({
782
+ filename: opts.preserveFilename === false ? void 0 : file.name,
783
+ contentType: file.type
784
+ }, opts);
785
+ }
786
+ class BaseAuthClient {
787
+ getLoginProviders() {
788
+ return this.client.request({
789
+ uri: "/auth/providers"
790
+ });
791
+ }
792
+ logout() {
793
+ return this.client.request({
794
+ uri: "/auth/logout",
795
+ method: "POST"
796
+ });
797
+ }
798
+ }
799
+ class ObservableAuthClient extends BaseAuthClient {
800
+ constructor(client) {
801
+ super();
802
+ this.client = client;
803
+ }
804
+ }
805
+ class AuthClient extends BaseAuthClient {
806
+ constructor(client) {
807
+ super();
808
+ this.client = client;
809
+ }
810
+ }
811
+ const BASE_URL = "https://docs.sanity.io/help/";
812
+ function generateHelpUrl(slug) {
813
+ return BASE_URL + slug;
814
+ }
815
+ var once = fn => {
816
+ let didCall = false;
817
+ let returnValue;
818
+ return function () {
819
+ if (didCall) {
820
+ return returnValue;
821
+ }
822
+ returnValue = fn(...arguments);
823
+ didCall = true;
824
+ return returnValue;
825
+ };
826
+ };
827
+ const createWarningPrinter = message => once(function () {
828
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
829
+ args[_key] = arguments[_key];
830
+ }
831
+ return console.warn(message.join(" "), ...args);
832
+ });
833
+ const printCdnWarning = createWarningPrinter(["You are not using the Sanity CDN. That means your data is always fresh, but the CDN is faster and", "cheaper. Think about it! For more info, see ".concat(generateHelpUrl("js-client-cdn-configuration"), "."), "To hide this warning, please set the `useCdn` option to either `true` or `false` when creating", "the client."]);
834
+ 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.")]);
835
+ const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
836
+ const defaultCdnHost = "apicdn.sanity.io";
837
+ const defaultConfig = {
838
+ apiHost: "https://api.sanity.io",
839
+ apiVersion: "1",
840
+ useProjectHostname: true
841
+ };
842
+ const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
843
+ const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
844
+ const validateApiVersion = function validateApiVersion2(apiVersion) {
845
+ if (apiVersion === "1" || apiVersion === "X") {
846
+ return;
847
+ }
848
+ const apiDate = new Date(apiVersion);
849
+ const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
850
+ if (!apiVersionValid) {
851
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
852
+ }
853
+ };
854
+ const initConfig = (config, prevConfig) => {
855
+ const specifiedConfig = Object.assign({}, prevConfig, config);
856
+ if (!specifiedConfig.apiVersion) {
857
+ printNoApiVersionSpecifiedWarning();
858
+ }
859
+ const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
860
+ const projectBased = newConfig.useProjectHostname;
861
+ if (typeof Promise === "undefined") {
862
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
863
+ throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
864
+ }
865
+ if (projectBased && !newConfig.projectId) {
866
+ throw new Error("Configuration must contain `projectId`");
867
+ }
868
+ const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
869
+ const isLocalhost = isBrowser && isLocal(window.location.hostname);
870
+ if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
871
+ printBrowserTokenWarning();
872
+ } else if (typeof newConfig.useCdn === "undefined") {
873
+ printCdnWarning();
874
+ }
875
+ if (projectBased) {
876
+ projectId(newConfig.projectId);
877
+ }
878
+ if (newConfig.dataset) {
879
+ dataset(newConfig.dataset);
880
+ }
881
+ if ("requestTagPrefix" in newConfig) {
882
+ newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
883
+ }
884
+ newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
885
+ newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
886
+ newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
887
+ validateApiVersion(newConfig.apiVersion);
888
+ const hostParts = newConfig.apiHost.split("://", 2);
889
+ const protocol = hostParts[0];
890
+ const host = hostParts[1];
891
+ const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
892
+ if (newConfig.useProjectHostname) {
893
+ newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
894
+ newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
895
+ } else {
896
+ newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
897
+ newConfig.cdnUrl = newConfig.url;
898
+ }
899
+ return newConfig;
900
+ };
901
+ var defaults = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
902
+ target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
903
+ return target;
904
+ }, {});
905
+ var pick = (obj, props) => props.reduce((selection, prop) => {
906
+ if (typeof obj[prop] === "undefined") {
907
+ return selection;
908
+ }
909
+ selection[prop] = obj[prop];
910
+ return selection;
911
+ }, {});
912
+ const MAX_URL_LENGTH = 16e3 - 1200;
913
+ const EventSource = polyfilledEventSource__default.default;
914
+ const possibleOptions = ["includePreviousRevision", "includeResult", "visibility", "effectFormat", "tag"];
915
+ const defaultOptions = {
916
+ includeResult: true
917
+ };
918
+ function _listen(query, params) {
919
+ let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
920
+ const {
921
+ url,
922
+ token,
923
+ withCredentials,
924
+ requestTagPrefix
925
+ } = this.config();
926
+ const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
927
+ const options = {
928
+ ...defaults(opts, defaultOptions),
929
+ tag
930
+ };
931
+ const listenOpts = pick(options, possibleOptions);
932
+ const qs = encodeQueryString({
933
+ query,
934
+ params,
935
+ options: {
936
+ tag,
937
+ ...listenOpts
938
+ }
939
+ });
940
+ const uri = "".concat(url).concat(this.getDataUrl("listen", qs));
941
+ if (uri.length > MAX_URL_LENGTH) {
942
+ return new rxjs.Observable(observer => observer.error(new Error("Query too large for listener")));
943
+ }
944
+ const listenFor = options.events ? options.events : ["mutation"];
945
+ const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
946
+ const esOptions = {};
947
+ if (token || withCredentials) {
948
+ esOptions.withCredentials = true;
949
+ }
950
+ if (token) {
951
+ esOptions.headers = {
952
+ Authorization: "Bearer ".concat(token)
953
+ };
954
+ }
955
+ return new rxjs.Observable(observer => {
956
+ let es = getEventSource();
957
+ let reconnectTimer;
958
+ let stopped = false;
959
+ function onError() {
960
+ if (stopped) {
961
+ return;
962
+ }
963
+ emitReconnect();
964
+ if (stopped) {
965
+ return;
966
+ }
967
+ if (es.readyState === EventSource.CLOSED) {
968
+ unsubscribe();
969
+ clearTimeout(reconnectTimer);
970
+ reconnectTimer = setTimeout(open, 100);
971
+ }
972
+ }
973
+ function onChannelError(err) {
974
+ observer.error(cooerceError(err));
975
+ }
976
+ function onMessage(evt) {
977
+ const event = parseEvent(evt);
978
+ return event instanceof Error ? observer.error(event) : observer.next(event);
979
+ }
980
+ function onDisconnect() {
981
+ stopped = true;
982
+ unsubscribe();
983
+ observer.complete();
984
+ }
985
+ function unsubscribe() {
986
+ es.removeEventListener("error", onError, false);
987
+ es.removeEventListener("channelError", onChannelError, false);
988
+ es.removeEventListener("disconnect", onDisconnect, false);
989
+ listenFor.forEach(type => es.removeEventListener(type, onMessage, false));
990
+ es.close();
991
+ }
992
+ function emitReconnect() {
993
+ if (shouldEmitReconnect) {
994
+ observer.next({
995
+ type: "reconnect"
996
+ });
997
+ }
998
+ }
999
+ function getEventSource() {
1000
+ const evs = new EventSource(uri, esOptions);
1001
+ evs.addEventListener("error", onError, false);
1002
+ evs.addEventListener("channelError", onChannelError, false);
1003
+ evs.addEventListener("disconnect", onDisconnect, false);
1004
+ listenFor.forEach(type => evs.addEventListener(type, onMessage, false));
1005
+ return evs;
1006
+ }
1007
+ function open() {
1008
+ es = getEventSource();
1009
+ }
1010
+ function stop() {
1011
+ stopped = true;
1012
+ unsubscribe();
1013
+ }
1014
+ return stop;
1015
+ });
1016
+ }
1017
+ function parseEvent(event) {
1018
+ try {
1019
+ const data = event.data && JSON.parse(event.data) || {};
1020
+ return Object.assign({
1021
+ type: event.type
1022
+ }, data);
1023
+ } catch (err) {
1024
+ return err;
1025
+ }
1026
+ }
1027
+ function cooerceError(err) {
1028
+ if (err instanceof Error) {
1029
+ return err;
1030
+ }
1031
+ const evt = parseEvent(err);
1032
+ return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
1033
+ }
1034
+ function extractErrorMessage(err) {
1035
+ if (!err.error) {
1036
+ return err.message || "Unknown listener error";
1037
+ }
1038
+ if (err.error.description) {
1039
+ return err.error.description;
1040
+ }
1041
+ return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
1042
+ }
1043
+ var __accessCheck$1 = (obj, member, msg) => {
1044
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
1045
+ };
1046
+ var __privateAdd$1 = (obj, member, value) => {
1047
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
1048
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1049
+ };
1050
+ var __privateMethod = (obj, member, method) => {
1051
+ __accessCheck$1(obj, member, "access private method");
1052
+ return method;
1053
+ };
1054
+ var __modify, _modify_fn;
1055
+ class BaseDatasetsClient {
1056
+ constructor() {
1057
+ __privateAdd$1(this, __modify);
1058
+ }
1059
+ create(name, options) {
1060
+ return __privateMethod(this, __modify, _modify_fn).call(this, "PUT", name, options);
1061
+ }
1062
+ edit(name, options) {
1063
+ return __privateMethod(this, __modify, _modify_fn).call(this, "PATCH", name, options);
1064
+ }
1065
+ delete(name) {
1066
+ return __privateMethod(this, __modify, _modify_fn).call(this, "DELETE", name);
1067
+ }
1068
+ list() {
1069
+ return this.client.request({
1070
+ uri: "/datasets"
1071
+ });
1072
+ }
1073
+ }
1074
+ __modify = new WeakSet();
1075
+ _modify_fn = function (method, name, options) {
1076
+ dataset(name);
1077
+ return this.client.request({
1078
+ method,
1079
+ uri: "/datasets/".concat(name),
1080
+ body: options
1081
+ });
1082
+ };
1083
+ class ObservableDatasetsClient extends BaseDatasetsClient {
1084
+ constructor(client) {
1085
+ super();
1086
+ this.client = client;
1087
+ }
1088
+ }
1089
+ class DatasetsClient extends BaseDatasetsClient {
1090
+ constructor(client) {
1091
+ super();
1092
+ this.client = client;
1093
+ }
1094
+ }
1095
+ class BaseProjectsClient {
1096
+ list() {
1097
+ return this.client.request({
1098
+ uri: "/projects"
1099
+ });
1100
+ }
1101
+ getById(projectId) {
1102
+ return this.client.request({
1103
+ uri: "/projects/".concat(projectId)
1104
+ });
1105
+ }
1106
+ }
1107
+ class ObservableProjectsClient extends BaseProjectsClient {
1108
+ constructor(client) {
1109
+ super();
1110
+ this.client = client;
1111
+ }
1112
+ }
1113
+ class ProjectsClient extends BaseProjectsClient {
1114
+ constructor(client) {
1115
+ super();
1116
+ this.client = client;
1117
+ }
1118
+ }
1119
+ class BaseUsersClient {
1120
+ getById(id) {
1121
+ return this.client.request({
1122
+ uri: "/users/".concat(id)
1123
+ });
1124
+ }
1125
+ }
1126
+ class ObservableUsersClient extends BaseUsersClient {
1127
+ constructor(client) {
1128
+ super();
1129
+ this.client = client;
1130
+ }
1131
+ }
1132
+ class UsersClient extends BaseUsersClient {
1133
+ constructor(client) {
1134
+ super();
1135
+ this.client = client;
1136
+ }
1137
+ }
1138
+ var __accessCheck = (obj, member, msg) => {
1139
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
1140
+ };
1141
+ var __privateGet = (obj, member, getter) => {
1142
+ __accessCheck(obj, member, "read from private field");
1143
+ return getter ? getter.call(obj) : member.get(obj);
1144
+ };
1145
+ var __privateAdd = (obj, member, value) => {
1146
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
1147
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1148
+ };
1149
+ var __privateSet = (obj, member, value, setter) => {
1150
+ __accessCheck(obj, member, "write to private field");
1151
+ setter ? setter.call(obj, value) : member.set(obj, value);
1152
+ return value;
1153
+ };
1154
+ var _clientConfig, _httpRequest, _httpRequest2;
1155
+ class BaseSanityClient {
1156
+ constructor(config) {
1157
+ __privateAdd(this, _clientConfig, void 0);
1158
+ this.config(config);
1159
+ }
1160
+ config(newConfig) {
1161
+ if (newConfig === void 0) {
1162
+ return {
1163
+ ...__privateGet(this, _clientConfig)
1164
+ };
1165
+ }
1166
+ if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === false) {
1167
+ throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
1168
+ }
1169
+ __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {}));
1170
+ return this;
1171
+ }
1172
+ isPromiseAPI() {
1173
+ return this instanceof SanityClient;
1174
+ }
1175
+ getUrl(uri) {
1176
+ let canUseCdn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
1177
+ const base = canUseCdn ? __privateGet(this, _clientConfig).cdnUrl : __privateGet(this, _clientConfig).url;
1178
+ return "".concat(base, "/").concat(uri.replace(/^\//, ""));
1179
+ }
1180
+ getDataUrl(operation, path) {
1181
+ const config = this.config();
1182
+ const catalog = hasDataset(config);
1183
+ const baseUri = "/".concat(operation, "/").concat(catalog);
1184
+ const uri = path ? "".concat(baseUri, "/").concat(path) : baseUri;
1185
+ return "/data".concat(uri).replace(/\/($|\?)/, "$1");
1186
+ }
1187
+ }
1188
+ _clientConfig = new WeakMap();
1189
+ const _ObservableSanityClient = class extends BaseSanityClient {
1190
+ constructor(httpRequest, config) {
1191
+ super(config);
1192
+ __privateAdd(this, _httpRequest, void 0);
1193
+ __privateSet(this, _httpRequest, httpRequest);
1194
+ this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest));
1195
+ this.auth = new ObservableAuthClient(this);
1196
+ this.datasets = new ObservableDatasetsClient(this);
1197
+ this.projects = new ObservableProjectsClient(this);
1198
+ this.users = new ObservableUsersClient(this);
1199
+ }
1200
+ clone() {
1201
+ return new _ObservableSanityClient(__privateGet(this, _httpRequest), this.config());
1202
+ }
1203
+ config(newConfig) {
1204
+ return super.config(newConfig);
1205
+ }
1206
+ withConfig(newConfig) {
1207
+ return new _ObservableSanityClient(__privateGet(this, _httpRequest), {
1208
+ ...this.config(),
1209
+ ...newConfig
1210
+ });
1211
+ }
1212
+ fetch(query, params) {
1213
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1214
+ return _fetch(this, __privateGet(this, _httpRequest), query, params, options);
1215
+ }
1216
+ getDocument(id, options) {
1217
+ return _getDocument(this, __privateGet(this, _httpRequest), id, options);
1218
+ }
1219
+ getDocuments(ids, options) {
1220
+ return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
1221
+ }
1222
+ create(document, options) {
1223
+ return _create(this, __privateGet(this, _httpRequest), document, "create", options);
1224
+ }
1225
+ createIfNotExists(document, options) {
1226
+ return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
1227
+ }
1228
+ createOrReplace(document, options) {
1229
+ return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
1230
+ }
1231
+ delete(selection, options) {
1232
+ return _delete(this, __privateGet(this, _httpRequest), selection, options);
1233
+ }
1234
+ mutate(operations, options) {
1235
+ return _mutate(this, __privateGet(this, _httpRequest), operations, options);
1236
+ }
1237
+ patch(documentId, operations) {
1238
+ return new ObservablePatch(documentId, operations, this);
1239
+ }
1240
+ transaction(operations) {
1241
+ return new ObservableTransaction(operations, this);
1242
+ }
1243
+ request(options) {
1244
+ return _request(this, __privateGet(this, _httpRequest), options);
1245
+ }
1246
+ };
1247
+ let ObservableSanityClient = _ObservableSanityClient;
1248
+ _httpRequest = new WeakMap();
1249
+ const _SanityClient = class extends BaseSanityClient {
1250
+ constructor(httpRequest, config) {
1251
+ super(config);
1252
+ __privateAdd(this, _httpRequest2, void 0);
1253
+ this.listen = _listen;
1254
+ __privateSet(this, _httpRequest2, httpRequest);
1255
+ this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2));
1256
+ this.auth = new AuthClient(this);
1257
+ this.datasets = new DatasetsClient(this);
1258
+ this.projects = new ProjectsClient(this);
1259
+ this.users = new UsersClient(this);
1260
+ this.observable = new ObservableSanityClient(httpRequest, this.config());
1261
+ }
1262
+ clone() {
1263
+ return new _SanityClient(__privateGet(this, _httpRequest2), this.config());
1264
+ }
1265
+ config(newConfig) {
1266
+ if (newConfig) {
1267
+ this.observable.config(newConfig);
1268
+ }
1269
+ return super.config(newConfig);
1270
+ }
1271
+ withConfig(newConfig) {
1272
+ return new _SanityClient(__privateGet(this, _httpRequest2), {
1273
+ ...this.config(),
1274
+ ...newConfig
1275
+ });
1276
+ }
1277
+ fetch(query, params) {
1278
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1279
+ return rxjs.lastValueFrom(_fetch(this, __privateGet(this, _httpRequest2), query, params, options));
1280
+ }
1281
+ getDocument(id, options) {
1282
+ return rxjs.lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
1283
+ }
1284
+ getDocuments(ids, options) {
1285
+ return rxjs.lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
1286
+ }
1287
+ create(document, options) {
1288
+ return rxjs.lastValueFrom(_create(this, __privateGet(this, _httpRequest2), document, "create", options));
1289
+ }
1290
+ createIfNotExists(document, options) {
1291
+ return rxjs.lastValueFrom(_createIfNotExists(this, __privateGet(this, _httpRequest2), document, options));
1292
+ }
1293
+ createOrReplace(document, options) {
1294
+ return rxjs.lastValueFrom(_createOrReplace(this, __privateGet(this, _httpRequest2), document, options));
1295
+ }
1296
+ delete(selection, options) {
1297
+ return rxjs.lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
1298
+ }
1299
+ mutate(operations, options) {
1300
+ return rxjs.lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
1301
+ }
1302
+ patch(documentId, operations) {
1303
+ return new Patch(documentId, operations, this);
1304
+ }
1305
+ transaction(operations) {
1306
+ return new Transaction(operations, this);
1307
+ }
1308
+ request(options) {
1309
+ return rxjs.lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
1310
+ }
1311
+ dataRequest(endpoint, body, options) {
1312
+ return rxjs.lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
1313
+ }
1314
+ };
1315
+ let SanityClient = _SanityClient;
1316
+ _httpRequest2 = new WeakMap();
1317
+ const httpRequest = defineHttpRequest(envMiddleware);
1318
+ const requester = httpRequest.defaultRequester;
1319
+ function createClient(config) {
1320
+ return new SanityClient(httpRequest, config);
1321
+ }
1322
+ exports.BasePatch = BasePatch;
1323
+ exports.BaseSanityClient = BaseSanityClient;
1324
+ exports.BaseTransaction = BaseTransaction;
1325
+ exports.ClientError = ClientError;
1326
+ exports.ObservablePatch = ObservablePatch;
1327
+ exports.ObservableSanityClient = ObservableSanityClient;
1328
+ exports.ObservableTransaction = ObservableTransaction;
1329
+ exports.Patch = Patch;
1330
+ exports.SanityClient = SanityClient;
1331
+ exports.ServerError = ServerError;
1332
+ exports.Transaction = Transaction;
1333
+ exports.createClient = createClient;
1334
+ exports.requester = requester;
1335
+ //# sourceMappingURL=index.browser.cjs.map