@sanity/client 3.3.3-esm.9 → 3.3.4

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