@sanity/client 0.0.0-dev.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1225 -0
  3. package/dist/index.browser.cjs +1760 -0
  4. package/dist/index.browser.cjs.map +1 -0
  5. package/dist/index.browser.js +1737 -0
  6. package/dist/index.browser.js.map +1 -0
  7. package/dist/index.cjs +1769 -0
  8. package/dist/index.cjs.js +16 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +2234 -0
  11. package/dist/index.js +1746 -0
  12. package/dist/index.js.map +1 -0
  13. package/package.json +127 -0
  14. package/src/SanityClient.ts +1253 -0
  15. package/src/assets/AssetsClient.ts +191 -0
  16. package/src/config.ts +96 -0
  17. package/src/data/dataMethods.ts +416 -0
  18. package/src/data/encodeQueryString.ts +29 -0
  19. package/src/data/listen.ts +196 -0
  20. package/src/data/patch.ts +345 -0
  21. package/src/data/transaction.ts +358 -0
  22. package/src/datasets/DatasetsClient.ts +115 -0
  23. package/src/generateHelpUrl.ts +5 -0
  24. package/src/http/browserMiddleware.ts +1 -0
  25. package/src/http/errors.ts +68 -0
  26. package/src/http/nodeMiddleware.ts +11 -0
  27. package/src/http/request.ts +48 -0
  28. package/src/http/requestOptions.ts +33 -0
  29. package/src/index.browser.ts +28 -0
  30. package/src/index.ts +28 -0
  31. package/src/projects/ProjectsClient.ts +61 -0
  32. package/src/types.ts +575 -0
  33. package/src/users/UsersClient.ts +55 -0
  34. package/src/util/defaults.ts +10 -0
  35. package/src/util/getSelection.ts +21 -0
  36. package/src/util/once.ts +14 -0
  37. package/src/util/pick.ts +11 -0
  38. package/src/validators.ts +78 -0
  39. package/src/warnings.ts +30 -0
  40. package/umd/.gitkeep +1 -0
  41. package/umd/sanityClient.js +4840 -0
  42. package/umd/sanityClient.min.js +14 -0
@@ -0,0 +1,4840 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.SanityClient = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ const isReactNative = typeof navigator === "undefined" ? false : navigator.product === "ReactNative";
8
+ const defaultOptions$1 = {
9
+ timeout: isReactNative ? 6e4 : 12e4
10
+ };
11
+ function processOptions(opts) {
12
+ const options = typeof opts === "string" ? Object.assign({
13
+ url: opts
14
+ }, defaultOptions$1) : Object.assign({}, defaultOptions$1, opts);
15
+ const url = new URL(options.url, "http://localhost");
16
+ options.timeout = normalizeTimeout(options.timeout);
17
+ if (options.query) {
18
+ for (const [key, value] of Object.entries(options.query)) {
19
+ if (value !== void 0) {
20
+ if (Array.isArray(value)) {
21
+ for (const v of value) {
22
+ url.searchParams.append(key, v);
23
+ }
24
+ } else {
25
+ url.searchParams.append(key, value);
26
+ }
27
+ }
28
+ }
29
+ }
30
+ options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase();
31
+ options.url = url.origin === "http://localhost" ? "".concat(url.pathname, "?").concat(url.searchParams) : url.toString();
32
+ return options;
33
+ }
34
+ function normalizeTimeout(time) {
35
+ if (time === false || time === 0) {
36
+ return false;
37
+ }
38
+ if (time.connect || time.socket) {
39
+ return time;
40
+ }
41
+ const delay = Number(time);
42
+ if (isNaN(delay)) {
43
+ return normalizeTimeout(defaultOptions$1.timeout);
44
+ }
45
+ return {
46
+ connect: delay,
47
+ socket: delay
48
+ };
49
+ }
50
+ const validUrl = /^https?:\/\//i;
51
+ function validateOptions(options) {
52
+ if (!validUrl.test(options.url)) {
53
+ throw new Error("\"".concat(options.url, "\" is not a valid URL"));
54
+ }
55
+ }
56
+
57
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
58
+
59
+ var trim = function(string) {
60
+ return string.replace(/^\s+|\s+$/g, '');
61
+ }
62
+ , isArray = function(arg) {
63
+ return Object.prototype.toString.call(arg) === '[object Array]';
64
+ };
65
+
66
+ var parseHeaders = function (headers) {
67
+ if (!headers)
68
+ return {}
69
+
70
+ var result = {};
71
+
72
+ var headersArr = trim(headers).split('\n');
73
+
74
+ for (var i = 0; i < headersArr.length; i++) {
75
+ var row = headersArr[i];
76
+ var index = row.indexOf(':')
77
+ , key = trim(row.slice(0, index)).toLowerCase()
78
+ , value = trim(row.slice(index + 1));
79
+
80
+ if (typeof(result[key]) === 'undefined') {
81
+ result[key] = value;
82
+ } else if (isArray(result[key])) {
83
+ result[key].push(value);
84
+ } else {
85
+ result[key] = [ result[key], value ];
86
+ }
87
+ }
88
+
89
+ return result
90
+ };
91
+
92
+ var middlewareReducer = middleware => {
93
+ const applyMiddleware = function (hook, defaultValue) {
94
+ const bailEarly = hook === "onError";
95
+ let value = defaultValue;
96
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
97
+ args[_key - 2] = arguments[_key];
98
+ }
99
+ for (let i = 0; i < middleware[hook].length; i++) {
100
+ const handler = middleware[hook][i];
101
+ value = handler(value, ...args);
102
+ if (bailEarly && !value) {
103
+ break;
104
+ }
105
+ }
106
+ return value;
107
+ };
108
+ return applyMiddleware;
109
+ };
110
+ function createPubSub() {
111
+ const subscribers = /* @__PURE__ */Object.create(null);
112
+ let nextId = 0;
113
+ function subscribe(subscriber) {
114
+ const id = nextId++;
115
+ subscribers[id] = subscriber;
116
+ return function unsubscribe() {
117
+ delete subscribers[id];
118
+ };
119
+ }
120
+ function publish(event) {
121
+ for (const id in subscribers) {
122
+ subscribers[id](event);
123
+ }
124
+ }
125
+ return {
126
+ publish,
127
+ subscribe
128
+ };
129
+ }
130
+ const channelNames = ["request", "response", "progress", "error", "abort"];
131
+ const middlehooks = ["processOptions", "validateOptions", "interceptRequest", "finalizeOptions", "onRequest", "onResponse", "onError", "onReturn", "onHeaders"];
132
+ function createRequester(initMiddleware, httpRequest) {
133
+ const loadedMiddleware = [];
134
+ const middleware = middlehooks.reduce((ware, name) => {
135
+ ware[name] = ware[name] || [];
136
+ return ware;
137
+ }, {
138
+ processOptions: [processOptions],
139
+ validateOptions: [validateOptions]
140
+ });
141
+ function request(opts) {
142
+ const channels = channelNames.reduce((target, name) => {
143
+ target[name] = createPubSub();
144
+ return target;
145
+ }, {});
146
+ const applyMiddleware = middlewareReducer(middleware);
147
+ const options = applyMiddleware("processOptions", opts);
148
+ applyMiddleware("validateOptions", options);
149
+ const context = {
150
+ options,
151
+ channels,
152
+ applyMiddleware
153
+ };
154
+ let ongoingRequest = null;
155
+ const unsubscribe = channels.request.subscribe(ctx => {
156
+ ongoingRequest = httpRequest(ctx, (err, res) => onResponse(err, res, ctx));
157
+ });
158
+ channels.abort.subscribe(() => {
159
+ unsubscribe();
160
+ if (ongoingRequest) {
161
+ ongoingRequest.abort();
162
+ }
163
+ });
164
+ const returnValue = applyMiddleware("onReturn", channels, context);
165
+ if (returnValue === channels) {
166
+ channels.request.publish(context);
167
+ }
168
+ return returnValue;
169
+ function onResponse(reqErr, res, ctx) {
170
+ let error = reqErr;
171
+ let response = res;
172
+ if (!error) {
173
+ try {
174
+ response = applyMiddleware("onResponse", res, ctx);
175
+ } catch (err) {
176
+ response = null;
177
+ error = err;
178
+ }
179
+ }
180
+ error = error && applyMiddleware("onError", error, ctx);
181
+ if (error) {
182
+ channels.error.publish(error);
183
+ } else if (response) {
184
+ channels.response.publish(response);
185
+ }
186
+ }
187
+ }
188
+ request.use = function use(newMiddleware) {
189
+ if (!newMiddleware) {
190
+ throw new Error("Tried to add middleware that resolved to falsey value");
191
+ }
192
+ if (typeof newMiddleware === "function") {
193
+ throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");
194
+ }
195
+ if (newMiddleware.onReturn && middleware.onReturn.length > 0) {
196
+ throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");
197
+ }
198
+ middlehooks.forEach(key => {
199
+ if (newMiddleware[key]) {
200
+ middleware[key].push(newMiddleware[key]);
201
+ }
202
+ });
203
+ loadedMiddleware.push(newMiddleware);
204
+ return request;
205
+ };
206
+ request.clone = function clone() {
207
+ return createRequester(loadedMiddleware, httpRequest);
208
+ };
209
+ initMiddleware.forEach(request.use);
210
+ return request;
211
+ }
212
+ var __accessCheck$7 = (obj, member, msg) => {
213
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
214
+ };
215
+ var __privateGet$7 = (obj, member, getter) => {
216
+ __accessCheck$7(obj, member, "read from private field");
217
+ return getter ? getter.call(obj) : member.get(obj);
218
+ };
219
+ var __privateAdd$7 = (obj, member, value) => {
220
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
221
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
222
+ };
223
+ var __privateSet$7 = (obj, member, value, setter) => {
224
+ __accessCheck$7(obj, member, "write to private field");
225
+ setter ? setter.call(obj, value) : member.set(obj, value);
226
+ return value;
227
+ };
228
+ var _method, _url, _resHeaders, _headers, _controller;
229
+ class FetchXhr {
230
+ constructor() {
231
+ /**
232
+ * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
233
+ */
234
+ this.readyState = 0;
235
+ /**
236
+ * Private implementation details
237
+ */
238
+ __privateAdd$7(this, _method, void 0);
239
+ __privateAdd$7(this, _url, void 0);
240
+ __privateAdd$7(this, _resHeaders, void 0);
241
+ __privateAdd$7(this, _headers, {});
242
+ __privateAdd$7(this, _controller, void 0);
243
+ }
244
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- _async is only declared for typings compatibility
245
+ open(method, url, _async) {
246
+ __privateSet$7(this, _method, method);
247
+ __privateSet$7(this, _url, url);
248
+ __privateSet$7(this, _resHeaders, "");
249
+ this.readyState = 1;
250
+ this.onreadystatechange();
251
+ __privateSet$7(this, _controller, void 0);
252
+ }
253
+ abort() {
254
+ if (__privateGet$7(this, _controller)) {
255
+ __privateGet$7(this, _controller).abort();
256
+ }
257
+ }
258
+ getAllResponseHeaders() {
259
+ return __privateGet$7(this, _resHeaders);
260
+ }
261
+ setRequestHeader(name, value) {
262
+ __privateGet$7(this, _headers)[name] = value;
263
+ }
264
+ send(body) {
265
+ const textBody = this.responseType !== "arraybuffer";
266
+ const options = {
267
+ method: __privateGet$7(this, _method),
268
+ headers: __privateGet$7(this, _headers),
269
+ signal: null,
270
+ body
271
+ };
272
+ if (typeof AbortController === "function") {
273
+ __privateSet$7(this, _controller, new AbortController());
274
+ options.signal = __privateGet$7(this, _controller).signal;
275
+ }
276
+ if (typeof document !== "undefined") {
277
+ options.credentials = this.withCredentials ? "include" : "omit";
278
+ }
279
+ fetch(__privateGet$7(this, _url), options).then(res => {
280
+ res.headers.forEach((value, key) => {
281
+ __privateSet$7(this, _resHeaders, __privateGet$7(this, _resHeaders) + "".concat(key, ": ").concat(value, "\r\n"));
282
+ });
283
+ this.status = res.status;
284
+ this.statusText = res.statusText;
285
+ this.readyState = 3;
286
+ return textBody ? res.text() : res.arrayBuffer();
287
+ }).then(resBody => {
288
+ if (typeof resBody === "string") {
289
+ this.responseText = resBody;
290
+ } else {
291
+ this.response = resBody;
292
+ }
293
+ this.readyState = 4;
294
+ this.onreadystatechange();
295
+ }).catch(err => {
296
+ var _a;
297
+ if (err.name === "AbortError") {
298
+ this.onabort();
299
+ return;
300
+ }
301
+ (_a = this.onerror) == null ? void 0 : _a.call(this, err);
302
+ });
303
+ }
304
+ }
305
+ _method = new WeakMap();
306
+ _url = new WeakMap();
307
+ _resHeaders = new WeakMap();
308
+ _headers = new WeakMap();
309
+ _controller = new WeakMap();
310
+ const adapter = typeof XMLHttpRequest === "function" ? "xhr" : "fetch";
311
+ const XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr;
312
+ var httpRequester = (context, callback) => {
313
+ const opts = context.options;
314
+ const options = context.applyMiddleware("finalizeOptions", opts);
315
+ const timers = {};
316
+ const injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
317
+ adapter,
318
+ context
319
+ });
320
+ if (injectedResponse) {
321
+ const cbTimer = setTimeout(callback, 0, null, injectedResponse);
322
+ const cancel = () => clearTimeout(cbTimer);
323
+ return {
324
+ abort: cancel
325
+ };
326
+ }
327
+ let xhr = new XmlHttpRequest();
328
+ const headers = options.headers;
329
+ const delays = options.timeout;
330
+ let aborted = false;
331
+ let loaded = false;
332
+ let timedOut = false;
333
+ xhr.onerror = onError;
334
+ xhr.ontimeout = onError;
335
+ xhr.onabort = () => {
336
+ stopTimers(true);
337
+ aborted = true;
338
+ };
339
+ xhr.onreadystatechange = () => {
340
+ resetTimers();
341
+ if (aborted || xhr.readyState !== 4) {
342
+ return;
343
+ }
344
+ if (xhr.status === 0) {
345
+ return;
346
+ }
347
+ onLoad();
348
+ };
349
+ xhr.open(options.method, options.url, true
350
+ // Always async
351
+ );
352
+
353
+ xhr.withCredentials = !!options.withCredentials;
354
+ if (headers && xhr.setRequestHeader) {
355
+ for (const key in headers) {
356
+ if (headers.hasOwnProperty(key)) {
357
+ xhr.setRequestHeader(key, headers[key]);
358
+ }
359
+ }
360
+ }
361
+ if (options.rawBody) {
362
+ xhr.responseType = "arraybuffer";
363
+ }
364
+ context.applyMiddleware("onRequest", {
365
+ options,
366
+ adapter,
367
+ request: xhr,
368
+ context
369
+ });
370
+ xhr.send(options.body || null);
371
+ if (delays) {
372
+ timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect);
373
+ }
374
+ return {
375
+ abort
376
+ };
377
+ function abort() {
378
+ aborted = true;
379
+ if (xhr) {
380
+ xhr.abort();
381
+ }
382
+ }
383
+ function timeoutRequest(code) {
384
+ timedOut = true;
385
+ xhr.abort();
386
+ const error = new Error(code === "ESOCKETTIMEDOUT" ? "Socket timed out on request to ".concat(options.url) : "Connection timed out on request to ".concat(options.url));
387
+ error.code = code;
388
+ context.channels.error.publish(error);
389
+ }
390
+ function resetTimers() {
391
+ if (!delays) {
392
+ return;
393
+ }
394
+ stopTimers();
395
+ timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket);
396
+ }
397
+ function stopTimers(force) {
398
+ if (force || aborted || xhr.readyState >= 2 && timers.connect) {
399
+ clearTimeout(timers.connect);
400
+ }
401
+ if (timers.socket) {
402
+ clearTimeout(timers.socket);
403
+ }
404
+ }
405
+ function onError(error) {
406
+ if (loaded) {
407
+ return;
408
+ }
409
+ stopTimers(true);
410
+ loaded = true;
411
+ xhr = null;
412
+ const err = error || new Error("Network error while attempting to reach ".concat(options.url));
413
+ err.isNetworkError = true;
414
+ err.request = options;
415
+ callback(err);
416
+ }
417
+ function reduceResponse() {
418
+ return {
419
+ body: xhr.response || xhr.responseText,
420
+ url: options.url,
421
+ method: options.method,
422
+ headers: parseHeaders(xhr.getAllResponseHeaders()),
423
+ statusCode: xhr.status,
424
+ statusMessage: xhr.statusText
425
+ };
426
+ }
427
+ function onLoad() {
428
+ if (aborted || loaded || timedOut) {
429
+ return;
430
+ }
431
+ if (xhr.status === 0) {
432
+ onError(new Error("Unknown XHR error"));
433
+ return;
434
+ }
435
+ stopTimers();
436
+ loaded = true;
437
+ callback(null, reduceResponse());
438
+ }
439
+ };
440
+ const getIt = function () {
441
+ let initMiddleware = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
442
+ let httpRequest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : httpRequester;
443
+ return createRequester(initMiddleware, httpRequest);
444
+ };
445
+
446
+ var browserExports = {};
447
+ var browser$1 = {
448
+ get exports(){ return browserExports; },
449
+ set exports(v){ browserExports = v; },
450
+ };
451
+
452
+ /**
453
+ * Helpers.
454
+ */
455
+
456
+ var ms;
457
+ var hasRequiredMs;
458
+
459
+ function requireMs () {
460
+ if (hasRequiredMs) return ms;
461
+ hasRequiredMs = 1;
462
+ var s = 1000;
463
+ var m = s * 60;
464
+ var h = m * 60;
465
+ var d = h * 24;
466
+ var w = d * 7;
467
+ var y = d * 365.25;
468
+
469
+ /**
470
+ * Parse or format the given `val`.
471
+ *
472
+ * Options:
473
+ *
474
+ * - `long` verbose formatting [false]
475
+ *
476
+ * @param {String|Number} val
477
+ * @param {Object} [options]
478
+ * @throws {Error} throw an error if val is not a non-empty string or a number
479
+ * @return {String|Number}
480
+ * @api public
481
+ */
482
+
483
+ ms = function(val, options) {
484
+ options = options || {};
485
+ var type = typeof val;
486
+ if (type === 'string' && val.length > 0) {
487
+ return parse(val);
488
+ } else if (type === 'number' && isFinite(val)) {
489
+ return options.long ? fmtLong(val) : fmtShort(val);
490
+ }
491
+ throw new Error(
492
+ 'val is not a non-empty string or a valid number. val=' +
493
+ JSON.stringify(val)
494
+ );
495
+ };
496
+
497
+ /**
498
+ * Parse the given `str` and return milliseconds.
499
+ *
500
+ * @param {String} str
501
+ * @return {Number}
502
+ * @api private
503
+ */
504
+
505
+ function parse(str) {
506
+ str = String(str);
507
+ if (str.length > 100) {
508
+ return;
509
+ }
510
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
511
+ str
512
+ );
513
+ if (!match) {
514
+ return;
515
+ }
516
+ var n = parseFloat(match[1]);
517
+ var type = (match[2] || 'ms').toLowerCase();
518
+ switch (type) {
519
+ case 'years':
520
+ case 'year':
521
+ case 'yrs':
522
+ case 'yr':
523
+ case 'y':
524
+ return n * y;
525
+ case 'weeks':
526
+ case 'week':
527
+ case 'w':
528
+ return n * w;
529
+ case 'days':
530
+ case 'day':
531
+ case 'd':
532
+ return n * d;
533
+ case 'hours':
534
+ case 'hour':
535
+ case 'hrs':
536
+ case 'hr':
537
+ case 'h':
538
+ return n * h;
539
+ case 'minutes':
540
+ case 'minute':
541
+ case 'mins':
542
+ case 'min':
543
+ case 'm':
544
+ return n * m;
545
+ case 'seconds':
546
+ case 'second':
547
+ case 'secs':
548
+ case 'sec':
549
+ case 's':
550
+ return n * s;
551
+ case 'milliseconds':
552
+ case 'millisecond':
553
+ case 'msecs':
554
+ case 'msec':
555
+ case 'ms':
556
+ return n;
557
+ default:
558
+ return undefined;
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Short format for `ms`.
564
+ *
565
+ * @param {Number} ms
566
+ * @return {String}
567
+ * @api private
568
+ */
569
+
570
+ function fmtShort(ms) {
571
+ var msAbs = Math.abs(ms);
572
+ if (msAbs >= d) {
573
+ return Math.round(ms / d) + 'd';
574
+ }
575
+ if (msAbs >= h) {
576
+ return Math.round(ms / h) + 'h';
577
+ }
578
+ if (msAbs >= m) {
579
+ return Math.round(ms / m) + 'm';
580
+ }
581
+ if (msAbs >= s) {
582
+ return Math.round(ms / s) + 's';
583
+ }
584
+ return ms + 'ms';
585
+ }
586
+
587
+ /**
588
+ * Long format for `ms`.
589
+ *
590
+ * @param {Number} ms
591
+ * @return {String}
592
+ * @api private
593
+ */
594
+
595
+ function fmtLong(ms) {
596
+ var msAbs = Math.abs(ms);
597
+ if (msAbs >= d) {
598
+ return plural(ms, msAbs, d, 'day');
599
+ }
600
+ if (msAbs >= h) {
601
+ return plural(ms, msAbs, h, 'hour');
602
+ }
603
+ if (msAbs >= m) {
604
+ return plural(ms, msAbs, m, 'minute');
605
+ }
606
+ if (msAbs >= s) {
607
+ return plural(ms, msAbs, s, 'second');
608
+ }
609
+ return ms + ' ms';
610
+ }
611
+
612
+ /**
613
+ * Pluralization helper.
614
+ */
615
+
616
+ function plural(ms, msAbs, n, name) {
617
+ var isPlural = msAbs >= n * 1.5;
618
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
619
+ }
620
+ return ms;
621
+ }
622
+
623
+ /**
624
+ * This is the common logic for both the Node.js and web browser
625
+ * implementations of `debug()`.
626
+ */
627
+
628
+ function setup(env) {
629
+ createDebug.debug = createDebug;
630
+ createDebug.default = createDebug;
631
+ createDebug.coerce = coerce;
632
+ createDebug.disable = disable;
633
+ createDebug.enable = enable;
634
+ createDebug.enabled = enabled;
635
+ createDebug.humanize = requireMs();
636
+ createDebug.destroy = destroy;
637
+
638
+ Object.keys(env).forEach(key => {
639
+ createDebug[key] = env[key];
640
+ });
641
+
642
+ /**
643
+ * The currently active debug mode names, and names to skip.
644
+ */
645
+
646
+ createDebug.names = [];
647
+ createDebug.skips = [];
648
+
649
+ /**
650
+ * Map of special "%n" handling functions, for the debug "format" argument.
651
+ *
652
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
653
+ */
654
+ createDebug.formatters = {};
655
+
656
+ /**
657
+ * Selects a color for a debug namespace
658
+ * @param {String} namespace The namespace string for the debug instance to be colored
659
+ * @return {Number|String} An ANSI color code for the given namespace
660
+ * @api private
661
+ */
662
+ function selectColor(namespace) {
663
+ let hash = 0;
664
+
665
+ for (let i = 0; i < namespace.length; i++) {
666
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
667
+ hash |= 0; // Convert to 32bit integer
668
+ }
669
+
670
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
671
+ }
672
+ createDebug.selectColor = selectColor;
673
+
674
+ /**
675
+ * Create a debugger with the given `namespace`.
676
+ *
677
+ * @param {String} namespace
678
+ * @return {Function}
679
+ * @api public
680
+ */
681
+ function createDebug(namespace) {
682
+ let prevTime;
683
+ let enableOverride = null;
684
+ let namespacesCache;
685
+ let enabledCache;
686
+
687
+ function debug(...args) {
688
+ // Disabled?
689
+ if (!debug.enabled) {
690
+ return;
691
+ }
692
+
693
+ const self = debug;
694
+
695
+ // Set `diff` timestamp
696
+ const curr = Number(new Date());
697
+ const ms = curr - (prevTime || curr);
698
+ self.diff = ms;
699
+ self.prev = prevTime;
700
+ self.curr = curr;
701
+ prevTime = curr;
702
+
703
+ args[0] = createDebug.coerce(args[0]);
704
+
705
+ if (typeof args[0] !== 'string') {
706
+ // Anything else let's inspect with %O
707
+ args.unshift('%O');
708
+ }
709
+
710
+ // Apply any `formatters` transformations
711
+ let index = 0;
712
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
713
+ // If we encounter an escaped % then don't increase the array index
714
+ if (match === '%%') {
715
+ return '%';
716
+ }
717
+ index++;
718
+ const formatter = createDebug.formatters[format];
719
+ if (typeof formatter === 'function') {
720
+ const val = args[index];
721
+ match = formatter.call(self, val);
722
+
723
+ // Now we need to remove `args[index]` since it's inlined in the `format`
724
+ args.splice(index, 1);
725
+ index--;
726
+ }
727
+ return match;
728
+ });
729
+
730
+ // Apply env-specific formatting (colors, etc.)
731
+ createDebug.formatArgs.call(self, args);
732
+
733
+ const logFn = self.log || createDebug.log;
734
+ logFn.apply(self, args);
735
+ }
736
+
737
+ debug.namespace = namespace;
738
+ debug.useColors = createDebug.useColors();
739
+ debug.color = createDebug.selectColor(namespace);
740
+ debug.extend = extend;
741
+ debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
742
+
743
+ Object.defineProperty(debug, 'enabled', {
744
+ enumerable: true,
745
+ configurable: false,
746
+ get: () => {
747
+ if (enableOverride !== null) {
748
+ return enableOverride;
749
+ }
750
+ if (namespacesCache !== createDebug.namespaces) {
751
+ namespacesCache = createDebug.namespaces;
752
+ enabledCache = createDebug.enabled(namespace);
753
+ }
754
+
755
+ return enabledCache;
756
+ },
757
+ set: v => {
758
+ enableOverride = v;
759
+ }
760
+ });
761
+
762
+ // Env-specific initialization logic for debug instances
763
+ if (typeof createDebug.init === 'function') {
764
+ createDebug.init(debug);
765
+ }
766
+
767
+ return debug;
768
+ }
769
+
770
+ function extend(namespace, delimiter) {
771
+ const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
772
+ newDebug.log = this.log;
773
+ return newDebug;
774
+ }
775
+
776
+ /**
777
+ * Enables a debug mode by namespaces. This can include modes
778
+ * separated by a colon and wildcards.
779
+ *
780
+ * @param {String} namespaces
781
+ * @api public
782
+ */
783
+ function enable(namespaces) {
784
+ createDebug.save(namespaces);
785
+ createDebug.namespaces = namespaces;
786
+
787
+ createDebug.names = [];
788
+ createDebug.skips = [];
789
+
790
+ let i;
791
+ const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
792
+ const len = split.length;
793
+
794
+ for (i = 0; i < len; i++) {
795
+ if (!split[i]) {
796
+ // ignore empty strings
797
+ continue;
798
+ }
799
+
800
+ namespaces = split[i].replace(/\*/g, '.*?');
801
+
802
+ if (namespaces[0] === '-') {
803
+ createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
804
+ } else {
805
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
806
+ }
807
+ }
808
+ }
809
+
810
+ /**
811
+ * Disable debug output.
812
+ *
813
+ * @return {String} namespaces
814
+ * @api public
815
+ */
816
+ function disable() {
817
+ const namespaces = [
818
+ ...createDebug.names.map(toNamespace),
819
+ ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
820
+ ].join(',');
821
+ createDebug.enable('');
822
+ return namespaces;
823
+ }
824
+
825
+ /**
826
+ * Returns true if the given mode name is enabled, false otherwise.
827
+ *
828
+ * @param {String} name
829
+ * @return {Boolean}
830
+ * @api public
831
+ */
832
+ function enabled(name) {
833
+ if (name[name.length - 1] === '*') {
834
+ return true;
835
+ }
836
+
837
+ let i;
838
+ let len;
839
+
840
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
841
+ if (createDebug.skips[i].test(name)) {
842
+ return false;
843
+ }
844
+ }
845
+
846
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
847
+ if (createDebug.names[i].test(name)) {
848
+ return true;
849
+ }
850
+ }
851
+
852
+ return false;
853
+ }
854
+
855
+ /**
856
+ * Convert regexp to namespace
857
+ *
858
+ * @param {RegExp} regxep
859
+ * @return {String} namespace
860
+ * @api private
861
+ */
862
+ function toNamespace(regexp) {
863
+ return regexp.toString()
864
+ .substring(2, regexp.toString().length - 2)
865
+ .replace(/\.\*\?$/, '*');
866
+ }
867
+
868
+ /**
869
+ * Coerce `val`.
870
+ *
871
+ * @param {Mixed} val
872
+ * @return {Mixed}
873
+ * @api private
874
+ */
875
+ function coerce(val) {
876
+ if (val instanceof Error) {
877
+ return val.stack || val.message;
878
+ }
879
+ return val;
880
+ }
881
+
882
+ /**
883
+ * XXX DO NOT USE. This is a temporary stub function.
884
+ * XXX It WILL be removed in the next major release.
885
+ */
886
+ function destroy() {
887
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
888
+ }
889
+
890
+ createDebug.enable(createDebug.load());
891
+
892
+ return createDebug;
893
+ }
894
+
895
+ var common = setup;
896
+
897
+ /* eslint-env browser */
898
+
899
+ (function (module, exports) {
900
+ /**
901
+ * This is the web browser implementation of `debug()`.
902
+ */
903
+
904
+ exports.formatArgs = formatArgs;
905
+ exports.save = save;
906
+ exports.load = load;
907
+ exports.useColors = useColors;
908
+ exports.storage = localstorage();
909
+ exports.destroy = (() => {
910
+ let warned = false;
911
+
912
+ return () => {
913
+ if (!warned) {
914
+ warned = true;
915
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
916
+ }
917
+ };
918
+ })();
919
+
920
+ /**
921
+ * Colors.
922
+ */
923
+
924
+ exports.colors = [
925
+ '#0000CC',
926
+ '#0000FF',
927
+ '#0033CC',
928
+ '#0033FF',
929
+ '#0066CC',
930
+ '#0066FF',
931
+ '#0099CC',
932
+ '#0099FF',
933
+ '#00CC00',
934
+ '#00CC33',
935
+ '#00CC66',
936
+ '#00CC99',
937
+ '#00CCCC',
938
+ '#00CCFF',
939
+ '#3300CC',
940
+ '#3300FF',
941
+ '#3333CC',
942
+ '#3333FF',
943
+ '#3366CC',
944
+ '#3366FF',
945
+ '#3399CC',
946
+ '#3399FF',
947
+ '#33CC00',
948
+ '#33CC33',
949
+ '#33CC66',
950
+ '#33CC99',
951
+ '#33CCCC',
952
+ '#33CCFF',
953
+ '#6600CC',
954
+ '#6600FF',
955
+ '#6633CC',
956
+ '#6633FF',
957
+ '#66CC00',
958
+ '#66CC33',
959
+ '#9900CC',
960
+ '#9900FF',
961
+ '#9933CC',
962
+ '#9933FF',
963
+ '#99CC00',
964
+ '#99CC33',
965
+ '#CC0000',
966
+ '#CC0033',
967
+ '#CC0066',
968
+ '#CC0099',
969
+ '#CC00CC',
970
+ '#CC00FF',
971
+ '#CC3300',
972
+ '#CC3333',
973
+ '#CC3366',
974
+ '#CC3399',
975
+ '#CC33CC',
976
+ '#CC33FF',
977
+ '#CC6600',
978
+ '#CC6633',
979
+ '#CC9900',
980
+ '#CC9933',
981
+ '#CCCC00',
982
+ '#CCCC33',
983
+ '#FF0000',
984
+ '#FF0033',
985
+ '#FF0066',
986
+ '#FF0099',
987
+ '#FF00CC',
988
+ '#FF00FF',
989
+ '#FF3300',
990
+ '#FF3333',
991
+ '#FF3366',
992
+ '#FF3399',
993
+ '#FF33CC',
994
+ '#FF33FF',
995
+ '#FF6600',
996
+ '#FF6633',
997
+ '#FF9900',
998
+ '#FF9933',
999
+ '#FFCC00',
1000
+ '#FFCC33'
1001
+ ];
1002
+
1003
+ /**
1004
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
1005
+ * and the Firebug extension (any Firefox version) are known
1006
+ * to support "%c" CSS customizations.
1007
+ *
1008
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
1009
+ */
1010
+
1011
+ // eslint-disable-next-line complexity
1012
+ function useColors() {
1013
+ // NB: In an Electron preload script, document will be defined but not fully
1014
+ // initialized. Since we know we're in Chrome, we'll just detect this case
1015
+ // explicitly
1016
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
1017
+ return true;
1018
+ }
1019
+
1020
+ // Internet Explorer and Edge do not support colors.
1021
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
1022
+ return false;
1023
+ }
1024
+
1025
+ // Is webkit? http://stackoverflow.com/a/16459606/376773
1026
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
1027
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
1028
+ // Is firebug? http://stackoverflow.com/a/398120/376773
1029
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
1030
+ // Is firefox >= v31?
1031
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
1032
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
1033
+ // Double check webkit in userAgent just in case we are in a worker
1034
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
1035
+ }
1036
+
1037
+ /**
1038
+ * Colorize log arguments if enabled.
1039
+ *
1040
+ * @api public
1041
+ */
1042
+
1043
+ function formatArgs(args) {
1044
+ args[0] = (this.useColors ? '%c' : '') +
1045
+ this.namespace +
1046
+ (this.useColors ? ' %c' : ' ') +
1047
+ args[0] +
1048
+ (this.useColors ? '%c ' : ' ') +
1049
+ '+' + module.exports.humanize(this.diff);
1050
+
1051
+ if (!this.useColors) {
1052
+ return;
1053
+ }
1054
+
1055
+ const c = 'color: ' + this.color;
1056
+ args.splice(1, 0, c, 'color: inherit');
1057
+
1058
+ // The final "%c" is somewhat tricky, because there could be other
1059
+ // arguments passed either before or after the %c, so we need to
1060
+ // figure out the correct index to insert the CSS into
1061
+ let index = 0;
1062
+ let lastC = 0;
1063
+ args[0].replace(/%[a-zA-Z%]/g, match => {
1064
+ if (match === '%%') {
1065
+ return;
1066
+ }
1067
+ index++;
1068
+ if (match === '%c') {
1069
+ // We only are interested in the *last* %c
1070
+ // (the user may have provided their own)
1071
+ lastC = index;
1072
+ }
1073
+ });
1074
+
1075
+ args.splice(lastC, 0, c);
1076
+ }
1077
+
1078
+ /**
1079
+ * Invokes `console.debug()` when available.
1080
+ * No-op when `console.debug` is not a "function".
1081
+ * If `console.debug` is not available, falls back
1082
+ * to `console.log`.
1083
+ *
1084
+ * @api public
1085
+ */
1086
+ exports.log = console.debug || console.log || (() => {});
1087
+
1088
+ /**
1089
+ * Save `namespaces`.
1090
+ *
1091
+ * @param {String} namespaces
1092
+ * @api private
1093
+ */
1094
+ function save(namespaces) {
1095
+ try {
1096
+ if (namespaces) {
1097
+ exports.storage.setItem('debug', namespaces);
1098
+ } else {
1099
+ exports.storage.removeItem('debug');
1100
+ }
1101
+ } catch (error) {
1102
+ // Swallow
1103
+ // XXX (@Qix-) should we be logging these?
1104
+ }
1105
+ }
1106
+
1107
+ /**
1108
+ * Load `namespaces`.
1109
+ *
1110
+ * @return {String} returns the previously persisted debug modes
1111
+ * @api private
1112
+ */
1113
+ function load() {
1114
+ let r;
1115
+ try {
1116
+ r = exports.storage.getItem('debug');
1117
+ } catch (error) {
1118
+ // Swallow
1119
+ // XXX (@Qix-) should we be logging these?
1120
+ }
1121
+
1122
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
1123
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
1124
+ r = process.env.DEBUG;
1125
+ }
1126
+
1127
+ return r;
1128
+ }
1129
+
1130
+ /**
1131
+ * Localstorage attempts to return the localstorage.
1132
+ *
1133
+ * This is necessary because safari throws
1134
+ * when a user disables cookies/localstorage
1135
+ * and you attempt to access it.
1136
+ *
1137
+ * @return {LocalStorage}
1138
+ * @api private
1139
+ */
1140
+
1141
+ function localstorage() {
1142
+ try {
1143
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
1144
+ // The Browser also has localStorage in the global context.
1145
+ return localStorage;
1146
+ } catch (error) {
1147
+ // Swallow
1148
+ // XXX (@Qix-) should we be logging these?
1149
+ }
1150
+ }
1151
+
1152
+ module.exports = common(exports);
1153
+
1154
+ const {formatters} = module.exports;
1155
+
1156
+ /**
1157
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
1158
+ */
1159
+
1160
+ formatters.j = function (v) {
1161
+ try {
1162
+ return JSON.stringify(v);
1163
+ } catch (error) {
1164
+ return '[UnexpectedJSONParseError]: ' + error.message;
1165
+ }
1166
+ };
1167
+ } (browser$1, browserExports));
1168
+
1169
+ /*!
1170
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
1171
+ *
1172
+ * Copyright (c) 2014-2017, Jon Schlinkert.
1173
+ * Released under the MIT License.
1174
+ */
1175
+
1176
+ function isObject(o) {
1177
+ return Object.prototype.toString.call(o) === '[object Object]';
1178
+ }
1179
+
1180
+ function isPlainObject(o) {
1181
+ var ctor,prot;
1182
+
1183
+ if (isObject(o) === false) return false;
1184
+
1185
+ // If has modified constructor
1186
+ ctor = o.constructor;
1187
+ if (ctor === undefined) return true;
1188
+
1189
+ // If has modified prototype
1190
+ prot = ctor.prototype;
1191
+ if (isObject(prot) === false) return false;
1192
+
1193
+ // If constructor does not have an Object-specific method
1194
+ if (prot.hasOwnProperty('isPrototypeOf') === false) {
1195
+ return false;
1196
+ }
1197
+
1198
+ // Most likely a plain Object
1199
+ return true;
1200
+ }
1201
+
1202
+ const isBuffer = typeof Buffer === "undefined" ? () => false : obj => Buffer.isBuffer(obj);
1203
+ const serializeTypes = ["boolean", "string", "number"];
1204
+ function jsonRequest() {
1205
+ return {
1206
+ processOptions: options => {
1207
+ const body = options.body;
1208
+ if (!body) {
1209
+ return options;
1210
+ }
1211
+ const isStream = typeof body.pipe === "function";
1212
+ const shouldSerialize = !isStream && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject(body));
1213
+ if (!shouldSerialize) {
1214
+ return options;
1215
+ }
1216
+ return Object.assign({}, options, {
1217
+ body: JSON.stringify(options.body),
1218
+ headers: Object.assign({}, options.headers, {
1219
+ "Content-Type": "application/json"
1220
+ })
1221
+ });
1222
+ }
1223
+ };
1224
+ }
1225
+ function jsonResponse(opts) {
1226
+ return {
1227
+ onResponse: response => {
1228
+ const contentType = response.headers["content-type"] || "";
1229
+ const shouldDecode = opts && opts.force || contentType.indexOf("application/json") !== -1;
1230
+ if (!response.body || !contentType || !shouldDecode) {
1231
+ return response;
1232
+ }
1233
+ return Object.assign({}, response, {
1234
+ body: tryParse(response.body)
1235
+ });
1236
+ },
1237
+ processOptions: options => Object.assign({}, options, {
1238
+ headers: Object.assign({
1239
+ Accept: "application/json"
1240
+ }, options.headers)
1241
+ })
1242
+ };
1243
+ function tryParse(body) {
1244
+ try {
1245
+ return JSON.parse(body);
1246
+ } catch (err) {
1247
+ err.message = "Failed to parsed response body as JSON: ".concat(err.message);
1248
+ throw err;
1249
+ }
1250
+ }
1251
+ }
1252
+ let actualGlobal;
1253
+ if (typeof globalThis !== "undefined") {
1254
+ actualGlobal = globalThis;
1255
+ } else if (typeof window !== "undefined") {
1256
+ actualGlobal = window;
1257
+ } else if (typeof global !== "undefined") {
1258
+ actualGlobal = global;
1259
+ } else if (typeof self !== "undefined") {
1260
+ actualGlobal = self;
1261
+ } else {
1262
+ actualGlobal = {};
1263
+ }
1264
+ var global$1 = actualGlobal;
1265
+ function observable$1() {
1266
+ let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1267
+ const Observable = opts.implementation || global$1.Observable;
1268
+ if (!Observable) {
1269
+ throw new Error("`Observable` is not available in global scope, and no implementation was passed");
1270
+ }
1271
+ return {
1272
+ onReturn: (channels, context) => new Observable(observer => {
1273
+ channels.error.subscribe(err => observer.error(err));
1274
+ channels.progress.subscribe(event => observer.next(Object.assign({
1275
+ type: "progress"
1276
+ }, event)));
1277
+ channels.response.subscribe(response => {
1278
+ observer.next(Object.assign({
1279
+ type: "response"
1280
+ }, response));
1281
+ observer.complete();
1282
+ });
1283
+ channels.request.publish(context);
1284
+ return () => channels.abort.publish();
1285
+ })
1286
+ };
1287
+ }
1288
+ function progress() {
1289
+ return {
1290
+ onRequest: evt => {
1291
+ if (evt.adapter !== "xhr") {
1292
+ return;
1293
+ }
1294
+ const xhr = evt.request;
1295
+ const context = evt.context;
1296
+ if ("upload" in xhr && "onprogress" in xhr.upload) {
1297
+ xhr.upload.onprogress = handleProgress("upload");
1298
+ }
1299
+ if ("onprogress" in xhr) {
1300
+ xhr.onprogress = handleProgress("download");
1301
+ }
1302
+ function handleProgress(stage) {
1303
+ return event => {
1304
+ const percent = event.lengthComputable ? event.loaded / event.total * 100 : -1;
1305
+ context.channels.progress.publish({
1306
+ stage,
1307
+ percent,
1308
+ total: event.total,
1309
+ loaded: event.loaded,
1310
+ lengthComputable: event.lengthComputable
1311
+ });
1312
+ };
1313
+ }
1314
+ }
1315
+ };
1316
+ }
1317
+ class Cancel {
1318
+ constructor(message) {
1319
+ this.__CANCEL__ = true;
1320
+ this.message = message;
1321
+ }
1322
+ toString() {
1323
+ return "Cancel".concat(this.message ? ": ".concat(this.message) : "");
1324
+ }
1325
+ }
1326
+ const _CancelToken = class {
1327
+ constructor(executor) {
1328
+ if (typeof executor !== "function") {
1329
+ throw new TypeError("executor must be a function.");
1330
+ }
1331
+ let resolvePromise = null;
1332
+ this.promise = new Promise(resolve => {
1333
+ resolvePromise = resolve;
1334
+ });
1335
+ executor(message => {
1336
+ if (this.reason) {
1337
+ return;
1338
+ }
1339
+ this.reason = new Cancel(message);
1340
+ resolvePromise(this.reason);
1341
+ });
1342
+ }
1343
+ };
1344
+ let CancelToken = _CancelToken;
1345
+ CancelToken.source = () => {
1346
+ let cancel;
1347
+ const token = new _CancelToken(can => {
1348
+ cancel = can;
1349
+ });
1350
+ return {
1351
+ token,
1352
+ cancel
1353
+ };
1354
+ };
1355
+
1356
+ /******************************************************************************
1357
+ Copyright (c) Microsoft Corporation.
1358
+
1359
+ Permission to use, copy, modify, and/or distribute this software for any
1360
+ purpose with or without fee is hereby granted.
1361
+
1362
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1363
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1364
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1365
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1366
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1367
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1368
+ PERFORMANCE OF THIS SOFTWARE.
1369
+ ***************************************************************************** */
1370
+ /* global Reflect, Promise */
1371
+
1372
+ var extendStatics = function(d, b) {
1373
+ extendStatics = Object.setPrototypeOf ||
1374
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1375
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
1376
+ return extendStatics(d, b);
1377
+ };
1378
+
1379
+ function __extends(d, b) {
1380
+ if (typeof b !== "function" && b !== null)
1381
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
1382
+ extendStatics(d, b);
1383
+ function __() { this.constructor = d; }
1384
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1385
+ }
1386
+
1387
+ function __values(o) {
1388
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
1389
+ if (m) return m.call(o);
1390
+ if (o && typeof o.length === "number") return {
1391
+ next: function () {
1392
+ if (o && i >= o.length) o = void 0;
1393
+ return { value: o && o[i++], done: !o };
1394
+ }
1395
+ };
1396
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1397
+ }
1398
+
1399
+ function __read(o, n) {
1400
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
1401
+ if (!m) return o;
1402
+ var i = m.call(o), r, ar = [], e;
1403
+ try {
1404
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1405
+ }
1406
+ catch (error) { e = { error: error }; }
1407
+ finally {
1408
+ try {
1409
+ if (r && !r.done && (m = i["return"])) m.call(i);
1410
+ }
1411
+ finally { if (e) throw e.error; }
1412
+ }
1413
+ return ar;
1414
+ }
1415
+
1416
+ function __spreadArray(to, from, pack) {
1417
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1418
+ if (ar || !(i in from)) {
1419
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1420
+ ar[i] = from[i];
1421
+ }
1422
+ }
1423
+ return to.concat(ar || Array.prototype.slice.call(from));
1424
+ }
1425
+
1426
+ function isFunction(value) {
1427
+ return typeof value === 'function';
1428
+ }
1429
+
1430
+ function createErrorClass(createImpl) {
1431
+ var _super = function (instance) {
1432
+ Error.call(instance);
1433
+ instance.stack = new Error().stack;
1434
+ };
1435
+ var ctorFunc = createImpl(_super);
1436
+ ctorFunc.prototype = Object.create(Error.prototype);
1437
+ ctorFunc.prototype.constructor = ctorFunc;
1438
+ return ctorFunc;
1439
+ }
1440
+
1441
+ var UnsubscriptionError = createErrorClass(function (_super) {
1442
+ return function UnsubscriptionErrorImpl(errors) {
1443
+ _super(this);
1444
+ this.message = errors
1445
+ ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
1446
+ : '';
1447
+ this.name = 'UnsubscriptionError';
1448
+ this.errors = errors;
1449
+ };
1450
+ });
1451
+
1452
+ function arrRemove(arr, item) {
1453
+ if (arr) {
1454
+ var index = arr.indexOf(item);
1455
+ 0 <= index && arr.splice(index, 1);
1456
+ }
1457
+ }
1458
+
1459
+ var Subscription = (function () {
1460
+ function Subscription(initialTeardown) {
1461
+ this.initialTeardown = initialTeardown;
1462
+ this.closed = false;
1463
+ this._parentage = null;
1464
+ this._finalizers = null;
1465
+ }
1466
+ Subscription.prototype.unsubscribe = function () {
1467
+ var e_1, _a, e_2, _b;
1468
+ var errors;
1469
+ if (!this.closed) {
1470
+ this.closed = true;
1471
+ var _parentage = this._parentage;
1472
+ if (_parentage) {
1473
+ this._parentage = null;
1474
+ if (Array.isArray(_parentage)) {
1475
+ try {
1476
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
1477
+ var parent_1 = _parentage_1_1.value;
1478
+ parent_1.remove(this);
1479
+ }
1480
+ }
1481
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1482
+ finally {
1483
+ try {
1484
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
1485
+ }
1486
+ finally { if (e_1) throw e_1.error; }
1487
+ }
1488
+ }
1489
+ else {
1490
+ _parentage.remove(this);
1491
+ }
1492
+ }
1493
+ var initialFinalizer = this.initialTeardown;
1494
+ if (isFunction(initialFinalizer)) {
1495
+ try {
1496
+ initialFinalizer();
1497
+ }
1498
+ catch (e) {
1499
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
1500
+ }
1501
+ }
1502
+ var _finalizers = this._finalizers;
1503
+ if (_finalizers) {
1504
+ this._finalizers = null;
1505
+ try {
1506
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
1507
+ var finalizer = _finalizers_1_1.value;
1508
+ try {
1509
+ execFinalizer(finalizer);
1510
+ }
1511
+ catch (err) {
1512
+ errors = errors !== null && errors !== void 0 ? errors : [];
1513
+ if (err instanceof UnsubscriptionError) {
1514
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
1515
+ }
1516
+ else {
1517
+ errors.push(err);
1518
+ }
1519
+ }
1520
+ }
1521
+ }
1522
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1523
+ finally {
1524
+ try {
1525
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
1526
+ }
1527
+ finally { if (e_2) throw e_2.error; }
1528
+ }
1529
+ }
1530
+ if (errors) {
1531
+ throw new UnsubscriptionError(errors);
1532
+ }
1533
+ }
1534
+ };
1535
+ Subscription.prototype.add = function (teardown) {
1536
+ var _a;
1537
+ if (teardown && teardown !== this) {
1538
+ if (this.closed) {
1539
+ execFinalizer(teardown);
1540
+ }
1541
+ else {
1542
+ if (teardown instanceof Subscription) {
1543
+ if (teardown.closed || teardown._hasParent(this)) {
1544
+ return;
1545
+ }
1546
+ teardown._addParent(this);
1547
+ }
1548
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
1549
+ }
1550
+ }
1551
+ };
1552
+ Subscription.prototype._hasParent = function (parent) {
1553
+ var _parentage = this._parentage;
1554
+ return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
1555
+ };
1556
+ Subscription.prototype._addParent = function (parent) {
1557
+ var _parentage = this._parentage;
1558
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
1559
+ };
1560
+ Subscription.prototype._removeParent = function (parent) {
1561
+ var _parentage = this._parentage;
1562
+ if (_parentage === parent) {
1563
+ this._parentage = null;
1564
+ }
1565
+ else if (Array.isArray(_parentage)) {
1566
+ arrRemove(_parentage, parent);
1567
+ }
1568
+ };
1569
+ Subscription.prototype.remove = function (teardown) {
1570
+ var _finalizers = this._finalizers;
1571
+ _finalizers && arrRemove(_finalizers, teardown);
1572
+ if (teardown instanceof Subscription) {
1573
+ teardown._removeParent(this);
1574
+ }
1575
+ };
1576
+ Subscription.EMPTY = (function () {
1577
+ var empty = new Subscription();
1578
+ empty.closed = true;
1579
+ return empty;
1580
+ })();
1581
+ return Subscription;
1582
+ }());
1583
+ Subscription.EMPTY;
1584
+ function isSubscription(value) {
1585
+ return (value instanceof Subscription ||
1586
+ (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
1587
+ }
1588
+ function execFinalizer(finalizer) {
1589
+ if (isFunction(finalizer)) {
1590
+ finalizer();
1591
+ }
1592
+ else {
1593
+ finalizer.unsubscribe();
1594
+ }
1595
+ }
1596
+
1597
+ var config = {
1598
+ onUnhandledError: null,
1599
+ onStoppedNotification: null,
1600
+ Promise: undefined,
1601
+ useDeprecatedSynchronousErrorHandling: false,
1602
+ useDeprecatedNextContext: false,
1603
+ };
1604
+
1605
+ var timeoutProvider = {
1606
+ setTimeout: function (handler, timeout) {
1607
+ var args = [];
1608
+ for (var _i = 2; _i < arguments.length; _i++) {
1609
+ args[_i - 2] = arguments[_i];
1610
+ }
1611
+ var delegate = timeoutProvider.delegate;
1612
+ if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
1613
+ return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
1614
+ }
1615
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1616
+ },
1617
+ clearTimeout: function (handle) {
1618
+ var delegate = timeoutProvider.delegate;
1619
+ return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
1620
+ },
1621
+ delegate: undefined,
1622
+ };
1623
+
1624
+ function reportUnhandledError(err) {
1625
+ timeoutProvider.setTimeout(function () {
1626
+ {
1627
+ throw err;
1628
+ }
1629
+ });
1630
+ }
1631
+
1632
+ function noop() { }
1633
+
1634
+ function errorContext(cb) {
1635
+ {
1636
+ cb();
1637
+ }
1638
+ }
1639
+
1640
+ var Subscriber = (function (_super) {
1641
+ __extends(Subscriber, _super);
1642
+ function Subscriber(destination) {
1643
+ var _this = _super.call(this) || this;
1644
+ _this.isStopped = false;
1645
+ if (destination) {
1646
+ _this.destination = destination;
1647
+ if (isSubscription(destination)) {
1648
+ destination.add(_this);
1649
+ }
1650
+ }
1651
+ else {
1652
+ _this.destination = EMPTY_OBSERVER;
1653
+ }
1654
+ return _this;
1655
+ }
1656
+ Subscriber.create = function (next, error, complete) {
1657
+ return new SafeSubscriber(next, error, complete);
1658
+ };
1659
+ Subscriber.prototype.next = function (value) {
1660
+ if (this.isStopped) ;
1661
+ else {
1662
+ this._next(value);
1663
+ }
1664
+ };
1665
+ Subscriber.prototype.error = function (err) {
1666
+ if (this.isStopped) ;
1667
+ else {
1668
+ this.isStopped = true;
1669
+ this._error(err);
1670
+ }
1671
+ };
1672
+ Subscriber.prototype.complete = function () {
1673
+ if (this.isStopped) ;
1674
+ else {
1675
+ this.isStopped = true;
1676
+ this._complete();
1677
+ }
1678
+ };
1679
+ Subscriber.prototype.unsubscribe = function () {
1680
+ if (!this.closed) {
1681
+ this.isStopped = true;
1682
+ _super.prototype.unsubscribe.call(this);
1683
+ this.destination = null;
1684
+ }
1685
+ };
1686
+ Subscriber.prototype._next = function (value) {
1687
+ this.destination.next(value);
1688
+ };
1689
+ Subscriber.prototype._error = function (err) {
1690
+ try {
1691
+ this.destination.error(err);
1692
+ }
1693
+ finally {
1694
+ this.unsubscribe();
1695
+ }
1696
+ };
1697
+ Subscriber.prototype._complete = function () {
1698
+ try {
1699
+ this.destination.complete();
1700
+ }
1701
+ finally {
1702
+ this.unsubscribe();
1703
+ }
1704
+ };
1705
+ return Subscriber;
1706
+ }(Subscription));
1707
+ var _bind = Function.prototype.bind;
1708
+ function bind(fn, thisArg) {
1709
+ return _bind.call(fn, thisArg);
1710
+ }
1711
+ var ConsumerObserver = (function () {
1712
+ function ConsumerObserver(partialObserver) {
1713
+ this.partialObserver = partialObserver;
1714
+ }
1715
+ ConsumerObserver.prototype.next = function (value) {
1716
+ var partialObserver = this.partialObserver;
1717
+ if (partialObserver.next) {
1718
+ try {
1719
+ partialObserver.next(value);
1720
+ }
1721
+ catch (error) {
1722
+ handleUnhandledError(error);
1723
+ }
1724
+ }
1725
+ };
1726
+ ConsumerObserver.prototype.error = function (err) {
1727
+ var partialObserver = this.partialObserver;
1728
+ if (partialObserver.error) {
1729
+ try {
1730
+ partialObserver.error(err);
1731
+ }
1732
+ catch (error) {
1733
+ handleUnhandledError(error);
1734
+ }
1735
+ }
1736
+ else {
1737
+ handleUnhandledError(err);
1738
+ }
1739
+ };
1740
+ ConsumerObserver.prototype.complete = function () {
1741
+ var partialObserver = this.partialObserver;
1742
+ if (partialObserver.complete) {
1743
+ try {
1744
+ partialObserver.complete();
1745
+ }
1746
+ catch (error) {
1747
+ handleUnhandledError(error);
1748
+ }
1749
+ }
1750
+ };
1751
+ return ConsumerObserver;
1752
+ }());
1753
+ var SafeSubscriber = (function (_super) {
1754
+ __extends(SafeSubscriber, _super);
1755
+ function SafeSubscriber(observerOrNext, error, complete) {
1756
+ var _this = _super.call(this) || this;
1757
+ var partialObserver;
1758
+ if (isFunction(observerOrNext) || !observerOrNext) {
1759
+ partialObserver = {
1760
+ next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),
1761
+ error: error !== null && error !== void 0 ? error : undefined,
1762
+ complete: complete !== null && complete !== void 0 ? complete : undefined,
1763
+ };
1764
+ }
1765
+ else {
1766
+ var context_1;
1767
+ if (_this && config.useDeprecatedNextContext) {
1768
+ context_1 = Object.create(observerOrNext);
1769
+ context_1.unsubscribe = function () { return _this.unsubscribe(); };
1770
+ partialObserver = {
1771
+ next: observerOrNext.next && bind(observerOrNext.next, context_1),
1772
+ error: observerOrNext.error && bind(observerOrNext.error, context_1),
1773
+ complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
1774
+ };
1775
+ }
1776
+ else {
1777
+ partialObserver = observerOrNext;
1778
+ }
1779
+ }
1780
+ _this.destination = new ConsumerObserver(partialObserver);
1781
+ return _this;
1782
+ }
1783
+ return SafeSubscriber;
1784
+ }(Subscriber));
1785
+ function handleUnhandledError(error) {
1786
+ {
1787
+ reportUnhandledError(error);
1788
+ }
1789
+ }
1790
+ function defaultErrorHandler(err) {
1791
+ throw err;
1792
+ }
1793
+ var EMPTY_OBSERVER = {
1794
+ closed: true,
1795
+ next: noop,
1796
+ error: defaultErrorHandler,
1797
+ complete: noop,
1798
+ };
1799
+
1800
+ var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
1801
+
1802
+ function identity(x) {
1803
+ return x;
1804
+ }
1805
+
1806
+ function pipeFromArray(fns) {
1807
+ if (fns.length === 0) {
1808
+ return identity;
1809
+ }
1810
+ if (fns.length === 1) {
1811
+ return fns[0];
1812
+ }
1813
+ return function piped(input) {
1814
+ return fns.reduce(function (prev, fn) { return fn(prev); }, input);
1815
+ };
1816
+ }
1817
+
1818
+ var Observable = (function () {
1819
+ function Observable(subscribe) {
1820
+ if (subscribe) {
1821
+ this._subscribe = subscribe;
1822
+ }
1823
+ }
1824
+ Observable.prototype.lift = function (operator) {
1825
+ var observable = new Observable();
1826
+ observable.source = this;
1827
+ observable.operator = operator;
1828
+ return observable;
1829
+ };
1830
+ Observable.prototype.subscribe = function (observerOrNext, error, complete) {
1831
+ var _this = this;
1832
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
1833
+ errorContext(function () {
1834
+ var _a = _this, operator = _a.operator, source = _a.source;
1835
+ subscriber.add(operator
1836
+ ?
1837
+ operator.call(subscriber, source)
1838
+ : source
1839
+ ?
1840
+ _this._subscribe(subscriber)
1841
+ :
1842
+ _this._trySubscribe(subscriber));
1843
+ });
1844
+ return subscriber;
1845
+ };
1846
+ Observable.prototype._trySubscribe = function (sink) {
1847
+ try {
1848
+ return this._subscribe(sink);
1849
+ }
1850
+ catch (err) {
1851
+ sink.error(err);
1852
+ }
1853
+ };
1854
+ Observable.prototype.forEach = function (next, promiseCtor) {
1855
+ var _this = this;
1856
+ promiseCtor = getPromiseCtor(promiseCtor);
1857
+ return new promiseCtor(function (resolve, reject) {
1858
+ var subscriber = new SafeSubscriber({
1859
+ next: function (value) {
1860
+ try {
1861
+ next(value);
1862
+ }
1863
+ catch (err) {
1864
+ reject(err);
1865
+ subscriber.unsubscribe();
1866
+ }
1867
+ },
1868
+ error: reject,
1869
+ complete: resolve,
1870
+ });
1871
+ _this.subscribe(subscriber);
1872
+ });
1873
+ };
1874
+ Observable.prototype._subscribe = function (subscriber) {
1875
+ var _a;
1876
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1877
+ };
1878
+ Observable.prototype[observable] = function () {
1879
+ return this;
1880
+ };
1881
+ Observable.prototype.pipe = function () {
1882
+ var operations = [];
1883
+ for (var _i = 0; _i < arguments.length; _i++) {
1884
+ operations[_i] = arguments[_i];
1885
+ }
1886
+ return pipeFromArray(operations)(this);
1887
+ };
1888
+ Observable.prototype.toPromise = function (promiseCtor) {
1889
+ var _this = this;
1890
+ promiseCtor = getPromiseCtor(promiseCtor);
1891
+ return new promiseCtor(function (resolve, reject) {
1892
+ var value;
1893
+ _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
1894
+ });
1895
+ };
1896
+ Observable.create = function (subscribe) {
1897
+ return new Observable(subscribe);
1898
+ };
1899
+ return Observable;
1900
+ }());
1901
+ function getPromiseCtor(promiseCtor) {
1902
+ var _a;
1903
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
1904
+ }
1905
+ function isObserver(value) {
1906
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1907
+ }
1908
+ function isSubscriber(value) {
1909
+ return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
1910
+ }
1911
+
1912
+ function hasLift(source) {
1913
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1914
+ }
1915
+ function operate(init) {
1916
+ return function (source) {
1917
+ if (hasLift(source)) {
1918
+ return source.lift(function (liftedSource) {
1919
+ try {
1920
+ return init(liftedSource, this);
1921
+ }
1922
+ catch (err) {
1923
+ this.error(err);
1924
+ }
1925
+ });
1926
+ }
1927
+ throw new TypeError('Unable to lift unknown Observable type');
1928
+ };
1929
+ }
1930
+
1931
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1932
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1933
+ }
1934
+ var OperatorSubscriber = (function (_super) {
1935
+ __extends(OperatorSubscriber, _super);
1936
+ function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1937
+ var _this = _super.call(this, destination) || this;
1938
+ _this.onFinalize = onFinalize;
1939
+ _this.shouldUnsubscribe = shouldUnsubscribe;
1940
+ _this._next = onNext
1941
+ ? function (value) {
1942
+ try {
1943
+ onNext(value);
1944
+ }
1945
+ catch (err) {
1946
+ destination.error(err);
1947
+ }
1948
+ }
1949
+ : _super.prototype._next;
1950
+ _this._error = onError
1951
+ ? function (err) {
1952
+ try {
1953
+ onError(err);
1954
+ }
1955
+ catch (err) {
1956
+ destination.error(err);
1957
+ }
1958
+ finally {
1959
+ this.unsubscribe();
1960
+ }
1961
+ }
1962
+ : _super.prototype._error;
1963
+ _this._complete = onComplete
1964
+ ? function () {
1965
+ try {
1966
+ onComplete();
1967
+ }
1968
+ catch (err) {
1969
+ destination.error(err);
1970
+ }
1971
+ finally {
1972
+ this.unsubscribe();
1973
+ }
1974
+ }
1975
+ : _super.prototype._complete;
1976
+ return _this;
1977
+ }
1978
+ OperatorSubscriber.prototype.unsubscribe = function () {
1979
+ var _a;
1980
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1981
+ var closed_1 = this.closed;
1982
+ _super.prototype.unsubscribe.call(this);
1983
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1984
+ }
1985
+ };
1986
+ return OperatorSubscriber;
1987
+ }(Subscriber));
1988
+
1989
+ var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
1990
+ _super(this);
1991
+ this.name = 'EmptyError';
1992
+ this.message = 'no elements in sequence';
1993
+ }; });
1994
+
1995
+ function lastValueFrom(source, config) {
1996
+ var hasConfig = typeof config === 'object';
1997
+ return new Promise(function (resolve, reject) {
1998
+ var _hasValue = false;
1999
+ var _value;
2000
+ source.subscribe({
2001
+ next: function (value) {
2002
+ _value = value;
2003
+ _hasValue = true;
2004
+ },
2005
+ error: reject,
2006
+ complete: function () {
2007
+ if (_hasValue) {
2008
+ resolve(_value);
2009
+ }
2010
+ else if (hasConfig) {
2011
+ resolve(config.defaultValue);
2012
+ }
2013
+ else {
2014
+ reject(new EmptyError());
2015
+ }
2016
+ },
2017
+ });
2018
+ });
2019
+ }
2020
+
2021
+ function map(project, thisArg) {
2022
+ return operate(function (source, subscriber) {
2023
+ var index = 0;
2024
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2025
+ subscriber.next(project.call(thisArg, value, index++));
2026
+ }));
2027
+ });
2028
+ }
2029
+
2030
+ function filter(predicate, thisArg) {
2031
+ return operate(function (source, subscriber) {
2032
+ var index = 0;
2033
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
2034
+ });
2035
+ }
2036
+
2037
+ var eventsourceExports = {};
2038
+ var eventsource = {
2039
+ get exports(){ return eventsourceExports; },
2040
+ set exports(v){ eventsourceExports = v; },
2041
+ };
2042
+
2043
+ /** @license
2044
+ * eventsource.js
2045
+ * Available under MIT License (MIT)
2046
+ * https://github.com/Yaffle/EventSource/
2047
+ */
2048
+
2049
+ (function (module, exports) {
2050
+ /*jslint indent: 2, vars: true, plusplus: true */
2051
+ /*global setTimeout, clearTimeout */
2052
+
2053
+ (function (global) {
2054
+
2055
+ var setTimeout = global.setTimeout;
2056
+ var clearTimeout = global.clearTimeout;
2057
+ var XMLHttpRequest = global.XMLHttpRequest;
2058
+ var XDomainRequest = global.XDomainRequest;
2059
+ var ActiveXObject = global.ActiveXObject;
2060
+ var NativeEventSource = global.EventSource;
2061
+
2062
+ var document = global.document;
2063
+ var Promise = global.Promise;
2064
+ var fetch = global.fetch;
2065
+ var Response = global.Response;
2066
+ var TextDecoder = global.TextDecoder;
2067
+ var TextEncoder = global.TextEncoder;
2068
+ var AbortController = global.AbortController;
2069
+
2070
+ if (typeof window !== "undefined" && typeof document !== "undefined" && !("readyState" in document) && document.body == null) { // Firefox 2
2071
+ document.readyState = "loading";
2072
+ window.addEventListener("load", function (event) {
2073
+ document.readyState = "complete";
2074
+ }, false);
2075
+ }
2076
+
2077
+ if (XMLHttpRequest == null && ActiveXObject != null) { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6
2078
+ XMLHttpRequest = function () {
2079
+ return new ActiveXObject("Microsoft.XMLHTTP");
2080
+ };
2081
+ }
2082
+
2083
+ if (Object.create == undefined) {
2084
+ Object.create = function (C) {
2085
+ function F(){}
2086
+ F.prototype = C;
2087
+ return new F();
2088
+ };
2089
+ }
2090
+
2091
+ if (!Date.now) {
2092
+ Date.now = function now() {
2093
+ return new Date().getTime();
2094
+ };
2095
+ }
2096
+
2097
+ // see #118 (Promise#finally with polyfilled Promise)
2098
+ // see #123 (data URLs crash Edge)
2099
+ // see #125 (CSP violations)
2100
+ // see pull/#138
2101
+ // => No way to polyfill Promise#finally
2102
+
2103
+ if (AbortController == undefined) {
2104
+ var originalFetch2 = fetch;
2105
+ fetch = function (url, options) {
2106
+ var signal = options.signal;
2107
+ return originalFetch2(url, {headers: options.headers, credentials: options.credentials, cache: options.cache}).then(function (response) {
2108
+ var reader = response.body.getReader();
2109
+ signal._reader = reader;
2110
+ if (signal._aborted) {
2111
+ signal._reader.cancel();
2112
+ }
2113
+ return {
2114
+ status: response.status,
2115
+ statusText: response.statusText,
2116
+ headers: response.headers,
2117
+ body: {
2118
+ getReader: function () {
2119
+ return reader;
2120
+ }
2121
+ }
2122
+ };
2123
+ });
2124
+ };
2125
+ AbortController = function () {
2126
+ this.signal = {
2127
+ _reader: null,
2128
+ _aborted: false
2129
+ };
2130
+ this.abort = function () {
2131
+ if (this.signal._reader != null) {
2132
+ this.signal._reader.cancel();
2133
+ }
2134
+ this.signal._aborted = true;
2135
+ };
2136
+ };
2137
+ }
2138
+
2139
+ function TextDecoderPolyfill() {
2140
+ this.bitsNeeded = 0;
2141
+ this.codePoint = 0;
2142
+ }
2143
+
2144
+ TextDecoderPolyfill.prototype.decode = function (octets) {
2145
+ function valid(codePoint, shift, octetsCount) {
2146
+ if (octetsCount === 1) {
2147
+ return codePoint >= 0x0080 >> shift && codePoint << shift <= 0x07FF;
2148
+ }
2149
+ if (octetsCount === 2) {
2150
+ return codePoint >= 0x0800 >> shift && codePoint << shift <= 0xD7FF || codePoint >= 0xE000 >> shift && codePoint << shift <= 0xFFFF;
2151
+ }
2152
+ if (octetsCount === 3) {
2153
+ return codePoint >= 0x010000 >> shift && codePoint << shift <= 0x10FFFF;
2154
+ }
2155
+ throw new Error();
2156
+ }
2157
+ function octetsCount(bitsNeeded, codePoint) {
2158
+ if (bitsNeeded === 6 * 1) {
2159
+ return codePoint >> 6 > 15 ? 3 : codePoint > 31 ? 2 : 1;
2160
+ }
2161
+ if (bitsNeeded === 6 * 2) {
2162
+ return codePoint > 15 ? 3 : 2;
2163
+ }
2164
+ if (bitsNeeded === 6 * 3) {
2165
+ return 3;
2166
+ }
2167
+ throw new Error();
2168
+ }
2169
+ var REPLACER = 0xFFFD;
2170
+ var string = "";
2171
+ var bitsNeeded = this.bitsNeeded;
2172
+ var codePoint = this.codePoint;
2173
+ for (var i = 0; i < octets.length; i += 1) {
2174
+ var octet = octets[i];
2175
+ if (bitsNeeded !== 0) {
2176
+ if (octet < 128 || octet > 191 || !valid(codePoint << 6 | octet & 63, bitsNeeded - 6, octetsCount(bitsNeeded, codePoint))) {
2177
+ bitsNeeded = 0;
2178
+ codePoint = REPLACER;
2179
+ string += String.fromCharCode(codePoint);
2180
+ }
2181
+ }
2182
+ if (bitsNeeded === 0) {
2183
+ if (octet >= 0 && octet <= 127) {
2184
+ bitsNeeded = 0;
2185
+ codePoint = octet;
2186
+ } else if (octet >= 192 && octet <= 223) {
2187
+ bitsNeeded = 6 * 1;
2188
+ codePoint = octet & 31;
2189
+ } else if (octet >= 224 && octet <= 239) {
2190
+ bitsNeeded = 6 * 2;
2191
+ codePoint = octet & 15;
2192
+ } else if (octet >= 240 && octet <= 247) {
2193
+ bitsNeeded = 6 * 3;
2194
+ codePoint = octet & 7;
2195
+ } else {
2196
+ bitsNeeded = 0;
2197
+ codePoint = REPLACER;
2198
+ }
2199
+ if (bitsNeeded !== 0 && !valid(codePoint, bitsNeeded, octetsCount(bitsNeeded, codePoint))) {
2200
+ bitsNeeded = 0;
2201
+ codePoint = REPLACER;
2202
+ }
2203
+ } else {
2204
+ bitsNeeded -= 6;
2205
+ codePoint = codePoint << 6 | octet & 63;
2206
+ }
2207
+ if (bitsNeeded === 0) {
2208
+ if (codePoint <= 0xFFFF) {
2209
+ string += String.fromCharCode(codePoint);
2210
+ } else {
2211
+ string += String.fromCharCode(0xD800 + (codePoint - 0xFFFF - 1 >> 10));
2212
+ string += String.fromCharCode(0xDC00 + (codePoint - 0xFFFF - 1 & 0x3FF));
2213
+ }
2214
+ }
2215
+ }
2216
+ this.bitsNeeded = bitsNeeded;
2217
+ this.codePoint = codePoint;
2218
+ return string;
2219
+ };
2220
+
2221
+ // Firefox < 38 throws an error with stream option
2222
+ var supportsStreamOption = function () {
2223
+ try {
2224
+ return new TextDecoder().decode(new TextEncoder().encode("test"), {stream: true}) === "test";
2225
+ } catch (error) {
2226
+ console.debug("TextDecoder does not support streaming option. Using polyfill instead: " + error);
2227
+ }
2228
+ return false;
2229
+ };
2230
+
2231
+ // IE, Edge
2232
+ if (TextDecoder == undefined || TextEncoder == undefined || !supportsStreamOption()) {
2233
+ TextDecoder = TextDecoderPolyfill;
2234
+ }
2235
+
2236
+ var k = function () {
2237
+ };
2238
+
2239
+ function XHRWrapper(xhr) {
2240
+ this.withCredentials = false;
2241
+ this.readyState = 0;
2242
+ this.status = 0;
2243
+ this.statusText = "";
2244
+ this.responseText = "";
2245
+ this.onprogress = k;
2246
+ this.onload = k;
2247
+ this.onerror = k;
2248
+ this.onreadystatechange = k;
2249
+ this._contentType = "";
2250
+ this._xhr = xhr;
2251
+ this._sendTimeout = 0;
2252
+ this._abort = k;
2253
+ }
2254
+
2255
+ XHRWrapper.prototype.open = function (method, url) {
2256
+ this._abort(true);
2257
+
2258
+ var that = this;
2259
+ var xhr = this._xhr;
2260
+ var state = 1;
2261
+ var timeout = 0;
2262
+
2263
+ this._abort = function (silent) {
2264
+ if (that._sendTimeout !== 0) {
2265
+ clearTimeout(that._sendTimeout);
2266
+ that._sendTimeout = 0;
2267
+ }
2268
+ if (state === 1 || state === 2 || state === 3) {
2269
+ state = 4;
2270
+ xhr.onload = k;
2271
+ xhr.onerror = k;
2272
+ xhr.onabort = k;
2273
+ xhr.onprogress = k;
2274
+ xhr.onreadystatechange = k;
2275
+ // IE 8 - 9: XDomainRequest#abort() does not fire any event
2276
+ // Opera < 10: XMLHttpRequest#abort() does not fire any event
2277
+ xhr.abort();
2278
+ if (timeout !== 0) {
2279
+ clearTimeout(timeout);
2280
+ timeout = 0;
2281
+ }
2282
+ if (!silent) {
2283
+ that.readyState = 4;
2284
+ that.onabort(null);
2285
+ that.onreadystatechange();
2286
+ }
2287
+ }
2288
+ state = 0;
2289
+ };
2290
+
2291
+ var onStart = function () {
2292
+ if (state === 1) {
2293
+ //state = 2;
2294
+ var status = 0;
2295
+ var statusText = "";
2296
+ var contentType = undefined;
2297
+ if (!("contentType" in xhr)) {
2298
+ try {
2299
+ status = xhr.status;
2300
+ statusText = xhr.statusText;
2301
+ contentType = xhr.getResponseHeader("Content-Type");
2302
+ } catch (error) {
2303
+ // IE < 10 throws exception for `xhr.status` when xhr.readyState === 2 || xhr.readyState === 3
2304
+ // Opera < 11 throws exception for `xhr.status` when xhr.readyState === 2
2305
+ // https://bugs.webkit.org/show_bug.cgi?id=29121
2306
+ status = 0;
2307
+ statusText = "";
2308
+ contentType = undefined;
2309
+ // Firefox < 14, Chrome ?, Safari ?
2310
+ // https://bugs.webkit.org/show_bug.cgi?id=29658
2311
+ // https://bugs.webkit.org/show_bug.cgi?id=77854
2312
+ }
2313
+ } else {
2314
+ status = 200;
2315
+ statusText = "OK";
2316
+ contentType = xhr.contentType;
2317
+ }
2318
+ if (status !== 0) {
2319
+ state = 2;
2320
+ that.readyState = 2;
2321
+ that.status = status;
2322
+ that.statusText = statusText;
2323
+ that._contentType = contentType;
2324
+ that.onreadystatechange();
2325
+ }
2326
+ }
2327
+ };
2328
+ var onProgress = function () {
2329
+ onStart();
2330
+ if (state === 2 || state === 3) {
2331
+ state = 3;
2332
+ var responseText = "";
2333
+ try {
2334
+ responseText = xhr.responseText;
2335
+ } catch (error) {
2336
+ // IE 8 - 9 with XMLHttpRequest
2337
+ }
2338
+ that.readyState = 3;
2339
+ that.responseText = responseText;
2340
+ that.onprogress();
2341
+ }
2342
+ };
2343
+ var onFinish = function (type, event) {
2344
+ if (event == null || event.preventDefault == null) {
2345
+ event = {
2346
+ preventDefault: k
2347
+ };
2348
+ }
2349
+ // Firefox 52 fires "readystatechange" (xhr.readyState === 4) without final "readystatechange" (xhr.readyState === 3)
2350
+ // IE 8 fires "onload" without "onprogress"
2351
+ onProgress();
2352
+ if (state === 1 || state === 2 || state === 3) {
2353
+ state = 4;
2354
+ if (timeout !== 0) {
2355
+ clearTimeout(timeout);
2356
+ timeout = 0;
2357
+ }
2358
+ that.readyState = 4;
2359
+ if (type === "load") {
2360
+ that.onload(event);
2361
+ } else if (type === "error") {
2362
+ that.onerror(event);
2363
+ } else if (type === "abort") {
2364
+ that.onabort(event);
2365
+ } else {
2366
+ throw new TypeError();
2367
+ }
2368
+ that.onreadystatechange();
2369
+ }
2370
+ };
2371
+ var onReadyStateChange = function (event) {
2372
+ if (xhr != undefined) { // Opera 12
2373
+ if (xhr.readyState === 4) {
2374
+ if (!("onload" in xhr) || !("onerror" in xhr) || !("onabort" in xhr)) {
2375
+ onFinish(xhr.responseText === "" ? "error" : "load", event);
2376
+ }
2377
+ } else if (xhr.readyState === 3) {
2378
+ if (!("onprogress" in xhr)) { // testing XMLHttpRequest#responseText too many times is too slow in IE 11
2379
+ // and in Firefox 3.6
2380
+ onProgress();
2381
+ }
2382
+ } else if (xhr.readyState === 2) {
2383
+ onStart();
2384
+ }
2385
+ }
2386
+ };
2387
+ var onTimeout = function () {
2388
+ timeout = setTimeout(function () {
2389
+ onTimeout();
2390
+ }, 500);
2391
+ if (xhr.readyState === 3) {
2392
+ onProgress();
2393
+ }
2394
+ };
2395
+
2396
+ // XDomainRequest#abort removes onprogress, onerror, onload
2397
+ if ("onload" in xhr) {
2398
+ xhr.onload = function (event) {
2399
+ onFinish("load", event);
2400
+ };
2401
+ }
2402
+ if ("onerror" in xhr) {
2403
+ xhr.onerror = function (event) {
2404
+ onFinish("error", event);
2405
+ };
2406
+ }
2407
+ // improper fix to match Firefox behaviour, but it is better than just ignore abort
2408
+ // see https://bugzilla.mozilla.org/show_bug.cgi?id=768596
2409
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=880200
2410
+ // https://code.google.com/p/chromium/issues/detail?id=153570
2411
+ // IE 8 fires "onload" without "onprogress
2412
+ if ("onabort" in xhr) {
2413
+ xhr.onabort = function (event) {
2414
+ onFinish("abort", event);
2415
+ };
2416
+ }
2417
+
2418
+ if ("onprogress" in xhr) {
2419
+ xhr.onprogress = onProgress;
2420
+ }
2421
+
2422
+ // IE 8 - 9 (XMLHTTPRequest)
2423
+ // Opera < 12
2424
+ // Firefox < 3.5
2425
+ // Firefox 3.5 - 3.6 - ? < 9.0
2426
+ // onprogress is not fired sometimes or delayed
2427
+ // see also #64 (significant lag in IE 11)
2428
+ if ("onreadystatechange" in xhr) {
2429
+ xhr.onreadystatechange = function (event) {
2430
+ onReadyStateChange(event);
2431
+ };
2432
+ }
2433
+
2434
+ if ("contentType" in xhr || !("ontimeout" in XMLHttpRequest.prototype)) {
2435
+ url += (url.indexOf("?") === -1 ? "?" : "&") + "padding=true";
2436
+ }
2437
+ xhr.open(method, url, true);
2438
+
2439
+ if ("readyState" in xhr) {
2440
+ // workaround for Opera 12 issue with "progress" events
2441
+ // #91 (XMLHttpRequest onprogress not fired for streaming response in Edge 14-15-?)
2442
+ timeout = setTimeout(function () {
2443
+ onTimeout();
2444
+ }, 0);
2445
+ }
2446
+ };
2447
+ XHRWrapper.prototype.abort = function () {
2448
+ this._abort(false);
2449
+ };
2450
+ XHRWrapper.prototype.getResponseHeader = function (name) {
2451
+ return this._contentType;
2452
+ };
2453
+ XHRWrapper.prototype.setRequestHeader = function (name, value) {
2454
+ var xhr = this._xhr;
2455
+ if ("setRequestHeader" in xhr) {
2456
+ xhr.setRequestHeader(name, value);
2457
+ }
2458
+ };
2459
+ XHRWrapper.prototype.getAllResponseHeaders = function () {
2460
+ // XMLHttpRequest#getAllResponseHeaders returns null for CORS requests in Firefox 3.6.28
2461
+ return this._xhr.getAllResponseHeaders != undefined ? this._xhr.getAllResponseHeaders() || "" : "";
2462
+ };
2463
+ XHRWrapper.prototype.send = function () {
2464
+ // loading indicator in Safari < ? (6), Chrome < 14, Firefox
2465
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=736723
2466
+ if ((!("ontimeout" in XMLHttpRequest.prototype) || (!("sendAsBinary" in XMLHttpRequest.prototype) && !("mozAnon" in XMLHttpRequest.prototype))) &&
2467
+ document != undefined &&
2468
+ document.readyState != undefined &&
2469
+ document.readyState !== "complete") {
2470
+ var that = this;
2471
+ that._sendTimeout = setTimeout(function () {
2472
+ that._sendTimeout = 0;
2473
+ that.send();
2474
+ }, 4);
2475
+ return;
2476
+ }
2477
+
2478
+ var xhr = this._xhr;
2479
+ // withCredentials should be set after "open" for Safari and Chrome (< 19 ?)
2480
+ if ("withCredentials" in xhr) {
2481
+ xhr.withCredentials = this.withCredentials;
2482
+ }
2483
+ try {
2484
+ // xhr.send(); throws "Not enough arguments" in Firefox 3.0
2485
+ xhr.send(undefined);
2486
+ } catch (error1) {
2487
+ // Safari 5.1.7, Opera 12
2488
+ throw error1;
2489
+ }
2490
+ };
2491
+
2492
+ function toLowerCase(name) {
2493
+ return name.replace(/[A-Z]/g, function (c) {
2494
+ return String.fromCharCode(c.charCodeAt(0) + 0x20);
2495
+ });
2496
+ }
2497
+
2498
+ function HeadersPolyfill(all) {
2499
+ // Get headers: implemented according to mozilla's example code: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#Example
2500
+ var map = Object.create(null);
2501
+ var array = all.split("\r\n");
2502
+ for (var i = 0; i < array.length; i += 1) {
2503
+ var line = array[i];
2504
+ var parts = line.split(": ");
2505
+ var name = parts.shift();
2506
+ var value = parts.join(": ");
2507
+ map[toLowerCase(name)] = value;
2508
+ }
2509
+ this._map = map;
2510
+ }
2511
+ HeadersPolyfill.prototype.get = function (name) {
2512
+ return this._map[toLowerCase(name)];
2513
+ };
2514
+
2515
+ if (XMLHttpRequest != null && XMLHttpRequest.HEADERS_RECEIVED == null) { // IE < 9, Firefox 3.6
2516
+ XMLHttpRequest.HEADERS_RECEIVED = 2;
2517
+ }
2518
+
2519
+ function XHRTransport() {
2520
+ }
2521
+
2522
+ XHRTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
2523
+ xhr.open("GET", url);
2524
+ var offset = 0;
2525
+ xhr.onprogress = function () {
2526
+ var responseText = xhr.responseText;
2527
+ var chunk = responseText.slice(offset);
2528
+ offset += chunk.length;
2529
+ onProgressCallback(chunk);
2530
+ };
2531
+ xhr.onerror = function (event) {
2532
+ event.preventDefault();
2533
+ onFinishCallback(new Error("NetworkError"));
2534
+ };
2535
+ xhr.onload = function () {
2536
+ onFinishCallback(null);
2537
+ };
2538
+ xhr.onabort = function () {
2539
+ onFinishCallback(null);
2540
+ };
2541
+ xhr.onreadystatechange = function () {
2542
+ if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
2543
+ var status = xhr.status;
2544
+ var statusText = xhr.statusText;
2545
+ var contentType = xhr.getResponseHeader("Content-Type");
2546
+ var headers = xhr.getAllResponseHeaders();
2547
+ onStartCallback(status, statusText, contentType, new HeadersPolyfill(headers));
2548
+ }
2549
+ };
2550
+ xhr.withCredentials = withCredentials;
2551
+ for (var name in headers) {
2552
+ if (Object.prototype.hasOwnProperty.call(headers, name)) {
2553
+ xhr.setRequestHeader(name, headers[name]);
2554
+ }
2555
+ }
2556
+ xhr.send();
2557
+ return xhr;
2558
+ };
2559
+
2560
+ function HeadersWrapper(headers) {
2561
+ this._headers = headers;
2562
+ }
2563
+ HeadersWrapper.prototype.get = function (name) {
2564
+ return this._headers.get(name);
2565
+ };
2566
+
2567
+ function FetchTransport() {
2568
+ }
2569
+
2570
+ FetchTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
2571
+ var reader = null;
2572
+ var controller = new AbortController();
2573
+ var signal = controller.signal;
2574
+ var textDecoder = new TextDecoder();
2575
+ fetch(url, {
2576
+ headers: headers,
2577
+ credentials: withCredentials ? "include" : "same-origin",
2578
+ signal: signal,
2579
+ cache: "no-store"
2580
+ }).then(function (response) {
2581
+ reader = response.body.getReader();
2582
+ onStartCallback(response.status, response.statusText, response.headers.get("Content-Type"), new HeadersWrapper(response.headers));
2583
+ // see https://github.com/promises-aplus/promises-spec/issues/179
2584
+ return new Promise(function (resolve, reject) {
2585
+ var readNextChunk = function () {
2586
+ reader.read().then(function (result) {
2587
+ if (result.done) {
2588
+ //Note: bytes in textDecoder are ignored
2589
+ resolve(undefined);
2590
+ } else {
2591
+ var chunk = textDecoder.decode(result.value, {stream: true});
2592
+ onProgressCallback(chunk);
2593
+ readNextChunk();
2594
+ }
2595
+ })["catch"](function (error) {
2596
+ reject(error);
2597
+ });
2598
+ };
2599
+ readNextChunk();
2600
+ });
2601
+ })["catch"](function (error) {
2602
+ if (error.name === "AbortError") {
2603
+ return undefined;
2604
+ } else {
2605
+ return error;
2606
+ }
2607
+ }).then(function (error) {
2608
+ onFinishCallback(error);
2609
+ });
2610
+ return {
2611
+ abort: function () {
2612
+ if (reader != null) {
2613
+ reader.cancel(); // https://bugzilla.mozilla.org/show_bug.cgi?id=1583815
2614
+ }
2615
+ controller.abort();
2616
+ }
2617
+ };
2618
+ };
2619
+
2620
+ function EventTarget() {
2621
+ this._listeners = Object.create(null);
2622
+ }
2623
+
2624
+ function throwError(e) {
2625
+ setTimeout(function () {
2626
+ throw e;
2627
+ }, 0);
2628
+ }
2629
+
2630
+ EventTarget.prototype.dispatchEvent = function (event) {
2631
+ event.target = this;
2632
+ var typeListeners = this._listeners[event.type];
2633
+ if (typeListeners != undefined) {
2634
+ var length = typeListeners.length;
2635
+ for (var i = 0; i < length; i += 1) {
2636
+ var listener = typeListeners[i];
2637
+ try {
2638
+ if (typeof listener.handleEvent === "function") {
2639
+ listener.handleEvent(event);
2640
+ } else {
2641
+ listener.call(this, event);
2642
+ }
2643
+ } catch (e) {
2644
+ throwError(e);
2645
+ }
2646
+ }
2647
+ }
2648
+ };
2649
+ EventTarget.prototype.addEventListener = function (type, listener) {
2650
+ type = String(type);
2651
+ var listeners = this._listeners;
2652
+ var typeListeners = listeners[type];
2653
+ if (typeListeners == undefined) {
2654
+ typeListeners = [];
2655
+ listeners[type] = typeListeners;
2656
+ }
2657
+ var found = false;
2658
+ for (var i = 0; i < typeListeners.length; i += 1) {
2659
+ if (typeListeners[i] === listener) {
2660
+ found = true;
2661
+ }
2662
+ }
2663
+ if (!found) {
2664
+ typeListeners.push(listener);
2665
+ }
2666
+ };
2667
+ EventTarget.prototype.removeEventListener = function (type, listener) {
2668
+ type = String(type);
2669
+ var listeners = this._listeners;
2670
+ var typeListeners = listeners[type];
2671
+ if (typeListeners != undefined) {
2672
+ var filtered = [];
2673
+ for (var i = 0; i < typeListeners.length; i += 1) {
2674
+ if (typeListeners[i] !== listener) {
2675
+ filtered.push(typeListeners[i]);
2676
+ }
2677
+ }
2678
+ if (filtered.length === 0) {
2679
+ delete listeners[type];
2680
+ } else {
2681
+ listeners[type] = filtered;
2682
+ }
2683
+ }
2684
+ };
2685
+
2686
+ function Event(type) {
2687
+ this.type = type;
2688
+ this.target = undefined;
2689
+ }
2690
+
2691
+ function MessageEvent(type, options) {
2692
+ Event.call(this, type);
2693
+ this.data = options.data;
2694
+ this.lastEventId = options.lastEventId;
2695
+ }
2696
+
2697
+ MessageEvent.prototype = Object.create(Event.prototype);
2698
+
2699
+ function ConnectionEvent(type, options) {
2700
+ Event.call(this, type);
2701
+ this.status = options.status;
2702
+ this.statusText = options.statusText;
2703
+ this.headers = options.headers;
2704
+ }
2705
+
2706
+ ConnectionEvent.prototype = Object.create(Event.prototype);
2707
+
2708
+ function ErrorEvent(type, options) {
2709
+ Event.call(this, type);
2710
+ this.error = options.error;
2711
+ }
2712
+
2713
+ ErrorEvent.prototype = Object.create(Event.prototype);
2714
+
2715
+ var WAITING = -1;
2716
+ var CONNECTING = 0;
2717
+ var OPEN = 1;
2718
+ var CLOSED = 2;
2719
+
2720
+ var AFTER_CR = -1;
2721
+ var FIELD_START = 0;
2722
+ var FIELD = 1;
2723
+ var VALUE_START = 2;
2724
+ var VALUE = 3;
2725
+
2726
+ var contentTypeRegExp = /^text\/event\-stream(;.*)?$/i;
2727
+
2728
+ var MINIMUM_DURATION = 1000;
2729
+ var MAXIMUM_DURATION = 18000000;
2730
+
2731
+ var parseDuration = function (value, def) {
2732
+ var n = value == null ? def : parseInt(value, 10);
2733
+ if (n !== n) {
2734
+ n = def;
2735
+ }
2736
+ return clampDuration(n);
2737
+ };
2738
+ var clampDuration = function (n) {
2739
+ return Math.min(Math.max(n, MINIMUM_DURATION), MAXIMUM_DURATION);
2740
+ };
2741
+
2742
+ var fire = function (that, f, event) {
2743
+ try {
2744
+ if (typeof f === "function") {
2745
+ f.call(that, event);
2746
+ }
2747
+ } catch (e) {
2748
+ throwError(e);
2749
+ }
2750
+ };
2751
+
2752
+ function EventSourcePolyfill(url, options) {
2753
+ EventTarget.call(this);
2754
+ options = options || {};
2755
+
2756
+ this.onopen = undefined;
2757
+ this.onmessage = undefined;
2758
+ this.onerror = undefined;
2759
+
2760
+ this.url = undefined;
2761
+ this.readyState = undefined;
2762
+ this.withCredentials = undefined;
2763
+ this.headers = undefined;
2764
+
2765
+ this._close = undefined;
2766
+
2767
+ start(this, url, options);
2768
+ }
2769
+
2770
+ function getBestXHRTransport() {
2771
+ return (XMLHttpRequest != undefined && ("withCredentials" in XMLHttpRequest.prototype)) || XDomainRequest == undefined
2772
+ ? new XMLHttpRequest()
2773
+ : new XDomainRequest();
2774
+ }
2775
+
2776
+ var isFetchSupported = fetch != undefined && Response != undefined && "body" in Response.prototype;
2777
+
2778
+ function start(es, url, options) {
2779
+ url = String(url);
2780
+ var withCredentials = Boolean(options.withCredentials);
2781
+ var lastEventIdQueryParameterName = options.lastEventIdQueryParameterName || "lastEventId";
2782
+
2783
+ var initialRetry = clampDuration(1000);
2784
+ var heartbeatTimeout = parseDuration(options.heartbeatTimeout, 45000);
2785
+
2786
+ var lastEventId = "";
2787
+ var retry = initialRetry;
2788
+ var wasActivity = false;
2789
+ var textLength = 0;
2790
+ var headers = options.headers || {};
2791
+ var TransportOption = options.Transport;
2792
+ var xhr = isFetchSupported && TransportOption == undefined ? undefined : new XHRWrapper(TransportOption != undefined ? new TransportOption() : getBestXHRTransport());
2793
+ var transport = TransportOption != null && typeof TransportOption !== "string" ? new TransportOption() : (xhr == undefined ? new FetchTransport() : new XHRTransport());
2794
+ var abortController = undefined;
2795
+ var timeout = 0;
2796
+ var currentState = WAITING;
2797
+ var dataBuffer = "";
2798
+ var lastEventIdBuffer = "";
2799
+ var eventTypeBuffer = "";
2800
+
2801
+ var textBuffer = "";
2802
+ var state = FIELD_START;
2803
+ var fieldStart = 0;
2804
+ var valueStart = 0;
2805
+
2806
+ var onStart = function (status, statusText, contentType, headers) {
2807
+ if (currentState === CONNECTING) {
2808
+ if (status === 200 && contentType != undefined && contentTypeRegExp.test(contentType)) {
2809
+ currentState = OPEN;
2810
+ wasActivity = Date.now();
2811
+ retry = initialRetry;
2812
+ es.readyState = OPEN;
2813
+ var event = new ConnectionEvent("open", {
2814
+ status: status,
2815
+ statusText: statusText,
2816
+ headers: headers
2817
+ });
2818
+ es.dispatchEvent(event);
2819
+ fire(es, es.onopen, event);
2820
+ } else {
2821
+ var message = "";
2822
+ if (status !== 200) {
2823
+ if (statusText) {
2824
+ statusText = statusText.replace(/\s+/g, " ");
2825
+ }
2826
+ message = "EventSource's response has a status " + status + " " + statusText + " that is not 200. Aborting the connection.";
2827
+ } else {
2828
+ message = "EventSource's response has a Content-Type specifying an unsupported type: " + (contentType == undefined ? "-" : contentType.replace(/\s+/g, " ")) + ". Aborting the connection.";
2829
+ }
2830
+ close();
2831
+ var event = new ConnectionEvent("error", {
2832
+ status: status,
2833
+ statusText: statusText,
2834
+ headers: headers
2835
+ });
2836
+ es.dispatchEvent(event);
2837
+ fire(es, es.onerror, event);
2838
+ console.error(message);
2839
+ }
2840
+ }
2841
+ };
2842
+
2843
+ var onProgress = function (textChunk) {
2844
+ if (currentState === OPEN) {
2845
+ var n = -1;
2846
+ for (var i = 0; i < textChunk.length; i += 1) {
2847
+ var c = textChunk.charCodeAt(i);
2848
+ if (c === "\n".charCodeAt(0) || c === "\r".charCodeAt(0)) {
2849
+ n = i;
2850
+ }
2851
+ }
2852
+ var chunk = (n !== -1 ? textBuffer : "") + textChunk.slice(0, n + 1);
2853
+ textBuffer = (n === -1 ? textBuffer : "") + textChunk.slice(n + 1);
2854
+ if (textChunk !== "") {
2855
+ wasActivity = Date.now();
2856
+ textLength += textChunk.length;
2857
+ }
2858
+ for (var position = 0; position < chunk.length; position += 1) {
2859
+ var c = chunk.charCodeAt(position);
2860
+ if (state === AFTER_CR && c === "\n".charCodeAt(0)) {
2861
+ state = FIELD_START;
2862
+ } else {
2863
+ if (state === AFTER_CR) {
2864
+ state = FIELD_START;
2865
+ }
2866
+ if (c === "\r".charCodeAt(0) || c === "\n".charCodeAt(0)) {
2867
+ if (state !== FIELD_START) {
2868
+ if (state === FIELD) {
2869
+ valueStart = position + 1;
2870
+ }
2871
+ var field = chunk.slice(fieldStart, valueStart - 1);
2872
+ var value = chunk.slice(valueStart + (valueStart < position && chunk.charCodeAt(valueStart) === " ".charCodeAt(0) ? 1 : 0), position);
2873
+ if (field === "data") {
2874
+ dataBuffer += "\n";
2875
+ dataBuffer += value;
2876
+ } else if (field === "id") {
2877
+ lastEventIdBuffer = value;
2878
+ } else if (field === "event") {
2879
+ eventTypeBuffer = value;
2880
+ } else if (field === "retry") {
2881
+ initialRetry = parseDuration(value, initialRetry);
2882
+ retry = initialRetry;
2883
+ } else if (field === "heartbeatTimeout") {
2884
+ heartbeatTimeout = parseDuration(value, heartbeatTimeout);
2885
+ if (timeout !== 0) {
2886
+ clearTimeout(timeout);
2887
+ timeout = setTimeout(function () {
2888
+ onTimeout();
2889
+ }, heartbeatTimeout);
2890
+ }
2891
+ }
2892
+ }
2893
+ if (state === FIELD_START) {
2894
+ if (dataBuffer !== "") {
2895
+ lastEventId = lastEventIdBuffer;
2896
+ if (eventTypeBuffer === "") {
2897
+ eventTypeBuffer = "message";
2898
+ }
2899
+ var event = new MessageEvent(eventTypeBuffer, {
2900
+ data: dataBuffer.slice(1),
2901
+ lastEventId: lastEventIdBuffer
2902
+ });
2903
+ es.dispatchEvent(event);
2904
+ if (eventTypeBuffer === "open") {
2905
+ fire(es, es.onopen, event);
2906
+ } else if (eventTypeBuffer === "message") {
2907
+ fire(es, es.onmessage, event);
2908
+ } else if (eventTypeBuffer === "error") {
2909
+ fire(es, es.onerror, event);
2910
+ }
2911
+ if (currentState === CLOSED) {
2912
+ return;
2913
+ }
2914
+ }
2915
+ dataBuffer = "";
2916
+ eventTypeBuffer = "";
2917
+ }
2918
+ state = c === "\r".charCodeAt(0) ? AFTER_CR : FIELD_START;
2919
+ } else {
2920
+ if (state === FIELD_START) {
2921
+ fieldStart = position;
2922
+ state = FIELD;
2923
+ }
2924
+ if (state === FIELD) {
2925
+ if (c === ":".charCodeAt(0)) {
2926
+ valueStart = position + 1;
2927
+ state = VALUE_START;
2928
+ }
2929
+ } else if (state === VALUE_START) {
2930
+ state = VALUE;
2931
+ }
2932
+ }
2933
+ }
2934
+ }
2935
+ }
2936
+ };
2937
+
2938
+ var onFinish = function (error) {
2939
+ if (currentState === OPEN || currentState === CONNECTING) {
2940
+ currentState = WAITING;
2941
+ if (timeout !== 0) {
2942
+ clearTimeout(timeout);
2943
+ timeout = 0;
2944
+ }
2945
+ timeout = setTimeout(function () {
2946
+ onTimeout();
2947
+ }, retry);
2948
+ retry = clampDuration(Math.min(initialRetry * 16, retry * 2));
2949
+
2950
+ es.readyState = CONNECTING;
2951
+ var event = new ErrorEvent("error", {error: error});
2952
+ es.dispatchEvent(event);
2953
+ fire(es, es.onerror, event);
2954
+ if (error != undefined) {
2955
+ console.error(error);
2956
+ }
2957
+ }
2958
+ };
2959
+
2960
+ var close = function () {
2961
+ currentState = CLOSED;
2962
+ if (abortController != undefined) {
2963
+ abortController.abort();
2964
+ abortController = undefined;
2965
+ }
2966
+ if (timeout !== 0) {
2967
+ clearTimeout(timeout);
2968
+ timeout = 0;
2969
+ }
2970
+ es.readyState = CLOSED;
2971
+ };
2972
+
2973
+ var onTimeout = function () {
2974
+ timeout = 0;
2975
+
2976
+ if (currentState !== WAITING) {
2977
+ if (!wasActivity && abortController != undefined) {
2978
+ onFinish(new Error("No activity within " + heartbeatTimeout + " milliseconds." + " " + (currentState === CONNECTING ? "No response received." : textLength + " chars received.") + " " + "Reconnecting."));
2979
+ if (abortController != undefined) {
2980
+ abortController.abort();
2981
+ abortController = undefined;
2982
+ }
2983
+ } else {
2984
+ var nextHeartbeat = Math.max((wasActivity || Date.now()) + heartbeatTimeout - Date.now(), 1);
2985
+ wasActivity = false;
2986
+ timeout = setTimeout(function () {
2987
+ onTimeout();
2988
+ }, nextHeartbeat);
2989
+ }
2990
+ return;
2991
+ }
2992
+
2993
+ wasActivity = false;
2994
+ textLength = 0;
2995
+ timeout = setTimeout(function () {
2996
+ onTimeout();
2997
+ }, heartbeatTimeout);
2998
+
2999
+ currentState = CONNECTING;
3000
+ dataBuffer = "";
3001
+ eventTypeBuffer = "";
3002
+ lastEventIdBuffer = lastEventId;
3003
+ textBuffer = "";
3004
+ fieldStart = 0;
3005
+ valueStart = 0;
3006
+ state = FIELD_START;
3007
+
3008
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=428916
3009
+ // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
3010
+ var requestURL = url;
3011
+ if (url.slice(0, 5) !== "data:" && url.slice(0, 5) !== "blob:") {
3012
+ if (lastEventId !== "") {
3013
+ // Remove the lastEventId parameter if it's already part of the request URL.
3014
+ var i = url.indexOf("?");
3015
+ requestURL = i === -1 ? url : url.slice(0, i + 1) + url.slice(i + 1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g, function (p, paramName) {
3016
+ return paramName === lastEventIdQueryParameterName ? '' : p;
3017
+ });
3018
+ // Append the current lastEventId to the request URL.
3019
+ requestURL += (url.indexOf("?") === -1 ? "?" : "&") + lastEventIdQueryParameterName +"=" + encodeURIComponent(lastEventId);
3020
+ }
3021
+ }
3022
+ var withCredentials = es.withCredentials;
3023
+ var requestHeaders = {};
3024
+ requestHeaders["Accept"] = "text/event-stream";
3025
+ var headers = es.headers;
3026
+ if (headers != undefined) {
3027
+ for (var name in headers) {
3028
+ if (Object.prototype.hasOwnProperty.call(headers, name)) {
3029
+ requestHeaders[name] = headers[name];
3030
+ }
3031
+ }
3032
+ }
3033
+ try {
3034
+ abortController = transport.open(xhr, onStart, onProgress, onFinish, requestURL, withCredentials, requestHeaders);
3035
+ } catch (error) {
3036
+ close();
3037
+ throw error;
3038
+ }
3039
+ };
3040
+
3041
+ es.url = url;
3042
+ es.readyState = CONNECTING;
3043
+ es.withCredentials = withCredentials;
3044
+ es.headers = headers;
3045
+ es._close = close;
3046
+
3047
+ onTimeout();
3048
+ }
3049
+
3050
+ EventSourcePolyfill.prototype = Object.create(EventTarget.prototype);
3051
+ EventSourcePolyfill.prototype.CONNECTING = CONNECTING;
3052
+ EventSourcePolyfill.prototype.OPEN = OPEN;
3053
+ EventSourcePolyfill.prototype.CLOSED = CLOSED;
3054
+ EventSourcePolyfill.prototype.close = function () {
3055
+ this._close();
3056
+ };
3057
+
3058
+ EventSourcePolyfill.CONNECTING = CONNECTING;
3059
+ EventSourcePolyfill.OPEN = OPEN;
3060
+ EventSourcePolyfill.CLOSED = CLOSED;
3061
+ EventSourcePolyfill.prototype.withCredentials = undefined;
3062
+
3063
+ var R = NativeEventSource;
3064
+ if (XMLHttpRequest != undefined && (NativeEventSource == undefined || !("withCredentials" in NativeEventSource.prototype))) {
3065
+ // Why replace a native EventSource ?
3066
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=444328
3067
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=831392
3068
+ // https://code.google.com/p/chromium/issues/detail?id=260144
3069
+ // https://code.google.com/p/chromium/issues/detail?id=225654
3070
+ // ...
3071
+ R = EventSourcePolyfill;
3072
+ }
3073
+
3074
+ (function (factory) {
3075
+ {
3076
+ var v = factory(exports);
3077
+ if (v !== undefined) module.exports = v;
3078
+ }
3079
+ })(function (exports) {
3080
+ exports.EventSourcePolyfill = EventSourcePolyfill;
3081
+ exports.NativeEventSource = NativeEventSource;
3082
+ exports.EventSource = R;
3083
+ });
3084
+ }(typeof globalThis === 'undefined' ? (typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal) : globalThis));
3085
+ } (eventsource, eventsourceExports));
3086
+
3087
+ /* eslint-disable no-var */
3088
+
3089
+ var evs = eventsourceExports;
3090
+
3091
+ var browser = evs.EventSourcePolyfill;
3092
+
3093
+ var envMiddleware = [];
3094
+ class ClientError extends Error {
3095
+ constructor(res) {
3096
+ const props = extractErrorProps(res);
3097
+ super(props.message);
3098
+ this.statusCode = 400;
3099
+ Object.assign(this, props);
3100
+ }
3101
+ }
3102
+ class ServerError extends Error {
3103
+ constructor(res) {
3104
+ const props = extractErrorProps(res);
3105
+ super(props.message);
3106
+ this.statusCode = 500;
3107
+ Object.assign(this, props);
3108
+ }
3109
+ }
3110
+ function extractErrorProps(res) {
3111
+ const body = res.body;
3112
+ const props = {
3113
+ response: res,
3114
+ statusCode: res.statusCode,
3115
+ responseBody: stringifyBody(body, res),
3116
+ message: "",
3117
+ details: void 0
3118
+ };
3119
+ if (body.error && body.message) {
3120
+ props.message = "".concat(body.error, " - ").concat(body.message);
3121
+ return props;
3122
+ }
3123
+ if (body.error && body.error.description) {
3124
+ props.message = body.error.description;
3125
+ props.details = body.error;
3126
+ return props;
3127
+ }
3128
+ props.message = body.error || body.message || httpErrorMessage(res);
3129
+ return props;
3130
+ }
3131
+ function httpErrorMessage(res) {
3132
+ const statusMessage = res.statusMessage ? " ".concat(res.statusMessage) : "";
3133
+ return "".concat(res.method, "-request to ").concat(res.url, " resulted in HTTP ").concat(res.statusCode).concat(statusMessage);
3134
+ }
3135
+ function stringifyBody(body, res) {
3136
+ const contentType = (res.headers["content-type"] || "").toLowerCase();
3137
+ const isJson = contentType.indexOf("application/json") !== -1;
3138
+ return isJson ? JSON.stringify(body, null, 2) : body;
3139
+ }
3140
+ const httpError = {
3141
+ onResponse: res => {
3142
+ if (res.statusCode >= 500) {
3143
+ throw new ServerError(res);
3144
+ } else if (res.statusCode >= 400) {
3145
+ throw new ClientError(res);
3146
+ }
3147
+ return res;
3148
+ }
3149
+ };
3150
+ const printWarnings = {
3151
+ onResponse: res => {
3152
+ const warn = res.headers["x-sanity-warning"];
3153
+ const warnings = Array.isArray(warn) ? warn : [warn];
3154
+ warnings.filter(Boolean).forEach(msg => console.warn(msg));
3155
+ return res;
3156
+ }
3157
+ };
3158
+ function defineHttpRequest(envMiddleware) {
3159
+ const request = getIt([...envMiddleware, printWarnings, jsonRequest(), jsonResponse(), progress(), httpError, observable$1({
3160
+ implementation: Observable
3161
+ })]);
3162
+ function httpRequest(options) {
3163
+ let requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : request;
3164
+ return requester({
3165
+ maxRedirects: 0,
3166
+ ...options
3167
+ });
3168
+ }
3169
+ httpRequest.defaultRequester = request;
3170
+ return httpRequest;
3171
+ }
3172
+ const projectHeader = "X-Sanity-Project-ID";
3173
+ function requestOptions(config) {
3174
+ let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3175
+ const headers = {};
3176
+ const token = overrides.token || config.token;
3177
+ if (token) {
3178
+ headers.Authorization = "Bearer ".concat(token);
3179
+ }
3180
+ if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
3181
+ headers[projectHeader] = config.projectId;
3182
+ }
3183
+ const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
3184
+ const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
3185
+ return Object.assign({}, overrides, {
3186
+ headers: Object.assign({}, headers, overrides.headers || {}),
3187
+ timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
3188
+ proxy: overrides.proxy || config.proxy,
3189
+ json: true,
3190
+ withCredentials
3191
+ });
3192
+ }
3193
+ function getSelection(sel) {
3194
+ if (typeof sel === "string" || Array.isArray(sel)) {
3195
+ return {
3196
+ id: sel
3197
+ };
3198
+ }
3199
+ if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
3200
+ return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
3201
+ query: sel.query,
3202
+ params: sel.params
3203
+ } : {
3204
+ query: sel.query
3205
+ };
3206
+ }
3207
+ const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
3208
+ throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
3209
+ }
3210
+ const VALID_ASSET_TYPES = ["image", "file"];
3211
+ const VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
3212
+ const dataset = name => {
3213
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
3214
+ throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
3215
+ }
3216
+ };
3217
+ const projectId = id => {
3218
+ if (!/^[-a-z0-9]+$/i.test(id)) {
3219
+ throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
3220
+ }
3221
+ };
3222
+ const validateAssetType = type => {
3223
+ if (VALID_ASSET_TYPES.indexOf(type) === -1) {
3224
+ throw new Error("Invalid asset type: ".concat(type, ". Must be one of ").concat(VALID_ASSET_TYPES.join(", ")));
3225
+ }
3226
+ };
3227
+ const validateObject = (op, val) => {
3228
+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
3229
+ throw new Error("".concat(op, "() takes an object of properties"));
3230
+ }
3231
+ };
3232
+ const validateDocumentId = (op, id) => {
3233
+ if (typeof id !== "string" || !/^[a-z0-9_.-]+$/i.test(id)) {
3234
+ throw new Error("".concat(op, "(): \"").concat(id, "\" is not a valid document ID"));
3235
+ }
3236
+ };
3237
+ const requireDocumentId = (op, doc) => {
3238
+ if (!doc._id) {
3239
+ throw new Error("".concat(op, "() requires that the document contains an ID (\"_id\" property)"));
3240
+ }
3241
+ validateDocumentId(op, doc._id);
3242
+ };
3243
+ const validateInsert = (at, selector, items) => {
3244
+ const signature = "insert(at, selector, items)";
3245
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
3246
+ const valid = VALID_INSERT_LOCATIONS.map(loc => "\"".concat(loc, "\"")).join(", ");
3247
+ throw new Error("".concat(signature, " takes an \"at\"-argument which is one of: ").concat(valid));
3248
+ }
3249
+ if (typeof selector !== "string") {
3250
+ throw new Error("".concat(signature, " takes a \"selector\"-argument which must be a string"));
3251
+ }
3252
+ if (!Array.isArray(items)) {
3253
+ throw new Error("".concat(signature, " takes an \"items\"-argument which must be an array"));
3254
+ }
3255
+ };
3256
+ const hasDataset = config => {
3257
+ if (!config.dataset) {
3258
+ throw new Error("`dataset` must be provided to perform queries");
3259
+ }
3260
+ return config.dataset || "";
3261
+ };
3262
+ const requestTag = tag => {
3263
+ if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
3264
+ throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
3265
+ }
3266
+ return tag;
3267
+ };
3268
+ const encodeQueryString = _ref => {
3269
+ let {
3270
+ query,
3271
+ params = {},
3272
+ options = {}
3273
+ } = _ref;
3274
+ const searchParams = new URLSearchParams();
3275
+ const {
3276
+ tag,
3277
+ ...opts
3278
+ } = options;
3279
+ if (tag) searchParams.set("tag", tag);
3280
+ searchParams.set("query", query);
3281
+ for (const [key, value] of Object.entries(params)) {
3282
+ searchParams.set("$".concat(key), JSON.stringify(value));
3283
+ }
3284
+ for (const [key, value] of Object.entries(opts)) {
3285
+ if (value) searchParams.set(key, "".concat(value));
3286
+ }
3287
+ return "?".concat(searchParams);
3288
+ };
3289
+ var __accessCheck$6 = (obj, member, msg) => {
3290
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
3291
+ };
3292
+ var __privateGet$6 = (obj, member, getter) => {
3293
+ __accessCheck$6(obj, member, "read from private field");
3294
+ return getter ? getter.call(obj) : member.get(obj);
3295
+ };
3296
+ var __privateAdd$6 = (obj, member, value) => {
3297
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
3298
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3299
+ };
3300
+ var __privateSet$6 = (obj, member, value, setter) => {
3301
+ __accessCheck$6(obj, member, "write to private field");
3302
+ setter ? setter.call(obj, value) : member.set(obj, value);
3303
+ return value;
3304
+ };
3305
+ var _client$5, _client2$5;
3306
+ class BasePatch {
3307
+ constructor(selection) {
3308
+ let operations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3309
+ this.selection = selection;
3310
+ this.operations = operations;
3311
+ }
3312
+ /**
3313
+ * Sets the given attributes to the document. Does NOT merge objects.
3314
+ * The operation is added to the current patch, ready to be commited by `commit()`
3315
+ *
3316
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
3317
+ */
3318
+ set(attrs) {
3319
+ return this._assign("set", attrs);
3320
+ }
3321
+ /**
3322
+ * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
3323
+ * The operation is added to the current patch, ready to be commited by `commit()`
3324
+ *
3325
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
3326
+ */
3327
+ setIfMissing(attrs) {
3328
+ return this._assign("setIfMissing", attrs);
3329
+ }
3330
+ /**
3331
+ * Performs a "diff-match-patch" operation on the string attributes provided.
3332
+ * The operation is added to the current patch, ready to be commited by `commit()`
3333
+ *
3334
+ * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
3335
+ */
3336
+ diffMatchPatch(attrs) {
3337
+ validateObject("diffMatchPatch", attrs);
3338
+ return this._assign("diffMatchPatch", attrs);
3339
+ }
3340
+ /**
3341
+ * Unsets the attribute paths provided.
3342
+ * The operation is added to the current patch, ready to be commited by `commit()`
3343
+ *
3344
+ * @param attrs - Attribute paths to unset.
3345
+ */
3346
+ unset(attrs) {
3347
+ if (!Array.isArray(attrs)) {
3348
+ throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
3349
+ }
3350
+ this.operations = Object.assign({}, this.operations, {
3351
+ unset: attrs
3352
+ });
3353
+ return this;
3354
+ }
3355
+ /**
3356
+ * 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.
3357
+ *
3358
+ * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
3359
+ */
3360
+ inc(attrs) {
3361
+ return this._assign("inc", attrs);
3362
+ }
3363
+ /**
3364
+ * 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.
3365
+ *
3366
+ * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
3367
+ */
3368
+ dec(attrs) {
3369
+ return this._assign("dec", attrs);
3370
+ }
3371
+ /**
3372
+ * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
3373
+ *
3374
+ * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
3375
+ * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
3376
+ * @param items - Array of items to insert/replace
3377
+ */
3378
+ insert(at, selector, items) {
3379
+ validateInsert(at, selector, items);
3380
+ return this._assign("insert", {
3381
+ [at]: selector,
3382
+ items
3383
+ });
3384
+ }
3385
+ /**
3386
+ * Append the given items to the array at the given JSONPath
3387
+ *
3388
+ * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
3389
+ * @param items - Array of items to append to the array
3390
+ */
3391
+ append(selector, items) {
3392
+ return this.insert("after", "".concat(selector, "[-1]"), items);
3393
+ }
3394
+ /**
3395
+ * Prepend the given items to the array at the given JSONPath
3396
+ *
3397
+ * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
3398
+ * @param items - Array of items to prepend to the array
3399
+ */
3400
+ prepend(selector, items) {
3401
+ return this.insert("before", "".concat(selector, "[0]"), items);
3402
+ }
3403
+ /**
3404
+ * Change the contents of an array by removing existing elements and/or adding new elements.
3405
+ *
3406
+ * @param selector - Attribute or JSONPath expression for array
3407
+ * @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
3408
+ * @param deleteCount - An integer indicating the number of old array elements to remove.
3409
+ * @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.
3410
+ */
3411
+ splice(selector, start, deleteCount, items) {
3412
+ const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
3413
+ const startIndex = start < 0 ? start - 1 : start;
3414
+ const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
3415
+ const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
3416
+ const rangeSelector = "".concat(selector, "[").concat(startIndex, ":").concat(delRange, "]");
3417
+ return this.insert("replace", rangeSelector, items || []);
3418
+ }
3419
+ /**
3420
+ * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
3421
+ *
3422
+ * @param rev - Revision to lock the patch to
3423
+ */
3424
+ ifRevisionId(rev) {
3425
+ this.operations.ifRevisionID = rev;
3426
+ return this;
3427
+ }
3428
+ /**
3429
+ * Return a plain JSON representation of the patch
3430
+ */
3431
+ serialize() {
3432
+ return {
3433
+ ...getSelection(this.selection),
3434
+ ...this.operations
3435
+ };
3436
+ }
3437
+ /**
3438
+ * Return a plain JSON representation of the patch
3439
+ */
3440
+ toJSON() {
3441
+ return this.serialize();
3442
+ }
3443
+ /**
3444
+ * Clears the patch of all operations
3445
+ */
3446
+ reset() {
3447
+ this.operations = {};
3448
+ return this;
3449
+ }
3450
+ _assign(op, props) {
3451
+ let merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
3452
+ validateObject(op, props);
3453
+ this.operations = Object.assign({}, this.operations, {
3454
+ [op]: Object.assign({}, merge && this.operations[op] || {}, props)
3455
+ });
3456
+ return this;
3457
+ }
3458
+ _set(op, props) {
3459
+ return this._assign(op, props, false);
3460
+ }
3461
+ }
3462
+ const _ObservablePatch = class extends BasePatch {
3463
+ constructor(selection, operations, client) {
3464
+ super(selection, operations);
3465
+ __privateAdd$6(this, _client$5, void 0);
3466
+ __privateSet$6(this, _client$5, client);
3467
+ }
3468
+ /**
3469
+ * Clones the patch
3470
+ */
3471
+ clone() {
3472
+ return new _ObservablePatch(this.selection, {
3473
+ ...this.operations
3474
+ }, __privateGet$6(this, _client$5));
3475
+ }
3476
+ commit(options) {
3477
+ if (!__privateGet$6(this, _client$5)) {
3478
+ throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
3479
+ }
3480
+ const returnFirst = typeof this.selection === "string";
3481
+ const opts = Object.assign({
3482
+ returnFirst,
3483
+ returnDocuments: true
3484
+ }, options);
3485
+ return __privateGet$6(this, _client$5).mutate({
3486
+ patch: this.serialize()
3487
+ }, opts);
3488
+ }
3489
+ };
3490
+ let ObservablePatch = _ObservablePatch;
3491
+ _client$5 = new WeakMap();
3492
+ const _Patch = class extends BasePatch {
3493
+ constructor(selection, operations, client) {
3494
+ super(selection, operations);
3495
+ __privateAdd$6(this, _client2$5, void 0);
3496
+ __privateSet$6(this, _client2$5, client);
3497
+ }
3498
+ /**
3499
+ * Clones the patch
3500
+ */
3501
+ clone() {
3502
+ return new _Patch(this.selection, {
3503
+ ...this.operations
3504
+ }, __privateGet$6(this, _client2$5));
3505
+ }
3506
+ commit(options) {
3507
+ if (!__privateGet$6(this, _client2$5)) {
3508
+ throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
3509
+ }
3510
+ const returnFirst = typeof this.selection === "string";
3511
+ const opts = Object.assign({
3512
+ returnFirst,
3513
+ returnDocuments: true
3514
+ }, options);
3515
+ return __privateGet$6(this, _client2$5).mutate({
3516
+ patch: this.serialize()
3517
+ }, opts);
3518
+ }
3519
+ };
3520
+ let Patch = _Patch;
3521
+ _client2$5 = new WeakMap();
3522
+ var __accessCheck$5 = (obj, member, msg) => {
3523
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
3524
+ };
3525
+ var __privateGet$5 = (obj, member, getter) => {
3526
+ __accessCheck$5(obj, member, "read from private field");
3527
+ return getter ? getter.call(obj) : member.get(obj);
3528
+ };
3529
+ var __privateAdd$5 = (obj, member, value) => {
3530
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
3531
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3532
+ };
3533
+ var __privateSet$5 = (obj, member, value, setter) => {
3534
+ __accessCheck$5(obj, member, "write to private field");
3535
+ setter ? setter.call(obj, value) : member.set(obj, value);
3536
+ return value;
3537
+ };
3538
+ var _client$4, _client2$4;
3539
+ const defaultMutateOptions = {
3540
+ returnDocuments: false
3541
+ };
3542
+ class BaseTransaction {
3543
+ constructor() {
3544
+ let operations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3545
+ let transactionId = arguments.length > 1 ? arguments[1] : undefined;
3546
+ this.operations = operations;
3547
+ this.trxId = transactionId;
3548
+ }
3549
+ /**
3550
+ * 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.
3551
+ * The operation is added to the current transaction, ready to be commited by `commit()`
3552
+ *
3553
+ * @param doc - Document to create. Requires a `_type` property.
3554
+ */
3555
+ create(doc) {
3556
+ validateObject("create", doc);
3557
+ return this._add({
3558
+ create: doc
3559
+ });
3560
+ }
3561
+ /**
3562
+ * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
3563
+ * The operation is added to the current transaction, ready to be commited by `commit()`
3564
+ *
3565
+ * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
3566
+ */
3567
+ createIfNotExists(doc) {
3568
+ const op = "createIfNotExists";
3569
+ validateObject(op, doc);
3570
+ requireDocumentId(op, doc);
3571
+ return this._add({
3572
+ [op]: doc
3573
+ });
3574
+ }
3575
+ /**
3576
+ * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
3577
+ * The operation is added to the current transaction, ready to be commited by `commit()`
3578
+ *
3579
+ * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
3580
+ */
3581
+ createOrReplace(doc) {
3582
+ const op = "createOrReplace";
3583
+ validateObject(op, doc);
3584
+ requireDocumentId(op, doc);
3585
+ return this._add({
3586
+ [op]: doc
3587
+ });
3588
+ }
3589
+ /**
3590
+ * Deletes the document with the given document ID
3591
+ * The operation is added to the current transaction, ready to be commited by `commit()`
3592
+ *
3593
+ * @param documentId - Document ID to delete
3594
+ */
3595
+ delete(documentId) {
3596
+ validateDocumentId("delete", documentId);
3597
+ return this._add({
3598
+ delete: {
3599
+ id: documentId
3600
+ }
3601
+ });
3602
+ }
3603
+ transactionId(id) {
3604
+ if (!id) {
3605
+ return this.trxId;
3606
+ }
3607
+ this.trxId = id;
3608
+ return this;
3609
+ }
3610
+ /**
3611
+ * Return a plain JSON representation of the transaction
3612
+ */
3613
+ serialize() {
3614
+ return [...this.operations];
3615
+ }
3616
+ /**
3617
+ * Return a plain JSON representation of the transaction
3618
+ */
3619
+ toJSON() {
3620
+ return this.serialize();
3621
+ }
3622
+ /**
3623
+ * Clears the transaction of all operations
3624
+ */
3625
+ reset() {
3626
+ this.operations = [];
3627
+ return this;
3628
+ }
3629
+ _add(mut) {
3630
+ this.operations.push(mut);
3631
+ return this;
3632
+ }
3633
+ }
3634
+ const _Transaction = class extends BaseTransaction {
3635
+ constructor(operations, client, transactionId) {
3636
+ super(operations, transactionId);
3637
+ __privateAdd$5(this, _client$4, void 0);
3638
+ __privateSet$5(this, _client$4, client);
3639
+ }
3640
+ /**
3641
+ * Clones the transaction
3642
+ */
3643
+ clone() {
3644
+ return new _Transaction([...this.operations], __privateGet$5(this, _client$4), this.trxId);
3645
+ }
3646
+ commit(options) {
3647
+ if (!__privateGet$5(this, _client$4)) {
3648
+ throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
3649
+ }
3650
+ return __privateGet$5(this, _client$4).mutate(this.serialize(), Object.assign({
3651
+ transactionId: this.trxId
3652
+ }, defaultMutateOptions, options || {}));
3653
+ }
3654
+ patch(patchOrDocumentId, patchOps) {
3655
+ const isBuilder = typeof patchOps === "function";
3656
+ const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof Patch;
3657
+ if (isPatch) {
3658
+ return this._add({
3659
+ patch: patchOrDocumentId.serialize()
3660
+ });
3661
+ }
3662
+ if (isBuilder) {
3663
+ const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$5(this, _client$4)));
3664
+ if (!(patch instanceof Patch)) {
3665
+ throw new Error("function passed to `patch()` must return the patch");
3666
+ }
3667
+ return this._add({
3668
+ patch: patch.serialize()
3669
+ });
3670
+ }
3671
+ return this._add({
3672
+ patch: {
3673
+ id: patchOrDocumentId,
3674
+ ...patchOps
3675
+ }
3676
+ });
3677
+ }
3678
+ };
3679
+ let Transaction = _Transaction;
3680
+ _client$4 = new WeakMap();
3681
+ const _ObservableTransaction = class extends BaseTransaction {
3682
+ constructor(operations, client, transactionId) {
3683
+ super(operations, transactionId);
3684
+ __privateAdd$5(this, _client2$4, void 0);
3685
+ __privateSet$5(this, _client2$4, client);
3686
+ }
3687
+ /**
3688
+ * Clones the transaction
3689
+ */
3690
+ clone() {
3691
+ return new _ObservableTransaction([...this.operations], __privateGet$5(this, _client2$4), this.trxId);
3692
+ }
3693
+ commit(options) {
3694
+ if (!__privateGet$5(this, _client2$4)) {
3695
+ throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
3696
+ }
3697
+ return __privateGet$5(this, _client2$4).mutate(this.serialize(), Object.assign({
3698
+ transactionId: this.trxId
3699
+ }, defaultMutateOptions, options || {}));
3700
+ }
3701
+ patch(patchOrDocumentId, patchOps) {
3702
+ const isBuilder = typeof patchOps === "function";
3703
+ const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof ObservablePatch;
3704
+ if (isPatch) {
3705
+ return this._add({
3706
+ patch: patchOrDocumentId.serialize()
3707
+ });
3708
+ }
3709
+ if (isBuilder) {
3710
+ const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$5(this, _client2$4)));
3711
+ if (!(patch instanceof ObservablePatch)) {
3712
+ throw new Error("function passed to `patch()` must return the patch");
3713
+ }
3714
+ return this._add({
3715
+ patch: patch.serialize()
3716
+ });
3717
+ }
3718
+ return this._add({
3719
+ patch: {
3720
+ id: patchOrDocumentId,
3721
+ ...patchOps
3722
+ }
3723
+ });
3724
+ }
3725
+ };
3726
+ let ObservableTransaction = _ObservableTransaction;
3727
+ _client2$4 = new WeakMap();
3728
+ const excludeFalsey = (param, defValue) => {
3729
+ const value = typeof param === "undefined" ? defValue : param;
3730
+ return param === false ? void 0 : value;
3731
+ };
3732
+ const getMutationQuery = function () {
3733
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3734
+ return {
3735
+ dryRun: options.dryRun,
3736
+ returnIds: true,
3737
+ returnDocuments: excludeFalsey(options.returnDocuments, true),
3738
+ visibility: options.visibility || "sync",
3739
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
3740
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
3741
+ };
3742
+ };
3743
+ const isResponse = event => event.type === "response";
3744
+ const getBody = event => event.body;
3745
+ const indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
3746
+ indexed[attr(doc)] = doc;
3747
+ return indexed;
3748
+ }, /* @__PURE__ */Object.create(null));
3749
+ const getQuerySizeLimit = 11264;
3750
+ function _fetch(client, httpRequest, query, params) {
3751
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
3752
+ const mapResponse = options.filterResponse === false ? res => res : res => res.result;
3753
+ return _dataRequest(client, httpRequest, "query", {
3754
+ query,
3755
+ params
3756
+ }, options).pipe(map(mapResponse));
3757
+ }
3758
+ function _getDocument(client, httpRequest, id) {
3759
+ let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3760
+ const options = {
3761
+ uri: _getDataUrl(client, "doc", id),
3762
+ json: true,
3763
+ tag: opts.tag
3764
+ };
3765
+ return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => event.body.documents && event.body.documents[0]));
3766
+ }
3767
+ function _getDocuments(client, httpRequest, ids) {
3768
+ let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3769
+ const options = {
3770
+ uri: _getDataUrl(client, "doc", ids.join(",")),
3771
+ json: true,
3772
+ tag: opts.tag
3773
+ };
3774
+ return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => {
3775
+ const indexed = indexBy(event.body.documents || [], doc => doc._id);
3776
+ return ids.map(id => indexed[id] || null);
3777
+ }));
3778
+ }
3779
+ function _createIfNotExists(client, httpRequest, doc, options) {
3780
+ requireDocumentId("createIfNotExists", doc);
3781
+ return _create(client, httpRequest, doc, "createIfNotExists", options);
3782
+ }
3783
+ function _createOrReplace(client, httpRequest, doc, options) {
3784
+ requireDocumentId("createOrReplace", doc);
3785
+ return _create(client, httpRequest, doc, "createOrReplace", options);
3786
+ }
3787
+ function _delete(client, httpRequest, selection, options) {
3788
+ return _dataRequest(client, httpRequest, "mutate", {
3789
+ mutations: [{
3790
+ delete: getSelection(selection)
3791
+ }]
3792
+ }, options);
3793
+ }
3794
+ function _mutate(client, httpRequest, mutations, options) {
3795
+ const mut = mutations instanceof Patch || mutations instanceof ObservablePatch || mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mutations.serialize() : mutations;
3796
+ const muts = Array.isArray(mut) ? mut : [mut];
3797
+ const transactionId = options && options.transactionId;
3798
+ return _dataRequest(client, httpRequest, "mutate", {
3799
+ mutations: muts,
3800
+ transactionId
3801
+ }, options);
3802
+ }
3803
+ function _dataRequest(client, httpRequest, endpoint, body) {
3804
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
3805
+ const isMutation = endpoint === "mutate";
3806
+ const isQuery = endpoint === "query";
3807
+ const strQuery = isMutation ? "" : encodeQueryString(body);
3808
+ const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
3809
+ const stringQuery = useGet ? strQuery : "";
3810
+ const returnFirst = options.returnFirst;
3811
+ const {
3812
+ timeout,
3813
+ token,
3814
+ tag,
3815
+ headers
3816
+ } = options;
3817
+ const uri = _getDataUrl(client, endpoint, stringQuery);
3818
+ const reqOptions = {
3819
+ method: useGet ? "GET" : "POST",
3820
+ uri,
3821
+ json: true,
3822
+ body: useGet ? void 0 : body,
3823
+ query: isMutation && getMutationQuery(options),
3824
+ timeout,
3825
+ headers,
3826
+ token,
3827
+ tag,
3828
+ canUseCdn: isQuery,
3829
+ signal: options.signal
3830
+ };
3831
+ return _requestObservable(client, httpRequest, reqOptions).pipe(filter(isResponse), map(getBody), map(res => {
3832
+ if (!isMutation) {
3833
+ return res;
3834
+ }
3835
+ const results = res.results || [];
3836
+ if (options.returnDocuments) {
3837
+ return returnFirst ? results[0] && results[0].document : results.map(mut => mut.document);
3838
+ }
3839
+ const key = returnFirst ? "documentId" : "documentIds";
3840
+ const ids = returnFirst ? results[0] && results[0].id : results.map(mut => mut.id);
3841
+ return {
3842
+ transactionId: res.transactionId,
3843
+ results,
3844
+ [key]: ids
3845
+ };
3846
+ }));
3847
+ }
3848
+ function _create(client, httpRequest, doc, op) {
3849
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
3850
+ const mutation = {
3851
+ [op]: doc
3852
+ };
3853
+ const opts = Object.assign({
3854
+ returnFirst: true,
3855
+ returnDocuments: true
3856
+ }, options);
3857
+ return _dataRequest(client, httpRequest, "mutate", {
3858
+ mutations: [mutation]
3859
+ }, opts);
3860
+ }
3861
+ function _requestObservable(client, httpRequest, options) {
3862
+ const uri = options.url || options.uri;
3863
+ const config = client.config();
3864
+ const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
3865
+ const useCdn = config.useCdn && canUseCdn;
3866
+ const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
3867
+ if (tag) {
3868
+ options.query = {
3869
+ tag: requestTag(tag),
3870
+ ...options.query
3871
+ };
3872
+ }
3873
+ if (config.unstable_overlayDrafts) {
3874
+ if (config.apiVersion !== "X") {
3875
+ console.error("You need to set `apiVersion` to `X` to use `unstable_overlayDrafts");
3876
+ }
3877
+ options.query = {
3878
+ overlayDrafts: true,
3879
+ ...options.query
3880
+ };
3881
+ }
3882
+ const reqOptions = requestOptions(config, Object.assign({}, options, {
3883
+ url: _getUrl(client, uri, useCdn)
3884
+ }));
3885
+ const request = new Observable(subscriber =>
3886
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- the typings thinks it's optional because it's not required to specify it when calling createClient, but it's always defined in practice since SanityClient provides a default
3887
+ httpRequest(reqOptions, config.requester).subscribe(subscriber));
3888
+ return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
3889
+ }
3890
+ function _request(client, httpRequest, options) {
3891
+ const observable = _requestObservable(client, httpRequest, options).pipe(filter(event => event.type === "response"), map(event => event.body));
3892
+ return observable;
3893
+ }
3894
+ function _getDataUrl(client, operation, path) {
3895
+ const config = client.config();
3896
+ const catalog = hasDataset(config);
3897
+ const baseUri = "/".concat(operation, "/").concat(catalog);
3898
+ const uri = path ? "".concat(baseUri, "/").concat(path) : baseUri;
3899
+ return "/data".concat(uri).replace(/\/($|\?)/, "$1");
3900
+ }
3901
+ function _getUrl(client, uri) {
3902
+ let canUseCdn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
3903
+ const {
3904
+ url,
3905
+ cdnUrl
3906
+ } = client.config();
3907
+ const base = canUseCdn ? cdnUrl : url;
3908
+ return "".concat(base, "/").concat(uri.replace(/^\//, ""));
3909
+ }
3910
+ function _withAbortSignal(signal) {
3911
+ return input => {
3912
+ return new Observable(observer => {
3913
+ const abort = () => observer.error(_createAbortError(signal));
3914
+ if (signal && signal.aborted) {
3915
+ abort();
3916
+ return;
3917
+ }
3918
+ const subscription = input.subscribe(observer);
3919
+ signal.addEventListener("abort", abort);
3920
+ return () => {
3921
+ signal.removeEventListener("abort", abort);
3922
+ subscription.unsubscribe();
3923
+ };
3924
+ });
3925
+ };
3926
+ }
3927
+ const isDomExceptionSupported = Boolean(globalThis.DOMException);
3928
+ function _createAbortError(signal) {
3929
+ var _a, _b;
3930
+ if (isDomExceptionSupported) {
3931
+ return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
3932
+ }
3933
+ const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
3934
+ error.name = "AbortError";
3935
+ return error;
3936
+ }
3937
+ var __accessCheck$4 = (obj, member, msg) => {
3938
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
3939
+ };
3940
+ var __privateGet$4 = (obj, member, getter) => {
3941
+ __accessCheck$4(obj, member, "read from private field");
3942
+ return getter ? getter.call(obj) : member.get(obj);
3943
+ };
3944
+ var __privateAdd$4 = (obj, member, value) => {
3945
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
3946
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3947
+ };
3948
+ var __privateSet$4 = (obj, member, value, setter) => {
3949
+ __accessCheck$4(obj, member, "write to private field");
3950
+ setter ? setter.call(obj, value) : member.set(obj, value);
3951
+ return value;
3952
+ };
3953
+ var _client$3, _httpRequest$4, _client2$3, _httpRequest2$4;
3954
+ class ObservableAssetsClient {
3955
+ constructor(client, httpRequest) {
3956
+ __privateAdd$4(this, _client$3, void 0);
3957
+ __privateAdd$4(this, _httpRequest$4, void 0);
3958
+ __privateSet$4(this, _client$3, client);
3959
+ __privateSet$4(this, _httpRequest$4, httpRequest);
3960
+ }
3961
+ upload(assetType, body, options) {
3962
+ return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
3963
+ }
3964
+ }
3965
+ _client$3 = new WeakMap();
3966
+ _httpRequest$4 = new WeakMap();
3967
+ class AssetsClient {
3968
+ constructor(client, httpRequest) {
3969
+ __privateAdd$4(this, _client2$3, void 0);
3970
+ __privateAdd$4(this, _httpRequest2$4, void 0);
3971
+ __privateSet$4(this, _client2$3, client);
3972
+ __privateSet$4(this, _httpRequest2$4, httpRequest);
3973
+ }
3974
+ upload(assetType, body, options) {
3975
+ const observable = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
3976
+ return lastValueFrom(observable.pipe(filter(event => event.type === "response"), map(event => event.body.document)));
3977
+ }
3978
+ }
3979
+ _client2$3 = new WeakMap();
3980
+ _httpRequest2$4 = new WeakMap();
3981
+ function _upload(client, httpRequest, assetType, body) {
3982
+ let opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
3983
+ validateAssetType(assetType);
3984
+ let meta = opts.extract || void 0;
3985
+ if (meta && !meta.length) {
3986
+ meta = ["none"];
3987
+ }
3988
+ const dataset = hasDataset(client.config());
3989
+ const assetEndpoint = assetType === "image" ? "images" : "files";
3990
+ const options = optionsFromFile(opts, body);
3991
+ const {
3992
+ tag,
3993
+ label,
3994
+ title,
3995
+ description,
3996
+ creditLine,
3997
+ filename,
3998
+ source
3999
+ } = options;
4000
+ const query = {
4001
+ label,
4002
+ title,
4003
+ description,
4004
+ filename,
4005
+ meta,
4006
+ creditLine
4007
+ };
4008
+ if (source) {
4009
+ query.sourceId = source.id;
4010
+ query.sourceName = source.name;
4011
+ query.sourceUrl = source.url;
4012
+ }
4013
+ return _requestObservable(client, httpRequest, {
4014
+ tag,
4015
+ method: "POST",
4016
+ timeout: options.timeout || 0,
4017
+ uri: "/assets/".concat(assetEndpoint, "/").concat(dataset),
4018
+ headers: options.contentType ? {
4019
+ "Content-Type": options.contentType
4020
+ } : {},
4021
+ query,
4022
+ body
4023
+ });
4024
+ }
4025
+ function optionsFromFile(opts, file) {
4026
+ if (typeof window === "undefined" || !(file instanceof window.File)) {
4027
+ return opts;
4028
+ }
4029
+ return Object.assign({
4030
+ filename: opts.preserveFilename === false ? void 0 : file.name,
4031
+ contentType: file.type
4032
+ }, opts);
4033
+ }
4034
+ const BASE_URL = "https://www.sanity.io/help/";
4035
+ function generateHelpUrl(slug) {
4036
+ return BASE_URL + slug;
4037
+ }
4038
+ function once(fn) {
4039
+ let didCall = false;
4040
+ let returnValue;
4041
+ return function () {
4042
+ if (didCall) {
4043
+ return returnValue;
4044
+ }
4045
+ returnValue = fn(...arguments);
4046
+ didCall = true;
4047
+ return returnValue;
4048
+ };
4049
+ }
4050
+ const createWarningPrinter = message =>
4051
+ // eslint-disable-next-line no-console
4052
+ once(function () {
4053
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
4054
+ args[_key] = arguments[_key];
4055
+ }
4056
+ return console.warn(message.join(" "), ...args);
4057
+ });
4058
+ 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."]);
4059
+ 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.")]);
4060
+ const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
4061
+ const printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead"]);
4062
+ const defaultCdnHost = "apicdn.sanity.io";
4063
+ const defaultConfig = {
4064
+ apiHost: "https://api.sanity.io",
4065
+ apiVersion: "1",
4066
+ useProjectHostname: true
4067
+ };
4068
+ const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
4069
+ const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
4070
+ const validateApiVersion = function validateApiVersion2(apiVersion) {
4071
+ if (apiVersion === "1" || apiVersion === "X") {
4072
+ return;
4073
+ }
4074
+ const apiDate = new Date(apiVersion);
4075
+ const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
4076
+ if (!apiVersionValid) {
4077
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
4078
+ }
4079
+ };
4080
+ const initConfig = (config, prevConfig) => {
4081
+ const specifiedConfig = Object.assign({}, prevConfig, config);
4082
+ if (!specifiedConfig.apiVersion) {
4083
+ printNoApiVersionSpecifiedWarning();
4084
+ }
4085
+ const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
4086
+ const projectBased = newConfig.useProjectHostname;
4087
+ if (typeof Promise === "undefined") {
4088
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
4089
+ throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
4090
+ }
4091
+ if (projectBased && !newConfig.projectId) {
4092
+ throw new Error("Configuration must contain `projectId`");
4093
+ }
4094
+ const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
4095
+ const isLocalhost = isBrowser && isLocal(window.location.hostname);
4096
+ if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
4097
+ printBrowserTokenWarning();
4098
+ } else if (typeof newConfig.useCdn === "undefined") {
4099
+ printCdnWarning();
4100
+ }
4101
+ if (projectBased) {
4102
+ projectId(newConfig.projectId);
4103
+ }
4104
+ if (newConfig.dataset) {
4105
+ dataset(newConfig.dataset);
4106
+ }
4107
+ if ("requestTagPrefix" in newConfig) {
4108
+ newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
4109
+ }
4110
+ newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
4111
+ newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
4112
+ newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
4113
+ validateApiVersion(newConfig.apiVersion);
4114
+ const hostParts = newConfig.apiHost.split("://", 2);
4115
+ const protocol = hostParts[0];
4116
+ const host = hostParts[1];
4117
+ const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
4118
+ if (newConfig.useProjectHostname) {
4119
+ newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
4120
+ newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
4121
+ } else {
4122
+ newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
4123
+ newConfig.cdnUrl = newConfig.url;
4124
+ }
4125
+ return newConfig;
4126
+ };
4127
+ var defaults = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
4128
+ target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
4129
+ return target;
4130
+ }, {});
4131
+ const pick = (obj, props) => props.reduce((selection, prop) => {
4132
+ if (typeof obj[prop] === "undefined") {
4133
+ return selection;
4134
+ }
4135
+ selection[prop] = obj[prop];
4136
+ return selection;
4137
+ }, {});
4138
+ const MAX_URL_LENGTH = 16e3 - 1200;
4139
+ const EventSource = browser;
4140
+ const possibleOptions = ["includePreviousRevision", "includeResult", "visibility", "effectFormat", "tag"];
4141
+ const defaultOptions = {
4142
+ includeResult: true
4143
+ };
4144
+ function _listen(query, params) {
4145
+ let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
4146
+ const {
4147
+ url,
4148
+ token,
4149
+ withCredentials,
4150
+ requestTagPrefix
4151
+ } = this.config();
4152
+ const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
4153
+ const options = {
4154
+ ...defaults(opts, defaultOptions),
4155
+ tag
4156
+ };
4157
+ const listenOpts = pick(options, possibleOptions);
4158
+ const qs = encodeQueryString({
4159
+ query,
4160
+ params,
4161
+ options: {
4162
+ tag,
4163
+ ...listenOpts
4164
+ }
4165
+ });
4166
+ const uri = "".concat(url).concat(_getDataUrl(this, "listen", qs));
4167
+ if (uri.length > MAX_URL_LENGTH) {
4168
+ return new Observable(observer => observer.error(new Error("Query too large for listener")));
4169
+ }
4170
+ const listenFor = options.events ? options.events : ["mutation"];
4171
+ const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
4172
+ const esOptions = {};
4173
+ if (token || withCredentials) {
4174
+ esOptions.withCredentials = true;
4175
+ }
4176
+ if (token) {
4177
+ esOptions.headers = {
4178
+ Authorization: "Bearer ".concat(token)
4179
+ };
4180
+ }
4181
+ return new Observable(observer => {
4182
+ let es = getEventSource();
4183
+ let reconnectTimer;
4184
+ let stopped = false;
4185
+ function onError() {
4186
+ if (stopped) {
4187
+ return;
4188
+ }
4189
+ emitReconnect();
4190
+ if (stopped) {
4191
+ return;
4192
+ }
4193
+ if (es.readyState === EventSource.CLOSED) {
4194
+ unsubscribe();
4195
+ clearTimeout(reconnectTimer);
4196
+ reconnectTimer = setTimeout(open, 100);
4197
+ }
4198
+ }
4199
+ function onChannelError(err) {
4200
+ observer.error(cooerceError(err));
4201
+ }
4202
+ function onMessage(evt) {
4203
+ const event = parseEvent(evt);
4204
+ return event instanceof Error ? observer.error(event) : observer.next(event);
4205
+ }
4206
+ function onDisconnect() {
4207
+ stopped = true;
4208
+ unsubscribe();
4209
+ observer.complete();
4210
+ }
4211
+ function unsubscribe() {
4212
+ es.removeEventListener("error", onError, false);
4213
+ es.removeEventListener("channelError", onChannelError, false);
4214
+ es.removeEventListener("disconnect", onDisconnect, false);
4215
+ listenFor.forEach(type => es.removeEventListener(type, onMessage, false));
4216
+ es.close();
4217
+ }
4218
+ function emitReconnect() {
4219
+ if (shouldEmitReconnect) {
4220
+ observer.next({
4221
+ type: "reconnect"
4222
+ });
4223
+ }
4224
+ }
4225
+ function getEventSource() {
4226
+ const evs = new EventSource(uri, esOptions);
4227
+ evs.addEventListener("error", onError, false);
4228
+ evs.addEventListener("channelError", onChannelError, false);
4229
+ evs.addEventListener("disconnect", onDisconnect, false);
4230
+ listenFor.forEach(type => evs.addEventListener(type, onMessage, false));
4231
+ return evs;
4232
+ }
4233
+ function open() {
4234
+ es = getEventSource();
4235
+ }
4236
+ function stop() {
4237
+ stopped = true;
4238
+ unsubscribe();
4239
+ }
4240
+ return stop;
4241
+ });
4242
+ }
4243
+ function parseEvent(event) {
4244
+ try {
4245
+ const data = event.data && JSON.parse(event.data) || {};
4246
+ return Object.assign({
4247
+ type: event.type
4248
+ }, data);
4249
+ } catch (err) {
4250
+ return err;
4251
+ }
4252
+ }
4253
+ function cooerceError(err) {
4254
+ if (err instanceof Error) {
4255
+ return err;
4256
+ }
4257
+ const evt = parseEvent(err);
4258
+ return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
4259
+ }
4260
+ function extractErrorMessage(err) {
4261
+ if (!err.error) {
4262
+ return err.message || "Unknown listener error";
4263
+ }
4264
+ if (err.error.description) {
4265
+ return err.error.description;
4266
+ }
4267
+ return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
4268
+ }
4269
+ var __accessCheck$3 = (obj, member, msg) => {
4270
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
4271
+ };
4272
+ var __privateGet$3 = (obj, member, getter) => {
4273
+ __accessCheck$3(obj, member, "read from private field");
4274
+ return getter ? getter.call(obj) : member.get(obj);
4275
+ };
4276
+ var __privateAdd$3 = (obj, member, value) => {
4277
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
4278
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4279
+ };
4280
+ var __privateSet$3 = (obj, member, value, setter) => {
4281
+ __accessCheck$3(obj, member, "write to private field");
4282
+ setter ? setter.call(obj, value) : member.set(obj, value);
4283
+ return value;
4284
+ };
4285
+ var _client$2, _httpRequest$3, _client2$2, _httpRequest2$3;
4286
+ class ObservableDatasetsClient {
4287
+ constructor(client, httpRequest) {
4288
+ __privateAdd$3(this, _client$2, void 0);
4289
+ __privateAdd$3(this, _httpRequest$3, void 0);
4290
+ __privateSet$3(this, _client$2, client);
4291
+ __privateSet$3(this, _httpRequest$3, httpRequest);
4292
+ }
4293
+ /**
4294
+ * Create a new dataset with the given name
4295
+ *
4296
+ * @param name - Name of the dataset to create
4297
+ * @param options - Options for the dataset
4298
+ */
4299
+ create(name, options) {
4300
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name, options);
4301
+ }
4302
+ /**
4303
+ * Edit a dataset with the given name
4304
+ *
4305
+ * @param name - Name of the dataset to edit
4306
+ * @param options - New options for the dataset
4307
+ */
4308
+ edit(name, options) {
4309
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name, options);
4310
+ }
4311
+ /**
4312
+ * Delete a dataset with the given name
4313
+ *
4314
+ * @param name - Name of the dataset to delete
4315
+ */
4316
+ delete(name) {
4317
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name);
4318
+ }
4319
+ /**
4320
+ * Fetch a list of datasets for the configured project
4321
+ */
4322
+ list() {
4323
+ return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
4324
+ uri: "/datasets"
4325
+ });
4326
+ }
4327
+ }
4328
+ _client$2 = new WeakMap();
4329
+ _httpRequest$3 = new WeakMap();
4330
+ class DatasetsClient {
4331
+ constructor(client, httpRequest) {
4332
+ __privateAdd$3(this, _client2$2, void 0);
4333
+ __privateAdd$3(this, _httpRequest2$3, void 0);
4334
+ __privateSet$3(this, _client2$2, client);
4335
+ __privateSet$3(this, _httpRequest2$3, httpRequest);
4336
+ }
4337
+ /**
4338
+ * Create a new dataset with the given name
4339
+ *
4340
+ * @param name - Name of the dataset to create
4341
+ * @param options - Options for the dataset
4342
+ */
4343
+ create(name, options) {
4344
+ return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name, options));
4345
+ }
4346
+ /**
4347
+ * Edit a dataset with the given name
4348
+ *
4349
+ * @param name - Name of the dataset to edit
4350
+ * @param options - New options for the dataset
4351
+ */
4352
+ edit(name, options) {
4353
+ return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name, options));
4354
+ }
4355
+ /**
4356
+ * Delete a dataset with the given name
4357
+ *
4358
+ * @param name - Name of the dataset to delete
4359
+ */
4360
+ delete(name) {
4361
+ return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name));
4362
+ }
4363
+ /**
4364
+ * Fetch a list of datasets for the configured project
4365
+ */
4366
+ list() {
4367
+ return lastValueFrom(_request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), {
4368
+ uri: "/datasets"
4369
+ }));
4370
+ }
4371
+ }
4372
+ _client2$2 = new WeakMap();
4373
+ _httpRequest2$3 = new WeakMap();
4374
+ function _modify(client, httpRequest, method, name, options) {
4375
+ dataset(name);
4376
+ return _request(client, httpRequest, {
4377
+ method,
4378
+ uri: "/datasets/".concat(name),
4379
+ body: options
4380
+ });
4381
+ }
4382
+ var __accessCheck$2 = (obj, member, msg) => {
4383
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
4384
+ };
4385
+ var __privateGet$2 = (obj, member, getter) => {
4386
+ __accessCheck$2(obj, member, "read from private field");
4387
+ return getter ? getter.call(obj) : member.get(obj);
4388
+ };
4389
+ var __privateAdd$2 = (obj, member, value) => {
4390
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
4391
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4392
+ };
4393
+ var __privateSet$2 = (obj, member, value, setter) => {
4394
+ __accessCheck$2(obj, member, "write to private field");
4395
+ setter ? setter.call(obj, value) : member.set(obj, value);
4396
+ return value;
4397
+ };
4398
+ var _client$1, _httpRequest$2, _client2$1, _httpRequest2$2;
4399
+ class ObservableProjectsClient {
4400
+ constructor(client, httpRequest) {
4401
+ __privateAdd$2(this, _client$1, void 0);
4402
+ __privateAdd$2(this, _httpRequest$2, void 0);
4403
+ __privateSet$2(this, _client$1, client);
4404
+ __privateSet$2(this, _httpRequest$2, httpRequest);
4405
+ }
4406
+ /**
4407
+ * Fetch a list of projects the authenticated user has access to
4408
+ */
4409
+ list() {
4410
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
4411
+ uri: "/projects"
4412
+ });
4413
+ }
4414
+ /**
4415
+ * Fetch a project by project ID
4416
+ *
4417
+ * @param projectId - ID of the project to fetch
4418
+ */
4419
+ getById(projectId) {
4420
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
4421
+ uri: "/projects/".concat(projectId)
4422
+ });
4423
+ }
4424
+ }
4425
+ _client$1 = new WeakMap();
4426
+ _httpRequest$2 = new WeakMap();
4427
+ class ProjectsClient {
4428
+ constructor(client, httpRequest) {
4429
+ __privateAdd$2(this, _client2$1, void 0);
4430
+ __privateAdd$2(this, _httpRequest2$2, void 0);
4431
+ __privateSet$2(this, _client2$1, client);
4432
+ __privateSet$2(this, _httpRequest2$2, httpRequest);
4433
+ }
4434
+ /**
4435
+ * Fetch a list of projects the authenticated user has access to
4436
+ */
4437
+ list() {
4438
+ return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
4439
+ uri: "/projects"
4440
+ }));
4441
+ }
4442
+ /**
4443
+ * Fetch a project by project ID
4444
+ *
4445
+ * @param projectId - ID of the project to fetch
4446
+ */
4447
+ getById(projectId) {
4448
+ return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
4449
+ uri: "/projects/".concat(projectId)
4450
+ }));
4451
+ }
4452
+ }
4453
+ _client2$1 = new WeakMap();
4454
+ _httpRequest2$2 = new WeakMap();
4455
+ var __accessCheck$1 = (obj, member, msg) => {
4456
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
4457
+ };
4458
+ var __privateGet$1 = (obj, member, getter) => {
4459
+ __accessCheck$1(obj, member, "read from private field");
4460
+ return getter ? getter.call(obj) : member.get(obj);
4461
+ };
4462
+ var __privateAdd$1 = (obj, member, value) => {
4463
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
4464
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4465
+ };
4466
+ var __privateSet$1 = (obj, member, value, setter) => {
4467
+ __accessCheck$1(obj, member, "write to private field");
4468
+ setter ? setter.call(obj, value) : member.set(obj, value);
4469
+ return value;
4470
+ };
4471
+ var _client, _httpRequest$1, _client2, _httpRequest2$1;
4472
+ class ObservableUsersClient {
4473
+ constructor(client, httpRequest) {
4474
+ __privateAdd$1(this, _client, void 0);
4475
+ __privateAdd$1(this, _httpRequest$1, void 0);
4476
+ __privateSet$1(this, _client, client);
4477
+ __privateSet$1(this, _httpRequest$1, httpRequest);
4478
+ }
4479
+ /**
4480
+ * Fetch a user by user ID
4481
+ *
4482
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
4483
+ */
4484
+ getById(id) {
4485
+ return _request(__privateGet$1(this, _client), __privateGet$1(this, _httpRequest$1), {
4486
+ uri: "/users/".concat(id)
4487
+ });
4488
+ }
4489
+ }
4490
+ _client = new WeakMap();
4491
+ _httpRequest$1 = new WeakMap();
4492
+ class UsersClient {
4493
+ constructor(client, httpRequest) {
4494
+ __privateAdd$1(this, _client2, void 0);
4495
+ __privateAdd$1(this, _httpRequest2$1, void 0);
4496
+ __privateSet$1(this, _client2, client);
4497
+ __privateSet$1(this, _httpRequest2$1, httpRequest);
4498
+ }
4499
+ /**
4500
+ * Fetch a user by user ID
4501
+ *
4502
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
4503
+ */
4504
+ getById(id) {
4505
+ return lastValueFrom(_request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
4506
+ uri: "/users/".concat(id)
4507
+ }));
4508
+ }
4509
+ }
4510
+ _client2 = new WeakMap();
4511
+ _httpRequest2$1 = new WeakMap();
4512
+ var __accessCheck = (obj, member, msg) => {
4513
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
4514
+ };
4515
+ var __privateGet = (obj, member, getter) => {
4516
+ __accessCheck(obj, member, "read from private field");
4517
+ return getter ? getter.call(obj) : member.get(obj);
4518
+ };
4519
+ var __privateAdd = (obj, member, value) => {
4520
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
4521
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4522
+ };
4523
+ var __privateSet = (obj, member, value, setter) => {
4524
+ __accessCheck(obj, member, "write to private field");
4525
+ setter ? setter.call(obj, value) : member.set(obj, value);
4526
+ return value;
4527
+ };
4528
+ var _clientConfig, _httpRequest, _clientConfig2, _httpRequest2;
4529
+ const _ObservableSanityClient = class {
4530
+ constructor(httpRequest) {
4531
+ let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
4532
+ /**
4533
+ * Private properties
4534
+ */
4535
+ __privateAdd(this, _clientConfig, void 0);
4536
+ __privateAdd(this, _httpRequest, void 0);
4537
+ /**
4538
+ * Instance properties
4539
+ */
4540
+ this.listen = _listen;
4541
+ this.config(config);
4542
+ __privateSet(this, _httpRequest, httpRequest);
4543
+ this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest));
4544
+ this.datasets = new ObservableDatasetsClient(this, __privateGet(this, _httpRequest));
4545
+ this.projects = new ObservableProjectsClient(this, __privateGet(this, _httpRequest));
4546
+ this.users = new ObservableUsersClient(this, __privateGet(this, _httpRequest));
4547
+ }
4548
+ /**
4549
+ * Clone the client - returns a new instance
4550
+ */
4551
+ clone() {
4552
+ return new _ObservableSanityClient(__privateGet(this, _httpRequest), this.config());
4553
+ }
4554
+ config(newConfig) {
4555
+ if (newConfig === void 0) {
4556
+ return {
4557
+ ...__privateGet(this, _clientConfig)
4558
+ };
4559
+ }
4560
+ if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === false) {
4561
+ throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
4562
+ }
4563
+ __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {}));
4564
+ return this;
4565
+ }
4566
+ /**
4567
+ * Clone the client with a new (partial) configuration.
4568
+ *
4569
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
4570
+ */
4571
+ withConfig(newConfig) {
4572
+ return new _ObservableSanityClient(__privateGet(this, _httpRequest), {
4573
+ ...this.config(),
4574
+ ...newConfig
4575
+ });
4576
+ }
4577
+ fetch(query, params) {
4578
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
4579
+ return _fetch(this, __privateGet(this, _httpRequest), query, params, options);
4580
+ }
4581
+ /**
4582
+ * Fetch a single document with the given ID.
4583
+ *
4584
+ * @param id - Document ID to fetch
4585
+ * @param options - Request options
4586
+ */
4587
+ getDocument(id, options) {
4588
+ return _getDocument(this, __privateGet(this, _httpRequest), id, options);
4589
+ }
4590
+ /**
4591
+ * Fetch multiple documents in one request.
4592
+ * Should be used sparingly - performing a query is usually a better option.
4593
+ * The order/position of documents is preserved based on the original array of IDs.
4594
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
4595
+ *
4596
+ * @param ids - Document IDs to fetch
4597
+ * @param options - Request options
4598
+ */
4599
+ getDocuments(ids, options) {
4600
+ return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
4601
+ }
4602
+ create(document, options) {
4603
+ return _create(this, __privateGet(this, _httpRequest), document, "create", options);
4604
+ }
4605
+ createIfNotExists(document, options) {
4606
+ return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
4607
+ }
4608
+ createOrReplace(document, options) {
4609
+ return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
4610
+ }
4611
+ delete(selection, options) {
4612
+ return _delete(this, __privateGet(this, _httpRequest), selection, options);
4613
+ }
4614
+ mutate(operations, options) {
4615
+ return _mutate(this, __privateGet(this, _httpRequest), operations, options);
4616
+ }
4617
+ /**
4618
+ * Create a new buildable patch of operations to perform
4619
+ *
4620
+ * @param documentId - Document ID(s) to patch
4621
+ * @param operations - Optional object of patch operations to initialize the patch instance with
4622
+ */
4623
+ patch(documentId, operations) {
4624
+ return new ObservablePatch(documentId, operations, this);
4625
+ }
4626
+ /**
4627
+ * Create a new transaction of mutations
4628
+ *
4629
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
4630
+ */
4631
+ transaction(operations) {
4632
+ return new ObservableTransaction(operations, this);
4633
+ }
4634
+ /**
4635
+ * DEPRECATED: Perform an HTTP request against the Sanity API
4636
+ *
4637
+ * @deprecated Use your own request library!
4638
+ * @param options - Request options
4639
+ */
4640
+ request(options) {
4641
+ return _request(this, __privateGet(this, _httpRequest), options);
4642
+ }
4643
+ /**
4644
+ * Get a Sanity API URL for the URI provided
4645
+ *
4646
+ * @param uri - URI/path to build URL for
4647
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
4648
+ */
4649
+ getUrl(uri, canUseCdn) {
4650
+ return _getUrl(this, uri, canUseCdn);
4651
+ }
4652
+ /**
4653
+ * Get a Sanity API URL for the data operation and path provided
4654
+ *
4655
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
4656
+ * @param path - Path to append after the operation
4657
+ */
4658
+ getDataUrl(operation, path) {
4659
+ return _getDataUrl(this, operation, path);
4660
+ }
4661
+ };
4662
+ let ObservableSanityClient = _ObservableSanityClient;
4663
+ _clientConfig = new WeakMap();
4664
+ _httpRequest = new WeakMap();
4665
+ const _SanityClient = class {
4666
+ constructor(httpRequest) {
4667
+ let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
4668
+ /**
4669
+ * Private properties
4670
+ */
4671
+ __privateAdd(this, _clientConfig2, void 0);
4672
+ __privateAdd(this, _httpRequest2, void 0);
4673
+ /**
4674
+ * Instance properties
4675
+ */
4676
+ this.listen = _listen;
4677
+ this.config(config);
4678
+ __privateSet(this, _httpRequest2, httpRequest);
4679
+ this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2));
4680
+ this.datasets = new DatasetsClient(this, __privateGet(this, _httpRequest2));
4681
+ this.projects = new ProjectsClient(this, __privateGet(this, _httpRequest2));
4682
+ this.users = new UsersClient(this, __privateGet(this, _httpRequest2));
4683
+ this.observable = new ObservableSanityClient(httpRequest, config);
4684
+ }
4685
+ /**
4686
+ * Clone the client - returns a new instance
4687
+ */
4688
+ clone() {
4689
+ return new _SanityClient(__privateGet(this, _httpRequest2), this.config());
4690
+ }
4691
+ config(newConfig) {
4692
+ if (newConfig === void 0) {
4693
+ return {
4694
+ ...__privateGet(this, _clientConfig2)
4695
+ };
4696
+ }
4697
+ if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === false) {
4698
+ throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
4699
+ }
4700
+ if (this.observable) {
4701
+ this.observable.config(newConfig);
4702
+ }
4703
+ __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {}));
4704
+ return this;
4705
+ }
4706
+ /**
4707
+ * Clone the client with a new (partial) configuration.
4708
+ *
4709
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
4710
+ */
4711
+ withConfig(newConfig) {
4712
+ return new _SanityClient(__privateGet(this, _httpRequest2), {
4713
+ ...this.config(),
4714
+ ...newConfig
4715
+ });
4716
+ }
4717
+ fetch(query, params) {
4718
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
4719
+ return lastValueFrom(_fetch(this, __privateGet(this, _httpRequest2), query, params, options));
4720
+ }
4721
+ /**
4722
+ * Fetch a single document with the given ID.
4723
+ *
4724
+ * @param id - Document ID to fetch
4725
+ * @param options - Request options
4726
+ */
4727
+ getDocument(id, options) {
4728
+ return lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
4729
+ }
4730
+ /**
4731
+ * Fetch multiple documents in one request.
4732
+ * Should be used sparingly - performing a query is usually a better option.
4733
+ * The order/position of documents is preserved based on the original array of IDs.
4734
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
4735
+ *
4736
+ * @param ids - Document IDs to fetch
4737
+ * @param options - Request options
4738
+ */
4739
+ getDocuments(ids, options) {
4740
+ return lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
4741
+ }
4742
+ create(document, options) {
4743
+ return lastValueFrom(_create(this, __privateGet(this, _httpRequest2), document, "create", options));
4744
+ }
4745
+ createIfNotExists(document, options) {
4746
+ return lastValueFrom(_createIfNotExists(this, __privateGet(this, _httpRequest2), document, options));
4747
+ }
4748
+ createOrReplace(document, options) {
4749
+ return lastValueFrom(_createOrReplace(this, __privateGet(this, _httpRequest2), document, options));
4750
+ }
4751
+ delete(selection, options) {
4752
+ return lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
4753
+ }
4754
+ mutate(operations, options) {
4755
+ return lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
4756
+ }
4757
+ /**
4758
+ * Create a new buildable patch of operations to perform
4759
+ *
4760
+ * @param documentId - Document ID(s)to patch
4761
+ * @param operations - Optional object of patch operations to initialize the patch instance with
4762
+ */
4763
+ patch(documentId, operations) {
4764
+ return new Patch(documentId, operations, this);
4765
+ }
4766
+ /**
4767
+ * Create a new transaction of mutations
4768
+ *
4769
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
4770
+ */
4771
+ transaction(operations) {
4772
+ return new Transaction(operations, this);
4773
+ }
4774
+ /**
4775
+ * DEPRECATED: Perform an HTTP request against the Sanity API
4776
+ *
4777
+ * @deprecated Use your own request library!
4778
+ * @param options - Request options
4779
+ */
4780
+ request(options) {
4781
+ return lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
4782
+ }
4783
+ /**
4784
+ * DEPRECATED: Perform an HTTP request a `/data` sub-endpoint
4785
+ *
4786
+ * @deprecated Use your own request library!
4787
+ * @param endpoint - Endpoint to hit (mutate, query etc)
4788
+ * @param body - Request body
4789
+ * @param options - Request options
4790
+ */
4791
+ dataRequest(endpoint, body, options) {
4792
+ return lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
4793
+ }
4794
+ /**
4795
+ * Get a Sanity API URL for the URI provided
4796
+ *
4797
+ * @param uri - URI/path to build URL for
4798
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
4799
+ */
4800
+ getUrl(uri, canUseCdn) {
4801
+ return _getUrl(this, uri, canUseCdn);
4802
+ }
4803
+ /**
4804
+ * Get a Sanity API URL for the data operation and path provided
4805
+ *
4806
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
4807
+ * @param path - Path to append after the operation
4808
+ */
4809
+ getDataUrl(operation, path) {
4810
+ return _getDataUrl(this, operation, path);
4811
+ }
4812
+ };
4813
+ let SanityClient = _SanityClient;
4814
+ _clientConfig2 = new WeakMap();
4815
+ _httpRequest2 = new WeakMap();
4816
+ const httpRequest = defineHttpRequest(envMiddleware);
4817
+ const requester = httpRequest.defaultRequester;
4818
+ const createClient = config => new SanityClient(httpRequest, config);
4819
+ function deprecatedCreateClient(config) {
4820
+ printNoDefaultExport();
4821
+ return new SanityClient(httpRequest, config);
4822
+ }
4823
+
4824
+ exports.BasePatch = BasePatch;
4825
+ exports.BaseTransaction = BaseTransaction;
4826
+ exports.ClientError = ClientError;
4827
+ exports.ObservablePatch = ObservablePatch;
4828
+ exports.ObservableSanityClient = ObservableSanityClient;
4829
+ exports.ObservableTransaction = ObservableTransaction;
4830
+ exports.Patch = Patch;
4831
+ exports.SanityClient = SanityClient;
4832
+ exports.ServerError = ServerError;
4833
+ exports.Transaction = Transaction;
4834
+ exports.createClient = createClient;
4835
+ exports.default = deprecatedCreateClient;
4836
+ exports.requester = requester;
4837
+
4838
+ Object.defineProperty(exports, '__esModule', { value: true });
4839
+
4840
+ }));