@sanity/client 6.23.0 → 6.24.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.
@@ -121,22 +121,9 @@ function shouldRetry(err, attempt, options) {
121
121
  const isSafe = options.method === "GET" || options.method === "HEAD", isQuery = (options.uri || options.url).startsWith("/data/query"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);
122
122
  return (isSafe || isQuery) && isRetriableResponse ? !0 : middleware.retry.shouldRetry(err, attempt, options);
123
123
  }
124
- function getSelection(sel) {
125
- if (typeof sel == "string")
126
- return { id: sel };
127
- if (Array.isArray(sel))
128
- return { query: "*[_id in $ids]", params: { ids: sel } };
129
- if (typeof sel == "object" && sel !== null && "query" in sel && typeof sel.query == "string")
130
- return "params" in sel && typeof sel.params == "object" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };
131
- const selectionOpts = [
132
- "* Document ID (<docId>)",
133
- "* Array of document IDs",
134
- "* Object containing `query`"
135
- ].join(`
136
- `);
137
- throw new Error(`Unknown selection - must be one of:
138
-
139
- ${selectionOpts}`);
124
+ const BASE_URL = "https://www.sanity.io/help/";
125
+ function generateHelpUrl(slug) {
126
+ return BASE_URL + slug;
140
127
  }
141
128
  const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name) => {
142
129
  if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name))
@@ -180,6 +167,124 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
180
167
  );
181
168
  return tag;
182
169
  };
170
+ function once(fn) {
171
+ let didCall = !1, returnValue;
172
+ return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
173
+ }
174
+ const createWarningPrinter = (message) => (
175
+ // eslint-disable-next-line no-console
176
+ once((...args) => console.warn(message.join(" "), ...args))
177
+ ), printCdnAndWithCredentialsWarning = createWarningPrinter([
178
+ "Because you set `withCredentials` to true, we will override your `useCdn`",
179
+ "setting to be false since (cookie-based) credentials are never set on the CDN"
180
+ ]), printCdnWarning = createWarningPrinter([
181
+ "Since you haven't set a value for `useCdn`, we will deliver content using our",
182
+ "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
183
+ "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
184
+ ]), printCdnPreviewDraftsWarning = createWarningPrinter([
185
+ "The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
186
+ "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
187
+ ]), printBrowserTokenWarning = createWarningPrinter([
188
+ "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
189
+ `See ${generateHelpUrl(
190
+ "js-client-browser-token"
191
+ )} for more information and how to hide this warning.`
192
+ ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
193
+ "Using the Sanity client without specifying an API version is deprecated.",
194
+ `See ${generateHelpUrl("js-client-api-version")}`
195
+ ]), printNoDefaultExport = createWarningPrinter([
196
+ "The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
197
+ ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
198
+ apiHost: "https://api.sanity.io",
199
+ apiVersion: "1",
200
+ useProjectHostname: !0,
201
+ stega: { enabled: !1 }
202
+ }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
203
+ function validateApiVersion(apiVersion) {
204
+ if (apiVersion === "1" || apiVersion === "X")
205
+ return;
206
+ const apiDate = new Date(apiVersion);
207
+ if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
208
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
209
+ }
210
+ const validateApiPerspective = function(perspective) {
211
+ if (Array.isArray(perspective)) {
212
+ for (const perspectiveValue of perspective)
213
+ if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
214
+ throw new TypeError(
215
+ "Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
216
+ );
217
+ return;
218
+ }
219
+ switch (perspective) {
220
+ case "previewDrafts":
221
+ case "drafts":
222
+ case "published":
223
+ case "raw":
224
+ return;
225
+ default:
226
+ throw new TypeError(
227
+ "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
228
+ );
229
+ }
230
+ }, initConfig = (config, prevConfig) => {
231
+ const specifiedConfig = {
232
+ ...prevConfig,
233
+ ...config,
234
+ stega: {
235
+ ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
236
+ ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
237
+ }
238
+ };
239
+ specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
240
+ const newConfig = {
241
+ ...defaultConfig,
242
+ ...specifiedConfig
243
+ }, projectBased = newConfig.useProjectHostname;
244
+ if (typeof Promise > "u") {
245
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
246
+ throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
247
+ }
248
+ if (projectBased && !newConfig.projectId)
249
+ throw new Error("Configuration must contain `projectId`");
250
+ if (typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
251
+ throw new Error(
252
+ "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?"
253
+ );
254
+ if ("encodeSourceMapAtPath" in newConfig)
255
+ throw new Error(
256
+ "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?"
257
+ );
258
+ if (typeof newConfig.stega.enabled != "boolean")
259
+ throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
260
+ if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
261
+ throw new Error("stega.studioUrl must be defined when stega.enabled is true");
262
+ if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
263
+ throw new Error(
264
+ `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
265
+ );
266
+ const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
267
+ isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > "u" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
268
+ const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
269
+ return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
270
+ };
271
+ function getSelection(sel) {
272
+ if (typeof sel == "string")
273
+ return { id: sel };
274
+ if (Array.isArray(sel))
275
+ return { query: "*[_id in $ids]", params: { ids: sel } };
276
+ if (typeof sel == "object" && sel !== null && "query" in sel && typeof sel.query == "string")
277
+ return "params" in sel && typeof sel.params == "object" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };
278
+ const selectionOpts = [
279
+ "* Document ID (<docId>)",
280
+ "* Array of document IDs",
281
+ "* Object containing `query`"
282
+ ].join(`
283
+ `);
284
+ throw new Error(`Unknown selection - must be one of:
285
+
286
+ ${selectionOpts}`);
287
+ }
183
288
  class BasePatch {
184
289
  selection;
185
290
  operations;
@@ -493,102 +598,7 @@ class ObservableTransaction extends BaseTransaction {
493
598
  return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
494
599
  }
495
600
  }
496
- const BASE_URL = "https://www.sanity.io/help/";
497
- function generateHelpUrl(slug) {
498
- return BASE_URL + slug;
499
- }
500
- function once(fn) {
501
- let didCall = !1, returnValue;
502
- return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
503
- }
504
- const createWarningPrinter = (message) => (
505
- // eslint-disable-next-line no-console
506
- once((...args) => console.warn(message.join(" "), ...args))
507
- ), printCdnAndWithCredentialsWarning = createWarningPrinter([
508
- "Because you set `withCredentials` to true, we will override your `useCdn`",
509
- "setting to be false since (cookie-based) credentials are never set on the CDN"
510
- ]), printCdnWarning = createWarningPrinter([
511
- "Since you haven't set a value for `useCdn`, we will deliver content using our",
512
- "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
513
- "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
514
- ]), printCdnPreviewDraftsWarning = createWarningPrinter([
515
- "The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
516
- "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
517
- ]), printBrowserTokenWarning = createWarningPrinter([
518
- "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
519
- `See ${generateHelpUrl(
520
- "js-client-browser-token"
521
- )} for more information and how to hide this warning.`
522
- ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
523
- "Using the Sanity client without specifying an API version is deprecated.",
524
- `See ${generateHelpUrl("js-client-api-version")}`
525
- ]), printNoDefaultExport = createWarningPrinter([
526
- "The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
527
- ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
528
- apiHost: "https://api.sanity.io",
529
- apiVersion: "1",
530
- useProjectHostname: !0,
531
- stega: { enabled: !1 }
532
- }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
533
- function validateApiVersion(apiVersion) {
534
- if (apiVersion === "1" || apiVersion === "X")
535
- return;
536
- const apiDate = new Date(apiVersion);
537
- if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
538
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
539
- }
540
- const validateApiPerspective = function(perspective) {
541
- switch (perspective) {
542
- case "previewDrafts":
543
- case "published":
544
- case "raw":
545
- return;
546
- default:
547
- throw new TypeError(
548
- "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
549
- );
550
- }
551
- }, initConfig = (config, prevConfig) => {
552
- const specifiedConfig = {
553
- ...prevConfig,
554
- ...config,
555
- stega: {
556
- ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
557
- ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
558
- }
559
- };
560
- specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
561
- const newConfig = {
562
- ...defaultConfig,
563
- ...specifiedConfig
564
- }, projectBased = newConfig.useProjectHostname;
565
- if (typeof Promise > "u") {
566
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
567
- throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
568
- }
569
- if (projectBased && !newConfig.projectId)
570
- throw new Error("Configuration must contain `projectId`");
571
- if (typeof newConfig.perspective == "string" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
572
- throw new Error(
573
- "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?"
574
- );
575
- if ("encodeSourceMapAtPath" in newConfig)
576
- throw new Error(
577
- "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?"
578
- );
579
- if (typeof newConfig.stega.enabled != "boolean")
580
- throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
581
- if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
582
- throw new Error("stega.studioUrl must be defined when stega.enabled is true");
583
- if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
584
- throw new Error(
585
- `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
586
- );
587
- const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
588
- isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > "u" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
589
- const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
590
- return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
591
- }, projectHeader = "X-Sanity-Project-ID";
601
+ const projectHeader = "X-Sanity-Project-ID";
592
602
  function requestOptions(config, overrides = {}) {
593
603
  const headers = {}, token = overrides.token || config.token;
594
604
  token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers[projectHeader] = config.projectId);
@@ -766,8 +776,11 @@ function _requestObservable(client, httpRequest, options) {
766
776
  if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/query/") === 0) {
767
777
  const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;
768
778
  resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
769
- const perspective = options.perspective || config.perspective;
770
- typeof perspective == "string" && perspective !== "raw" && (validateApiPerspective(perspective), options.query = { perspective, ...options.query }, perspective === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query }), useCdn && options.cacheMode == "noStale" && (options.query = { cacheMode: "noStale", ...options.query });
779
+ const perspectiveOption = options.perspective || config.perspective;
780
+ typeof perspectiveOption < "u" && (validateApiPerspective(perspectiveOption), options.query = {
781
+ perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption,
782
+ ...options.query
783
+ }, perspectiveOption === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query }), useCdn && options.cacheMode == "noStale" && (options.query = { cacheMode: "noStale", ...options.query });
771
784
  }
772
785
  const reqOptions = requestOptions(
773
786
  config,
@@ -1597,4 +1610,5 @@ exports.Transaction = Transaction;
1597
1610
  exports.createClient = createClient;
1598
1611
  exports.default = deprecatedCreateClient;
1599
1612
  exports.requester = requester;
1613
+ exports.validateApiPerspective = validateApiPerspective;
1600
1614
  //# sourceMappingURL=index.browser.cjs.map