@sanity/client 6.28.4-beta.1 → 6.28.4-resources.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.
package/dist/index.d.cts CHANGED
@@ -339,6 +339,8 @@ export declare interface ClientConfig {
339
339
  /** @defaultValue true */
340
340
  useCdn?: boolean
341
341
  token?: string
342
+ /** @internal */
343
+ '~experimental_resource'?: ClientConfigResource
342
344
  /**
343
345
  * What perspective to use for the client. See {@link https://www.sanity.io/docs/perspectives|perspective documentation}
344
346
  * @remarks
@@ -399,6 +401,24 @@ export declare interface ClientConfig {
399
401
  stega?: StegaConfig | boolean
400
402
  }
401
403
 
404
+ declare type ClientConfigResource =
405
+ | {
406
+ type: 'canvas'
407
+ id: string
408
+ }
409
+ | {
410
+ type: 'media-library'
411
+ id: string
412
+ }
413
+ | {
414
+ type: 'dataset'
415
+ id: string
416
+ }
417
+ | {
418
+ type: 'dashboard'
419
+ id: string
420
+ }
421
+
402
422
  /** @public */
403
423
  export declare class ClientError extends Error {
404
424
  response: ErrorProps['response']
package/dist/index.d.ts CHANGED
@@ -339,6 +339,8 @@ export declare interface ClientConfig {
339
339
  /** @defaultValue true */
340
340
  useCdn?: boolean
341
341
  token?: string
342
+ /** @internal */
343
+ '~experimental_resource'?: ClientConfigResource
342
344
  /**
343
345
  * What perspective to use for the client. See {@link https://www.sanity.io/docs/perspectives|perspective documentation}
344
346
  * @remarks
@@ -399,6 +401,24 @@ export declare interface ClientConfig {
399
401
  stega?: StegaConfig | boolean
400
402
  }
401
403
 
404
+ declare type ClientConfigResource =
405
+ | {
406
+ type: 'canvas'
407
+ id: string
408
+ }
409
+ | {
410
+ type: 'media-library'
411
+ id: string
412
+ }
413
+ | {
414
+ type: 'dataset'
415
+ id: string
416
+ }
417
+ | {
418
+ type: 'dashboard'
419
+ id: string
420
+ }
421
+
402
422
  /** @public */
403
423
  export declare class ClientError extends Error {
404
424
  response: ErrorProps['response']
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { retry, jsonRequest, jsonResponse, progress, observable, debug, headers,
4
4
  import { Observable, defer, of, isObservable, mergeMap, from, lastValueFrom, shareReplay, catchError, concat, throwError, timer, tap, finalize, share, merge, EMPTY } from "rxjs";
5
5
  import { stegaClean } from "./_chunks-es/stegaClean.js";
6
6
  import { combineLatestWith, map, filter, finalize as finalize$1 } from "rxjs/operators";
7
- import { validateObject, validateInsert, requireDocumentId, validateDocumentId, hasDataset, requestTag, printPreviewDraftsDeprecationWarning, validateApiPerspective, printCdnPreviewDraftsWarning, validateAssetType, dataset, defaultConfig, initConfig, printNoDefaultExport } from "./_chunks-es/config.js";
7
+ import { validateObject, validateInsert, requireDocumentId, validateDocumentId, resourceConfig, hasDataset, requestTag, printPreviewDraftsDeprecationWarning, validateApiPerspective, printCdnPreviewDraftsWarning, validateAssetType, resourceGuard, dataset, defaultConfig, initConfig, printNoDefaultExport } from "./_chunks-es/config.js";
8
8
  class ClientError extends Error {
9
9
  response;
10
10
  statusCode = 400;
@@ -108,8 +108,8 @@ function defineHttpRequest(envMiddleware) {
108
108
  }
109
109
  function shouldRetry(err, attempt, options) {
110
110
  if (options.maxRetries === 0) return !1;
111
- 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);
112
- return (isSafe || isQuery) && isRetriableResponse ? !0 : retry.shouldRetry(err, attempt, options);
111
+ const isSafe = options.method === "GET" || options.method === "HEAD", isQuery2 = (options.uri || options.url).startsWith("/data/query"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);
112
+ return (isSafe || isQuery2) && isRetriableResponse ? !0 : retry.shouldRetry(err, attempt, options);
113
113
  }
114
114
  class ConnectionFailedError extends Error {
115
115
  name = "ConnectionFailedError";
@@ -677,7 +677,7 @@ function _action(client, httpRequest, actions, options) {
677
677
  );
678
678
  }
679
679
  function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
680
- const isMutation = endpoint === "mutate", isAction = endpoint === "actions", isQuery = endpoint === "query", strQuery = isMutation || isAction ? "" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers: headers2, returnQuery, lastLiveEventId, cacheMode } = options, uri = _getDataUrl(client, endpoint, stringQuery), reqOptions = {
680
+ const isMutation = endpoint === "mutate", isAction = endpoint === "actions", isQuery2 = endpoint === "query", strQuery = isMutation || isAction ? "" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers: headers2, returnQuery, lastLiveEventId, cacheMode } = options, uri = _getDataUrl(client, endpoint, stringQuery), reqOptions = {
681
681
  method: useGet ? "GET" : "POST",
682
682
  uri,
683
683
  json: !0,
@@ -692,7 +692,7 @@ function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
692
692
  resultSourceMap: options.resultSourceMap,
693
693
  lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,
694
694
  cacheMode,
695
- canUseCdn: isQuery,
695
+ canUseCdn: isQuery2,
696
696
  signal: options.signal,
697
697
  fetch: options.fetch,
698
698
  useAbortSignal: options.useAbortSignal,
@@ -720,11 +720,12 @@ function _create(client, httpRequest, doc, op, options = {}) {
720
720
  const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);
721
721
  return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
722
722
  }
723
+ const hasDataConfig = (client) => client.config().dataset !== void 0 && client.config().projectId !== void 0 || client.config()["~experimental_resource"] !== void 0, isQuery = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "query")), isMutate = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "mutate")), isDoc = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "doc", "")), isListener = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "listen")), isHistory = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "history", "")), isData = (client, uri) => uri.startsWith("/data/") || isQuery(client, uri) || isMutate(client, uri) || isDoc(client, uri) || isListener(client, uri) || isHistory(client, uri);
723
724
  function _requestObservable(client, httpRequest, options) {
724
- const uri = options.url || options.uri, config = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
725
+ const uri = options.url || options.uri, config = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(client, uri) : options.canUseCdn;
725
726
  let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn;
726
727
  const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
727
- 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) {
728
+ if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && isQuery(client, uri)) {
728
729
  const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;
729
730
  resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
730
731
  const perspectiveOption = options.perspective || config.perspective;
@@ -751,8 +752,14 @@ function _request(client, httpRequest, options) {
751
752
  );
752
753
  }
753
754
  function _getDataUrl(client, operation, path) {
754
- const config = client.config(), catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;
755
- return `/data${path ? `${baseUri}/${path}` : baseUri}`.replace(/\/($|\?)/, "$1");
755
+ const config = client.config();
756
+ if (config["~experimental_resource"]) {
757
+ resourceConfig(config);
758
+ const resourceBase = resourceDataBase(config), uri2 = path !== void 0 ? `${operation}/${path}` : operation;
759
+ return `${resourceBase}/${uri2}`.replace(/\/($|\?)/, "$1");
760
+ }
761
+ const catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;
762
+ return `/data${path !== void 0 ? `${baseUri}/${path}` : baseUri}`.replace(/\/($|\?)/, "$1");
756
763
  }
757
764
  function _getUrl(client, uri, canUseCdn = !1) {
758
765
  const { url, cdnUrl } = client.config();
@@ -778,6 +785,27 @@ function _createAbortError(signal) {
778
785
  const error = new Error(signal?.reason ?? "The operation was aborted.");
779
786
  return error.name = "AbortError", error;
780
787
  }
788
+ const resourceDataBase = (config) => {
789
+ if (!config["~experimental_resource"])
790
+ throw new Error("`resource` must be provided to perform resource queries");
791
+ const { type, id } = config["~experimental_resource"];
792
+ switch (type) {
793
+ case "dataset": {
794
+ const segments = id.split(".");
795
+ if (segments.length !== 2)
796
+ throw new Error('Dataset ID must be in the format "project.dataset"');
797
+ return `/projects/${segments[0]}/datasets/${segments[1]}`;
798
+ }
799
+ case "canvas":
800
+ return `/canvases/${id}`;
801
+ case "media-library":
802
+ return `/media-libraries/${id}`;
803
+ case "dashboard":
804
+ return `/dashboards/${id}`;
805
+ default:
806
+ throw new Error(`Unsupported resource type: ${type.toString()}`);
807
+ }
808
+ };
781
809
  class ObservableAssetsClient {
782
810
  #client;
783
811
  #httpRequest;
@@ -810,7 +838,7 @@ function _upload(client, httpRequest, assetType, body, opts = {}) {
810
838
  validateAssetType(assetType);
811
839
  let meta = opts.extract || void 0;
812
840
  meta && !meta.length && (meta = ["none"]);
813
- const dataset2 = hasDataset(client.config()), assetEndpoint = assetType === "image" ? "images" : "files", options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {
841
+ const config = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {
814
842
  label,
815
843
  title,
816
844
  description,
@@ -822,12 +850,34 @@ function _upload(client, httpRequest, assetType, body, opts = {}) {
822
850
  tag,
823
851
  method: "POST",
824
852
  timeout: options.timeout || 0,
825
- uri: `/assets/${assetEndpoint}/${dataset2}`,
853
+ uri: buildAssetUploadUrl(config, assetType),
826
854
  headers: options.contentType ? { "Content-Type": options.contentType } : {},
827
855
  query,
828
856
  body
829
857
  });
830
858
  }
859
+ function buildAssetUploadUrl(config, assetType) {
860
+ const assetTypeEndpoint = assetType === "image" ? "images" : "files";
861
+ if (config["~experimental_resource"]) {
862
+ const { type, id } = config["~experimental_resource"];
863
+ switch (type) {
864
+ case "dataset":
865
+ throw new Error(
866
+ "Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead."
867
+ );
868
+ case "canvas":
869
+ return `/canvases/${id}/assets/${assetTypeEndpoint}`;
870
+ case "media-library":
871
+ return `/media-libraries/${id}/upload`;
872
+ case "dashboard":
873
+ return `/dashboards/${id}/assets/${assetTypeEndpoint}`;
874
+ default:
875
+ throw new Error(`Unsupported resource type: ${type.toString()}`);
876
+ }
877
+ }
878
+ const dataset2 = hasDataset(config);
879
+ return `assets/${assetTypeEndpoint}/${dataset2}`;
880
+ }
831
881
  function optionsFromFile(opts, file) {
832
882
  return typeof File > "u" || !(file instanceof File) ? opts : Object.assign(
833
883
  {
@@ -919,6 +969,7 @@ class LiveClient {
919
969
  includeDrafts = !1,
920
970
  tag: _tag
921
971
  } = {}) {
972
+ resourceGuard("live", this.#client.config());
922
973
  const {
923
974
  projectId,
924
975
  apiVersion: _apiVersion,
@@ -1048,7 +1099,7 @@ class DatasetsClient {
1048
1099
  * @param options - Options for the dataset
1049
1100
  */
1050
1101
  create(name2, options) {
1051
- return lastValueFrom(
1102
+ return resourceGuard("dataset", this.#client.config()), lastValueFrom(
1052
1103
  _modify(this.#client, this.#httpRequest, "PUT", name2, options)
1053
1104
  );
1054
1105
  }
@@ -1059,7 +1110,7 @@ class DatasetsClient {
1059
1110
  * @param options - New options for the dataset
1060
1111
  */
1061
1112
  edit(name2, options) {
1062
- return lastValueFrom(
1113
+ return resourceGuard("dataset", this.#client.config()), lastValueFrom(
1063
1114
  _modify(this.#client, this.#httpRequest, "PATCH", name2, options)
1064
1115
  );
1065
1116
  }
@@ -1069,19 +1120,19 @@ class DatasetsClient {
1069
1120
  * @param name - Name of the dataset to delete
1070
1121
  */
1071
1122
  delete(name2) {
1072
- return lastValueFrom(_modify(this.#client, this.#httpRequest, "DELETE", name2));
1123
+ return resourceGuard("dataset", this.#client.config()), lastValueFrom(_modify(this.#client, this.#httpRequest, "DELETE", name2));
1073
1124
  }
1074
1125
  /**
1075
1126
  * Fetch a list of datasets for the configured project
1076
1127
  */
1077
1128
  list() {
1078
- return lastValueFrom(
1129
+ return resourceGuard("dataset", this.#client.config()), lastValueFrom(
1079
1130
  _request(this.#client, this.#httpRequest, { uri: "/datasets", tag: null })
1080
1131
  );
1081
1132
  }
1082
1133
  }
1083
1134
  function _modify(client, httpRequest, method, name2, options) {
1084
- return dataset(name2), _request(client, httpRequest, {
1135
+ return resourceGuard("dataset", client.config()), dataset(name2), _request(client, httpRequest, {
1085
1136
  method,
1086
1137
  uri: `/datasets/${name2}`,
1087
1138
  body: options,
@@ -1095,6 +1146,7 @@ class ObservableProjectsClient {
1095
1146
  this.#client = client, this.#httpRequest = httpRequest;
1096
1147
  }
1097
1148
  list(options) {
1149
+ resourceGuard("projects", this.#client.config());
1098
1150
  const uri = options?.includeMembers === !1 ? "/projects?includeMembers=false" : "/projects";
1099
1151
  return _request(this.#client, this.#httpRequest, { uri });
1100
1152
  }
@@ -1104,7 +1156,7 @@ class ObservableProjectsClient {
1104
1156
  * @param projectId - ID of the project to fetch
1105
1157
  */
1106
1158
  getById(projectId) {
1107
- return _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` });
1159
+ return resourceGuard("projects", this.#client.config()), _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` });
1108
1160
  }
1109
1161
  }
1110
1162
  class ProjectsClient {
@@ -1114,6 +1166,7 @@ class ProjectsClient {
1114
1166
  this.#client = client, this.#httpRequest = httpRequest;
1115
1167
  }
1116
1168
  list(options) {
1169
+ resourceGuard("projects", this.#client.config());
1117
1170
  const uri = options?.includeMembers === !1 ? "/projects?includeMembers=false" : "/projects";
1118
1171
  return lastValueFrom(_request(this.#client, this.#httpRequest, { uri }));
1119
1172
  }
@@ -1123,7 +1176,7 @@ class ProjectsClient {
1123
1176
  * @param projectId - ID of the project to fetch
1124
1177
  */
1125
1178
  getById(projectId) {
1126
- return lastValueFrom(
1179
+ return resourceGuard("projects", this.#client.config()), lastValueFrom(
1127
1180
  _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` })
1128
1181
  );
1129
1182
  }
@@ -1511,7 +1564,7 @@ function defineDeprecatedCreateClient(createClient2) {
1511
1564
  return printNoDefaultExport(), createClient2(config);
1512
1565
  };
1513
1566
  }
1514
- var name = "@sanity/client", version = "6.28.4-beta.1";
1567
+ var name = "@sanity/client", version = "6.28.4-resources.4";
1515
1568
  const middleware = [
1516
1569
  debug({ verbose: !0, namespace: "sanity:client" }),
1517
1570
  headers({ "User-Agent": `${name} ${version}` }),