@sanity/client 7.26.2 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +63 -341
  2. package/dist/browserUpload-2tz6Sdqp.js +87 -0
  3. package/dist/browserUpload-2tz6Sdqp.js.map +1 -0
  4. package/dist/browserUpload-CwpNx7Vl.js +87 -0
  5. package/dist/browserUpload-CwpNx7Vl.js.map +1 -0
  6. package/dist/config-3wiPP-sZ.js +126 -0
  7. package/dist/config-3wiPP-sZ.js.map +1 -0
  8. package/dist/csm.d.ts +122 -335
  9. package/dist/csm.js +79 -91
  10. package/dist/csm.js.map +1 -1
  11. package/dist/dist-C9ExSk2R.js +73 -0
  12. package/dist/dist-C9ExSk2R.js.map +1 -0
  13. package/dist/dist-Z8cIRxoB.js +69 -0
  14. package/dist/dist-Z8cIRxoB.js.map +1 -0
  15. package/dist/index.d.ts +112 -6722
  16. package/dist/index.js +2950 -2848
  17. package/dist/index.js.map +1 -1
  18. package/dist/{index.d.cts → index.node.d.ts} +4529 -5322
  19. package/dist/index.node.js +3264 -0
  20. package/dist/index.node.js.map +1 -0
  21. package/dist/isRecord-Kfmt-nk-.js +7 -0
  22. package/dist/isRecord-Kfmt-nk-.js.map +1 -0
  23. package/dist/media-library.d.ts +9 -100
  24. package/dist/media-library.js +36 -14
  25. package/dist/media-library.js.map +1 -1
  26. package/dist/request-BhMuKj0D.js +373 -0
  27. package/dist/request-BhMuKj0D.js.map +1 -0
  28. package/dist/request-SnMg7nUX.js +355 -0
  29. package/dist/request-SnMg7nUX.js.map +1 -0
  30. package/dist/resolveEditInfo-Cz-smq3a.js +339 -0
  31. package/dist/resolveEditInfo-Cz-smq3a.js.map +1 -0
  32. package/dist/rolldown-runtime-vyAXikos.js +9 -0
  33. package/dist/stega.d.ts +78 -7137
  34. package/dist/stega.js +27 -20
  35. package/dist/stega.js.map +1 -1
  36. package/dist/stegaClean-C18wLWau.js +21 -0
  37. package/dist/stegaClean-C18wLWau.js.map +1 -0
  38. package/dist/stegaEncodeSourceMap-DbM2fTN4.js +373 -0
  39. package/dist/stegaEncodeSourceMap-DbM2fTN4.js.map +1 -0
  40. package/dist/stegaEncodeSourceMap-YR3NQ3iz.js +163 -0
  41. package/dist/stegaEncodeSourceMap-YR3NQ3iz.js.map +1 -0
  42. package/dist/{index.browser.d.cts → types-BODIEY7F.d.ts} +4196 -5258
  43. package/dist/types-CfGzbXrl.d.ts +108 -0
  44. package/package.json +80 -142
  45. package/src/SanityClient.ts +101 -137
  46. package/src/agent/actions/AgentActionsClient.ts +12 -12
  47. package/src/agent/actions/commonTypes.ts +2 -1
  48. package/src/agent/actions/generate.ts +26 -6
  49. package/src/agent/actions/patch.ts +27 -7
  50. package/src/agent/actions/prompt.ts +19 -5
  51. package/src/agent/actions/transform.ts +23 -5
  52. package/src/agent/actions/translate.ts +23 -5
  53. package/src/assets/AssetsClient.ts +121 -24
  54. package/src/csm/applySourceDocuments.ts +5 -5
  55. package/src/csm/createEditUrl.ts +1 -1
  56. package/src/csm/draftUtils.ts +23 -5
  57. package/src/csm/index.ts +2 -2
  58. package/src/csm/studioPath.ts +2 -1
  59. package/src/csm/types.ts +8 -2
  60. package/src/data/dataMethods.ts +784 -349
  61. package/src/data/eventsource.ts +82 -49
  62. package/src/data/listen.ts +18 -23
  63. package/src/data/live.ts +60 -35
  64. package/src/data/resolveEventSourceFetch.ts +104 -0
  65. package/src/datasets/DatasetsClient.ts +58 -41
  66. package/src/defineCreateClient.ts +38 -22
  67. package/src/functions/FunctionsClient.ts +66 -0
  68. package/src/functions/invoke.ts +176 -0
  69. package/src/http/browserMiddleware.ts +7 -1
  70. package/src/http/browserUpload.ts +163 -0
  71. package/src/http/errors.ts +61 -6
  72. package/src/http/nodeMiddleware.ts +94 -30
  73. package/src/http/request.ts +304 -87
  74. package/src/http/requestOptions.ts +131 -15
  75. package/src/{index.browser.ts → index.node.ts} +9 -4
  76. package/src/index.ts +4 -3
  77. package/src/mediaLibrary/MediaLibraryVideoClient.ts +27 -12
  78. package/src/projects/ProjectsClient.ts +18 -16
  79. package/src/releases/ReleasesClient.ts +38 -33
  80. package/src/stega/index.ts +1 -2
  81. package/src/stega/stegaEncodeSourceMap.ts +5 -0
  82. package/src/stega/types.ts +2 -2
  83. package/src/types.ts +328 -103
  84. package/src/users/UsersClient.ts +10 -14
  85. package/src/util/shareReplayLatest.ts +1 -1
  86. package/src/validators.ts +1 -1
  87. package/src/warnings.ts +13 -2
  88. package/dist/_chunks-cjs/config.cjs +0 -206
  89. package/dist/_chunks-cjs/config.cjs.map +0 -1
  90. package/dist/_chunks-cjs/isRecord.cjs +0 -6
  91. package/dist/_chunks-cjs/isRecord.cjs.map +0 -1
  92. package/dist/_chunks-cjs/resolveEditInfo.cjs +0 -334
  93. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +0 -1
  94. package/dist/_chunks-cjs/stegaClean.cjs +0 -46
  95. package/dist/_chunks-cjs/stegaClean.cjs.map +0 -1
  96. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +0 -388
  97. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +0 -1
  98. package/dist/_chunks-es/config.js +0 -207
  99. package/dist/_chunks-es/config.js.map +0 -1
  100. package/dist/_chunks-es/isRecord.js +0 -7
  101. package/dist/_chunks-es/isRecord.js.map +0 -1
  102. package/dist/_chunks-es/resolveEditInfo.js +0 -335
  103. package/dist/_chunks-es/resolveEditInfo.js.map +0 -1
  104. package/dist/_chunks-es/stegaClean.js +0 -47
  105. package/dist/_chunks-es/stegaClean.js.map +0 -1
  106. package/dist/_chunks-es/stegaEncodeSourceMap.js +0 -389
  107. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +0 -1
  108. package/dist/csm.cjs +0 -99
  109. package/dist/csm.cjs.map +0 -1
  110. package/dist/csm.d.cts +0 -391
  111. package/dist/index.browser.cjs +0 -3106
  112. package/dist/index.browser.cjs.map +0 -1
  113. package/dist/index.browser.d.ts +0 -6802
  114. package/dist/index.browser.js +0 -3082
  115. package/dist/index.browser.js.map +0 -1
  116. package/dist/index.cjs +0 -2946
  117. package/dist/index.cjs.map +0 -1
  118. package/dist/media-library.cjs +0 -20
  119. package/dist/media-library.cjs.map +0 -1
  120. package/dist/media-library.d.cts +0 -117
  121. package/dist/stega.browser.cjs +0 -29
  122. package/dist/stega.browser.cjs.map +0 -1
  123. package/dist/stega.browser.d.cts +0 -7200
  124. package/dist/stega.browser.d.ts +0 -7200
  125. package/dist/stega.browser.js +0 -24
  126. package/dist/stega.browser.js.map +0 -1
  127. package/dist/stega.cjs +0 -29
  128. package/dist/stega.cjs.map +0 -1
  129. package/dist/stega.d.cts +0 -7200
  130. package/src/data/eventsourcePolyfill.ts +0 -7
  131. package/umd/.gitkeep +0 -1
  132. package/umd/sanityClient.js +0 -6543
  133. package/umd/sanityClient.min.js +0 -6
@@ -0,0 +1,3264 @@
1
+ import { t as require_dist } from "./dist-C9ExSk2R.js";
2
+ import { a as ServerError, c as isHttpError, i as CorsOriginError, l as isQueryParseError, o as formatQueryParseError, r as ClientError, t as defineRequester } from "./request-SnMg7nUX.js";
3
+ import { t as isRecord } from "./isRecord-Kfmt-nk-.js";
4
+ import { isTimeoutError } from "get-it";
5
+ import { debug } from "get-it/middleware";
6
+ import { Observable, catchError, concat, defer, finalize, isObservable, lastValueFrom, map, merge, mergeMap, of, share, tap, throwError, timer } from "rxjs";
7
+ import { getDraftId, getPublishedId, getVersionFromId, getVersionId, isDraftId, isVersionId } from "@sanity/client/csm";
8
+ import { filter, finalize as finalize$1, map as map$1, mergeAll } from "rxjs/operators";
9
+ import { EventSource } from "eventsource";
10
+ import { customAlphabet } from "nanoid";
11
+ import { Readable } from "node:stream";
12
+ import { createNodeFetch } from "get-it/node";
13
+ import { createDebug } from "obug";
14
+ function generateHelpUrl(slug) {
15
+ return "https://www.sanity.io/help/" + slug;
16
+ }
17
+ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = [
18
+ "before",
19
+ "after",
20
+ "replace"
21
+ ], dataset = (name) => {
22
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) throw Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
23
+ }, projectId = (id) => {
24
+ if (!/^[-a-z0-9]+$/i.test(id)) throw Error("`projectId` can only contain only a-z, 0-9 and dashes");
25
+ }, validateAssetType = (type) => {
26
+ if (VALID_ASSET_TYPES.indexOf(type) === -1) throw Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
27
+ }, validateObject = (op, val) => {
28
+ if (typeof val != "object" || !val || Array.isArray(val)) throw Error(`${op}() takes an object of properties`);
29
+ }, validateDocumentId = (op, id) => {
30
+ if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes("..")) throw Error(`${op}(): "${id}" is not a valid document ID`);
31
+ }, requireDocumentId = (op, doc) => {
32
+ if (!doc._id) throw Error(`${op}() requires that the document contains an ID ("_id" property)`);
33
+ validateDocumentId(op, doc._id);
34
+ }, validateDocumentType = (op, type) => {
35
+ if (typeof type != "string") throw Error(`\`${op}()\`: \`${type}\` is not a valid document type`);
36
+ }, requireDocumentType = (op, doc) => {
37
+ if (!doc._type) throw Error(`\`${op}()\` requires that the document contains a type (\`_type\` property)`);
38
+ validateDocumentType(op, doc._type);
39
+ }, validateVersionIdMatch = (builtVersionId, document) => {
40
+ if (document._id && document._id !== builtVersionId) throw Error(`The provided document ID (\`${document._id}\`) does not match the generated version ID (\`${builtVersionId}\`)`);
41
+ }, validateInsert = (at, selector, items) => {
42
+ let signature = "insert(at, selector, items)";
43
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
44
+ let valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
45
+ throw Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
46
+ }
47
+ if (typeof selector != "string") throw Error(`${signature} takes a "selector"-argument which must be a string`);
48
+ if (!Array.isArray(items)) throw Error(`${signature} takes an "items"-argument which must be an array`);
49
+ }, hasDataset = (config) => {
50
+ if (config.dataset) return config.dataset;
51
+ let resource = config.resource;
52
+ if (resource && resource.type === "dataset") {
53
+ let segments = resource.id.split(".");
54
+ if (segments.length !== 2) throw Error("Dataset resource ID must be in the format \"project.dataset\"");
55
+ return segments[1];
56
+ }
57
+ throw Error("`dataset` must be provided to perform queries");
58
+ }, requestTag = (tag) => {
59
+ if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) throw Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
60
+ return tag;
61
+ }, resourceConfig = (config) => {
62
+ let resource = config.resource;
63
+ if (!resource) throw Error("`resource` must be provided to perform resource queries");
64
+ let { type, id } = resource;
65
+ switch (type) {
66
+ case "dataset":
67
+ if (id.split(".").length !== 2) throw Error("Dataset resource ID must be in the format \"project.dataset\"");
68
+ return;
69
+ case "dashboard":
70
+ case "media-library":
71
+ case "canvas": return;
72
+ default: throw Error(`Unsupported resource type: ${type.toString()}`);
73
+ }
74
+ }, resourceGuard = (service, config) => {
75
+ if (config.resource) throw Error(`\`${service}\` does not support resource-based operations`);
76
+ }, EXPERIMENTAL_API_WARNING = "This is an experimental API version";
77
+ function once(fn) {
78
+ let didCall = !1, returnValue;
79
+ return (...args) => didCall ? returnValue : (returnValue = fn(...args), didCall = !0, returnValue);
80
+ }
81
+ const createWarningPrinter = (message) => once((...args) => console.warn(message.join(" "), ...args)), printCdnAndWithCredentialsWarning = createWarningPrinter(["Because you set `withCredentials` to true, we will override your `useCdn`", "setting to be false since (cookie-based) credentials are never set on the CDN"]), printCdnWarning = createWarningPrinter([
82
+ "Since you haven't set a value for `useCdn`, we will deliver content using our",
83
+ "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
84
+ "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
85
+ ]), printCdnPreviewDraftsWarning = createWarningPrinter(["The Sanity client is configured with the `perspective` set to `drafts` or `previewDrafts`, which doesn't support the API-CDN.", "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]), printPreviewDraftsDeprecationWarning = createWarningPrinter(["The `previewDrafts` perspective has been renamed to `drafts` and will be removed in a future API version"]), printBrowserTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.", `See ${generateHelpUrl("js-client-browser-token")} for more information and how to hide this warning.`]), printCredentialedTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token, but also provided `withCredentials: true`.", "This is no longer supported - only token will be used - remove `withCredentials: true`."]), printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", `See ${generateHelpUrl("js-client-api-version")}`]), printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]), printCreateVersionWithBaseIdWarning = createWarningPrinter(["You have called `createVersion()` with a defined `document`.", "If you are creating a version of a document that already exists, prefer providing `baseId` and `releaseId` instead."]), printDeprecatedUriOptionWarning = createWarningPrinter(["The `uri` request option has been renamed to `url`.", "Please update your code to use `url` instead. Support for `uri` will be removed in a future version."]), printDeprecatedResourceConfigWarning = createWarningPrinter(["The `~experimental_resource` configuration property has been renamed to `resource`.", "Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version."]), defaultConfig = {
86
+ apiHost: "https://api.sanity.io",
87
+ apiVersion: "1",
88
+ useProjectHostname: !0,
89
+ stega: { enabled: !1 }
90
+ }, LOCALHOSTS = [
91
+ "localhost",
92
+ "127.0.0.1",
93
+ "0.0.0.0"
94
+ ], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
95
+ function validateApiVersion(apiVersion) {
96
+ if (apiVersion === "1" || apiVersion === "X") return;
97
+ let apiDate = new Date(apiVersion);
98
+ if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0)) throw Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
99
+ }
100
+ /**
101
+ * @internal - it may have breaking changes in any release
102
+ */
103
+ function validateApiPerspective(perspective) {
104
+ if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes("raw")) throw TypeError("Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives");
105
+ }
106
+ const initConfig = (config, prevConfig) => {
107
+ let specifiedConfig = {
108
+ ...prevConfig,
109
+ ...config,
110
+ stega: {
111
+ ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
112
+ ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
113
+ }
114
+ };
115
+ specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
116
+ let newConfig = {
117
+ ...defaultConfig,
118
+ ...specifiedConfig
119
+ };
120
+ newConfig["~experimental_resource"] && !newConfig.resource && (printDeprecatedResourceConfigWarning(), newConfig.resource = newConfig["~experimental_resource"]);
121
+ let resourceConfig$1 = newConfig.resource, projectBased = newConfig.useProjectHostname && !resourceConfig$1;
122
+ if (typeof Promise > "u") {
123
+ let helpUrl = generateHelpUrl("js-client-promise-polyfill");
124
+ throw Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
125
+ }
126
+ if (projectBased && !newConfig.projectId) throw Error("Configuration must contain `projectId`");
127
+ if (resourceConfig$1 && resourceConfig(newConfig), newConfig.perspective !== void 0 && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig) throw Error("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'?");
128
+ if ("encodeSourceMapAtPath" in newConfig) throw Error("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'?");
129
+ if (typeof newConfig.stega.enabled != "boolean") throw Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
130
+ if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0) throw Error("stega.studioUrl must be defined when stega.enabled is true");
131
+ if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function") throw Error(`stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`);
132
+ let isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname), hasToken = !!newConfig.token;
133
+ newConfig.withCredentials && hasToken && (printCredentialedTokenWarning(), newConfig.withCredentials = !1), isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : newConfig.useCdn === void 0 && 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);
134
+ let hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? "apicdn.sanity.io" : host;
135
+ return projectBased ? (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;
136
+ };
137
+ /**
138
+ * Thrown when the EventSource connection could not be established, or was rejected by the server.
139
+ * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
140
+ * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
141
+ * stream with this class so consumers can react — check `status` for the rejection code.
142
+ *
143
+ * @public
144
+ */
145
+ var ConnectionFailedError = class extends Error {
146
+ name = "ConnectionFailedError";
147
+ /**
148
+ * HTTP status code of the rejected connection attempt, if known.
149
+ * Only set when the EventSource implementation exposes it — the `eventsource`
150
+ * package used by the client does (as `code` on its error events), while
151
+ * native EventSource implementations (browser and Node.js) do not.
152
+ */
153
+ status;
154
+ constructor(message, options = {}) {
155
+ let { status, ...errorOptions } = options;
156
+ super(message, errorOptions), this.status = status;
157
+ }
158
+ }, DisconnectError = class extends Error {
159
+ name = "DisconnectError";
160
+ reason;
161
+ constructor(message, reason, options = {}) {
162
+ super(message, options), this.reason = reason;
163
+ }
164
+ }, ChannelError = class extends Error {
165
+ name = "ChannelError";
166
+ data;
167
+ constructor(message, data) {
168
+ super(message), this.data = data;
169
+ }
170
+ }, MessageError = class extends Error {
171
+ name = "MessageError";
172
+ data;
173
+ constructor(message, data, options = {}) {
174
+ super(message, options), this.data = data;
175
+ }
176
+ }, MessageParseError = class extends Error {
177
+ name = "MessageParseError";
178
+ };
179
+ const REQUIRED_EVENTS = ["channelError", "disconnect"];
180
+ /**
181
+ * Sanity API specific EventSource handler shared between the listen and live APIs
182
+ *
183
+ * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance
184
+ * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers)
185
+ * via the passed `initEventSource` function which must return an EventSource instance.
186
+ *
187
+ * Possible errors to be thrown on the returned observable are:
188
+ * - {@link MessageError}
189
+ * - {@link MessageParseError}
190
+ * - {@link ChannelError}
191
+ * - {@link DisconnectError}
192
+ * - {@link ConnectionFailedError}
193
+ *
194
+ * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance
195
+ * @param events - an array of named events from the API to listen for.
196
+ *
197
+ * @internal
198
+ */
199
+ function connectEventSource(initEventSource, events) {
200
+ return defer(() => {
201
+ let es = initEventSource();
202
+ return isObservable(es) ? es : of(es);
203
+ }).pipe(mergeMap((es) => connectWithESInstance(es, events)));
204
+ }
205
+ /**
206
+ * Provides an observable from the passed EventSource instance, subscribing to the passed list of names of events types to listen for
207
+ * Handles connection logic, adding/removing event listeners, payload parsing, error propagation, etc.
208
+ *
209
+ * @param es - The EventSource instance
210
+ * @param events - List of event names to listen for
211
+ */
212
+ function connectWithESInstance(es, events) {
213
+ return new Observable((observer) => {
214
+ let requestedEvents = new Set(events), isRequestedEvent = (type) => requestedEvents.has(type), emitOpen = isRequestedEvent("open");
215
+ function onError(evt) {
216
+ if ("data" in evt) {
217
+ let [parseError, event] = parseEvent(evt);
218
+ observer.error(parseError || !event ? new MessageParseError("Unable to parse EventSource error message", { cause: parseError }) : new MessageError(isRecord(event.data) && typeof event.data.message == "string" ? event.data.message : "", event));
219
+ return;
220
+ }
221
+ if (evt.code !== void 0) {
222
+ observer.error(new ConnectionFailedError("EventSource connection failed", { status: evt.code }));
223
+ return;
224
+ }
225
+ if (es.readyState === es.CLOSED) observer.error(new ConnectionFailedError("EventSource connection failed"));
226
+ else {
227
+ let type = "reconnect";
228
+ isRequestedEvent(type) && observer.next({ type });
229
+ }
230
+ }
231
+ function onOpen() {
232
+ let type = "open";
233
+ isRequestedEvent(type) && observer.next({ type });
234
+ }
235
+ function onMessage(message) {
236
+ let [parseError, event] = parseEvent(message);
237
+ if (parseError || !event) {
238
+ observer.error(new MessageParseError("Unable to parse EventSource message", { cause: parseError }));
239
+ return;
240
+ }
241
+ if (message.type === "channelError") {
242
+ let tag = new URL(es.url).searchParams.get("tag");
243
+ observer.error(new ChannelError(extractErrorMessage(event?.data, tag), event.data));
244
+ return;
245
+ }
246
+ if (message.type === "disconnect") {
247
+ observer.error(new DisconnectError(`Server disconnected client: ${isRecord(event.data) && typeof event.data.reason == "string" && event.data.reason || "unknown error"}`));
248
+ return;
249
+ }
250
+ isRequestedEvent(message.type) && observer.next({
251
+ type: message.type,
252
+ id: message.lastEventId,
253
+ ...event.data ? { data: event.data } : {}
254
+ });
255
+ }
256
+ es.addEventListener("error", onError), emitOpen && es.addEventListener("open", onOpen);
257
+ let cleanedEvents = [.../* @__PURE__ */ new Set([...REQUIRED_EVENTS, ...events])].filter((type) => type !== "error" && type !== "open" && type !== "reconnect");
258
+ return cleanedEvents.forEach((type) => es.addEventListener(type, onMessage)), () => {
259
+ es.removeEventListener("error", onError), emitOpen && es.removeEventListener("open", onOpen), cleanedEvents.forEach((type) => es.removeEventListener(type, onMessage)), es.close();
260
+ };
261
+ });
262
+ }
263
+ function parseEvent(message) {
264
+ try {
265
+ let data = typeof message.data == "string" && JSON.parse(message.data);
266
+ return [null, {
267
+ type: message.type,
268
+ id: message.lastEventId,
269
+ ...isEmptyObject(data) ? {} : { data }
270
+ }];
271
+ } catch (err) {
272
+ return [err, null];
273
+ }
274
+ }
275
+ function extractErrorMessage(err, tag) {
276
+ let error = isRecord(err) ? err.error : void 0;
277
+ if (!error) {
278
+ let message = isRecord(err) ? err.message : void 0;
279
+ return typeof message == "string" && message || "Unknown listener error";
280
+ }
281
+ if (isRecord(error)) {
282
+ if (isQueryParseError(error)) return formatQueryParseError(error, tag);
283
+ if (typeof error.description == "string") return error.description;
284
+ }
285
+ return typeof error == "string" ? error : JSON.stringify(error, null, 2);
286
+ }
287
+ function isEmptyObject(data) {
288
+ for (let _ in data) return !1;
289
+ return !0;
290
+ }
291
+ function getSelection(sel) {
292
+ if (typeof sel == "string") return { id: sel };
293
+ if (Array.isArray(sel)) return {
294
+ query: "*[_id in $ids]",
295
+ params: { ids: sel }
296
+ };
297
+ if (typeof sel == "object" && sel && "query" in sel && typeof sel.query == "string") return "params" in sel && typeof sel.params == "object" && sel.params !== null ? {
298
+ query: sel.query,
299
+ params: sel.params
300
+ } : { query: sel.query };
301
+ let selectionOpts = [
302
+ "* Document ID (<docId>)",
303
+ "* Array of document IDs",
304
+ "* Object containing `query`"
305
+ ].join("\n");
306
+ throw Error(`Unknown selection - must be one of:\n\n${selectionOpts}`);
307
+ }
308
+ /** @internal */
309
+ var BasePatch = class {
310
+ selection;
311
+ operations;
312
+ constructor(selection, operations = {}) {
313
+ this.selection = selection, this.operations = operations;
314
+ }
315
+ /**
316
+ * Sets the given attributes to the document. Does NOT merge objects.
317
+ * The operation is added to the current patch, ready to be commited by `commit()`
318
+ *
319
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
320
+ */
321
+ set(attrs) {
322
+ return this._assign("set", attrs);
323
+ }
324
+ /**
325
+ * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
326
+ * The operation is added to the current patch, ready to be commited by `commit()`
327
+ *
328
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
329
+ */
330
+ setIfMissing(attrs) {
331
+ return this._assign("setIfMissing", attrs);
332
+ }
333
+ /**
334
+ * Performs a "diff-match-patch" operation on the string attributes provided.
335
+ * The operation is added to the current patch, ready to be commited by `commit()`
336
+ *
337
+ * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
338
+ */
339
+ diffMatchPatch(attrs) {
340
+ return validateObject("diffMatchPatch", attrs), this._assign("diffMatchPatch", attrs);
341
+ }
342
+ /**
343
+ * Unsets the attribute paths provided.
344
+ * The operation is added to the current patch, ready to be commited by `commit()`
345
+ *
346
+ * @param attrs - Attribute paths to unset.
347
+ */
348
+ unset(attrs) {
349
+ if (!Array.isArray(attrs)) throw Error("unset(attrs) takes an array of attributes to unset, non-array given");
350
+ return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;
351
+ }
352
+ /**
353
+ * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
354
+ *
355
+ * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
356
+ */
357
+ inc(attrs) {
358
+ return this._assign("inc", attrs);
359
+ }
360
+ /**
361
+ * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
362
+ *
363
+ * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
364
+ */
365
+ dec(attrs) {
366
+ return this._assign("dec", attrs);
367
+ }
368
+ /**
369
+ * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
370
+ *
371
+ * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
372
+ * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
373
+ * @param items - Array of items to insert/replace
374
+ */
375
+ insert(at, selector, items) {
376
+ return validateInsert(at, selector, items), this._assign("insert", {
377
+ [at]: selector,
378
+ items
379
+ });
380
+ }
381
+ /**
382
+ * Append the given items to the array at the given JSONPath
383
+ *
384
+ * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
385
+ * @param items - Array of items to append to the array
386
+ */
387
+ append(selector, items) {
388
+ return this.insert("after", `${selector}[-1]`, items);
389
+ }
390
+ /**
391
+ * Prepend the given items to the array at the given JSONPath
392
+ *
393
+ * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
394
+ * @param items - Array of items to prepend to the array
395
+ */
396
+ prepend(selector, items) {
397
+ return this.insert("before", `${selector}[0]`, items);
398
+ }
399
+ /**
400
+ * Change the contents of an array by removing existing elements and/or adding new elements.
401
+ *
402
+ * @param selector - Attribute or JSONPath expression for array
403
+ * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x
404
+ * @param deleteCount - An integer indicating the number of old array elements to remove.
405
+ * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.
406
+ */
407
+ splice(selector, start, deleteCount, items) {
408
+ let delAll = deleteCount === void 0 || deleteCount === -1, startIndex = start < 0 ? start - 1 : start, delCount = delAll ? -1 : Math.max(0, start + deleteCount), rangeSelector = `${selector}[${startIndex}:${startIndex < 0 && delCount >= 0 ? "" : delCount}]`;
409
+ return this.insert("replace", rangeSelector, items || []);
410
+ }
411
+ /**
412
+ * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
413
+ *
414
+ * @param rev - Revision to lock the patch to
415
+ */
416
+ ifRevisionId(rev) {
417
+ return this.operations.ifRevisionID = rev, this;
418
+ }
419
+ /**
420
+ * Return a plain JSON representation of the patch
421
+ */
422
+ serialize() {
423
+ return {
424
+ ...getSelection(this.selection),
425
+ ...this.operations
426
+ };
427
+ }
428
+ /**
429
+ * Return a plain JSON representation of the patch
430
+ */
431
+ toJSON() {
432
+ return this.serialize();
433
+ }
434
+ /**
435
+ * Clears the patch of all operations
436
+ */
437
+ reset() {
438
+ return this.operations = {}, this;
439
+ }
440
+ _assign(op, props, merge = !0) {
441
+ return validateObject(op, props), this.operations = Object.assign({}, this.operations, { [op]: Object.assign({}, merge && this.operations[op] || {}, props) }), this;
442
+ }
443
+ _set(op, props) {
444
+ return this._assign(op, props, !1);
445
+ }
446
+ }, ObservablePatch = class ObservablePatch extends BasePatch {
447
+ #client;
448
+ constructor(selection, operations, client) {
449
+ super(selection, operations), this.#client = client;
450
+ }
451
+ /**
452
+ * Clones the patch
453
+ */
454
+ clone() {
455
+ return new ObservablePatch(this.selection, { ...this.operations }, this.#client);
456
+ }
457
+ commit(options) {
458
+ if (!this.#client) throw Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
459
+ let returnFirst = typeof this.selection == "string", opts = Object.assign({
460
+ returnFirst,
461
+ returnDocuments: !0
462
+ }, options);
463
+ return this.#client.mutate({ patch: this.serialize() }, opts);
464
+ }
465
+ }, Patch = class Patch extends BasePatch {
466
+ #client;
467
+ constructor(selection, operations, client) {
468
+ super(selection, operations), this.#client = client;
469
+ }
470
+ /**
471
+ * Clones the patch
472
+ */
473
+ clone() {
474
+ return new Patch(this.selection, { ...this.operations }, this.#client);
475
+ }
476
+ commit(options) {
477
+ if (!this.#client) throw Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
478
+ let returnFirst = typeof this.selection == "string", opts = Object.assign({
479
+ returnFirst,
480
+ returnDocuments: !0
481
+ }, options);
482
+ return this.#client.mutate({ patch: this.serialize() }, opts);
483
+ }
484
+ };
485
+ const defaultMutateOptions = { returnDocuments: !1 };
486
+ /** @internal */
487
+ var BaseTransaction = class {
488
+ operations;
489
+ trxId;
490
+ constructor(operations = [], transactionId) {
491
+ this.operations = operations, this.trxId = transactionId;
492
+ }
493
+ /**
494
+ * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.
495
+ * The operation is added to the current transaction, ready to be commited by `commit()`
496
+ *
497
+ * @param doc - Document to create. Requires a `_type` property.
498
+ */
499
+ create(doc) {
500
+ return validateObject("create", doc), this._add({ create: doc });
501
+ }
502
+ /**
503
+ * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
504
+ * The operation is added to the current transaction, ready to be commited by `commit()`
505
+ *
506
+ * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
507
+ */
508
+ createIfNotExists(doc) {
509
+ let op = "createIfNotExists";
510
+ return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
511
+ }
512
+ /**
513
+ * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
514
+ * The operation is added to the current transaction, ready to be commited by `commit()`
515
+ *
516
+ * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
517
+ */
518
+ createOrReplace(doc) {
519
+ let op = "createOrReplace";
520
+ return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
521
+ }
522
+ /**
523
+ * Deletes the document with the given document ID
524
+ * The operation is added to the current transaction, ready to be commited by `commit()`
525
+ *
526
+ * @param documentId - Document ID to delete
527
+ */
528
+ delete(documentId) {
529
+ return validateDocumentId("delete", documentId), this._add({ delete: { id: documentId } });
530
+ }
531
+ transactionId(id) {
532
+ return id ? (this.trxId = id, this) : this.trxId;
533
+ }
534
+ /**
535
+ * Return a plain JSON representation of the transaction
536
+ */
537
+ serialize() {
538
+ return [...this.operations];
539
+ }
540
+ /**
541
+ * Return a plain JSON representation of the transaction
542
+ */
543
+ toJSON() {
544
+ return this.serialize();
545
+ }
546
+ /**
547
+ * Clears the transaction of all operations
548
+ */
549
+ reset() {
550
+ return this.operations = [], this;
551
+ }
552
+ _add(mut) {
553
+ return this.operations.push(mut), this;
554
+ }
555
+ }, Transaction = class Transaction extends BaseTransaction {
556
+ #client;
557
+ constructor(operations, client, transactionId) {
558
+ super(operations, transactionId), this.#client = client;
559
+ }
560
+ /**
561
+ * Clones the transaction
562
+ */
563
+ clone() {
564
+ return new Transaction([...this.operations], this.#client, this.trxId);
565
+ }
566
+ commit(options) {
567
+ if (!this.#client) throw Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
568
+ return this.#client.mutate(this.serialize(), Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {}));
569
+ }
570
+ patch(patchOrDocumentId, patchOps) {
571
+ let isBuilder = typeof patchOps == "function", isPatch = typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof Patch, isMutationSelection = typeof patchOrDocumentId == "object" && ("query" in patchOrDocumentId || "id" in patchOrDocumentId);
572
+ if (isPatch) return this._add({ patch: patchOrDocumentId.serialize() });
573
+ if (isBuilder) {
574
+ let patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client));
575
+ if (!(patch instanceof Patch)) throw Error("function passed to `patch()` must return the patch");
576
+ return this._add({ patch: patch.serialize() });
577
+ }
578
+ if (isMutationSelection) {
579
+ let patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client);
580
+ return this._add({ patch: patch.serialize() });
581
+ }
582
+ return this._add({ patch: {
583
+ id: patchOrDocumentId,
584
+ ...patchOps
585
+ } });
586
+ }
587
+ }, ObservableTransaction = class ObservableTransaction extends BaseTransaction {
588
+ #client;
589
+ constructor(operations, client, transactionId) {
590
+ super(operations, transactionId), this.#client = client;
591
+ }
592
+ /**
593
+ * Clones the transaction
594
+ */
595
+ clone() {
596
+ return new ObservableTransaction([...this.operations], this.#client, this.trxId);
597
+ }
598
+ commit(options) {
599
+ if (!this.#client) throw Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
600
+ return this.#client.mutate(this.serialize(), Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {}));
601
+ }
602
+ patch(patchOrDocumentId, patchOps) {
603
+ let isBuilder = typeof patchOps == "function";
604
+ if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof ObservablePatch) return this._add({ patch: patchOrDocumentId.serialize() });
605
+ if (isBuilder) {
606
+ let patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client));
607
+ if (!(patch instanceof ObservablePatch)) throw Error("function passed to `patch()` must return the patch");
608
+ return this._add({ patch: patch.serialize() });
609
+ }
610
+ return this._add({ patch: {
611
+ id: patchOrDocumentId,
612
+ ...patchOps
613
+ } });
614
+ }
615
+ };
616
+ /**
617
+ * Project the public request options (`timeout: 0` to disable,
618
+ * `withCredentials`, `maxRedirects`, the function/object-form `fetch`, ...)
619
+ * plus the client config into a get-it v9 fetch-shaped request. This is the
620
+ * single translation boundary between the client's public option names and
621
+ * the transport — everything below it speaks get-it v9.
622
+ *
623
+ * Reads the live client config, so reconfiguration via `client.config()` /
624
+ * `withConfig()` (token, headers, proxy, ...) applies to subsequent requests.
625
+ *
626
+ * @internal
627
+ */
628
+ function requestOptions(config, overrides = {}) {
629
+ let headers = {};
630
+ config.headers && Object.assign(headers, config.headers);
631
+ let token = overrides.token || config.token;
632
+ token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers["X-Sanity-Project-ID"] = config.projectId);
633
+ let request = {
634
+ url: overrides.url,
635
+ headers: Object.assign(headers, overrides.headers || {})
636
+ };
637
+ overrides.method && (request.method = overrides.method), overrides.body !== void 0 && (request.body = overrides.body), overrides.query && (request.query = expandQueryArrays(overrides.query)), overrides.signal && (request.signal = overrides.signal), (overrides.withCredentials === void 0 ? config.withCredentials : overrides.withCredentials) && (request.credentials = "include"), typeof overrides.maxRedirects == "number" && (request.redirect = overrides.maxRedirects === 0 ? "manual" : "follow");
638
+ let timeout = overrides.timeout === void 0 ? config.timeout : overrides.timeout;
639
+ request.timeout = timeout === void 0 ? 3e5 : timeout !== 0 && timeout, overrides.useAbortSignal === !1 && !request.signal && (request.timeout = typeof request.timeout == "number" && request.timeout > 0 && {
640
+ total: request.timeout,
641
+ signal: !1
642
+ });
643
+ let fetchOption = typeof overrides.fetch == "object" && typeof config.fetch == "object" ? {
644
+ ...config.fetch,
645
+ ...overrides.fetch
646
+ } : overrides.fetch || config.fetch;
647
+ return typeof fetchOption == "function" ? request.fetch = fetchOption : typeof fetchOption == "object" && fetchOption && (request.meta = {
648
+ ...request.meta,
649
+ fetchInit: fetchOption
650
+ }), !request.fetch && config.resolveFetch && (request.fetch = config.resolveFetch(typeof config.proxy == "string" ? config.proxy : void 0)), typeof overrides.maxRetries == "number" && (request.maxRetries = overrides.maxRetries), typeof config.lineage == "string" && config.lineage && (request.meta = {
651
+ ...request.meta,
652
+ lineage: config.lineage
653
+ }), request;
654
+ }
655
+ /**
656
+ * Expand array-valued query params into repeated keys.
657
+ *
658
+ * get-it v9 stringifies a plain object's values directly, so passing
659
+ * `{meta: ['palette', 'location']}` would produce `?meta=palette,location`
660
+ * — which Content Lake doesn't recognise. Repeated keys
661
+ * (`?meta=palette&meta=location`) are produced via `URLSearchParams`.
662
+ */
663
+ function expandQueryArrays(query) {
664
+ if (query instanceof URLSearchParams || !query || typeof query != "object" || !Object.values(query).some(Array.isArray)) return query;
665
+ let params = new URLSearchParams();
666
+ for (let [key, value] of Object.entries(query)) if (value != null) {
667
+ if (Array.isArray(value)) for (let item of value) item != null && params.append(key, `${item}`);
668
+ else params.append(key, `${value}`);
669
+ }
670
+ return params;
671
+ }
672
+ var import_dist = require_dist();
673
+ /**
674
+ * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`
675
+ * and remove all stega-encoded data from it.
676
+ * If the result type has strings branded as `StegaString` (by `ClientReturnStega` or `stegaBrand()`),
677
+ * the brand is stripped and the original string type is restored.
678
+ * @public
679
+ */
680
+ function stegaClean(result) {
681
+ return (0, import_dist.vercelStegaClean)(result);
682
+ }
683
+ const encodeQueryString = ({ query, params = {}, options = {} }) => {
684
+ let searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;
685
+ tag && searchParams.append("tag", tag), searchParams.append("query", query);
686
+ for (let [key, value] of Object.entries(params)) value !== void 0 && searchParams.append(`$${key}`, JSON.stringify(value));
687
+ for (let [key, value] of Object.entries(opts)) value && searchParams.append(key, `${value}`);
688
+ return returnQuery === !1 && searchParams.append("returnQuery", "false"), includeMutations === !1 && searchParams.append("includeMutations", "false"), `?${searchParams}`;
689
+ }, excludeFalsey = (param, defValue) => param === !1 ? void 0 : param === void 0 ? defValue : param, getMutationQuery = (options = {}) => ({
690
+ dryRun: options.dryRun,
691
+ returnIds: !0,
692
+ returnDocuments: excludeFalsey(options.returnDocuments, !0),
693
+ visibility: options.visibility || "sync",
694
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
695
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
696
+ }), indexBy = (docs, attr) => docs.reduce((indexed, doc) => (indexed[attr(doc)] = doc, indexed), Object.create(null));
697
+ /**
698
+ * Resolve the effective stega config, cleaned params, response mapper and
699
+ * transport request options for a `fetch()` call. Shared by the observable and
700
+ * promise paths.
701
+ *
702
+ * @internal
703
+ */
704
+ function _fetchRequest(_stega, _params, options) {
705
+ let stega = "stega" in options ? {
706
+ ..._stega,
707
+ ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
708
+ } : _stega, params = stega.enabled ? stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
709
+ useAbortSignal: options.signal !== void 0,
710
+ resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
711
+ ...options,
712
+ returnQuery: options.filterResponse === !1 && options.returnQuery !== !1
713
+ };
714
+ return {
715
+ stega,
716
+ params,
717
+ mapResponse,
718
+ reqOpts: cache !== void 0 || next !== void 0 ? {
719
+ ...opts,
720
+ fetch: {
721
+ cache,
722
+ next
723
+ }
724
+ } : opts
725
+ };
726
+ }
727
+ /** @internal */
728
+ function _fetchObservable(client, httpRequest, _stega, query, _params = {}, options = {}) {
729
+ return _observe(options.signal, (signal) => _fetch(client, httpRequest, _stega, query, _params, {
730
+ ...options,
731
+ signal
732
+ }));
733
+ }
734
+ /**
735
+ * Promise-based sibling of {@link _fetchObservable}.
736
+ *
737
+ * @internal
738
+ */
739
+ function _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {
740
+ let { stega, params, mapResponse, reqOpts } = _fetchRequest(_stega, _params, options), request = _dataRequest(client, httpRequest, "query", {
741
+ query,
742
+ params
743
+ }, reqOpts);
744
+ return stega.enabled ? Promise.all([request, import("./stegaEncodeSourceMap-DbM2fTN4.js")]).then(([res, { stegaEncodeSourceMap }]) => {
745
+ let result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
746
+ return mapResponse({
747
+ ...res,
748
+ result
749
+ });
750
+ }) : request.then(mapResponse);
751
+ }
752
+ /** @internal */
753
+ function _getDocumentObservable(client, httpRequest, id, opts = {}) {
754
+ return _observe(opts.signal, (signal) => _request(client, httpRequest, _getDocumentOptions(client, id, {
755
+ ...opts,
756
+ signal
757
+ })).then((body) => _mapGetDocument(body, opts.includeAllVersions)));
758
+ }
759
+ /** @internal */
760
+ function _getDocument(client, httpRequest, id, opts = {}) {
761
+ return _request(client, httpRequest, _getDocumentOptions(client, id, opts)).then((body) => _mapGetDocument(body, opts.includeAllVersions));
762
+ }
763
+ /**
764
+ * Resolve the document id (honoring `releaseId`) and build the transport
765
+ * request options for {@link _getDocumentObservable}. Shared by the observable and
766
+ * promise paths.
767
+ *
768
+ * @internal
769
+ */
770
+ function _getDocumentOptions(client, id, opts) {
771
+ let docId = id;
772
+ if (opts.releaseId) {
773
+ let versionId = getVersionFromId(id);
774
+ if (!versionId) {
775
+ if (isDraftId(id)) throw Error(`The document ID (\`${id}\`) is a draft, but \`options.releaseId\` is set as \`${opts.releaseId}\``);
776
+ docId = getVersionId(id, opts.releaseId);
777
+ } else if (versionId !== opts.releaseId) throw Error(`The document ID (\`${id}\`) is already a version of \`${versionId}\` release, but this does not match the provided \`options.releaseId\` (\`${opts.releaseId}\`)`);
778
+ }
779
+ return {
780
+ url: _getDataUrl(client, "doc", docId),
781
+ tag: opts.tag,
782
+ signal: opts.signal,
783
+ query: opts.includeAllVersions === void 0 ? void 0 : { includeAllVersions: opts.includeAllVersions }
784
+ };
785
+ }
786
+ function _mapGetDocument(body, includeAllVersions) {
787
+ let documents = body.documents;
788
+ return documents ? includeAllVersions ? documents : documents[0] : includeAllVersions ? [] : void 0;
789
+ }
790
+ /** @internal */
791
+ function _getDocumentsObservable(client, httpRequest, ids, opts = {}) {
792
+ return _observe(opts.signal, (signal) => _getDocuments(client, httpRequest, ids, {
793
+ ...opts,
794
+ signal
795
+ }));
796
+ }
797
+ /**
798
+ * Promise-based sibling of {@link _getDocumentsObservable}.
799
+ *
800
+ * @internal
801
+ */
802
+ function _getDocuments(client, httpRequest, ids, opts = {}) {
803
+ return _request(client, httpRequest, _getDocumentsOptions(client, ids, opts)).then((body) => _mapGetDocuments(body, ids));
804
+ }
805
+ function _getDocumentsOptions(client, ids, opts) {
806
+ return {
807
+ url: _getDataUrl(client, "doc", ids.join(",")),
808
+ tag: opts.tag,
809
+ signal: opts.signal
810
+ };
811
+ }
812
+ function _mapGetDocuments(body, ids) {
813
+ let indexed = indexBy(body.documents || [], (doc) => doc._id);
814
+ return ids.map((id) => indexed[id] || null);
815
+ }
816
+ /** @internal */
817
+ function _documentsExistsObservable(client, httpRequest, ids, opts = {}) {
818
+ return _observe(opts.signal, (signal) => _documentsExists(client, httpRequest, ids, {
819
+ ...opts,
820
+ signal
821
+ }));
822
+ }
823
+ /**
824
+ * Promise-based sibling of {@link _documentsExistsObservable}. Checks document
825
+ * existence in batches, resolving to the set of IDs that exist.
826
+ *
827
+ * @internal
828
+ */
829
+ async function _documentsExists(client, httpRequest, ids, opts = {}) {
830
+ let existing = /* @__PURE__ */ new Set();
831
+ if (ids.length === 0) return existing;
832
+ for (let i = 0; i < ids.length; i += 100) {
833
+ let batchIds = ids.slice(i, i + 100), body = await _request(client, httpRequest, {
834
+ url: _getDataUrl(client, "doc", batchIds.map(encodeURIComponent).join(",")),
835
+ tag: opts.tag,
836
+ signal: opts.signal,
837
+ query: { excludeContent: !0 }
838
+ }), missing = /* @__PURE__ */ new Set();
839
+ for (let omitted of body.omitted || []) omitted.reason === "existence" && missing.add(omitted.id);
840
+ for (let id of batchIds) missing.has(id) || existing.add(id);
841
+ }
842
+ return existing;
843
+ }
844
+ /** @internal */
845
+ function _getReleaseDocumentsObservable(client, httpRequest, releaseId, opts = {}) {
846
+ return _observe(opts.signal, (signal) => _getReleaseDocuments(client, httpRequest, releaseId, {
847
+ ...opts,
848
+ signal
849
+ }));
850
+ }
851
+ /**
852
+ * Promise-based sibling of {@link _getReleaseDocumentsObservable}.
853
+ *
854
+ * @internal
855
+ */
856
+ function _getReleaseDocuments(client, httpRequest, releaseId, opts = {}) {
857
+ return _dataRequest(client, httpRequest, "query", {
858
+ query: "*[sanity::partOfRelease($releaseId)]",
859
+ params: { releaseId }
860
+ }, opts);
861
+ }
862
+ /** @internal */
863
+ function _createIfNotExistsObservable(client, httpRequest, doc, options) {
864
+ return _observe(options?.signal, (signal) => _createIfNotExists(client, httpRequest, doc, {
865
+ ...options,
866
+ signal
867
+ }));
868
+ }
869
+ /** @internal */
870
+ function _createOrReplaceObservable(client, httpRequest, doc, options) {
871
+ return _observe(options?.signal, (signal) => _createOrReplace(client, httpRequest, doc, {
872
+ ...options,
873
+ signal
874
+ }));
875
+ }
876
+ /** @internal */
877
+ function _createVersionObservable(client, httpRequest, doc, publishedId, options) {
878
+ return _observe(options?.signal, (signal) => _createVersion(client, httpRequest, doc, publishedId, {
879
+ ...options,
880
+ signal
881
+ }));
882
+ }
883
+ /** @internal */
884
+ function _createVersionFromBaseObservable(client, httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options) {
885
+ return _observe(options?.signal, (signal) => _createVersionFromBase(client, httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, {
886
+ ...options,
887
+ signal
888
+ }));
889
+ }
890
+ /** @internal */
891
+ function _deleteObservable(client, httpRequest, selection, options) {
892
+ return _observe(options?.signal, (signal) => _delete(client, httpRequest, selection, {
893
+ ...options,
894
+ signal
895
+ }));
896
+ }
897
+ /** @internal */
898
+ function _discardVersionObservable(client, httpRequest, versionId, purge = !1, options) {
899
+ return _observe(options?.signal, (signal) => _discardVersion(client, httpRequest, versionId, purge, {
900
+ ...options,
901
+ signal
902
+ }));
903
+ }
904
+ /** @internal */
905
+ function _replaceVersionObservable(client, httpRequest, doc, options) {
906
+ return _observe(options?.signal, (signal) => _replaceVersion(client, httpRequest, doc, {
907
+ ...options,
908
+ signal
909
+ }));
910
+ }
911
+ /** @internal */
912
+ function _unpublishVersionObservable(client, httpRequest, versionId, publishedId, options) {
913
+ return _observe(options?.signal, (signal) => _unpublishVersion(client, httpRequest, versionId, publishedId, {
914
+ ...options,
915
+ signal
916
+ }));
917
+ }
918
+ /** @internal */
919
+ function _mutateObservable(client, httpRequest, mutations, options) {
920
+ return _observe(options?.signal, (signal) => _mutate(client, httpRequest, mutations, {
921
+ ...options,
922
+ signal
923
+ }));
924
+ }
925
+ /**
926
+ * @internal
927
+ */
928
+ function _actionObservable(client, httpRequest, actions, options) {
929
+ return _observe(options?.signal, (signal) => _action(client, httpRequest, actions, {
930
+ ...options,
931
+ signal
932
+ }));
933
+ }
934
+ /**
935
+ * Build the transport request options for a data endpoint (`query` / `mutate`
936
+ * / `actions`). Shared by the observable and promise request paths.
937
+ *
938
+ * @internal
939
+ */
940
+ function _dataRequestOptions(client, endpoint, body, options = {}) {
941
+ let isMutation = endpoint === "mutate", isAction = endpoint === "actions", isQuery = endpoint === "query", strQuery = isMutation || isAction ? "" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < 11264, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode } = options, url = _getDataUrl(client, endpoint, stringQuery);
942
+ return {
943
+ reqOptions: {
944
+ method: useGet ? "GET" : "POST",
945
+ url,
946
+ body: useGet ? void 0 : body,
947
+ query: isMutation && getMutationQuery(options),
948
+ timeout,
949
+ headers,
950
+ token,
951
+ tag,
952
+ returnQuery,
953
+ perspective: options.perspective,
954
+ variant: options.variant,
955
+ resultSourceMap: options.resultSourceMap,
956
+ lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,
957
+ cacheMode,
958
+ canUseCdn: isQuery,
959
+ signal: options.signal,
960
+ fetch: options.fetch,
961
+ useAbortSignal: options.useAbortSignal,
962
+ useCdn: options.useCdn
963
+ },
964
+ isMutation,
965
+ returnFirst
966
+ };
967
+ }
968
+ /**
969
+ * Shape the raw response body of a data request. For mutations this reduces
970
+ * the API response to documents or ids; everything else passes through. Pure
971
+ * function shared by the observable and promise request paths.
972
+ *
973
+ * @internal
974
+ */
975
+ function _mapDataResponse(res, isMutation, returnFirst, returnDocuments) {
976
+ if (!isMutation) return res;
977
+ let results = res.results || [];
978
+ if (returnDocuments) return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
979
+ let key = returnFirst ? "documentId" : "documentIds", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
980
+ return {
981
+ transactionId: res.transactionId,
982
+ results,
983
+ [key]: ids
984
+ };
985
+ }
986
+ /**
987
+ * @internal
988
+ */
989
+ function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
990
+ let { reqOptions, isMutation, returnFirst } = _dataRequestOptions(client, endpoint, body, options);
991
+ return _request(client, httpRequest, reqOptions).then((res) => _mapDataResponse(res, isMutation, returnFirst, options.returnDocuments));
992
+ }
993
+ /**
994
+ * @internal
995
+ */
996
+ function _createObservable(client, httpRequest, doc, op, options = {}) {
997
+ return _observe(options.signal, (signal) => _create(client, httpRequest, doc, op, {
998
+ ...options,
999
+ signal
1000
+ }));
1001
+ }
1002
+ /**
1003
+ * Promise-based sibling of {@link _createObservable}.
1004
+ *
1005
+ * @internal
1006
+ */
1007
+ function _create(client, httpRequest, doc, op, options = {}) {
1008
+ let mutation = { [op]: doc }, opts = Object.assign({
1009
+ returnFirst: !0,
1010
+ returnDocuments: !0
1011
+ }, options);
1012
+ return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
1013
+ }
1014
+ /**
1015
+ * Promise-based sibling of {@link _actionObservable}.
1016
+ *
1017
+ * @internal
1018
+ */
1019
+ function _action(client, httpRequest, actions, options) {
1020
+ return _dataRequest(client, httpRequest, "actions", {
1021
+ actions: Array.isArray(actions) ? actions : [actions],
1022
+ transactionId: options && options.transactionId || void 0,
1023
+ skipCrossDatasetReferenceValidation: options && options.skipCrossDatasetReferenceValidation || void 0,
1024
+ dryRun: options && options.dryRun || void 0
1025
+ }, options);
1026
+ }
1027
+ /**
1028
+ * Promise-based sibling of {@link _mutateObservable}.
1029
+ *
1030
+ * @internal
1031
+ */
1032
+ function _mutate(client, httpRequest, mutations, options) {
1033
+ let mut;
1034
+ return mut = mutations instanceof Patch || mutations instanceof ObservablePatch ? { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mutations.serialize() : mutations, _dataRequest(client, httpRequest, "mutate", {
1035
+ mutations: Array.isArray(mut) ? mut : [mut],
1036
+ transactionId: options && options.transactionId || void 0
1037
+ }, options);
1038
+ }
1039
+ /**
1040
+ * Promise-based sibling of {@link _deleteObservable}.
1041
+ *
1042
+ * @internal
1043
+ */
1044
+ function _delete(client, httpRequest, selection, options) {
1045
+ return _dataRequest(client, httpRequest, "mutate", { mutations: [{ delete: getSelection(selection) }] }, options);
1046
+ }
1047
+ /**
1048
+ * Promise-based sibling of {@link _createIfNotExistsObservable}.
1049
+ *
1050
+ * @internal
1051
+ */
1052
+ function _createIfNotExists(client, httpRequest, doc, options) {
1053
+ return requireDocumentId("createIfNotExists", doc), _create(client, httpRequest, doc, "createIfNotExists", options);
1054
+ }
1055
+ /**
1056
+ * Promise-based sibling of {@link _createOrReplaceObservable}.
1057
+ *
1058
+ * @internal
1059
+ */
1060
+ function _createOrReplace(client, httpRequest, doc, options) {
1061
+ return requireDocumentId("createOrReplace", doc), _create(client, httpRequest, doc, "createOrReplace", options);
1062
+ }
1063
+ /**
1064
+ * Promise-based sibling of {@link _createVersionObservable}.
1065
+ *
1066
+ * @internal
1067
+ */
1068
+ function _createVersion(client, httpRequest, doc, publishedId, options) {
1069
+ return requireDocumentId("createVersion", doc), requireDocumentType("createVersion", doc), printCreateVersionWithBaseIdWarning(), _action(client, httpRequest, {
1070
+ actionType: "sanity.action.document.version.create",
1071
+ publishedId,
1072
+ document: doc
1073
+ }, options);
1074
+ }
1075
+ /**
1076
+ * Promise-based sibling of {@link _createVersionFromBaseObservable}.
1077
+ *
1078
+ * @internal
1079
+ */
1080
+ function _createVersionFromBase(client, httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options) {
1081
+ if (!baseId) throw Error("`createVersion()` requires `baseId` when no `document` is provided");
1082
+ if (!publishedId) throw Error("`createVersion()` requires `publishedId` when `baseId` is provided");
1083
+ return validateDocumentId("createVersion", baseId), validateDocumentId("createVersion", publishedId), _action(client, httpRequest, {
1084
+ actionType: "sanity.action.document.version.create",
1085
+ publishedId,
1086
+ baseId,
1087
+ versionId: releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId),
1088
+ ifBaseRevisionId
1089
+ }, options);
1090
+ }
1091
+ /**
1092
+ * Promise-based sibling of {@link _discardVersionObservable}.
1093
+ *
1094
+ * @internal
1095
+ */
1096
+ function _discardVersion(client, httpRequest, versionId, purge = !1, options) {
1097
+ return _action(client, httpRequest, {
1098
+ actionType: "sanity.action.document.version.discard",
1099
+ versionId,
1100
+ purge
1101
+ }, options);
1102
+ }
1103
+ /**
1104
+ * Promise-based sibling of {@link _replaceVersionObservable}.
1105
+ *
1106
+ * @internal
1107
+ */
1108
+ function _replaceVersion(client, httpRequest, doc, options) {
1109
+ return requireDocumentId("replaceVersion", doc), requireDocumentType("replaceVersion", doc), _action(client, httpRequest, {
1110
+ actionType: "sanity.action.document.version.replace",
1111
+ document: doc
1112
+ }, options);
1113
+ }
1114
+ /**
1115
+ * Promise-based sibling of {@link _unpublishVersionObservable}.
1116
+ *
1117
+ * @internal
1118
+ */
1119
+ function _unpublishVersion(client, httpRequest, versionId, publishedId, options) {
1120
+ return _action(client, httpRequest, {
1121
+ actionType: "sanity.action.document.version.unpublish",
1122
+ versionId,
1123
+ publishedId
1124
+ }, options);
1125
+ }
1126
+ const hasDataConfig = (client) => {
1127
+ let config = client.config();
1128
+ return config.dataset !== void 0 && config.projectId !== void 0 || config.resource !== void 0;
1129
+ }, 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);
1130
+ /**
1131
+ * Build the final request options (URL, headers, query params, etc.) used by
1132
+ * both the regular request pipeline and the asset upload path.
1133
+ *
1134
+ * @internal
1135
+ */
1136
+ function _prepareRequest(client, options) {
1137
+ options.uri !== void 0 && printDeprecatedUriOptionWarning();
1138
+ let uri = options.uri || options.url;
1139
+ if (typeof uri != "string") throw TypeError("Request options must include a `url`");
1140
+ let config = client.config(), canUseCdn = options.canUseCdn === void 0 ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(client, uri) : options.canUseCdn, useCdn = (options.useCdn ?? config.useCdn) && canUseCdn, tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
1141
+ if (tag && options.tag !== null && (options.query = {
1142
+ tag: requestTag(tag),
1143
+ ...options.query
1144
+ }), [
1145
+ "GET",
1146
+ "HEAD",
1147
+ "POST"
1148
+ ].indexOf(options.method || "GET") >= 0 && isQuery(client, uri)) {
1149
+ let resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;
1150
+ resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = {
1151
+ resultSourceMap,
1152
+ ...options.query
1153
+ });
1154
+ let perspectiveOption = options.perspective || config.perspective;
1155
+ perspectiveOption !== void 0 && (perspectiveOption === "previewDrafts" && printPreviewDraftsDeprecationWarning(), validateApiPerspective(perspectiveOption), options.query = {
1156
+ perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption,
1157
+ ...options.query
1158
+ }, (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || perspectiveOption === "previewDrafts" || perspectiveOption === "drafts") && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning()));
1159
+ let variantOption = options.variant || config.variant;
1160
+ typeof variantOption == "string" && (options.query = {
1161
+ variant: variantOption,
1162
+ ...options.query
1163
+ }), typeof variantOption == "object" && (options.query = {
1164
+ variantCondition: variantConditionsToQueryArray(variantOption),
1165
+ ...options.query
1166
+ }), options.lastLiveEventId && (options.query = {
1167
+ ...options.query,
1168
+ lastLiveEventId: options.lastLiveEventId
1169
+ }), options.returnQuery === !1 && (options.query = {
1170
+ returnQuery: "false",
1171
+ ...options.query
1172
+ }), useCdn && options.cacheMode == "noStale" && (options.query = {
1173
+ cacheMode: "noStale",
1174
+ ...options.query
1175
+ });
1176
+ }
1177
+ return requestOptions(config, Object.assign({}, options, { url: _getUrl(client, uri, useCdn) }));
1178
+ }
1179
+ /**
1180
+ * Wrap a promise-returning request in a cold, single-value Observable.
1181
+ *
1182
+ * Each subscription invokes `run` with a fresh `AbortSignal` that is aborted
1183
+ * when the subscriber unsubscribes — so unsubscribing cancels the in-flight
1184
+ * `fetch`. A caller-supplied `userSignal` is chained in too, so the request
1185
+ * still aborts when the caller's own signal fires. The single resolved value
1186
+ * (or rejection) is forwarded to the subscriber.
1187
+ *
1188
+ * This is the bridge that lets the observable client surface reuse the exact
1189
+ * same promise implementations as the promise client surface, with no
1190
+ * duplicated request logic.
1191
+ *
1192
+ * @internal
1193
+ */
1194
+ function _observe(userSignal, run) {
1195
+ return new Observable((subscriber) => {
1196
+ let controller = new AbortController();
1197
+ return run(userSignal ? AbortSignal.any([userSignal, controller.signal]) : controller.signal).then((value) => {
1198
+ subscriber.next(value), subscriber.complete();
1199
+ }, (err) => subscriber.error(err)), () => controller.abort();
1200
+ });
1201
+ }
1202
+ /**
1203
+ * Promise-based sibling of {@link _requestObservable}. Resolves directly to
1204
+ * the parsed response body without ever constructing an Observable. The abort
1205
+ * signal is honored by the underlying `fetch` (it is threaded onto the request
1206
+ * options), so no RxJS-level teardown is required.
1207
+ *
1208
+ * @internal
1209
+ */
1210
+ function _request(client, httpRequest, options) {
1211
+ return httpRequest(_prepareRequest(client, options), client.config().requestHandler).then((body) => body);
1212
+ }
1213
+ /**
1214
+ * Execute an HTTP request through the regular pipeline and resolve to the
1215
+ * parsed response body. Observable wrapper over {@link _request}.
1216
+ *
1217
+ * @internal
1218
+ */
1219
+ function _requestObservable(client, httpRequest, options) {
1220
+ return _observe(options.signal, (signal) => _request(client, httpRequest, {
1221
+ ...options,
1222
+ signal
1223
+ }));
1224
+ }
1225
+ /**
1226
+ * Execute an asset upload through the underlying requester directly,
1227
+ * exposing the full upload event stream (progress + response).
1228
+ *
1229
+ * Bypasses the body-only `HttpRequest` boundary so progress events from the
1230
+ * transport layer can surface to consumers, reading the resolved requester
1231
+ * straight off the initialized config.
1232
+ *
1233
+ * @internal
1234
+ */
1235
+ function _uploadObservable(client, options) {
1236
+ let reqOptions = _prepareRequest(client, options), requester = client.config().requester, request = new Observable((subscriber) => requester(reqOptions).subscribe(subscriber)).pipe(filter((event) => event?.type === "progress" || event?.type === "response"), map$1((event) => event.type === "progress" ? {
1237
+ type: "progress",
1238
+ stage: event.stage,
1239
+ percent: event.percent,
1240
+ total: event.total,
1241
+ loaded: event.loaded,
1242
+ lengthComputable: event.lengthComputable
1243
+ } : {
1244
+ type: "response",
1245
+ body: event.body
1246
+ }));
1247
+ return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
1248
+ }
1249
+ /**
1250
+ * @internal
1251
+ */
1252
+ function _getDataUrl(client, operation, path) {
1253
+ let config = client.config();
1254
+ if (config.resource) return resourceConfig(config), `${resourceDataBase(config)}/${path === void 0 ? operation : `${operation}/${path}`}`.replace(/\/($|\?)/, "$1");
1255
+ let baseUri = `/${operation}/${hasDataset(config)}`;
1256
+ return `/data${path === void 0 ? baseUri : `${baseUri}/${path}`}`.replace(/\/($|\?)/, "$1");
1257
+ }
1258
+ /**
1259
+ * @internal
1260
+ */
1261
+ function _getUrl(client, uri, canUseCdn = !1) {
1262
+ let { url, cdnUrl } = client.config();
1263
+ return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
1264
+ }
1265
+ /**
1266
+ * @internal
1267
+ */
1268
+ function _withAbortSignal(signal) {
1269
+ return (input) => new Observable((observer) => {
1270
+ let abort = () => observer.error(_createAbortError(signal));
1271
+ if (signal && signal.aborted) {
1272
+ abort();
1273
+ return;
1274
+ }
1275
+ let subscription = input.subscribe(observer);
1276
+ return signal.addEventListener("abort", abort), () => {
1277
+ signal.removeEventListener("abort", abort), subscription.unsubscribe();
1278
+ };
1279
+ });
1280
+ }
1281
+ /**
1282
+ * `DOMException` is globally available in every supported runtime
1283
+ * (Node 22.12+ and all modern browsers), so we can construct one directly.
1284
+ *
1285
+ * @internal
1286
+ */
1287
+ function _createAbortError(signal) {
1288
+ return new DOMException(signal?.reason ?? "The operation was aborted.", "AbortError");
1289
+ }
1290
+ const resourceDataBase = (config) => {
1291
+ let resource = config.resource;
1292
+ if (!resource) throw Error("`resource` must be provided to perform resource queries");
1293
+ let { type, id } = resource;
1294
+ switch (type) {
1295
+ case "dataset": {
1296
+ let segments = id.split(".");
1297
+ if (segments.length !== 2) throw Error("Dataset ID must be in the format \"project.dataset\"");
1298
+ return `/projects/${segments[0]}/datasets/${segments[1]}`;
1299
+ }
1300
+ case "canvas": return `/canvases/${id}`;
1301
+ case "media-library": return `/media-libraries/${id}`;
1302
+ case "dashboard": return `/dashboards/${id}`;
1303
+ default: throw Error(`Unsupported resource type: ${type.toString()}`);
1304
+ }
1305
+ };
1306
+ function variantConditionsToQueryArray(variantConditions) {
1307
+ return Object.entries(variantConditions).map(([condition, value]) => `${condition}:${value}`).toSorted();
1308
+ }
1309
+ function _generateObservable(client, httpRequest, request) {
1310
+ return _requestObservable(client, httpRequest, {
1311
+ method: "POST",
1312
+ url: `/agent/action/generate/${hasDataset(client.config())}`,
1313
+ body: request
1314
+ });
1315
+ }
1316
+ function _generate(client, httpRequest, request) {
1317
+ return _request(client, httpRequest, {
1318
+ method: "POST",
1319
+ url: `/agent/action/generate/${hasDataset(client.config())}`,
1320
+ body: request
1321
+ });
1322
+ }
1323
+ function _patch(client, httpRequest, request) {
1324
+ return _request(client, httpRequest, {
1325
+ method: "POST",
1326
+ url: `/agent/action/patch/${hasDataset(client.config())}`,
1327
+ body: request
1328
+ });
1329
+ }
1330
+ function _prompt(client, httpRequest, request) {
1331
+ return _request(client, httpRequest, {
1332
+ method: "POST",
1333
+ url: `/agent/action/prompt/${hasDataset(client.config())}`,
1334
+ body: request
1335
+ });
1336
+ }
1337
+ function _transformObservable(client, httpRequest, request) {
1338
+ return _requestObservable(client, httpRequest, {
1339
+ method: "POST",
1340
+ url: `/agent/action/transform/${hasDataset(client.config())}`,
1341
+ body: request
1342
+ });
1343
+ }
1344
+ function _transform(client, httpRequest, request) {
1345
+ return _request(client, httpRequest, {
1346
+ method: "POST",
1347
+ url: `/agent/action/transform/${hasDataset(client.config())}`,
1348
+ body: request
1349
+ });
1350
+ }
1351
+ function _translateObservable(client, httpRequest, request) {
1352
+ return _requestObservable(client, httpRequest, {
1353
+ method: "POST",
1354
+ url: `/agent/action/translate/${hasDataset(client.config())}`,
1355
+ body: request
1356
+ });
1357
+ }
1358
+ function _translate(client, httpRequest, request) {
1359
+ return _request(client, httpRequest, {
1360
+ method: "POST",
1361
+ url: `/agent/action/translate/${hasDataset(client.config())}`,
1362
+ body: request
1363
+ });
1364
+ }
1365
+ /** @public */
1366
+ var ObservableAgentsActionClient = class {
1367
+ #client;
1368
+ #httpRequest;
1369
+ constructor(client, httpRequest) {
1370
+ this.#client = client, this.#httpRequest = httpRequest;
1371
+ }
1372
+ /**
1373
+ * Run an instruction to generate content in a target document.
1374
+ * @param request - instruction request
1375
+ */
1376
+ generate(request) {
1377
+ return _generateObservable(this.#client, this.#httpRequest, request);
1378
+ }
1379
+ /**
1380
+ * Transform a target document based on a source.
1381
+ * @param request - translation request
1382
+ */
1383
+ transform(request) {
1384
+ return _transformObservable(this.#client, this.#httpRequest, request);
1385
+ }
1386
+ /**
1387
+ * Translate a target document based on a source.
1388
+ * @param request - translation request
1389
+ */
1390
+ translate(request) {
1391
+ return _translateObservable(this.#client, this.#httpRequest, request);
1392
+ }
1393
+ }, AgentActionsClient = class {
1394
+ #client;
1395
+ #httpRequest;
1396
+ constructor(client, httpRequest) {
1397
+ this.#client = client, this.#httpRequest = httpRequest;
1398
+ }
1399
+ /**
1400
+ * Run an instruction to generate content in a target document.
1401
+ * @param request - instruction request
1402
+ */
1403
+ generate(request) {
1404
+ return _generate(this.#client, this.#httpRequest, request);
1405
+ }
1406
+ /**
1407
+ * Transform a target document based on a source.
1408
+ * @param request - translation request
1409
+ */
1410
+ transform(request) {
1411
+ return _transform(this.#client, this.#httpRequest, request);
1412
+ }
1413
+ /**
1414
+ * Translate a target document based on a source.
1415
+ * @param request - translation request
1416
+ */
1417
+ translate(request) {
1418
+ return _translate(this.#client, this.#httpRequest, request);
1419
+ }
1420
+ /**
1421
+ * Run a raw instruction and return the result either as text or json
1422
+ * @param request - prompt request
1423
+ */
1424
+ prompt(request) {
1425
+ return _prompt(this.#client, this.#httpRequest, request);
1426
+ }
1427
+ /**
1428
+ * Patch a document using a schema aware API.
1429
+ * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.
1430
+ * @param request - instruction request
1431
+ */
1432
+ patch(request) {
1433
+ return _patch(this.#client, this.#httpRequest, request);
1434
+ }
1435
+ }, ObservableAssetsClient = class {
1436
+ #client;
1437
+ #httpRequest;
1438
+ constructor(client, httpRequest) {
1439
+ this.#client = client, this.#httpRequest = httpRequest;
1440
+ }
1441
+ upload(assetType, body, options) {
1442
+ return _upload(this.#client, this.#httpRequest, assetType, body, options);
1443
+ }
1444
+ }, AssetsClient = class {
1445
+ #client;
1446
+ #httpRequest;
1447
+ constructor(client, httpRequest) {
1448
+ this.#client = client, this.#httpRequest = httpRequest;
1449
+ }
1450
+ upload(assetType, body, options) {
1451
+ let observable = _upload(this.#client, this.#httpRequest, assetType, body, options);
1452
+ return lastValueFrom(observable.pipe(filter((event) => event.type === "response"), map$1((event) => pluckUploadedAsset(event.body))));
1453
+ }
1454
+ };
1455
+ /**
1456
+ * Content Lake's upload endpoint responds with `{document: ...}`; the Media
1457
+ * Library upload endpoint responds with `{asset: ...}` instead (a
1458
+ * `sanity.asset` document, not a Content Lake asset document). Narrowing on
1459
+ * the response body itself - rather than on the client's `resource` config -
1460
+ * keeps this correct regardless of how the two are ever wired together.
1461
+ */
1462
+ function isMediaLibraryUploadBody(body) {
1463
+ return "asset" in body;
1464
+ }
1465
+ function pluckUploadedAsset(body) {
1466
+ return isMediaLibraryUploadBody(body) ? body.asset : body.document;
1467
+ }
1468
+ function _upload(client, _httpRequest, assetType, body, opts = {}) {
1469
+ validateAssetType(assetType);
1470
+ let meta = opts.extract || void 0;
1471
+ meta && !meta.length && (meta = ["none"]);
1472
+ let config = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, isMediaLibrary = config.resource?.type === "media-library", query = isMediaLibrary ? {
1473
+ title,
1474
+ filename
1475
+ } : {
1476
+ label,
1477
+ title,
1478
+ description,
1479
+ filename,
1480
+ meta,
1481
+ creditLine
1482
+ };
1483
+ source && !isMediaLibrary && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url);
1484
+ let headers = options.contentType ? { "Content-Type": options.contentType } : {}, baseRequest = {
1485
+ tag,
1486
+ method: "POST",
1487
+ timeout: options.timeout || 0,
1488
+ url: buildAssetUploadUrl(config, assetType),
1489
+ headers,
1490
+ query,
1491
+ body
1492
+ };
1493
+ return typeof XMLHttpRequest < "u" ? defer(async () => {
1494
+ let { uploadWithProgress } = await import("./browserUpload-2tz6Sdqp.js"), req = _prepareRequest(client, { ...baseRequest });
1495
+ return uploadWithProgress({
1496
+ url: appendQuery(req.url, req.query),
1497
+ method: req.method ?? "POST",
1498
+ headers: req.headers,
1499
+ body,
1500
+ withCredentials: req.credentials === "include",
1501
+ timeout: typeof req.timeout == "object" ? req.timeout.total : req.timeout,
1502
+ signal: req.signal
1503
+ });
1504
+ }).pipe(mergeAll()) : _uploadObservable(client, baseRequest);
1505
+ }
1506
+ function appendQuery(url, query) {
1507
+ if (!query) return url;
1508
+ let qs = (query instanceof URLSearchParams ? query : new URLSearchParams(Object.entries(query).flatMap(([key, value]) => value == null ? [] : [[key, `${value}`]]))).toString();
1509
+ return qs ? url + (url.includes("?") ? "&" : "?") + qs : url;
1510
+ }
1511
+ function buildAssetUploadUrl(config, assetType) {
1512
+ let assetTypeEndpoint = assetType === "image" ? "images" : "files", resource = config.resource;
1513
+ if (resource) {
1514
+ let { type, id } = resource;
1515
+ switch (type) {
1516
+ case "dataset": throw Error("Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.");
1517
+ case "canvas": return `/canvases/${id}/assets/${assetTypeEndpoint}`;
1518
+ case "media-library": return `/media-libraries/${id}/upload`;
1519
+ case "dashboard": return `/dashboards/${id}/assets/${assetTypeEndpoint}`;
1520
+ default: throw Error(`Unsupported resource type: ${type.toString()}`);
1521
+ }
1522
+ }
1523
+ return `assets/${assetTypeEndpoint}/${hasDataset(config)}`;
1524
+ }
1525
+ function optionsFromFile(opts, file) {
1526
+ return typeof File > "u" || !(file instanceof File) ? opts : Object.assign({
1527
+ filename: opts.preserveFilename === !1 ? void 0 : file.name,
1528
+ contentType: file.type
1529
+ }, opts);
1530
+ }
1531
+ var defaults_default = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = obj[prop] === void 0 ? defaults[prop] : obj[prop], target), {});
1532
+ const pick = (obj, props) => props.reduce((selection, prop) => (obj[prop] === void 0 || (selection[prop] = obj[prop]), selection), {}), RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429]);
1533
+ /**
1534
+ * Note: connection failure is not the same as network disconnect which may happen more frequent.
1535
+ * The EventSource instance will automatically reconnect in case of a network disconnect, however,
1536
+ * in some rare cases a ConnectionFailed Error will be thrown and this operator explicitly retries these
1537
+ */
1538
+ function reconnectOnConnectionFailure() {
1539
+ return function(source) {
1540
+ return source.pipe(catchError((err, caught) => err instanceof ConnectionFailedError && (typeof err.status != "number" || err.status < 400 || err.status >= 500 || RETRYABLE_STATUSES.has(err.status)) ? concat(of({ type: "reconnect" }), timer(1e3).pipe(mergeMap(() => caught))) : throwError(() => err)));
1541
+ };
1542
+ }
1543
+ /**
1544
+ * Build a `fetch` implementation suitable for the `eventsource` package's
1545
+ * `fetch` option. Routes the EventSource connection through the same
1546
+ * transport layer the rest of the client uses, so things like the
1547
+ * test-fetch override, the per-request `proxy` config, and `HTTPS_PROXY`
1548
+ * env-var support apply to SSE too.
1549
+ *
1550
+ * Resolution order on each request:
1551
+ *
1552
+ * 1. `config.resolveFetch(config.proxy)` if set — the client's fetch
1553
+ * resolver, so SSE uses the same transport as regular requests:
1554
+ * custom fetch variants (incl. the test suite's injected mock),
1555
+ * undici configuration, an explicit `proxy` config, and env-proxy
1556
+ * support all apply to SSE too. The Node entry supplies get-it's
1557
+ * undici-backed fetch (threading the resolver through the env
1558
+ * instead of importing `get-it/node` directly keeps `undici` out of
1559
+ * the browser bundle); the browser entry leaves it unset.
1560
+ * 2. `globalThis.fetch`. Note that Node's global fetch does NOT read
1561
+ * proxy env vars (that is opt-in via `NODE_USE_ENV_PROXY`), which
1562
+ * is one of the reasons step 1 exists.
1563
+ *
1564
+ * The returned fetch always merges `options.headers` into the outgoing
1565
+ * request, regardless of which underlying fetch was picked.
1566
+ *
1567
+ * @internal
1568
+ */
1569
+ function resolveEventSourceFetch(config, options = {}) {
1570
+ let extraHeaders = options.headers, credentials = options.withCredentials ? "include" : void 0;
1571
+ return function eventSourceFetch(url, init) {
1572
+ let baseFetch = pickBaseFetch(config), mergedInit = { ...init };
1573
+ if (extraHeaders) {
1574
+ let headers = new Headers(init?.headers);
1575
+ for (let [key, value] of Object.entries(extraHeaders)) headers.set(key, value);
1576
+ mergedInit.headers = headers;
1577
+ }
1578
+ return credentials !== void 0 && (mergedInit.credentials = credentials), baseFetch(typeof url == "string" ? url : url.href, mergedInit);
1579
+ };
1580
+ }
1581
+ /**
1582
+ * The fetch the client's own transport resolves for this config: the
1583
+ * configured `resolveFetch` (honouring an explicit `proxy`) if present,
1584
+ * otherwise the global fetch. Shared by the EventSource connection and the
1585
+ * `/check/cors` probe so both resolve identically.
1586
+ *
1587
+ * @internal
1588
+ */
1589
+ function pickBaseFetch(config) {
1590
+ return config.resolveFetch ? config.resolveFetch(typeof config.proxy == "string" ? config.proxy : void 0) : globalThis.fetch.bind(globalThis);
1591
+ }
1592
+ const possibleOptions = [
1593
+ "includePreviousRevision",
1594
+ "includeResult",
1595
+ "includeMutations",
1596
+ "includeAllVersions",
1597
+ "visibility",
1598
+ "effectFormat",
1599
+ "enableResume",
1600
+ "tag"
1601
+ ], defaultOptions = { includeResult: !0 };
1602
+ /** @public */
1603
+ function _listen(query, params, opts = {}) {
1604
+ let config = this.config(), { url, token, withCredentials, requestTagPrefix, headers: configHeaders } = config, tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = {
1605
+ ...defaults_default(opts, defaultOptions),
1606
+ tag
1607
+ }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({
1608
+ query,
1609
+ params,
1610
+ options: {
1611
+ tag,
1612
+ ...listenOpts
1613
+ }
1614
+ }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
1615
+ if (uri.length > 14800) return throwError(() => /* @__PURE__ */ Error("Query too large for listener"));
1616
+ let listenFor = options.events ? options.events : ["mutation"], headers = {};
1617
+ token && (headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(headers, configHeaders);
1618
+ let initEventSource = () => new EventSource(uri, { fetch: resolveEventSourceFetch(config, {
1619
+ headers: Object.keys(headers).length ? headers : void 0,
1620
+ withCredentials
1621
+ }) });
1622
+ return connectEventSource(initEventSource, listenFor).pipe(reconnectOnConnectionFailure(), filter((event) => listenFor.includes(event.type)), map$1((event) => ({
1623
+ type: event.type,
1624
+ ..."data" in event ? event.data : {}
1625
+ })));
1626
+ }
1627
+ /**
1628
+ * A variant of share that takes a predicate function to determine which value to replay to new subscribers
1629
+ * @param configOrPredicate - Predicate function to determine which value to replay
1630
+ * @param config - Optional ShareConfig
1631
+ */
1632
+ function shareReplayLatest(configOrPredicate, config) {
1633
+ return _shareReplayLatest(typeof configOrPredicate == "function" ? {
1634
+ predicate: configOrPredicate,
1635
+ ...config
1636
+ } : configOrPredicate);
1637
+ }
1638
+ function _shareReplayLatest(config) {
1639
+ return (source) => {
1640
+ let latest, emitted = !1, { predicate, ...shareConfig } = config, wrapped = source.pipe(tap((value) => {
1641
+ config.predicate(value) && (emitted = !0, latest = value);
1642
+ }), finalize(() => {
1643
+ emitted = !1, latest = void 0;
1644
+ }), share(shareConfig)), emitLatest = new Observable((subscriber) => {
1645
+ emitted && subscriber.next(latest), subscriber.complete();
1646
+ });
1647
+ return merge(wrapped, emitLatest);
1648
+ };
1649
+ }
1650
+ const requiredApiVersion = "2021-03-25";
1651
+ /**
1652
+ * @public
1653
+ */
1654
+ var LiveClient = class {
1655
+ #client;
1656
+ constructor(client) {
1657
+ this.#client = client;
1658
+ }
1659
+ /**
1660
+ * Requires `apiVersion` to be `2021-03-25` or later.
1661
+ */
1662
+ events({ includeDrafts = !1, tag: _tag, waitFor } = {}) {
1663
+ let config = this.#client.config(), { projectId, apiVersion: _apiVersion, token, withCredentials, requestTagPrefix, headers: configHeaders } = config, apiVersion = _apiVersion.replace(/^v/, "");
1664
+ if (apiVersion !== "X" && apiVersion < requiredApiVersion) throw Error(`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.`);
1665
+ if (includeDrafts && !token && !withCredentials) throw Error("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.");
1666
+ let path = _getDataUrl(this.#client, "live/events"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(".") : _tag;
1667
+ tag && url.searchParams.set("tag", tag), includeDrafts && url.searchParams.set("includeDrafts", "true"), waitFor && url.searchParams.set("waitFor", waitFor);
1668
+ let eventSourceHeaders = {};
1669
+ includeDrafts && token && (eventSourceHeaders.Authorization = `Bearer ${token}`), configHeaders && Object.assign(eventSourceHeaders, configHeaders);
1670
+ let eventSourceWithCredentials = !!(includeDrafts && withCredentials), transportCache = eventsCache.get(config.resolveFetch);
1671
+ transportCache || (transportCache = /* @__PURE__ */ new Map(), eventsCache.set(config.resolveFetch, transportCache));
1672
+ let cacheKey = JSON.stringify([
1673
+ url.href,
1674
+ typeof config.proxy == "string" ? config.proxy : null,
1675
+ eventSourceHeaders,
1676
+ eventSourceWithCredentials
1677
+ ]), existing = transportCache.get(cacheKey);
1678
+ if (existing) return existing;
1679
+ let initEventSource = () => new EventSource(url.href, { fetch: resolveEventSourceFetch(config, {
1680
+ headers: Object.keys(eventSourceHeaders).length ? eventSourceHeaders : void 0,
1681
+ withCredentials: eventSourceWithCredentials
1682
+ }) }), events = connectEventSource(initEventSource, [
1683
+ "message",
1684
+ "restart",
1685
+ "welcome",
1686
+ "reconnect",
1687
+ "goaway"
1688
+ ]), checkCors = checkCorsObservable(new URL(this.#client.getUrl("/check/cors", !1)), projectId, eventSourceWithCredentials, pickBaseFetch(config)), observable = events.pipe(reconnectOnConnectionFailure(), mergeMap((event) => event.type === "reconnect" ? checkCors.pipe(mergeMap(() => of(event))) : of(event)), catchError((err) => err instanceof CorsOriginError ? throwError(() => err) : checkCors.pipe(mergeMap(() => {
1689
+ throw err;
1690
+ }))), map$1((event) => {
1691
+ if (event.type === "message") {
1692
+ let { data, ...rest } = event;
1693
+ return {
1694
+ ...rest,
1695
+ tags: data.tags
1696
+ };
1697
+ }
1698
+ return event;
1699
+ })).pipe(finalize$1(() => {
1700
+ transportCache.delete(cacheKey), transportCache.size === 0 && eventsCache.delete(config.resolveFetch);
1701
+ }), shareReplayLatest({ predicate: (event) => event.type === "welcome" }));
1702
+ return transportCache.set(cacheKey, observable), observable;
1703
+ }
1704
+ };
1705
+ /**
1706
+ * Probes the `/check/cors` endpoint to confirm whether the current origin is
1707
+ * allowed by the project's CORS configuration. EventSource failures are opaque,
1708
+ * so we use this side-channel purely to tell "the server actively rejected our
1709
+ * origin" apart from every other class of failure.
1710
+ *
1711
+ * Errors with `CorsOriginError` when either:
1712
+ *
1713
+ * - `requireCredentials` is `true` (the EventSource was about to send
1714
+ * credentials) and `/check/cors` reports `result.withCredentials === false`.
1715
+ * The credentialed request would fail due to a missing
1716
+ * `access-control-allow-credentials` header. The resulting error carries
1717
+ * `credentials: true` so its `addOriginUrl` deep-link pre-selects the
1718
+ * "Allow credentials" toggle in the Sanity management form.
1719
+ * - `/check/cors` reports `result.allowed === false` (origin is not on the
1720
+ * project's CORS allow-list). The error carries `credentials: requireCredentials`
1721
+ * so the deep-link still pre-selects credentials when the caller needed them.
1722
+ *
1723
+ * Every other outcome is intentionally treated as "we don't know": the
1724
+ * observable emits a single `void` value and then completes, so downstream
1725
+ * `mergeMap(() => ...)` consumers can continue. No error is surfaced for any
1726
+ * of these cases:
1727
+ *
1728
+ * - `allowed: true` (with credentials satisfied if required) or an
1729
+ * unrecognised body shape: the server did not confirm a CORS rejection.
1730
+ * - Non-2xx HTTP response from `/check/cors`: same - no signal either way, and
1731
+ * a 5xx on the probe shouldn't poison the EventSource's original error.
1732
+ * - `fetch` / network / JSON parse failures: indistinguishable from ordinary
1733
+ * connectivity hiccups (offline, DNS, certs, transient outages). Reporting
1734
+ * those as CORS errors is exactly the false-positive class this helper
1735
+ * exists to prevent.
1736
+ * - The subscription was aborted: nothing to emit and nothing to complete.
1737
+ *
1738
+ * In all of those cases the caller's original underlying error from the
1739
+ * EventSource is allowed to propagate unchanged.
1740
+ */
1741
+ function checkCorsObservable(url, projectId, requireCredentials, fetcher) {
1742
+ return new Observable((observer) => {
1743
+ let controller = new AbortController(), { signal } = controller;
1744
+ return fetcher(url.href, {
1745
+ method: "GET",
1746
+ credentials: "omit",
1747
+ signal
1748
+ }).then((response) => {
1749
+ if (!(signal.aborted || !response.ok)) return response.text();
1750
+ }).then((text) => {
1751
+ if (signal.aborted) return;
1752
+ let parsed = text === void 0 ? void 0 : JSON.parse(text), result = isRecord(parsed) ? parsed.result : void 0;
1753
+ if (requireCredentials && isRecord(result) && result.withCredentials === !1) {
1754
+ observer.error(new CorsOriginError({
1755
+ projectId,
1756
+ credentials: !0
1757
+ }));
1758
+ return;
1759
+ }
1760
+ if (isRecord(result) && result.allowed === !1) {
1761
+ observer.error(new CorsOriginError({
1762
+ projectId,
1763
+ credentials: requireCredentials
1764
+ }));
1765
+ return;
1766
+ }
1767
+ observer.next(), observer.complete();
1768
+ }).catch(() => {
1769
+ signal.aborted || observer.closed || (observer.next(), observer.complete());
1770
+ }), () => controller.abort();
1771
+ });
1772
+ }
1773
+ /**
1774
+ * Cached observables capture their transport (`initEventSource` closes over
1775
+ * `config.resolveFetch` and `config.proxy`), so the cache is scoped per
1776
+ * resolver — `undefined` covers the `globalThis.fetch` fallback.
1777
+ */
1778
+ const eventsCache = /* @__PURE__ */ new Map();
1779
+ /** @internal */
1780
+ var ObservableDatasetsClient = class {
1781
+ #client;
1782
+ #httpRequest;
1783
+ constructor(client, httpRequest) {
1784
+ this.#client = client, this.#httpRequest = httpRequest;
1785
+ }
1786
+ /**
1787
+ * Create a new dataset with the given name
1788
+ *
1789
+ * @param name - Name of the dataset to create
1790
+ * @param options - Options for the dataset, including optional embeddings configuration
1791
+ */
1792
+ create(name, options) {
1793
+ return _modifyObservable(this.#client, this.#httpRequest, "PUT", name, options);
1794
+ }
1795
+ /**
1796
+ * Edit a dataset with the given name
1797
+ *
1798
+ * @param name - Name of the dataset to edit
1799
+ * @param options - New options for the dataset
1800
+ */
1801
+ edit(name, options) {
1802
+ return _modifyObservable(this.#client, this.#httpRequest, "PATCH", name, options);
1803
+ }
1804
+ /**
1805
+ * Delete a dataset with the given name
1806
+ *
1807
+ * @param name - Name of the dataset to delete
1808
+ */
1809
+ delete(name) {
1810
+ return _modifyObservable(this.#client, this.#httpRequest, "DELETE", name);
1811
+ }
1812
+ /**
1813
+ * Fetch a list of datasets for the configured project
1814
+ */
1815
+ list() {
1816
+ resourceGuard("dataset", this.#client.config());
1817
+ let config = this.#client.config(), projectId = config.projectId, url = "/datasets";
1818
+ return config.useProjectHostname === !1 && (url = `/projects/${projectId}/datasets`), _requestObservable(this.#client, this.#httpRequest, {
1819
+ url,
1820
+ tag: null
1821
+ });
1822
+ }
1823
+ /**
1824
+ * Get embeddings settings for a dataset
1825
+ *
1826
+ * @param name - Name of the dataset
1827
+ */
1828
+ getEmbeddingsSettings(name) {
1829
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _requestObservable(this.#client, this.#httpRequest, {
1830
+ url: _embeddingsSettingsUri(this.#client, name),
1831
+ tag: null
1832
+ });
1833
+ }
1834
+ /**
1835
+ * Edit embeddings settings for a dataset
1836
+ *
1837
+ * @param name - Name of the dataset
1838
+ * @param settings - Embeddings settings to apply
1839
+ */
1840
+ editEmbeddingsSettings(name, settings) {
1841
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _requestObservable(this.#client, this.#httpRequest, {
1842
+ method: "PUT",
1843
+ url: _embeddingsSettingsUri(this.#client, name),
1844
+ body: settings,
1845
+ tag: null
1846
+ });
1847
+ }
1848
+ }, DatasetsClient = class {
1849
+ #client;
1850
+ #httpRequest;
1851
+ constructor(client, httpRequest) {
1852
+ this.#client = client, this.#httpRequest = httpRequest;
1853
+ }
1854
+ /**
1855
+ * Create a new dataset with the given name
1856
+ *
1857
+ * @param name - Name of the dataset to create
1858
+ * @param options - Options for the dataset, including optional embeddings configuration
1859
+ */
1860
+ create(name, options) {
1861
+ return resourceGuard("dataset", this.#client.config()), _modify(this.#client, this.#httpRequest, "PUT", name, options);
1862
+ }
1863
+ /**
1864
+ * Edit a dataset with the given name
1865
+ *
1866
+ * @param name - Name of the dataset to edit
1867
+ * @param options - New options for the dataset
1868
+ */
1869
+ edit(name, options) {
1870
+ return resourceGuard("dataset", this.#client.config()), _modify(this.#client, this.#httpRequest, "PATCH", name, options);
1871
+ }
1872
+ /**
1873
+ * Delete a dataset with the given name
1874
+ *
1875
+ * @param name - Name of the dataset to delete
1876
+ */
1877
+ delete(name) {
1878
+ return resourceGuard("dataset", this.#client.config()), _modify(this.#client, this.#httpRequest, "DELETE", name);
1879
+ }
1880
+ /**
1881
+ * Fetch a list of datasets for the configured project
1882
+ */
1883
+ list() {
1884
+ resourceGuard("dataset", this.#client.config());
1885
+ let config = this.#client.config(), projectId = config.projectId, url = "/datasets";
1886
+ return config.useProjectHostname === !1 && (url = `/projects/${projectId}/datasets`), _request(this.#client, this.#httpRequest, {
1887
+ url,
1888
+ tag: null
1889
+ });
1890
+ }
1891
+ /**
1892
+ * Get embeddings settings for a dataset
1893
+ *
1894
+ * @param name - Name of the dataset
1895
+ */
1896
+ getEmbeddingsSettings(name) {
1897
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _request(this.#client, this.#httpRequest, {
1898
+ url: _embeddingsSettingsUri(this.#client, name),
1899
+ tag: null
1900
+ });
1901
+ }
1902
+ /**
1903
+ * Edit embeddings settings for a dataset
1904
+ *
1905
+ * @param name - Name of the dataset
1906
+ * @param settings - Embeddings settings to apply
1907
+ */
1908
+ editEmbeddingsSettings(name, settings) {
1909
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _request(this.#client, this.#httpRequest, {
1910
+ method: "PUT",
1911
+ url: _embeddingsSettingsUri(this.#client, name),
1912
+ body: settings,
1913
+ tag: null
1914
+ });
1915
+ }
1916
+ };
1917
+ function _embeddingsSettingsUri(client, name) {
1918
+ let config = client.config();
1919
+ return config.useProjectHostname === !1 ? `/projects/${config.projectId}/datasets/${name}/settings/embeddings` : `/datasets/${name}/settings/embeddings`;
1920
+ }
1921
+ function _modifyObservable(client, httpRequest, method, name, options) {
1922
+ return resourceGuard("dataset", client.config()), dataset(name), _requestObservable(client, httpRequest, {
1923
+ method,
1924
+ url: `/datasets/${name}`,
1925
+ body: options,
1926
+ tag: null
1927
+ });
1928
+ }
1929
+ function _modify(client, httpRequest, method, name, options) {
1930
+ return resourceGuard("dataset", client.config()), dataset(name), _request(client, httpRequest, {
1931
+ method,
1932
+ url: `/datasets/${name}`,
1933
+ body: options,
1934
+ tag: null
1935
+ });
1936
+ }
1937
+ /** Function resource types in a blueprint are namespaced under this prefix. */
1938
+ const scopeHeaders = (config, request) => {
1939
+ let organizationId = request?.organizationId || config.organizationId;
1940
+ if (organizationId) return {
1941
+ "X-Sanity-Scope-Type": "organization",
1942
+ "X-Sanity-Scope-Id": organizationId
1943
+ };
1944
+ let { projectId } = config;
1945
+ if (!projectId) throw Error("`functions.invoke()` requires a `projectId` to be set in the client config, or an `organizationId` for a stack deployed at organization scope");
1946
+ return {
1947
+ "X-Sanity-Scope-Type": "project",
1948
+ "X-Sanity-Scope-Id": projectId
1949
+ };
1950
+ }, resolveStackId = (config, request) => {
1951
+ let stackId = request?.stackId || config.stackId;
1952
+ if (!stackId) throw Error("`functions.invoke()` requires a `stackId`, either in the client config or on the request. Function names are only unique within a stack.");
1953
+ return stackId;
1954
+ };
1955
+ /**
1956
+ * The invoke route is keyed by function id, but callers know functions by the
1957
+ * name declared in the blueprint. Names are unique within a stack, so the stack
1958
+ * both makes the name resolvable and confines the call to its own functions.
1959
+ *
1960
+ * @internal
1961
+ */
1962
+ function _resolveFunctionId(client, httpRequest, functionName, stackId, headers, request) {
1963
+ return _requestObservable(client, httpRequest, {
1964
+ method: "GET",
1965
+ url: `/blueprints/stacks/${stackId}`,
1966
+ headers,
1967
+ signal: request?.signal
1968
+ }).pipe(map((stack) => {
1969
+ let match = (stack?.resources || []).find((resource) => resource.type?.startsWith("sanity.function.") && resource.name === functionName);
1970
+ if (!match) throw Error(`Function "${functionName}" not found in stack "${stackId}"`);
1971
+ if (!match.externalId) throw Error(`Function "${functionName}" is declared in stack "${stackId}" but is not deployed`);
1972
+ if (match.type !== "sanity.function.pubsub") throw Error(`Function invocation is not supported for ${match.type}`);
1973
+ return match.externalId;
1974
+ }));
1975
+ }
1976
+ /** @internal */
1977
+ function _invoke(client, httpRequest, functionName, request) {
1978
+ return defer(() => {
1979
+ let config = client.config(), headers = scopeHeaders(config, request);
1980
+ return _resolveFunctionId(client, httpRequest, functionName, resolveStackId(config, request), headers, request).pipe(mergeMap((functionId) => _requestObservable(client, httpRequest, {
1981
+ method: "POST",
1982
+ url: `/functions/${functionId}/invoke`,
1983
+ headers,
1984
+ body: { event: { data: request?.event?.data ?? {} } },
1985
+ timeout: request?.timeout,
1986
+ signal: request?.signal
1987
+ })));
1988
+ });
1989
+ }
1990
+ /** @public */
1991
+ var ObservableFunctionsClient = class {
1992
+ #client;
1993
+ #httpRequest;
1994
+ constructor(client, httpRequest) {
1995
+ this.#client = client, this.#httpRequest = httpRequest;
1996
+ }
1997
+ /**
1998
+ * Invoke a deployed function by its blueprint name.
1999
+ *
2000
+ * The name is resolved within the stack given by `stackId` on the request or
2001
+ * the client config. Passes the function's return value once it finishes.
2002
+ *
2003
+ * @param functionName - name of the function, as declared in the blueprint
2004
+ * @param request - payload and request options
2005
+ */
2006
+ invoke(functionName, request) {
2007
+ return _invoke(this.#client, this.#httpRequest, functionName, request);
2008
+ }
2009
+ }, FunctionsClient = class {
2010
+ #client;
2011
+ #httpRequest;
2012
+ constructor(client, httpRequest) {
2013
+ this.#client = client, this.#httpRequest = httpRequest;
2014
+ }
2015
+ /**
2016
+ * Invoke a deployed function by its blueprint name.
2017
+ *
2018
+ * The name is resolved within the stack given by `stackId` on the request or
2019
+ * the client config, which costs one extra request per call. Rejects if the
2020
+ * stack has no function by that name, or if the name resolves to anything
2021
+ * other than a `sanity.function.pubsub` function.
2022
+ *
2023
+ * The lookup is scoped to `projectId`, or to `organizationId` when one is set
2024
+ * for a stack deployed at organization scope.
2025
+ *
2026
+ * The request stays open until the function finishes, and resolves with its
2027
+ * return value, or `undefined` if it returns nothing. Long-running functions
2028
+ * may need an explicit `timeout`.
2029
+ *
2030
+ * @param functionName - name of the function, as declared in the blueprint
2031
+ * @param request - payload and request options
2032
+ */
2033
+ invoke(functionName, request) {
2034
+ return lastValueFrom(_invoke(this.#client, this.#httpRequest, functionName, request));
2035
+ }
2036
+ }, ObservableMediaLibraryVideoClient = class {
2037
+ #client;
2038
+ #httpRequest;
2039
+ constructor(client, httpRequest) {
2040
+ this.#client = client, this.#httpRequest = httpRequest;
2041
+ }
2042
+ /**
2043
+ * Get video playback information for a media library asset
2044
+ *
2045
+ * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
2046
+ * @param options - Options for transformations and expiration
2047
+ */
2048
+ getPlaybackInfo(assetIdentifier, options = {}) {
2049
+ let config = this.#client.config(), configMediaLibraryId = (config.resource || config["~experimental_resource"])?.id, { instanceId, libraryId } = parseAssetInstanceId(assetIdentifier), effectiveLibraryId = libraryId || configMediaLibraryId;
2050
+ if (!effectiveLibraryId) throw Error("Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR");
2051
+ let url = buildVideoPlaybackInfoUrl(instanceId, effectiveLibraryId), queryParams = buildQueryParams(options);
2052
+ return _requestObservable(this.#client, this.#httpRequest, {
2053
+ method: "GET",
2054
+ url,
2055
+ query: queryParams
2056
+ });
2057
+ }
2058
+ }, MediaLibraryVideoClient = class {
2059
+ #client;
2060
+ #httpRequest;
2061
+ constructor(client, httpRequest) {
2062
+ this.#client = client, this.#httpRequest = httpRequest;
2063
+ }
2064
+ /**
2065
+ * Get video playback information for a media library asset
2066
+ *
2067
+ * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
2068
+ * @param options - Options for transformations and expiration
2069
+ */
2070
+ getPlaybackInfo(assetIdentifier, options = {}) {
2071
+ let config = this.#client.config(), configMediaLibraryId = (config.resource || config["~experimental_resource"])?.id, { instanceId, libraryId } = parseAssetInstanceId(assetIdentifier), effectiveLibraryId = libraryId || configMediaLibraryId;
2072
+ if (!effectiveLibraryId) throw Error("Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR");
2073
+ let url = buildVideoPlaybackInfoUrl(instanceId, effectiveLibraryId), queryParams = buildQueryParams(options);
2074
+ return _request(this.#client, this.#httpRequest, {
2075
+ method: "GET",
2076
+ url,
2077
+ query: queryParams
2078
+ });
2079
+ }
2080
+ };
2081
+ const ML_GDR_PATTERN = /^media-library:(ml[^:]+):([^:]+)$/;
2082
+ /** @internal */
2083
+ function isSanityReference(assetIdentifier) {
2084
+ return typeof assetIdentifier == "object" && "_ref" in assetIdentifier;
2085
+ }
2086
+ /**
2087
+ * Parse the asset instance id and library id from the asset identifier
2088
+ *
2089
+ * @param assetIdentifier - The asset identifier - either a asset instance id or a Media Library GDR
2090
+ * @returns The asset instance id and library id
2091
+ */
2092
+ function parseAssetInstanceId(assetIdentifier) {
2093
+ let ref = isSanityReference(assetIdentifier) ? assetIdentifier._ref : assetIdentifier, match = ML_GDR_PATTERN.exec(ref);
2094
+ if (match) {
2095
+ let [, libraryId, instanceId] = match;
2096
+ return {
2097
+ libraryId,
2098
+ instanceId
2099
+ };
2100
+ }
2101
+ if (typeof assetIdentifier == "string" && assetIdentifier.startsWith("video-")) return { instanceId: assetIdentifier };
2102
+ throw Error(`Invalid video asset instance identifier "${ref}": must be a valid video instance id or a Global Dataset Reference (GDR) to the video asset in the Media Library`);
2103
+ }
2104
+ function buildVideoPlaybackInfoUrl(instanceId, libraryId) {
2105
+ return `/media-libraries/${libraryId}/video/${instanceId}/playback-info`;
2106
+ }
2107
+ function buildQueryParams(options) {
2108
+ let params = {};
2109
+ if (options.transformations) {
2110
+ let { thumbnail, animated, storyboard } = options.transformations;
2111
+ thumbnail && (thumbnail.width && (params.thumbnailWidth = thumbnail.width), thumbnail.height && (params.thumbnailHeight = thumbnail.height), thumbnail.time !== void 0 && (params.thumbnailTime = thumbnail.time), thumbnail.fit && (params.thumbnailFit = thumbnail.fit), thumbnail.format && (params.thumbnailFormat = thumbnail.format)), animated && (animated.width && (params.animatedWidth = animated.width), animated.height && (params.animatedHeight = animated.height), animated.start !== void 0 && (params.animatedStart = animated.start), animated.end !== void 0 && (params.animatedEnd = animated.end), animated.fps && (params.animatedFps = animated.fps), animated.format && (params.animatedFormat = animated.format)), storyboard && storyboard.format && (params.storyboardFormat = storyboard.format);
2112
+ }
2113
+ return options.expiration && (params.expiration = options.expiration), params;
2114
+ }
2115
+ /** @internal */
2116
+ var ObservableProjectsClient = class {
2117
+ #client;
2118
+ #httpRequest;
2119
+ constructor(client, httpRequest) {
2120
+ this.#client = client, this.#httpRequest = httpRequest;
2121
+ }
2122
+ /**
2123
+ * Fetch a list of projects the authenticated user has access to.
2124
+ *
2125
+ * @param options - Options for the list request
2126
+ * - `includeMembers` - Whether to include members in the response (default: true)
2127
+ * - `includeFeatures` - Whether to include features in the response (default: true)
2128
+ * - `organizationId` - ID of the organization to fetch projects for
2129
+ * - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
2130
+ */
2131
+ list(options) {
2132
+ let query = {};
2133
+ return options?.includeMembers === !1 && (query.includeMembers = "false"), options?.includeFeatures === !1 && (query.includeFeatures = "false"), options?.organizationId && (query.organizationId = options.organizationId), options?.onlyExplicitMembership && (query.onlyExplicitMembership = "true"), _requestObservable(this.#client, this.#httpRequest, {
2134
+ url: "/projects",
2135
+ query
2136
+ });
2137
+ }
2138
+ /**
2139
+ * Fetch a project by project ID
2140
+ *
2141
+ * @param projectId - ID of the project to fetch
2142
+ */
2143
+ getById(projectId) {
2144
+ return _requestObservable(this.#client, this.#httpRequest, { url: `/projects/${projectId}` });
2145
+ }
2146
+ }, ProjectsClient = class {
2147
+ #client;
2148
+ #httpRequest;
2149
+ constructor(client, httpRequest) {
2150
+ this.#client = client, this.#httpRequest = httpRequest;
2151
+ }
2152
+ /**
2153
+ * Fetch a list of projects the authenticated user has access to.
2154
+ *
2155
+ * @param options - Options for the list request
2156
+ * - `includeMembers` - Whether to include members in the response (default: true)
2157
+ * - `includeFeatures` - Whether to include features in the response (default: true)
2158
+ * - `organizationId` - ID of the organization to fetch projects for
2159
+ * - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
2160
+ */
2161
+ list(options) {
2162
+ let query = {};
2163
+ return options?.includeMembers === !1 && (query.includeMembers = "false"), options?.includeFeatures === !1 && (query.includeFeatures = "false"), options?.organizationId && (query.organizationId = options.organizationId), options?.onlyExplicitMembership && (query.onlyExplicitMembership = "true"), _request(this.#client, this.#httpRequest, {
2164
+ url: "/projects",
2165
+ query
2166
+ });
2167
+ }
2168
+ /**
2169
+ * Fetch a project by project ID
2170
+ *
2171
+ * @param projectId - ID of the project to fetch
2172
+ */
2173
+ getById(projectId) {
2174
+ return _request(this.#client, this.#httpRequest, { url: `/projects/${projectId}` });
2175
+ }
2176
+ };
2177
+ /**
2178
+ * @internal
2179
+ *
2180
+ * ~24 years (or 7.54e+8 seconds) needed, in order to have a 1% probability of at least one collision if 10 ID's are generated every hour.
2181
+ */
2182
+ const generateReleaseId = customAlphabet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 8), getDocumentVersionId = (publishedId, releaseId) => releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId);
2183
+ /** @internal */
2184
+ function deriveDocumentVersionId(op, { releaseId, publishedId, document }) {
2185
+ if (publishedId && document._id) {
2186
+ let versionId = getDocumentVersionId(publishedId, releaseId);
2187
+ return validateVersionIdMatch(versionId, document), versionId;
2188
+ }
2189
+ if (document._id) {
2190
+ let isDraft = isDraftId(document._id), isVersion = isVersionId(document._id);
2191
+ if (!isDraft && !isVersion) throw Error(`\`${op}()\` requires a document with an \`_id\` that is a version or draft ID`);
2192
+ if (releaseId) {
2193
+ if (isDraft) throw Error(`\`${op}()\` was called with a document ID (\`${document._id}\`) that is a draft ID, but a release ID (\`${releaseId}\`) was also provided.`);
2194
+ let builtVersionId = getVersionFromId(document._id);
2195
+ if (builtVersionId !== releaseId) throw Error(`\`${op}()\` was called with a document ID (\`${document._id}\`) that is a version ID, but the release ID (\`${releaseId}\`) does not match the document's version ID (\`${builtVersionId}\`).`);
2196
+ }
2197
+ return document._id;
2198
+ }
2199
+ if (publishedId) return getDocumentVersionId(publishedId, releaseId);
2200
+ throw Error(`\`${op}()\` requires either a publishedId or a document with an \`_id\``);
2201
+ }
2202
+ const getArgs = (releaseOrOptions, maybeOptions) => {
2203
+ if (typeof releaseOrOptions == "object" && releaseOrOptions && ("releaseId" in releaseOrOptions || "metadata" in releaseOrOptions)) {
2204
+ let { releaseId = generateReleaseId(), metadata = {} } = releaseOrOptions;
2205
+ return [
2206
+ releaseId,
2207
+ metadata,
2208
+ maybeOptions
2209
+ ];
2210
+ }
2211
+ return [
2212
+ generateReleaseId(),
2213
+ {},
2214
+ releaseOrOptions
2215
+ ];
2216
+ }, createRelease = (releaseOrOptions, maybeOptions) => {
2217
+ let [releaseId, metadata, options] = getArgs(releaseOrOptions, maybeOptions);
2218
+ return {
2219
+ action: {
2220
+ actionType: "sanity.action.release.create",
2221
+ releaseId,
2222
+ metadata: {
2223
+ ...metadata,
2224
+ releaseType: metadata.releaseType || "undecided"
2225
+ }
2226
+ },
2227
+ options
2228
+ };
2229
+ };
2230
+ /** @public */
2231
+ var ObservableReleasesClient = class {
2232
+ #client;
2233
+ #httpRequest;
2234
+ constructor(client, httpRequest) {
2235
+ this.#client = client, this.#httpRequest = httpRequest;
2236
+ }
2237
+ /**
2238
+ * @public
2239
+ *
2240
+ * Retrieve a release by id.
2241
+ *
2242
+ * @category Releases
2243
+ *
2244
+ * @param params - Release action parameters:
2245
+ * - `releaseId` - The id of the release to retrieve.
2246
+ * @param options - Additional query options including abort signal and query tag.
2247
+ * @returns An observable that resolves to the release document {@link ReleaseDocument}.
2248
+ *
2249
+ * @example Retrieving a release by id
2250
+ * ```ts
2251
+ * client.observable.releases.get({releaseId: 'my-release'}).pipe(
2252
+ * tap((release) => console.log(release)),
2253
+ * // {
2254
+ * // _id: '_.releases.my-release',
2255
+ * // name: 'my-release'
2256
+ * // _type: 'system.release',
2257
+ * // metadata: {releaseType: 'asap'},
2258
+ * // _createdAt: '2021-01-01T00:00:00.000Z',
2259
+ * // ...
2260
+ * // }
2261
+ * ).subscribe()
2262
+ * ```
2263
+ */
2264
+ get({ releaseId }, options) {
2265
+ return _getDocumentObservable(this.#client, this.#httpRequest, `_.releases.${releaseId}`, options);
2266
+ }
2267
+ create(releaseOrOptions, maybeOptions) {
2268
+ let { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
2269
+ return _actionObservable(this.#client, this.#httpRequest, action, options).pipe(map((actionResult) => ({
2270
+ ...actionResult,
2271
+ releaseId,
2272
+ metadata
2273
+ })));
2274
+ }
2275
+ /**
2276
+ * @public
2277
+ *
2278
+ * Edits an existing release, updating the metadata.
2279
+ *
2280
+ * @category Releases
2281
+ *
2282
+ * @param params - Release action parameters:
2283
+ * - `releaseId` - The id of the release to edit.
2284
+ * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
2285
+ * @param options - Additional action options.
2286
+ * @returns An observable that resolves to the `transactionId`.
2287
+ */
2288
+ edit({ releaseId, patch }, options) {
2289
+ let editAction = {
2290
+ actionType: "sanity.action.release.edit",
2291
+ releaseId,
2292
+ patch
2293
+ };
2294
+ return _actionObservable(this.#client, this.#httpRequest, editAction, options);
2295
+ }
2296
+ /**
2297
+ * @public
2298
+ *
2299
+ * Publishes all documents in a release at once. For larger releases the effect of the publish
2300
+ * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
2301
+ * documents and creation of the corresponding published documents with the new content may
2302
+ * take some time.
2303
+ *
2304
+ * During this period both the source and target documents are locked and cannot be
2305
+ * modified through any other means.
2306
+ *
2307
+ * @category Releases
2308
+ *
2309
+ * @param params - Release action parameters:
2310
+ * - `releaseId` - The id of the release to publish.
2311
+ * @param options - Additional action options.
2312
+ * @returns An observable that resolves to the `transactionId`.
2313
+ */
2314
+ publish({ releaseId }, options) {
2315
+ let publishAction = {
2316
+ actionType: "sanity.action.release.publish",
2317
+ releaseId
2318
+ };
2319
+ return _actionObservable(this.#client, this.#httpRequest, publishAction, options);
2320
+ }
2321
+ /**
2322
+ * @public
2323
+ *
2324
+ * An archive action removes an active release. The documents that comprise the release
2325
+ * are deleted and therefore no longer queryable.
2326
+ *
2327
+ * While the documents remain in retention the last version can still be accessed using document history endpoint.
2328
+ *
2329
+ * @category Releases
2330
+ *
2331
+ * @param params - Release action parameters:
2332
+ * - `releaseId` - The id of the release to archive.
2333
+ * @param options - Additional action options.
2334
+ * @returns An observable that resolves to the `transactionId`.
2335
+ */
2336
+ archive({ releaseId }, options) {
2337
+ let archiveAction = {
2338
+ actionType: "sanity.action.release.archive",
2339
+ releaseId
2340
+ };
2341
+ return _actionObservable(this.#client, this.#httpRequest, archiveAction, options);
2342
+ }
2343
+ /**
2344
+ * @public
2345
+ *
2346
+ * An unarchive action restores an archived release and all documents
2347
+ * with the content they had just prior to archiving.
2348
+ *
2349
+ * @category Releases
2350
+ *
2351
+ * @param params - Release action parameters:
2352
+ * - `releaseId` - The id of the release to unarchive.
2353
+ * @param options - Additional action options.
2354
+ * @returns An observable that resolves to the `transactionId`.
2355
+ */
2356
+ unarchive({ releaseId }, options) {
2357
+ let unarchiveAction = {
2358
+ actionType: "sanity.action.release.unarchive",
2359
+ releaseId
2360
+ };
2361
+ return _actionObservable(this.#client, this.#httpRequest, unarchiveAction, options);
2362
+ }
2363
+ /**
2364
+ * @public
2365
+ *
2366
+ * A schedule action queues a release for publishing at the given future time.
2367
+ * The release is locked such that no documents in the release can be modified and
2368
+ * no documents that it references can be deleted as this would make the publish fail.
2369
+ * At the given time, the same logic as for the publish action is triggered.
2370
+ *
2371
+ * @category Releases
2372
+ *
2373
+ * @param params - Release action parameters:
2374
+ * - `releaseId` - The id of the release to schedule.
2375
+ * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
2376
+ * @param options - Additional action options.
2377
+ * @returns An observable that resolves to the `transactionId`.
2378
+ */
2379
+ schedule({ releaseId, publishAt }, options) {
2380
+ let scheduleAction = {
2381
+ actionType: "sanity.action.release.schedule",
2382
+ releaseId,
2383
+ publishAt
2384
+ };
2385
+ return _actionObservable(this.#client, this.#httpRequest, scheduleAction, options);
2386
+ }
2387
+ /**
2388
+ * @public
2389
+ *
2390
+ * An unschedule action stops a release from being published.
2391
+ * The documents in the release are considered unlocked and can be edited again.
2392
+ * This may fail if another release is scheduled to be published after this one and
2393
+ * has a reference to a document created by this one.
2394
+ *
2395
+ * @category Releases
2396
+ *
2397
+ * @param params - Release action parameters:
2398
+ * - `releaseId` - The id of the release to unschedule.
2399
+ * @param options - Additional action options.
2400
+ * @returns An observable that resolves to the `transactionId`.
2401
+ */
2402
+ unschedule({ releaseId }, options) {
2403
+ let unscheduleAction = {
2404
+ actionType: "sanity.action.release.unschedule",
2405
+ releaseId
2406
+ };
2407
+ return _actionObservable(this.#client, this.#httpRequest, unscheduleAction, options);
2408
+ }
2409
+ /**
2410
+ * @public
2411
+ *
2412
+ * A delete action removes a published or archived release.
2413
+ * The backing system document will be removed from the dataset.
2414
+ *
2415
+ * @category Releases
2416
+ *
2417
+ * @param params - Release action parameters:
2418
+ * - `releaseId` - The id of the release to delete.
2419
+ * @param options - Additional action options.
2420
+ * @returns An observable that resolves to the `transactionId`.
2421
+ */
2422
+ delete({ releaseId }, options) {
2423
+ let deleteAction = {
2424
+ actionType: "sanity.action.release.delete",
2425
+ releaseId
2426
+ };
2427
+ return _actionObservable(this.#client, this.#httpRequest, deleteAction, options);
2428
+ }
2429
+ /**
2430
+ * @public
2431
+ *
2432
+ * Fetch the documents in a release by release id.
2433
+ *
2434
+ * @category Releases
2435
+ *
2436
+ * @param params - Release action parameters:
2437
+ * - `releaseId` - The id of the release to fetch documents for.
2438
+ * @param options - Additional mutation options {@link BaseMutationOptions}.
2439
+ * @returns An observable that resolves to the documents in the release.
2440
+ */
2441
+ fetchDocuments({ releaseId }, options) {
2442
+ return _getReleaseDocumentsObservable(this.#client, this.#httpRequest, releaseId, options);
2443
+ }
2444
+ }, ReleasesClient = class {
2445
+ #client;
2446
+ #httpRequest;
2447
+ constructor(client, httpRequest) {
2448
+ this.#client = client, this.#httpRequest = httpRequest;
2449
+ }
2450
+ /**
2451
+ * @public
2452
+ *
2453
+ * Retrieve a release by id.
2454
+ *
2455
+ * @category Releases
2456
+ *
2457
+ * @param params - Release action parameters:
2458
+ * - `releaseId` - The id of the release to retrieve.
2459
+ * @param options - Additional query options including abort signal and query tag.
2460
+ * @returns A promise that resolves to the release document {@link ReleaseDocument}.
2461
+ *
2462
+ * @example Retrieving a release by id
2463
+ * ```ts
2464
+ * const release = await client.releases.get({releaseId: 'my-release'})
2465
+ * console.log(release)
2466
+ * // {
2467
+ * // _id: '_.releases.my-release',
2468
+ * // name: 'my-release'
2469
+ * // _type: 'system.release',
2470
+ * // metadata: {releaseType: 'asap'},
2471
+ * // _createdAt: '2021-01-01T00:00:00.000Z',
2472
+ * // ...
2473
+ * // }
2474
+ * ```
2475
+ */
2476
+ get({ releaseId }, options) {
2477
+ return _getDocument(this.#client, this.#httpRequest, `_.releases.${releaseId}`, options);
2478
+ }
2479
+ async create(releaseOrOptions, maybeOptions) {
2480
+ let { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
2481
+ return {
2482
+ ...await _action(this.#client, this.#httpRequest, action, options),
2483
+ releaseId,
2484
+ metadata
2485
+ };
2486
+ }
2487
+ /**
2488
+ * @public
2489
+ *
2490
+ * Edits an existing release, updating the metadata.
2491
+ *
2492
+ * @category Releases
2493
+ *
2494
+ * @param params - Release action parameters:
2495
+ * - `releaseId` - The id of the release to edit.
2496
+ * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
2497
+ * @param options - Additional action options.
2498
+ * @returns A promise that resolves to the `transactionId`.
2499
+ */
2500
+ edit({ releaseId, patch }, options) {
2501
+ let editAction = {
2502
+ actionType: "sanity.action.release.edit",
2503
+ releaseId,
2504
+ patch
2505
+ };
2506
+ return _action(this.#client, this.#httpRequest, editAction, options);
2507
+ }
2508
+ /**
2509
+ * @public
2510
+ *
2511
+ * Publishes all documents in a release at once. For larger releases the effect of the publish
2512
+ * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
2513
+ * documents and creation of the corresponding published documents with the new content may
2514
+ * take some time.
2515
+ *
2516
+ * During this period both the source and target documents are locked and cannot be
2517
+ * modified through any other means.
2518
+ *
2519
+ * @category Releases
2520
+ *
2521
+ * @param params - Release action parameters:
2522
+ * - `releaseId` - The id of the release to publish.
2523
+ * @param options - Additional action options.
2524
+ * @returns A promise that resolves to the `transactionId`.
2525
+ */
2526
+ publish({ releaseId }, options) {
2527
+ let publishAction = {
2528
+ actionType: "sanity.action.release.publish",
2529
+ releaseId
2530
+ };
2531
+ return _action(this.#client, this.#httpRequest, publishAction, options);
2532
+ }
2533
+ /**
2534
+ * @public
2535
+ *
2536
+ * An archive action removes an active release. The documents that comprise the release
2537
+ * are deleted and therefore no longer queryable.
2538
+ *
2539
+ * While the documents remain in retention the last version can still be accessed using document history endpoint.
2540
+ *
2541
+ * @category Releases
2542
+ *
2543
+ * @param params - Release action parameters:
2544
+ * - `releaseId` - The id of the release to archive.
2545
+ * @param options - Additional action options.
2546
+ * @returns A promise that resolves to the `transactionId`.
2547
+ */
2548
+ archive({ releaseId }, options) {
2549
+ let archiveAction = {
2550
+ actionType: "sanity.action.release.archive",
2551
+ releaseId
2552
+ };
2553
+ return _action(this.#client, this.#httpRequest, archiveAction, options);
2554
+ }
2555
+ /**
2556
+ * @public
2557
+ *
2558
+ * An unarchive action restores an archived release and all documents
2559
+ * with the content they had just prior to archiving.
2560
+ *
2561
+ * @category Releases
2562
+ *
2563
+ * @param params - Release action parameters:
2564
+ * - `releaseId` - The id of the release to unarchive.
2565
+ * @param options - Additional action options.
2566
+ * @returns A promise that resolves to the `transactionId`.
2567
+ */
2568
+ unarchive({ releaseId }, options) {
2569
+ let unarchiveAction = {
2570
+ actionType: "sanity.action.release.unarchive",
2571
+ releaseId
2572
+ };
2573
+ return _action(this.#client, this.#httpRequest, unarchiveAction, options);
2574
+ }
2575
+ /**
2576
+ * @public
2577
+ *
2578
+ * A schedule action queues a release for publishing at the given future time.
2579
+ * The release is locked such that no documents in the release can be modified and
2580
+ * no documents that it references can be deleted as this would make the publish fail.
2581
+ * At the given time, the same logic as for the publish action is triggered.
2582
+ *
2583
+ * @category Releases
2584
+ *
2585
+ * @param params - Release action parameters:
2586
+ * - `releaseId` - The id of the release to schedule.
2587
+ * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
2588
+ * @param options - Additional action options.
2589
+ * @returns A promise that resolves to the `transactionId`.
2590
+ */
2591
+ schedule({ releaseId, publishAt }, options) {
2592
+ let scheduleAction = {
2593
+ actionType: "sanity.action.release.schedule",
2594
+ releaseId,
2595
+ publishAt
2596
+ };
2597
+ return _action(this.#client, this.#httpRequest, scheduleAction, options);
2598
+ }
2599
+ /**
2600
+ * @public
2601
+ *
2602
+ * An unschedule action stops a release from being published.
2603
+ * The documents in the release are considered unlocked and can be edited again.
2604
+ * This may fail if another release is scheduled to be published after this one and
2605
+ * has a reference to a document created by this one.
2606
+ *
2607
+ * @category Releases
2608
+ *
2609
+ * @param params - Release action parameters:
2610
+ * - `releaseId` - The id of the release to unschedule.
2611
+ * @param options - Additional action options.
2612
+ * @returns A promise that resolves to the `transactionId`.
2613
+ */
2614
+ unschedule({ releaseId }, options) {
2615
+ let unscheduleAction = {
2616
+ actionType: "sanity.action.release.unschedule",
2617
+ releaseId
2618
+ };
2619
+ return _action(this.#client, this.#httpRequest, unscheduleAction, options);
2620
+ }
2621
+ /**
2622
+ * @public
2623
+ *
2624
+ * A delete action removes a published or archived release.
2625
+ * The backing system document will be removed from the dataset.
2626
+ *
2627
+ * @category Releases
2628
+ *
2629
+ * @param params - Release action parameters:
2630
+ * - `releaseId` - The id of the release to delete.
2631
+ * @param options - Additional action options.
2632
+ * @returns A promise that resolves to the `transactionId`.
2633
+ */
2634
+ delete({ releaseId }, options) {
2635
+ let deleteAction = {
2636
+ actionType: "sanity.action.release.delete",
2637
+ releaseId
2638
+ };
2639
+ return _action(this.#client, this.#httpRequest, deleteAction, options);
2640
+ }
2641
+ /**
2642
+ * @public
2643
+ *
2644
+ * Fetch the documents in a release by release id.
2645
+ *
2646
+ * @category Releases
2647
+ *
2648
+ * @param params - Release action parameters:
2649
+ * - `releaseId` - The id of the release to fetch documents for.
2650
+ * @param options - Additional mutation options {@link BaseMutationOptions}.
2651
+ * @returns A promise that resolves to the documents in the release.
2652
+ */
2653
+ fetchDocuments({ releaseId }, options) {
2654
+ return _getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options);
2655
+ }
2656
+ }, ObservableUsersClient = class {
2657
+ #client;
2658
+ #httpRequest;
2659
+ constructor(client, httpRequest) {
2660
+ this.#client = client, this.#httpRequest = httpRequest;
2661
+ }
2662
+ /**
2663
+ * Fetch a user by user ID
2664
+ *
2665
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2666
+ */
2667
+ getById(id) {
2668
+ return _requestObservable(this.#client, this.#httpRequest, { url: `/users/${id}` });
2669
+ }
2670
+ }, UsersClient = class {
2671
+ #client;
2672
+ #httpRequest;
2673
+ constructor(client, httpRequest) {
2674
+ this.#client = client, this.#httpRequest = httpRequest;
2675
+ }
2676
+ /**
2677
+ * Fetch a user by user ID
2678
+ *
2679
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2680
+ */
2681
+ getById(id) {
2682
+ return _request(this.#client, this.#httpRequest, { url: `/users/${id}` });
2683
+ }
2684
+ }, ObservableSanityClient = class ObservableSanityClient {
2685
+ assets;
2686
+ datasets;
2687
+ live;
2688
+ mediaLibrary;
2689
+ projects;
2690
+ users;
2691
+ agent;
2692
+ functions;
2693
+ releases;
2694
+ /**
2695
+ * Private properties
2696
+ */
2697
+ #clientConfig;
2698
+ #httpRequest;
2699
+ /**
2700
+ * Instance properties
2701
+ */
2702
+ listen = _listen;
2703
+ constructor(httpRequest, config = defaultConfig) {
2704
+ this.config(config), this.#httpRequest = httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = { video: new ObservableMediaLibraryVideoClient(this, this.#httpRequest) }, this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest), this.agent = { action: new ObservableAgentsActionClient(this, this.#httpRequest) }, this.functions = new ObservableFunctionsClient(this, this.#httpRequest), this.releases = new ObservableReleasesClient(this, this.#httpRequest);
2705
+ }
2706
+ /**
2707
+ * Clone the client - returns a new instance
2708
+ */
2709
+ clone() {
2710
+ return new ObservableSanityClient(this.#httpRequest, this.config());
2711
+ }
2712
+ config(newConfig) {
2713
+ if (newConfig === void 0) return { ...this.#clientConfig };
2714
+ if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1) throw Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
2715
+ return this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;
2716
+ }
2717
+ /**
2718
+ * Clone the client with a new (partial) configuration.
2719
+ *
2720
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2721
+ */
2722
+ withConfig(newConfig) {
2723
+ let thisConfig = this.config();
2724
+ return new ObservableSanityClient(this.#httpRequest, {
2725
+ ...thisConfig,
2726
+ ...newConfig,
2727
+ stega: {
2728
+ ...thisConfig.stega,
2729
+ ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2730
+ }
2731
+ });
2732
+ }
2733
+ fetch(query, params, options) {
2734
+ return _fetchObservable(this, this.#httpRequest, this.#clientConfig.stega, query, params, options);
2735
+ }
2736
+ getDocument(id, options) {
2737
+ if (options?.includeAllVersions === !0) return _getDocumentObservable(this, this.#httpRequest, id, {
2738
+ ...options,
2739
+ includeAllVersions: !0
2740
+ });
2741
+ let opts = {
2742
+ signal: options?.signal,
2743
+ tag: options?.tag,
2744
+ releaseId: options?.releaseId,
2745
+ ...options && "includeAllVersions" in options ? { includeAllVersions: !1 } : {}
2746
+ };
2747
+ return _getDocumentObservable(this, this.#httpRequest, id, opts);
2748
+ }
2749
+ /**
2750
+ * Fetch multiple documents in one request.
2751
+ * Should be used sparingly - performing a query is usually a better option.
2752
+ * The order/position of documents is preserved based on the original array of IDs.
2753
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2754
+ *
2755
+ * @param ids - Document IDs to fetch
2756
+ * @param options - Request options
2757
+ */
2758
+ getDocuments(ids, options) {
2759
+ return _getDocumentsObservable(this, this.#httpRequest, ids, options);
2760
+ }
2761
+ /**
2762
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
2763
+ * Returns a set of the IDs that exist.
2764
+ *
2765
+ * @param ids - Document IDs to check
2766
+ * @param options - Request options
2767
+ */
2768
+ documentsExists(ids, options) {
2769
+ return _documentsExistsObservable(this, this.#httpRequest, ids, options);
2770
+ }
2771
+ create(document, options) {
2772
+ return _createObservable(this, this.#httpRequest, document, "create", options);
2773
+ }
2774
+ createIfNotExists(document, options) {
2775
+ return _createIfNotExistsObservable(this, this.#httpRequest, document, options);
2776
+ }
2777
+ createOrReplace(document, options) {
2778
+ return _createOrReplaceObservable(this, this.#httpRequest, document, options);
2779
+ }
2780
+ createVersion({ document, publishedId, releaseId, baseId, ifBaseRevisionId }, options) {
2781
+ if (!document) return _createVersionFromBaseObservable(this, this.#httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options);
2782
+ let documentVersionId = deriveDocumentVersionId("createVersion", {
2783
+ document,
2784
+ publishedId,
2785
+ releaseId
2786
+ }), documentVersion = {
2787
+ ...document,
2788
+ _id: documentVersionId
2789
+ }, versionPublishedId = publishedId || getPublishedId(document._id);
2790
+ return _createVersionObservable(this, this.#httpRequest, documentVersion, versionPublishedId, options);
2791
+ }
2792
+ delete(selection, options) {
2793
+ return _deleteObservable(this, this.#httpRequest, selection, options);
2794
+ }
2795
+ /**
2796
+ * @public
2797
+ *
2798
+ * Deletes the draft or release version of a document.
2799
+ *
2800
+ * @remarks
2801
+ * * Discarding a version with no `releaseId` will discard the draft version of the published document.
2802
+ * * If the draft or release version does not exist, any error will throw.
2803
+ *
2804
+ * @param params - Version action parameters:
2805
+ * - `releaseId` - The ID of the release to discard the document from.
2806
+ * - `publishedId` - The published ID of the document to discard.
2807
+ * @param purge - if `true` the document history is also discarded.
2808
+ * @param options - Additional action options.
2809
+ * @returns an observable that resolves to the `transactionId`.
2810
+ *
2811
+ * @example Discarding a release version of a document
2812
+ * ```ts
2813
+ * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2814
+ * // The document with the ID `versions.myRelease.myDocument` will be discarded.
2815
+ * ```
2816
+ *
2817
+ * @example Discarding a draft version of a document
2818
+ * ```ts
2819
+ * client.observable.discardVersion({publishedId: 'myDocument'})
2820
+ * // The document with the ID `drafts.myDocument` will be discarded.
2821
+ * ```
2822
+ */
2823
+ discardVersion({ releaseId, publishedId }, purge, options) {
2824
+ let documentVersionId = getDocumentVersionId(publishedId, releaseId);
2825
+ return _discardVersionObservable(this, this.#httpRequest, documentVersionId, purge, options);
2826
+ }
2827
+ replaceVersion({ document, publishedId, releaseId }, options) {
2828
+ let documentVersionId = deriveDocumentVersionId("replaceVersion", {
2829
+ document,
2830
+ publishedId,
2831
+ releaseId
2832
+ }), documentVersion = {
2833
+ ...document,
2834
+ _id: documentVersionId
2835
+ };
2836
+ return _replaceVersionObservable(this, this.#httpRequest, documentVersion, options);
2837
+ }
2838
+ /**
2839
+ * @public
2840
+ *
2841
+ * Used to indicate when a document within a release should be unpublished when
2842
+ * the release is run.
2843
+ *
2844
+ * @remarks
2845
+ * * If the published document does not exist, an error will be thrown.
2846
+ *
2847
+ * @param params - Version action parameters:
2848
+ * - `releaseId` - The ID of the release to unpublish the document from.
2849
+ * - `publishedId` - The published ID of the document to unpublish.
2850
+ * @param options - Additional action options.
2851
+ * @returns an observable that resolves to the `transactionId`.
2852
+ *
2853
+ * @example Unpublishing a release version of a published document
2854
+ * ```ts
2855
+ * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2856
+ * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
2857
+ * ```
2858
+ */
2859
+ unpublishVersion({ releaseId, publishedId }, options) {
2860
+ let versionId = getVersionId(publishedId, releaseId);
2861
+ return _unpublishVersionObservable(this, this.#httpRequest, versionId, publishedId, options);
2862
+ }
2863
+ mutate(operations, options) {
2864
+ return _mutateObservable(this, this.#httpRequest, operations, options);
2865
+ }
2866
+ /**
2867
+ * Create a new buildable patch of operations to perform
2868
+ *
2869
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
2870
+ * @param operations - Optional object of patch operations to initialize the patch instance with
2871
+ * @returns Patch instance - call `.commit()` to perform the operations defined
2872
+ */
2873
+ patch(selection, operations) {
2874
+ return new ObservablePatch(selection, operations, this);
2875
+ }
2876
+ /**
2877
+ * Create a new transaction of mutations
2878
+ *
2879
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
2880
+ */
2881
+ transaction(operations) {
2882
+ return new ObservableTransaction(operations, this);
2883
+ }
2884
+ /**
2885
+ * Perform action operations against the configured dataset
2886
+ *
2887
+ * @param operations - Action operation(s) to execute
2888
+ * @param options - Action options
2889
+ */
2890
+ action(operations, options) {
2891
+ return _actionObservable(this, this.#httpRequest, operations, options);
2892
+ }
2893
+ /**
2894
+ * Perform an HTTP request against the Sanity API
2895
+ *
2896
+ * @param options - Request options
2897
+ */
2898
+ request(options) {
2899
+ return _requestObservable(this, this.#httpRequest, options);
2900
+ }
2901
+ /**
2902
+ * Get a Sanity API URL for the URI provided
2903
+ *
2904
+ * @param uri - URI/path to build URL for
2905
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
2906
+ */
2907
+ getUrl(uri, canUseCdn) {
2908
+ return _getUrl(this, uri, canUseCdn);
2909
+ }
2910
+ /**
2911
+ * Get a Sanity API URL for the data operation and path provided
2912
+ *
2913
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
2914
+ * @param path - Path to append after the operation
2915
+ */
2916
+ getDataUrl(operation, path) {
2917
+ return _getDataUrl(this, operation, path);
2918
+ }
2919
+ }, SanityClient = class SanityClient {
2920
+ assets;
2921
+ datasets;
2922
+ live;
2923
+ mediaLibrary;
2924
+ projects;
2925
+ users;
2926
+ agent;
2927
+ functions;
2928
+ releases;
2929
+ /**
2930
+ * Observable version of the Sanity client, with the same configuration as the promise-based one
2931
+ */
2932
+ observable;
2933
+ /**
2934
+ * Private properties
2935
+ */
2936
+ #clientConfig;
2937
+ #httpRequest;
2938
+ /**
2939
+ * Instance properties
2940
+ */
2941
+ listen = _listen;
2942
+ constructor(httpRequest, config = defaultConfig) {
2943
+ this.config(config), this.#httpRequest = httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = { video: new MediaLibraryVideoClient(this, this.#httpRequest) }, this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.agent = { action: new AgentActionsClient(this, this.#httpRequest) }, this.functions = new FunctionsClient(this, this.#httpRequest), this.releases = new ReleasesClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config);
2944
+ }
2945
+ /**
2946
+ * Clone the client - returns a new instance
2947
+ */
2948
+ clone() {
2949
+ return new SanityClient(this.#httpRequest, this.config());
2950
+ }
2951
+ config(newConfig) {
2952
+ if (newConfig === void 0) return { ...this.#clientConfig };
2953
+ if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1) throw Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
2954
+ return this.observable && this.observable.config(newConfig), this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;
2955
+ }
2956
+ /**
2957
+ * Clone the client with a new (partial) configuration.
2958
+ *
2959
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2960
+ */
2961
+ withConfig(newConfig) {
2962
+ let thisConfig = this.config();
2963
+ return new SanityClient(this.#httpRequest, {
2964
+ ...thisConfig,
2965
+ ...newConfig,
2966
+ stega: {
2967
+ ...thisConfig.stega,
2968
+ ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2969
+ }
2970
+ });
2971
+ }
2972
+ fetch(query, params, options) {
2973
+ return _fetch(this, this.#httpRequest, this.#clientConfig.stega, query, params, options);
2974
+ }
2975
+ getDocument(id, options) {
2976
+ if (options?.includeAllVersions === !0) return _getDocument(this, this.#httpRequest, id, {
2977
+ ...options,
2978
+ includeAllVersions: !0
2979
+ });
2980
+ let opts = {
2981
+ signal: options?.signal,
2982
+ tag: options?.tag,
2983
+ releaseId: options?.releaseId,
2984
+ ...options && "includeAllVersions" in options ? { includeAllVersions: !1 } : {}
2985
+ };
2986
+ return _getDocument(this, this.#httpRequest, id, opts);
2987
+ }
2988
+ /**
2989
+ * Fetch multiple documents in one request.
2990
+ * Should be used sparingly - performing a query is usually a better option.
2991
+ * The order/position of documents is preserved based on the original array of IDs.
2992
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2993
+ *
2994
+ * @param ids - Document IDs to fetch
2995
+ * @param options - Request options
2996
+ */
2997
+ getDocuments(ids, options) {
2998
+ return _getDocuments(this, this.#httpRequest, ids, options);
2999
+ }
3000
+ /**
3001
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
3002
+ * Returns a set of the IDs that exist.
3003
+ *
3004
+ * @param ids - Document IDs to check
3005
+ * @param options - Request options
3006
+ */
3007
+ documentsExists(ids, options) {
3008
+ return _documentsExists(this, this.#httpRequest, ids, options);
3009
+ }
3010
+ create(document, options) {
3011
+ return _create(this, this.#httpRequest, document, "create", options);
3012
+ }
3013
+ createIfNotExists(document, options) {
3014
+ return _createIfNotExists(this, this.#httpRequest, document, options);
3015
+ }
3016
+ createOrReplace(document, options) {
3017
+ return _createOrReplace(this, this.#httpRequest, document, options);
3018
+ }
3019
+ createVersion({ document, publishedId, releaseId, baseId, ifBaseRevisionId }, options) {
3020
+ if (!document) return _createVersionFromBase(this, this.#httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options);
3021
+ let documentVersionId = deriveDocumentVersionId("createVersion", {
3022
+ document,
3023
+ publishedId,
3024
+ releaseId
3025
+ }), documentVersion = {
3026
+ ...document,
3027
+ _id: documentVersionId
3028
+ }, versionPublishedId = publishedId || getPublishedId(document._id);
3029
+ return _createVersion(this, this.#httpRequest, documentVersion, versionPublishedId, options);
3030
+ }
3031
+ delete(selection, options) {
3032
+ return _delete(this, this.#httpRequest, selection, options);
3033
+ }
3034
+ /**
3035
+ * @public
3036
+ *
3037
+ * Deletes the draft or release version of a document.
3038
+ *
3039
+ * @remarks
3040
+ * * Discarding a version with no `releaseId` will discard the draft version of the published document.
3041
+ * * If the draft or release version does not exist, any error will throw.
3042
+ *
3043
+ * @param params - Version action parameters:
3044
+ * - `releaseId` - The ID of the release to discard the document from.
3045
+ * - `publishedId` - The published ID of the document to discard.
3046
+ * @param purge - if `true` the document history is also discarded.
3047
+ * @param options - Additional action options.
3048
+ * @returns a promise that resolves to the `transactionId`.
3049
+ *
3050
+ * @example Discarding a release version of a document
3051
+ * ```ts
3052
+ * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
3053
+ * // The document with the ID `versions.myRelease.myDocument` will be discarded.
3054
+ * ```
3055
+ *
3056
+ * @example Discarding a draft version of a document
3057
+ * ```ts
3058
+ * client.discardVersion({publishedId: 'myDocument'})
3059
+ * // The document with the ID `drafts.myDocument` will be discarded.
3060
+ * ```
3061
+ */
3062
+ discardVersion({ releaseId, publishedId }, purge, options) {
3063
+ let documentVersionId = getDocumentVersionId(publishedId, releaseId);
3064
+ return _discardVersion(this, this.#httpRequest, documentVersionId, purge, options);
3065
+ }
3066
+ replaceVersion({ document, publishedId, releaseId }, options) {
3067
+ let documentVersionId = deriveDocumentVersionId("replaceVersion", {
3068
+ document,
3069
+ publishedId,
3070
+ releaseId
3071
+ }), documentVersion = {
3072
+ ...document,
3073
+ _id: documentVersionId
3074
+ };
3075
+ return _replaceVersion(this, this.#httpRequest, documentVersion, options);
3076
+ }
3077
+ /**
3078
+ * @public
3079
+ *
3080
+ * Used to indicate when a document within a release should be unpublished when
3081
+ * the release is run.
3082
+ *
3083
+ * @remarks
3084
+ * * If the published document does not exist, an error will be thrown.
3085
+ *
3086
+ * @param params - Version action parameters:
3087
+ * - `releaseId` - The ID of the release to unpublish the document from.
3088
+ * - `publishedId` - The published ID of the document to unpublish.
3089
+ * @param options - Additional action options.
3090
+ * @returns a promise that resolves to the `transactionId`.
3091
+ *
3092
+ * @example Unpublishing a release version of a published document
3093
+ * ```ts
3094
+ * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
3095
+ * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
3096
+ * ```
3097
+ */
3098
+ unpublishVersion({ releaseId, publishedId }, options) {
3099
+ let versionId = getVersionId(publishedId, releaseId);
3100
+ return _unpublishVersion(this, this.#httpRequest, versionId, publishedId, options);
3101
+ }
3102
+ mutate(operations, options) {
3103
+ return _mutate(this, this.#httpRequest, operations, options);
3104
+ }
3105
+ /**
3106
+ * Create a new buildable patch of operations to perform
3107
+ *
3108
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
3109
+ * @param operations - Optional object of patch operations to initialize the patch instance with
3110
+ * @returns Patch instance - call `.commit()` to perform the operations defined
3111
+ */
3112
+ patch(documentId, operations) {
3113
+ return new Patch(documentId, operations, this);
3114
+ }
3115
+ /**
3116
+ * Create a new transaction of mutations
3117
+ *
3118
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
3119
+ */
3120
+ transaction(operations) {
3121
+ return new Transaction(operations, this);
3122
+ }
3123
+ /**
3124
+ * Perform action operations against the configured dataset
3125
+ * Returns a promise that resolves to the transaction result
3126
+ *
3127
+ * @param operations - Action operation(s) to execute
3128
+ * @param options - Action options
3129
+ */
3130
+ action(operations, options) {
3131
+ return _action(this, this.#httpRequest, operations, options);
3132
+ }
3133
+ /**
3134
+ * Perform a request against the Sanity API
3135
+ * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
3136
+ *
3137
+ * @param options - Request options
3138
+ * @returns Promise resolving to the response body
3139
+ */
3140
+ request(options) {
3141
+ return _request(this, this.#httpRequest, options);
3142
+ }
3143
+ /**
3144
+ * Perform an HTTP request a `/data` sub-endpoint
3145
+ * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
3146
+ *
3147
+ * @deprecated - Use `request()` or your own HTTP library instead
3148
+ * @param endpoint - Endpoint to hit (mutate, query etc)
3149
+ * @param body - Request body
3150
+ * @param options - Request options
3151
+ * @internal
3152
+ */
3153
+ dataRequest(endpoint, body, options) {
3154
+ return _dataRequest(this, this.#httpRequest, endpoint, body, options);
3155
+ }
3156
+ /**
3157
+ * Get a Sanity API URL for the URI provided
3158
+ *
3159
+ * @param uri - URI/path to build URL for
3160
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
3161
+ */
3162
+ getUrl(uri, canUseCdn) {
3163
+ return _getUrl(this, uri, canUseCdn);
3164
+ }
3165
+ /**
3166
+ * Get a Sanity API URL for the data operation and path provided
3167
+ *
3168
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
3169
+ * @param path - Path to append after the operation
3170
+ */
3171
+ getDataUrl(operation, path) {
3172
+ return _getDataUrl(this, operation, path);
3173
+ }
3174
+ };
3175
+ /**
3176
+ * Create the `requester` and `createClient` exports, that have environment specific middleware for node and browsers
3177
+ * @internal
3178
+ */
3179
+ function defineCreateClientExports(envOptions, ClassConstructor) {
3180
+ let defaultRequester = defineRequester(envOptions).observable, createClient = (config) => {
3181
+ let { observable: clientRequester, promise: clientRequesterPromise } = defineRequester(envOptions, {
3182
+ ignoreWarnings: config.ignoreWarnings,
3183
+ maxRetries: config.maxRetries,
3184
+ retryDelay: config.retryDelay
3185
+ }), performRequest = async (options) => (await clientRequesterPromise({
3186
+ redirect: "manual",
3187
+ ...options
3188
+ })).body, httpRequest = (options, requestHandler) => requestHandler ? requestHandler(options, performRequest) : performRequest(options);
3189
+ return new ClassConstructor(httpRequest, {
3190
+ ...config,
3191
+ requester: clientRequester,
3192
+ resolveFetch: config.resolveFetch ?? envOptions.resolveFetch
3193
+ });
3194
+ };
3195
+ return {
3196
+ requester: defaultRequester,
3197
+ createClient
3198
+ };
3199
+ }
3200
+ function defineDeprecatedCreateClient(createClient) {
3201
+ return function deprecatedCreateClient(config) {
3202
+ return printNoDefaultExport(), createClient(config);
3203
+ };
3204
+ }
3205
+ var name = "@sanity/client", version = "8.1.0";
3206
+ const log = createDebug("sanity:client");
3207
+ function isNodeReadableStream(value) {
3208
+ return typeof value != "object" || !value || !("pipe" in value) ? !1 : typeof value.pipe == "function";
3209
+ }
3210
+ const proxyFetchCache = /* @__PURE__ */ new Map();
3211
+ function getProxyFetch(proxyUrl) {
3212
+ let cached = proxyFetchCache.get(proxyUrl);
3213
+ if (cached) return cached;
3214
+ let fetch = createNodeFetch({
3215
+ proxy: proxyUrl,
3216
+ connections: 30
3217
+ });
3218
+ return proxyFetchCache.set(proxyUrl, fetch), fetch;
3219
+ }
3220
+ let envDefaultFetch;
3221
+ /**
3222
+ * Exposed via `EnvironmentOptions.resolveFetch` so EventSource connections
3223
+ * use the same transport as regular requests instead of falling back to
3224
+ * `globalThis.fetch`. Everything get-it's Node fetch provides then applies
3225
+ * to SSE too: the undici dispatcher configuration, an explicit `proxy`
3226
+ * config (pass the URL), and env-proxy support
3227
+ * (`HTTP_PROXY`/`HTTPS_PROXY`/`NO_PROXY`, which Node's own global fetch does
3228
+ * not read — that is opt-in via `NODE_USE_ENV_PROXY`, and not on our 22.12
3229
+ * floor). Reached via the env rather than a direct import so `get-it/node`
3230
+ * (and with it `undici`) stays out of the browser bundle.
3231
+ *
3232
+ * @internal
3233
+ */
3234
+ function resolveFetch(proxyUrl) {
3235
+ return typeof proxyUrl == "string" ? getProxyFetch(proxyUrl) : (envDefaultFetch ??= createNodeFetch(), envDefaultFetch);
3236
+ }
3237
+ const middleware = [
3238
+ debug({
3239
+ log: (message, ...args) => log(message, ...args),
3240
+ verbose: !0
3241
+ }),
3242
+ { beforeRequest(opts) {
3243
+ let configLineage = typeof opts.meta?.lineage == "string" ? opts.meta.lineage : void 0, lineage = typeof process < "u" && process.env.X_SANITY_LINEAGE || configLineage;
3244
+ if (!lineage) return opts;
3245
+ let headers = new Headers(opts.headers);
3246
+ return headers.set("x-sanity-lineage", lineage), {
3247
+ ...opts,
3248
+ headers
3249
+ };
3250
+ } },
3251
+ { beforeRequest(opts) {
3252
+ return isNodeReadableStream(opts.body) ? {
3253
+ ...opts,
3254
+ body: Readable.toWeb(opts.body)
3255
+ } : opts;
3256
+ } }
3257
+ ], exp = defineCreateClientExports({
3258
+ headers: { "User-Agent": `${name} ${version}` },
3259
+ middleware,
3260
+ resolveFetch
3261
+ }, SanityClient), requester = exp.requester, createClient = exp.createClient, deprecatedCreateClient = defineDeprecatedCreateClient(createClient);
3262
+ export { BasePatch, BaseTransaction, ChannelError, ClientError, ConnectionFailedError, CorsOriginError, DisconnectError, EXPERIMENTAL_API_WARNING, MessageError, MessageParseError, ObservablePatch, ObservableSanityClient, ObservableTransaction, Patch, SanityClient, ServerError, Transaction, connectEventSource, createClient, deprecatedCreateClient as default, formatQueryParseError, isHttpError, isQueryParseError, isTimeoutError, requester, validateApiPerspective };
3263
+
3264
+ //# sourceMappingURL=index.node.js.map