@sanity/client 6.22.1-bundle-perspective → 6.22.2-bundle-perspective

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/client",
3
- "version": "6.22.1-bundle-perspective",
3
+ "version": "6.22.2-bundle-perspective",
4
4
  "description": "Client for retrieving, creating and patching data from Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
package/src/config.ts CHANGED
@@ -41,6 +41,16 @@ export const validateApiPerspective = function validateApiPerspective(perspectiv
41
41
  }
42
42
  }
43
43
 
44
+ export const validateApiBundlePerspective = function validateApiBundlePerspective(
45
+ perspective?: string,
46
+ bundlePerspective?: string[],
47
+ ) {
48
+ if (perspective !== 'raw' && bundlePerspective) {
49
+ throw new TypeError(
50
+ 'Invalid, perspective and bundlePerspective parameters are mutually exclusive',
51
+ )
52
+ }
53
+ }
44
54
  export const initConfig = (
45
55
  config: Partial<ClientConfig>,
46
56
  prevConfig: Partial<ClientConfig>,
@@ -1,7 +1,7 @@
1
1
  import {from, type MonoTypeOperatorFunction, Observable} from 'rxjs'
2
2
  import {combineLatestWith, filter, map} from 'rxjs/operators'
3
3
 
4
- import {validateApiPerspective} from '../config'
4
+ import {validateApiBundlePerspective, validateApiPerspective} from '../config'
5
5
  import {requestOptions} from '../http/requestOptions'
6
6
  import type {ObservableSanityClient, SanityClient} from '../SanityClient'
7
7
  import {stegaClean} from '../stega/stegaClean'
@@ -406,7 +406,6 @@ export function _requestObservable<R>(
406
406
  options.query = {resultSourceMap, ...options.query}
407
407
  }
408
408
  const perspective = options.perspective || config.perspective
409
- const bundlePerspective = options.bundlePerspective || config.bundlePerspective
410
409
  if (typeof perspective === 'string' && perspective !== 'raw') {
411
410
  validateApiPerspective(perspective)
412
411
  options.query = {perspective, ...options.query}
@@ -417,10 +416,9 @@ export function _requestObservable<R>(
417
416
  }
418
417
  }
419
418
 
420
- if (typeof bundlePerspective === 'string') {
421
- if (perspective) {
422
- // printWarning()
423
- }
419
+ const bundlePerspective = options.bundlePerspective || config.bundlePerspective
420
+ if (Array.isArray(bundlePerspective) && bundlePerspective.length > 0) {
421
+ validateApiBundlePerspective(perspective, bundlePerspective)
424
422
  options.query = {perspective: undefined, bundlePerspective, ...options.query}
425
423
  }
426
424
 
package/src/data/live.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  import {Observable} from 'rxjs'
2
2
 
3
3
  import type {ObservableSanityClient, SanityClient} from '../SanityClient'
4
- import type {Any, LiveEventMessage, LiveEventRestart} from '../types'
4
+ import type {
5
+ Any,
6
+ LiveEventMessage,
7
+ LiveEventReconnect,
8
+ LiveEventRestart,
9
+ LiveEventWelcome,
10
+ } from '../types'
5
11
  import {_getDataUrl} from './dataMethods'
6
12
 
7
13
  const requiredApiVersion = '2021-03-26'
@@ -20,11 +26,23 @@ export class LiveClient {
20
26
  */
21
27
  events({
22
28
  includeDrafts = false,
29
+ tag: _tag,
23
30
  }: {
24
31
  /** @alpha this API is experimental and may change or even be removed */
25
32
  includeDrafts?: boolean
26
- } = {}): Observable<LiveEventMessage | LiveEventRestart> {
27
- const {apiVersion: _apiVersion, token} = this.#client.config()
33
+ /**
34
+ * Optional request tag for the listener. Use to identify the request in logs.
35
+ *
36
+ * @defaultValue `undefined`
37
+ */
38
+ tag?: string
39
+ } = {}): Observable<LiveEventMessage | LiveEventRestart | LiveEventReconnect | LiveEventWelcome> {
40
+ const {
41
+ apiVersion: _apiVersion,
42
+ token,
43
+ withCredentials,
44
+ requestTagPrefix,
45
+ } = this.#client.config()
28
46
  const apiVersion = _apiVersion.replace(/^v/, '')
29
47
  if (apiVersion !== 'X' && apiVersion < requiredApiVersion) {
30
48
  throw new Error(
@@ -33,9 +51,9 @@ export class LiveClient {
33
51
  `Please update your API version to use this feature.`,
34
52
  )
35
53
  }
36
- if (includeDrafts && !token) {
54
+ if (includeDrafts && !token && !withCredentials) {
37
55
  throw new Error(
38
- `The live events API requires a token when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.`,
56
+ `The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.`,
39
57
  )
40
58
  }
41
59
  if (includeDrafts && apiVersion !== 'X') {
@@ -45,17 +63,24 @@ export class LiveClient {
45
63
  }
46
64
  const path = _getDataUrl(this.#client, 'live/events')
47
65
  const url = new URL(this.#client.getUrl(path, false))
66
+ const tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join('.') : _tag
67
+ if (tag) {
68
+ url.searchParams.set('tag', tag)
69
+ }
48
70
  if (includeDrafts) {
49
71
  url.searchParams.set('includeDrafts', 'true')
50
72
  }
51
73
 
52
- const listenFor = ['restart', 'message'] as const
74
+ const listenFor = ['restart', 'message', 'welcome', 'reconnect'] as const
53
75
  const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}
54
76
  if (includeDrafts && token) {
55
77
  esOptions.headers = {
56
78
  Authorization: `Bearer ${token}`,
57
79
  }
58
80
  }
81
+ if (includeDrafts && withCredentials) {
82
+ esOptions.withCredentials = true
83
+ }
59
84
 
60
85
  return new Observable((observer) => {
61
86
  let es: InstanceType<typeof EventSource> | undefined
@@ -108,7 +133,7 @@ export class LiveClient {
108
133
 
109
134
  async function getEventSource() {
110
135
  const EventSourceImplementation: typeof EventSource =
111
- typeof EventSource === 'undefined' || esOptions.headers
136
+ typeof EventSource === 'undefined' || esOptions.headers || esOptions.withCredentials
112
137
  ? ((await import('@sanity/eventsource')).default as unknown as typeof EventSource)
113
138
  : EventSource
114
139
 
package/src/types.ts CHANGED
@@ -42,7 +42,8 @@ export interface ClientConfig {
42
42
  token?: string
43
43
  /** @defaultValue 'raw' */
44
44
  perspective?: ClientPerspective
45
- bundlePerspective?: string
45
+ /** @defaultValue 'raw' */
46
+ bundlePerspective?: string[]
46
47
  apiHost?: string
47
48
  apiVersion?: string
48
49
  proxy?: string
@@ -222,7 +223,7 @@ export type SanityDocument<T extends Record<string, Any> = Record<string, Any>>
222
223
  _createdAt: string
223
224
  _updatedAt: string
224
225
  /**
225
- * Present when `perspective` is set to `previewDrafts` or `bundlePerspective` is specified
226
+ * Present when `perspective` is set to `previewDrafts`
226
227
  */
227
228
  _originalId?: string
228
229
  }
@@ -307,7 +308,7 @@ export interface RequestObservableOptions extends Omit<RequestOptions, 'url'> {
307
308
  returnQuery?: boolean
308
309
  resultSourceMap?: boolean | 'withKeyArraySelector'
309
310
  perspective?: ClientPerspective
310
- bundlePerspective?: string
311
+ bundlePerspective?: string[]
311
312
  lastLiveEventId?: string
312
313
  }
313
314
 
@@ -941,7 +942,7 @@ export interface ListenOptions {
941
942
  /** @public */
942
943
  export interface ResponseQueryOptions extends RequestOptions {
943
944
  perspective?: ClientPerspective
944
- bundlePerspective?: string
945
+ bundlePerspective?: string[]
945
946
  resultSourceMap?: boolean | 'withKeyArraySelector'
946
947
  returnQuery?: boolean
947
948
  useCdn?: boolean
@@ -1249,6 +1250,11 @@ export type SyncTag = `s1:${string}`
1249
1250
  /** @public */
1250
1251
  export interface LiveEventRestart {
1251
1252
  type: 'restart'
1253
+ id: string
1254
+ }
1255
+ /** @public */
1256
+ export interface LiveEventReconnect {
1257
+ type: 'reconnect'
1252
1258
  }
1253
1259
  /** @public */
1254
1260
  export interface LiveEventMessage {
@@ -1256,6 +1262,10 @@ export interface LiveEventMessage {
1256
1262
  id: string
1257
1263
  tags: SyncTag[]
1258
1264
  }
1265
+ /** @public */
1266
+ export interface LiveEventWelcome {
1267
+ type: 'welcome'
1268
+ }
1259
1269
 
1260
1270
  /** @public */
1261
1271
  export interface SanityQueries {}
@@ -125,9 +125,8 @@
125
125
  function __asyncGenerator(thisArg, _arguments, generator) {
126
126
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
127
127
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
128
- return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
129
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
130
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
128
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
129
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
131
130
  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
132
131
  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
133
132
  function fulfill(value) { resume("next", value); }
@@ -1045,7 +1044,8 @@
1045
1044
  let e = JSON.stringify(t);
1046
1045
  return `${u}${Array.from(e).map((r) => {
1047
1046
  let n = r.charCodeAt(0);
1048
- if (n > 255) throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);
1047
+ if (n > 255)
1048
+ throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);
1049
1049
  return Array.from(n.toString(4).padStart(4, "0")).map((o) => String.fromCodePoint(c[o])).join("");
1050
1050
  }).join("")}`;
1051
1051
  }
@@ -1160,7 +1160,8 @@
1160
1160
  ]);
1161
1161
  }
1162
1162
  function shouldRetry(err, attempt, options) {
1163
- if (options.maxRetries === 0) return !1;
1163
+ if (options.maxRetries === 0)
1164
+ return !1;
1164
1165
  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);
1165
1166
  return (isSafe || isQuery) && isRetriableResponse ? !0 : _$1.shouldRetry(err, attempt, options);
1166
1167
  }
@@ -1591,6 +1592,11 @@ ${selectionOpts}`);
1591
1592
  "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
1592
1593
  );
1593
1594
  }
1595
+ }, validateApiBundlePerspective = function(perspective, bundlePerspective) {
1596
+ if (perspective !== "raw" && bundlePerspective)
1597
+ throw new TypeError(
1598
+ "Invalid, perspective and bundlePerspective parameters are mutually exclusive"
1599
+ );
1594
1600
  }, initConfig = (config, prevConfig) => {
1595
1601
  const specifiedConfig = {
1596
1602
  ...prevConfig,
@@ -1807,8 +1813,10 @@ ${selectionOpts}`);
1807
1813
  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) {
1808
1814
  const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;
1809
1815
  resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
1810
- const perspective = options.perspective || config.perspective, bundlePerspective = options.bundlePerspective || config.bundlePerspective;
1811
- typeof perspective == "string" && perspective !== "raw" && (validateApiPerspective(perspective), options.query = { perspective, ...options.query }, perspective === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), typeof bundlePerspective == "string" && (options.query = { perspective: void 0, bundlePerspective, ...options.query }), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query });
1816
+ const perspective = options.perspective || config.perspective;
1817
+ typeof perspective == "string" && perspective !== "raw" && (validateApiPerspective(perspective), options.query = { perspective, ...options.query }, perspective === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning()));
1818
+ const bundlePerspective = options.bundlePerspective || config.bundlePerspective;
1819
+ Array.isArray(bundlePerspective) && bundlePerspective.length > 0 && (validateApiBundlePerspective(perspective, bundlePerspective), options.query = { perspective: void 0, bundlePerspective, ...options.query }), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query });
1812
1820
  }
1813
1821
  const reqOptions = requestOptions(
1814
1822
  config,
@@ -2000,27 +2008,33 @@ ${selectionOpts}`);
2000
2008
  * Requires `apiVersion` to be `2021-03-26` or later.
2001
2009
  */
2002
2010
  events({
2003
- includeDrafts = !1
2011
+ includeDrafts = !1,
2012
+ tag: _tag
2004
2013
  } = {}) {
2005
- const { apiVersion: _apiVersion, token } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, "");
2014
+ const {
2015
+ apiVersion: _apiVersion,
2016
+ token,
2017
+ withCredentials,
2018
+ requestTagPrefix
2019
+ } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, "");
2006
2020
  if (apiVersion !== "X" && apiVersion < requiredApiVersion)
2007
2021
  throw new Error(
2008
2022
  `The live events API requires API version ${requiredApiVersion} or later. The current API version is ${apiVersion}. Please update your API version to use this feature.`
2009
2023
  );
2010
- if (includeDrafts && !token)
2024
+ if (includeDrafts && !token && !withCredentials)
2011
2025
  throw new Error(
2012
- "The live events API requires a token when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role."
2026
+ "The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role."
2013
2027
  );
2014
2028
  if (includeDrafts && apiVersion !== "X")
2015
2029
  throw new Error(
2016
2030
  "The live events API requires API version X when 'includeDrafts: true'. This API is experimental and may change or even be removed."
2017
2031
  );
2018
- const path = _getDataUrl(this.#client, "live/events"), url = new URL(this.#client.getUrl(path, !1));
2019
- includeDrafts && url.searchParams.set("includeDrafts", "true");
2020
- const listenFor = ["restart", "message"], esOptions = {};
2032
+ const path = _getDataUrl(this.#client, "live/events"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(".") : _tag;
2033
+ tag && url.searchParams.set("tag", tag), includeDrafts && url.searchParams.set("includeDrafts", "true");
2034
+ const listenFor = ["restart", "message", "welcome", "reconnect"], esOptions = {};
2021
2035
  return includeDrafts && token && (esOptions.headers = {
2022
2036
  Authorization: `Bearer ${token}`
2023
- }), new Observable((observer) => {
2037
+ }), includeDrafts && withCredentials && (esOptions.withCredentials = !0), new Observable((observer) => {
2024
2038
  let es, reconnectTimer, stopped = !1, unsubscribed = !1;
2025
2039
  open();
2026
2040
  function onError(evt) {
@@ -2045,7 +2059,7 @@ ${selectionOpts}`);
2045
2059
  }
2046
2060
  }
2047
2061
  async function getEventSource() {
2048
- const EventSourceImplementation = typeof EventSource > "u" || esOptions.headers ? (await Promise.resolve().then(function () { return browser$2; })).default : EventSource;
2062
+ const EventSourceImplementation = typeof EventSource > "u" || esOptions.headers || esOptions.withCredentials ? (await Promise.resolve().then(function () { return browser$2; })).default : EventSource;
2049
2063
  if (unsubscribed)
2050
2064
  return;
2051
2065
  const evs = new EventSourceImplementation(url.toString(), esOptions);
@@ -2876,7 +2890,8 @@ ${selectionOpts}`);
2876
2890
  const { baseUrl, workspace, tool } = resolveStudioBaseRoute(
2877
2891
  typeof config.studioUrl == "function" ? config.studioUrl(sourceDocument) : config.studioUrl
2878
2892
  );
2879
- if (!baseUrl) return value;
2893
+ if (!baseUrl)
2894
+ return value;
2880
2895
  const { _id: id, _type: type, _projectId: projectId, _dataset: dataset } = sourceDocument;
2881
2896
  return C(
2882
2897
  value,