index.js 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. import { debug, headers, retry, jsonRequest, jsonResponse, progress, observable } from 'get-it/middleware';
  2. import { getIt } from 'get-it';
  3. export { adapter as unstable__adapter, environment as unstable__environment } from 'get-it';
  4. import { Observable, lastValueFrom } from 'rxjs';
  5. import { map, filter } from 'rxjs/operators';
  6. var name = "@sanity/client";
  7. var version = "5.4.2";
  8. const middleware = [debug({
  9. verbose: true,
  10. namespace: "sanity:client"
  11. }), headers({
  12. "User-Agent": "".concat(name, " ").concat(version)
  13. }), retry({
  14. maxRetries: 3
  15. })];
  16. const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
  17. class ClientError extends Error {
  18. constructor(res) {
  19. const props = extractErrorProps(res);
  20. super(props.message);
  21. this.statusCode = 400;
  22. Object.assign(this, props);
  23. }
  24. }
  25. class ServerError extends Error {
  26. constructor(res) {
  27. const props = extractErrorProps(res);
  28. super(props.message);
  29. this.statusCode = 500;
  30. Object.assign(this, props);
  31. }
  32. }
  33. function extractErrorProps(res) {
  34. const body = res.body;
  35. const props = {
  36. response: res,
  37. statusCode: res.statusCode,
  38. responseBody: stringifyBody(body, res),
  39. message: "",
  40. details: void 0
  41. };
  42. if (body.error && body.message) {
  43. props.message = "".concat(body.error, " - ").concat(body.message);
  44. return props;
  45. }
  46. if (isMutationError(body)) {
  47. const allItems = body.error.items || [];
  48. const items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map(item => {
  49. var _a;
  50. return (_a = item.error) == null ? void 0 : _a.description;
  51. }).filter(Boolean);
  52. let itemsStr = items.length ? ":\n- ".concat(items.join("\n- ")) : "";
  53. if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {
  54. itemsStr += "\n...and ".concat(allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE, " more");
  55. }
  56. props.message = "".concat(body.error.description).concat(itemsStr);
  57. props.details = body.error;
  58. return props;
  59. }
  60. if (body.error && body.error.description) {
  61. props.message = body.error.description;
  62. props.details = body.error;
  63. return props;
  64. }
  65. props.message = body.error || body.message || httpErrorMessage(res);
  66. return props;
  67. }
  68. function isMutationError(body) {
  69. return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description === "string";
  70. }
  71. function isPlainObject(obj) {
  72. return typeof obj === "object" && obj !== null && !Array.isArray(obj);
  73. }
  74. function httpErrorMessage(res) {
  75. const statusMessage = res.statusMessage ? " ".concat(res.statusMessage) : "";
  76. return "".concat(res.method, "-request to ").concat(res.url, " resulted in HTTP ").concat(res.statusCode).concat(statusMessage);
  77. }
  78. function stringifyBody(body, res) {
  79. const contentType = (res.headers["content-type"] || "").toLowerCase();
  80. const isJson = contentType.indexOf("application/json") !== -1;
  81. return isJson ? JSON.stringify(body, null, 2) : body;
  82. }
  83. const httpError = {
  84. onResponse: res => {
  85. if (res.statusCode >= 500) {
  86. throw new ServerError(res);
  87. } else if (res.statusCode >= 400) {
  88. throw new ClientError(res);
  89. }
  90. return res;
  91. }
  92. };
  93. const printWarnings = {
  94. onResponse: res => {
  95. const warn = res.headers["x-sanity-warning"];
  96. const warnings = Array.isArray(warn) ? warn : [warn];
  97. warnings.filter(Boolean).forEach(msg => console.warn(msg));
  98. return res;
  99. }
  100. };
  101. function defineHttpRequest(envMiddleware) {
  102. const request = getIt([...envMiddleware, printWarnings, jsonRequest(), jsonResponse(), progress(), httpError, observable({
  103. implementation: Observable
  104. })]);
  105. function httpRequest(options) {
  106. let requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : request;
  107. return requester({
  108. maxRedirects: 0,
  109. ...options
  110. });
  111. }
  112. httpRequest.defaultRequester = request;
  113. return httpRequest;
  114. }
  115. const projectHeader = "X-Sanity-Project-ID";
  116. function requestOptions(config) {
  117. let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  118. const headers = {};
  119. const token = overrides.token || config.token;
  120. if (token) {
  121. headers.Authorization = "Bearer ".concat(token);
  122. }
  123. if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
  124. headers[projectHeader] = config.projectId;
  125. }
  126. const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
  127. const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
  128. return Object.assign({}, overrides, {
  129. headers: Object.assign({}, headers, overrides.headers || {}),
  130. timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
  131. proxy: overrides.proxy || config.proxy,
  132. json: true,
  133. withCredentials
  134. });
  135. }
  136. function getSelection(sel) {
  137. if (typeof sel === "string" || Array.isArray(sel)) {
  138. return {
  139. id: sel
  140. };
  141. }
  142. if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
  143. return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
  144. query: sel.query,
  145. params: sel.params
  146. } : {
  147. query: sel.query
  148. };
  149. }
  150. const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
  151. throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
  152. }
  153. const VALID_ASSET_TYPES = ["image", "file"];
  154. const VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
  155. const dataset = name => {
  156. if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
  157. throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
  158. }
  159. };
  160. const projectId = id => {
  161. if (!/^[-a-z0-9]+$/i.test(id)) {
  162. throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
  163. }
  164. };
  165. const validateAssetType = type => {
  166. if (VALID_ASSET_TYPES.indexOf(type) === -1) {
  167. throw new Error("Invalid asset type: ".concat(type, ". Must be one of ").concat(VALID_ASSET_TYPES.join(", ")));
  168. }
  169. };
  170. const validateObject = (op, val) => {
  171. if (val === null || typeof val !== "object" || Array.isArray(val)) {
  172. throw new Error("".concat(op, "() takes an object of properties"));
  173. }
  174. };
  175. const validateDocumentId = (op, id) => {
  176. if (typeof id !== "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes("..")) {
  177. throw new Error("".concat(op, "(): \"").concat(id, "\" is not a valid document ID"));
  178. }
  179. };
  180. const requireDocumentId = (op, doc) => {
  181. if (!doc._id) {
  182. throw new Error("".concat(op, "() requires that the document contains an ID (\"_id\" property)"));
  183. }
  184. validateDocumentId(op, doc._id);
  185. };
  186. const validateInsert = (at, selector, items) => {
  187. const signature = "insert(at, selector, items)";
  188. if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
  189. const valid = VALID_INSERT_LOCATIONS.map(loc => "\"".concat(loc, "\"")).join(", ");
  190. throw new Error("".concat(signature, " takes an \"at\"-argument which is one of: ").concat(valid));
  191. }
  192. if (typeof selector !== "string") {
  193. throw new Error("".concat(signature, " takes a \"selector\"-argument which must be a string"));
  194. }
  195. if (!Array.isArray(items)) {
  196. throw new Error("".concat(signature, " takes an \"items\"-argument which must be an array"));
  197. }
  198. };
  199. const hasDataset = config => {
  200. if (!config.dataset) {
  201. throw new Error("`dataset` must be provided to perform queries");
  202. }
  203. return config.dataset || "";
  204. };
  205. const requestTag = tag => {
  206. if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
  207. throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
  208. }
  209. return tag;
  210. };
  211. const encodeQueryString = _ref => {
  212. let {
  213. query,
  214. params = {},
  215. options = {}
  216. } = _ref;
  217. const searchParams = new URLSearchParams();
  218. const {
  219. tag,
  220. ...opts
  221. } = options;
  222. if (tag) searchParams.set("tag", tag);
  223. searchParams.set("query", query);
  224. for (const [key, value] of Object.entries(params)) {
  225. searchParams.set("$".concat(key), JSON.stringify(value));
  226. }
  227. for (const [key, value] of Object.entries(opts)) {
  228. if (value) searchParams.set(key, "".concat(value));
  229. }
  230. return "?".concat(searchParams);
  231. };
  232. var __accessCheck$6 = (obj, member, msg) => {
  233. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  234. };
  235. var __privateGet$6 = (obj, member, getter) => {
  236. __accessCheck$6(obj, member, "read from private field");
  237. return getter ? getter.call(obj) : member.get(obj);
  238. };
  239. var __privateAdd$6 = (obj, member, value) => {
  240. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  241. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  242. };
  243. var __privateSet$6 = (obj, member, value, setter) => {
  244. __accessCheck$6(obj, member, "write to private field");
  245. setter ? setter.call(obj, value) : member.set(obj, value);
  246. return value;
  247. };
  248. var _client$5, _client2$5;
  249. class BasePatch {
  250. constructor(selection) {
  251. let operations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  252. this.selection = selection;
  253. this.operations = operations;
  254. }
  255. /**
  256. * Sets the given attributes to the document. Does NOT merge objects.
  257. * The operation is added to the current patch, ready to be commited by `commit()`
  258. *
  259. * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
  260. */
  261. set(attrs) {
  262. return this._assign("set", attrs);
  263. }
  264. /**
  265. * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
  266. * The operation is added to the current patch, ready to be commited by `commit()`
  267. *
  268. * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
  269. */
  270. setIfMissing(attrs) {
  271. return this._assign("setIfMissing", attrs);
  272. }
  273. /**
  274. * Performs a "diff-match-patch" operation on the string attributes provided.
  275. * The operation is added to the current patch, ready to be commited by `commit()`
  276. *
  277. * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
  278. */
  279. diffMatchPatch(attrs) {
  280. validateObject("diffMatchPatch", attrs);
  281. return this._assign("diffMatchPatch", attrs);
  282. }
  283. /**
  284. * Unsets the attribute paths provided.
  285. * The operation is added to the current patch, ready to be commited by `commit()`
  286. *
  287. * @param attrs - Attribute paths to unset.
  288. */
  289. unset(attrs) {
  290. if (!Array.isArray(attrs)) {
  291. throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
  292. }
  293. this.operations = Object.assign({}, this.operations, {
  294. unset: attrs
  295. });
  296. return this;
  297. }
  298. /**
  299. * 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.
  300. *
  301. * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
  302. */
  303. inc(attrs) {
  304. return this._assign("inc", attrs);
  305. }
  306. /**
  307. * 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.
  308. *
  309. * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
  310. */
  311. dec(attrs) {
  312. return this._assign("dec", attrs);
  313. }
  314. /**
  315. * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
  316. *
  317. * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
  318. * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
  319. * @param items - Array of items to insert/replace
  320. */
  321. insert(at, selector, items) {
  322. validateInsert(at, selector, items);
  323. return this._assign("insert", {
  324. [at]: selector,
  325. items
  326. });
  327. }
  328. /**
  329. * Append the given items to the array at the given JSONPath
  330. *
  331. * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
  332. * @param items - Array of items to append to the array
  333. */
  334. append(selector, items) {
  335. return this.insert("after", "".concat(selector, "[-1]"), items);
  336. }
  337. /**
  338. * Prepend the given items to the array at the given JSONPath
  339. *
  340. * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
  341. * @param items - Array of items to prepend to the array
  342. */
  343. prepend(selector, items) {
  344. return this.insert("before", "".concat(selector, "[0]"), items);
  345. }
  346. /**
  347. * Change the contents of an array by removing existing elements and/or adding new elements.
  348. *
  349. * @param selector - Attribute or JSONPath expression for array
  350. * @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
  351. * @param deleteCount - An integer indicating the number of old array elements to remove.
  352. * @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.
  353. */
  354. splice(selector, start, deleteCount, items) {
  355. const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
  356. const startIndex = start < 0 ? start - 1 : start;
  357. const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
  358. const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
  359. const rangeSelector = "".concat(selector, "[").concat(startIndex, ":").concat(delRange, "]");
  360. return this.insert("replace", rangeSelector, items || []);
  361. }
  362. /**
  363. * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
  364. *
  365. * @param rev - Revision to lock the patch to
  366. */
  367. ifRevisionId(rev) {
  368. this.operations.ifRevisionID = rev;
  369. return this;
  370. }
  371. /**
  372. * Return a plain JSON representation of the patch
  373. */
  374. serialize() {
  375. return {
  376. ...getSelection(this.selection),
  377. ...this.operations
  378. };
  379. }
  380. /**
  381. * Return a plain JSON representation of the patch
  382. */
  383. toJSON() {
  384. return this.serialize();
  385. }
  386. /**
  387. * Clears the patch of all operations
  388. */
  389. reset() {
  390. this.operations = {};
  391. return this;
  392. }
  393. _assign(op, props) {
  394. let merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  395. validateObject(op, props);
  396. this.operations = Object.assign({}, this.operations, {
  397. [op]: Object.assign({}, merge && this.operations[op] || {}, props)
  398. });
  399. return this;
  400. }
  401. _set(op, props) {
  402. return this._assign(op, props, false);
  403. }
  404. }
  405. const _ObservablePatch = class extends BasePatch {
  406. constructor(selection, operations, client) {
  407. super(selection, operations);
  408. __privateAdd$6(this, _client$5, void 0);
  409. __privateSet$6(this, _client$5, client);
  410. }
  411. /**
  412. * Clones the patch
  413. */
  414. clone() {
  415. return new _ObservablePatch(this.selection, {
  416. ...this.operations
  417. }, __privateGet$6(this, _client$5));
  418. }
  419. commit(options) {
  420. if (!__privateGet$6(this, _client$5)) {
  421. throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
  422. }
  423. const returnFirst = typeof this.selection === "string";
  424. const opts = Object.assign({
  425. returnFirst,
  426. returnDocuments: true
  427. }, options);
  428. return __privateGet$6(this, _client$5).mutate({
  429. patch: this.serialize()
  430. }, opts);
  431. }
  432. };
  433. let ObservablePatch = _ObservablePatch;
  434. _client$5 = new WeakMap();
  435. const _Patch = class extends BasePatch {
  436. constructor(selection, operations, client) {
  437. super(selection, operations);
  438. __privateAdd$6(this, _client2$5, void 0);
  439. __privateSet$6(this, _client2$5, client);
  440. }
  441. /**
  442. * Clones the patch
  443. */
  444. clone() {
  445. return new _Patch(this.selection, {
  446. ...this.operations
  447. }, __privateGet$6(this, _client2$5));
  448. }
  449. commit(options) {
  450. if (!__privateGet$6(this, _client2$5)) {
  451. throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
  452. }
  453. const returnFirst = typeof this.selection === "string";
  454. const opts = Object.assign({
  455. returnFirst,
  456. returnDocuments: true
  457. }, options);
  458. return __privateGet$6(this, _client2$5).mutate({
  459. patch: this.serialize()
  460. }, opts);
  461. }
  462. };
  463. let Patch = _Patch;
  464. _client2$5 = new WeakMap();
  465. var __accessCheck$5 = (obj, member, msg) => {
  466. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  467. };
  468. var __privateGet$5 = (obj, member, getter) => {
  469. __accessCheck$5(obj, member, "read from private field");
  470. return getter ? getter.call(obj) : member.get(obj);
  471. };
  472. var __privateAdd$5 = (obj, member, value) => {
  473. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  474. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  475. };
  476. var __privateSet$5 = (obj, member, value, setter) => {
  477. __accessCheck$5(obj, member, "write to private field");
  478. setter ? setter.call(obj, value) : member.set(obj, value);
  479. return value;
  480. };
  481. var _client$4, _client2$4;
  482. const defaultMutateOptions = {
  483. returnDocuments: false
  484. };
  485. class BaseTransaction {
  486. constructor() {
  487. let operations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  488. let transactionId = arguments.length > 1 ? arguments[1] : undefined;
  489. this.operations = operations;
  490. this.trxId = transactionId;
  491. }
  492. /**
  493. * 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.
  494. * The operation is added to the current transaction, ready to be commited by `commit()`
  495. *
  496. * @param doc - Document to create. Requires a `_type` property.
  497. */
  498. create(doc) {
  499. validateObject("create", doc);
  500. return this._add({
  501. create: doc
  502. });
  503. }
  504. /**
  505. * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
  506. * The operation is added to the current transaction, ready to be commited by `commit()`
  507. *
  508. * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
  509. */
  510. createIfNotExists(doc) {
  511. const op = "createIfNotExists";
  512. validateObject(op, doc);
  513. requireDocumentId(op, doc);
  514. return this._add({
  515. [op]: doc
  516. });
  517. }
  518. /**
  519. * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
  520. * The operation is added to the current transaction, ready to be commited by `commit()`
  521. *
  522. * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
  523. */
  524. createOrReplace(doc) {
  525. const op = "createOrReplace";
  526. validateObject(op, doc);
  527. requireDocumentId(op, doc);
  528. return this._add({
  529. [op]: doc
  530. });
  531. }
  532. /**
  533. * Deletes the document with the given document ID
  534. * The operation is added to the current transaction, ready to be commited by `commit()`
  535. *
  536. * @param documentId - Document ID to delete
  537. */
  538. delete(documentId) {
  539. validateDocumentId("delete", documentId);
  540. return this._add({
  541. delete: {
  542. id: documentId
  543. }
  544. });
  545. }
  546. transactionId(id) {
  547. if (!id) {
  548. return this.trxId;
  549. }
  550. this.trxId = id;
  551. return this;
  552. }
  553. /**
  554. * Return a plain JSON representation of the transaction
  555. */
  556. serialize() {
  557. return [...this.operations];
  558. }
  559. /**
  560. * Return a plain JSON representation of the transaction
  561. */
  562. toJSON() {
  563. return this.serialize();
  564. }
  565. /**
  566. * Clears the transaction of all operations
  567. */
  568. reset() {
  569. this.operations = [];
  570. return this;
  571. }
  572. _add(mut) {
  573. this.operations.push(mut);
  574. return this;
  575. }
  576. }
  577. const _Transaction = class extends BaseTransaction {
  578. constructor(operations, client, transactionId) {
  579. super(operations, transactionId);
  580. __privateAdd$5(this, _client$4, void 0);
  581. __privateSet$5(this, _client$4, client);
  582. }
  583. /**
  584. * Clones the transaction
  585. */
  586. clone() {
  587. return new _Transaction([...this.operations], __privateGet$5(this, _client$4), this.trxId);
  588. }
  589. commit(options) {
  590. if (!__privateGet$5(this, _client$4)) {
  591. throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
  592. }
  593. return __privateGet$5(this, _client$4).mutate(this.serialize(), Object.assign({
  594. transactionId: this.trxId
  595. }, defaultMutateOptions, options || {}));
  596. }
  597. patch(patchOrDocumentId, patchOps) {
  598. const isBuilder = typeof patchOps === "function";
  599. const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof Patch;
  600. if (isPatch) {
  601. return this._add({
  602. patch: patchOrDocumentId.serialize()
  603. });
  604. }
  605. if (isBuilder) {
  606. const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$5(this, _client$4)));
  607. if (!(patch instanceof Patch)) {
  608. throw new Error("function passed to `patch()` must return the patch");
  609. }
  610. return this._add({
  611. patch: patch.serialize()
  612. });
  613. }
  614. return this._add({
  615. patch: {
  616. id: patchOrDocumentId,
  617. ...patchOps
  618. }
  619. });
  620. }
  621. };
  622. let Transaction = _Transaction;
  623. _client$4 = new WeakMap();
  624. const _ObservableTransaction = class extends BaseTransaction {
  625. constructor(operations, client, transactionId) {
  626. super(operations, transactionId);
  627. __privateAdd$5(this, _client2$4, void 0);
  628. __privateSet$5(this, _client2$4, client);
  629. }
  630. /**
  631. * Clones the transaction
  632. */
  633. clone() {
  634. return new _ObservableTransaction([...this.operations], __privateGet$5(this, _client2$4), this.trxId);
  635. }
  636. commit(options) {
  637. if (!__privateGet$5(this, _client2$4)) {
  638. throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
  639. }
  640. return __privateGet$5(this, _client2$4).mutate(this.serialize(), Object.assign({
  641. transactionId: this.trxId
  642. }, defaultMutateOptions, options || {}));
  643. }
  644. patch(patchOrDocumentId, patchOps) {
  645. const isBuilder = typeof patchOps === "function";
  646. const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof ObservablePatch;
  647. if (isPatch) {
  648. return this._add({
  649. patch: patchOrDocumentId.serialize()
  650. });
  651. }
  652. if (isBuilder) {
  653. const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$5(this, _client2$4)));
  654. if (!(patch instanceof ObservablePatch)) {
  655. throw new Error("function passed to `patch()` must return the patch");
  656. }
  657. return this._add({
  658. patch: patch.serialize()
  659. });
  660. }
  661. return this._add({
  662. patch: {
  663. id: patchOrDocumentId,
  664. ...patchOps
  665. }
  666. });
  667. }
  668. };
  669. let ObservableTransaction = _ObservableTransaction;
  670. _client2$4 = new WeakMap();
  671. const excludeFalsey = (param, defValue) => {
  672. const value = typeof param === "undefined" ? defValue : param;
  673. return param === false ? void 0 : value;
  674. };
  675. const getMutationQuery = function () {
  676. let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  677. return {
  678. dryRun: options.dryRun,
  679. returnIds: true,
  680. returnDocuments: excludeFalsey(options.returnDocuments, true),
  681. visibility: options.visibility || "sync",
  682. autoGenerateArrayKeys: options.autoGenerateArrayKeys,
  683. skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
  684. };
  685. };
  686. const isResponse = event => event.type === "response";
  687. const getBody = event => event.body;
  688. const indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
  689. indexed[attr(doc)] = doc;
  690. return indexed;
  691. }, /* @__PURE__ */Object.create(null));
  692. const getQuerySizeLimit = 11264;
  693. function _fetch(client, httpRequest, query, params) {
  694. let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  695. const mapResponse = options.filterResponse === false ? res => res : res => res.result;
  696. return _dataRequest(client, httpRequest, "query", {
  697. query,
  698. params
  699. }, options).pipe(map(mapResponse));
  700. }
  701. function _getDocument(client, httpRequest, id) {
  702. let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  703. const options = {
  704. uri: _getDataUrl(client, "doc", id),
  705. json: true,
  706. tag: opts.tag
  707. };
  708. return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => event.body.documents && event.body.documents[0]));
  709. }
  710. function _getDocuments(client, httpRequest, ids) {
  711. let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  712. const options = {
  713. uri: _getDataUrl(client, "doc", ids.join(",")),
  714. json: true,
  715. tag: opts.tag
  716. };
  717. return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => {
  718. const indexed = indexBy(event.body.documents || [], doc => doc._id);
  719. return ids.map(id => indexed[id] || null);
  720. }));
  721. }
  722. function _createIfNotExists(client, httpRequest, doc, options) {
  723. requireDocumentId("createIfNotExists", doc);
  724. return _create(client, httpRequest, doc, "createIfNotExists", options);
  725. }
  726. function _createOrReplace(client, httpRequest, doc, options) {
  727. requireDocumentId("createOrReplace", doc);
  728. return _create(client, httpRequest, doc, "createOrReplace", options);
  729. }
  730. function _delete(client, httpRequest, selection, options) {
  731. return _dataRequest(client, httpRequest, "mutate", {
  732. mutations: [{
  733. delete: getSelection(selection)
  734. }]
  735. }, options);
  736. }
  737. function _mutate(client, httpRequest, mutations, options) {
  738. let mut;
  739. if (mutations instanceof Patch || mutations instanceof ObservablePatch) {
  740. mut = {
  741. patch: mutations.serialize()
  742. };
  743. } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {
  744. mut = mutations.serialize();
  745. } else {
  746. mut = mutations;
  747. }
  748. const muts = Array.isArray(mut) ? mut : [mut];
  749. const transactionId = options && options.transactionId || void 0;
  750. return _dataRequest(client, httpRequest, "mutate", {
  751. mutations: muts,
  752. transactionId
  753. }, options);
  754. }
  755. function _dataRequest(client, httpRequest, endpoint, body) {
  756. let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  757. const isMutation = endpoint === "mutate";
  758. const isQuery = endpoint === "query";
  759. const strQuery = isMutation ? "" : encodeQueryString(body);
  760. const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
  761. const stringQuery = useGet ? strQuery : "";
  762. const returnFirst = options.returnFirst;
  763. const {
  764. timeout,
  765. token,
  766. tag,
  767. headers
  768. } = options;
  769. const uri = _getDataUrl(client, endpoint, stringQuery);
  770. const reqOptions = {
  771. method: useGet ? "GET" : "POST",
  772. uri,
  773. json: true,
  774. body: useGet ? void 0 : body,
  775. query: isMutation && getMutationQuery(options),
  776. timeout,
  777. headers,
  778. token,
  779. tag,
  780. canUseCdn: isQuery,
  781. signal: options.signal
  782. };
  783. return _requestObservable(client, httpRequest, reqOptions).pipe(filter(isResponse), map(getBody), map(res => {
  784. if (!isMutation) {
  785. return res;
  786. }
  787. const results = res.results || [];
  788. if (options.returnDocuments) {
  789. return returnFirst ? results[0] && results[0].document : results.map(mut => mut.document);
  790. }
  791. const key = returnFirst ? "documentId" : "documentIds";
  792. const ids = returnFirst ? results[0] && results[0].id : results.map(mut => mut.id);
  793. return {
  794. transactionId: res.transactionId,
  795. results,
  796. [key]: ids
  797. };
  798. }));
  799. }
  800. function _create(client, httpRequest, doc, op) {
  801. let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  802. const mutation = {
  803. [op]: doc
  804. };
  805. const opts = Object.assign({
  806. returnFirst: true,
  807. returnDocuments: true
  808. }, options);
  809. return _dataRequest(client, httpRequest, "mutate", {
  810. mutations: [mutation]
  811. }, opts);
  812. }
  813. function _requestObservable(client, httpRequest, options) {
  814. const uri = options.url || options.uri;
  815. const config = client.config();
  816. const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
  817. const useCdn = config.useCdn && canUseCdn;
  818. const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
  819. if (tag) {
  820. options.query = {
  821. tag: requestTag(tag),
  822. ...options.query
  823. };
  824. }
  825. const reqOptions = requestOptions(config, Object.assign({}, options, {
  826. url: _getUrl(client, uri, useCdn)
  827. }));
  828. const request = new Observable(subscriber =>
  829. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- the typings thinks it's optional because it's not required to specify it when calling createClient, but it's always defined in practice since SanityClient provides a default
  830. httpRequest(reqOptions, config.requester).subscribe(subscriber));
  831. return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
  832. }
  833. function _request(client, httpRequest, options) {
  834. const observable = _requestObservable(client, httpRequest, options).pipe(filter(event => event.type === "response"), map(event => event.body));
  835. return observable;
  836. }
  837. function _getDataUrl(client, operation, path) {
  838. const config = client.config();
  839. const catalog = hasDataset(config);
  840. const baseUri = "/".concat(operation, "/").concat(catalog);
  841. const uri = path ? "".concat(baseUri, "/").concat(path) : baseUri;
  842. return "/data".concat(uri).replace(/\/($|\?)/, "$1");
  843. }
  844. function _getUrl(client, uri) {
  845. let canUseCdn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  846. const {
  847. url,
  848. cdnUrl
  849. } = client.config();
  850. const base = canUseCdn ? cdnUrl : url;
  851. return "".concat(base, "/").concat(uri.replace(/^\//, ""));
  852. }
  853. function _withAbortSignal(signal) {
  854. return input => {
  855. return new Observable(observer => {
  856. const abort = () => observer.error(_createAbortError(signal));
  857. if (signal && signal.aborted) {
  858. abort();
  859. return;
  860. }
  861. const subscription = input.subscribe(observer);
  862. signal.addEventListener("abort", abort);
  863. return () => {
  864. signal.removeEventListener("abort", abort);
  865. subscription.unsubscribe();
  866. };
  867. });
  868. };
  869. }
  870. const isDomExceptionSupported = Boolean(globalThis.DOMException);
  871. function _createAbortError(signal) {
  872. var _a, _b;
  873. if (isDomExceptionSupported) {
  874. return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
  875. }
  876. const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
  877. error.name = "AbortError";
  878. return error;
  879. }
  880. var __accessCheck$4 = (obj, member, msg) => {
  881. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  882. };
  883. var __privateGet$4 = (obj, member, getter) => {
  884. __accessCheck$4(obj, member, "read from private field");
  885. return getter ? getter.call(obj) : member.get(obj);
  886. };
  887. var __privateAdd$4 = (obj, member, value) => {
  888. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  889. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  890. };
  891. var __privateSet$4 = (obj, member, value, setter) => {
  892. __accessCheck$4(obj, member, "write to private field");
  893. setter ? setter.call(obj, value) : member.set(obj, value);
  894. return value;
  895. };
  896. var _client$3, _httpRequest$4, _client2$3, _httpRequest2$4;
  897. class ObservableAssetsClient {
  898. constructor(client, httpRequest) {
  899. __privateAdd$4(this, _client$3, void 0);
  900. __privateAdd$4(this, _httpRequest$4, void 0);
  901. __privateSet$4(this, _client$3, client);
  902. __privateSet$4(this, _httpRequest$4, httpRequest);
  903. }
  904. upload(assetType, body, options) {
  905. return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
  906. }
  907. }
  908. _client$3 = new WeakMap();
  909. _httpRequest$4 = new WeakMap();
  910. class AssetsClient {
  911. constructor(client, httpRequest) {
  912. __privateAdd$4(this, _client2$3, void 0);
  913. __privateAdd$4(this, _httpRequest2$4, void 0);
  914. __privateSet$4(this, _client2$3, client);
  915. __privateSet$4(this, _httpRequest2$4, httpRequest);
  916. }
  917. upload(assetType, body, options) {
  918. const observable = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
  919. return lastValueFrom(observable.pipe(filter(event => event.type === "response"), map(event => event.body.document)));
  920. }
  921. }
  922. _client2$3 = new WeakMap();
  923. _httpRequest2$4 = new WeakMap();
  924. function _upload(client, httpRequest, assetType, body) {
  925. let opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  926. validateAssetType(assetType);
  927. let meta = opts.extract || void 0;
  928. if (meta && !meta.length) {
  929. meta = ["none"];
  930. }
  931. const dataset = hasDataset(client.config());
  932. const assetEndpoint = assetType === "image" ? "images" : "files";
  933. const options = optionsFromFile(opts, body);
  934. const {
  935. tag,
  936. label,
  937. title,
  938. description,
  939. creditLine,
  940. filename,
  941. source
  942. } = options;
  943. const query = {
  944. label,
  945. title,
  946. description,
  947. filename,
  948. meta,
  949. creditLine
  950. };
  951. if (source) {
  952. query.sourceId = source.id;
  953. query.sourceName = source.name;
  954. query.sourceUrl = source.url;
  955. }
  956. return _requestObservable(client, httpRequest, {
  957. tag,
  958. method: "POST",
  959. timeout: options.timeout || 0,
  960. uri: "/assets/".concat(assetEndpoint, "/").concat(dataset),
  961. headers: options.contentType ? {
  962. "Content-Type": options.contentType
  963. } : {},
  964. query,
  965. body
  966. });
  967. }
  968. function optionsFromFile(opts, file) {
  969. if (typeof File === "undefined" || !(file instanceof File)) {
  970. return opts;
  971. }
  972. return Object.assign({
  973. filename: opts.preserveFilename === false ? void 0 : file.name,
  974. contentType: file.type
  975. }, opts);
  976. }
  977. const BASE_URL = "https://www.sanity.io/help/";
  978. function generateHelpUrl(slug) {
  979. return BASE_URL + slug;
  980. }
  981. function once(fn) {
  982. let didCall = false;
  983. let returnValue;
  984. return function () {
  985. if (didCall) {
  986. return returnValue;
  987. }
  988. returnValue = fn(...arguments);
  989. didCall = true;
  990. return returnValue;
  991. };
  992. }
  993. const createWarningPrinter = message =>
  994. // eslint-disable-next-line no-console
  995. once(function () {
  996. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  997. args[_key] = arguments[_key];
  998. }
  999. return console.warn(message.join(" "), ...args);
  1000. });
  1001. const printCdnWarning = createWarningPrinter(["You are not using the Sanity CDN. That means your data is always fresh, but the CDN is faster and", "cheaper. Think about it! For more info, see ".concat(generateHelpUrl("js-client-cdn-configuration"), " "), "To hide this warning, please set the `useCdn` option to either `true` or `false` when creating", "the client."]);
  1002. const printBrowserTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.", "See ".concat(generateHelpUrl("js-client-browser-token"), " for more information and how to hide this warning.")]);
  1003. const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
  1004. const printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead"]);
  1005. const defaultCdnHost = "apicdn.sanity.io";
  1006. const defaultConfig = {
  1007. apiHost: "https://api.sanity.io",
  1008. apiVersion: "1",
  1009. useProjectHostname: true
  1010. };
  1011. const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
  1012. const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
  1013. const validateApiVersion = function validateApiVersion2(apiVersion) {
  1014. if (apiVersion === "1" || apiVersion === "X") {
  1015. return;
  1016. }
  1017. const apiDate = new Date(apiVersion);
  1018. const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
  1019. if (!apiVersionValid) {
  1020. throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
  1021. }
  1022. };
  1023. const initConfig = (config, prevConfig) => {
  1024. const specifiedConfig = Object.assign({}, prevConfig, config);
  1025. if (!specifiedConfig.apiVersion) {
  1026. printNoApiVersionSpecifiedWarning();
  1027. }
  1028. const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
  1029. const projectBased = newConfig.useProjectHostname;
  1030. if (typeof Promise === "undefined") {
  1031. const helpUrl = generateHelpUrl("js-client-promise-polyfill");
  1032. throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
  1033. }
  1034. if (projectBased && !newConfig.projectId) {
  1035. throw new Error("Configuration must contain `projectId`");
  1036. }
  1037. const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
  1038. const isLocalhost = isBrowser && isLocal(window.location.hostname);
  1039. if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
  1040. printBrowserTokenWarning();
  1041. } else if (typeof newConfig.useCdn === "undefined") {
  1042. printCdnWarning();
  1043. }
  1044. if (projectBased) {
  1045. projectId(newConfig.projectId);
  1046. }
  1047. if (newConfig.dataset) {
  1048. dataset(newConfig.dataset);
  1049. }
  1050. if ("requestTagPrefix" in newConfig) {
  1051. newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
  1052. }
  1053. newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
  1054. newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
  1055. newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
  1056. validateApiVersion(newConfig.apiVersion);
  1057. const hostParts = newConfig.apiHost.split("://", 2);
  1058. const protocol = hostParts[0];
  1059. const host = hostParts[1];
  1060. const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
  1061. if (newConfig.useProjectHostname) {
  1062. newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
  1063. newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
  1064. } else {
  1065. newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
  1066. newConfig.cdnUrl = newConfig.url;
  1067. }
  1068. return newConfig;
  1069. };
  1070. var defaults = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
  1071. target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
  1072. return target;
  1073. }, {});
  1074. const pick = (obj, props) => props.reduce((selection, prop) => {
  1075. if (typeof obj[prop] === "undefined") {
  1076. return selection;
  1077. }
  1078. selection[prop] = obj[prop];
  1079. return selection;
  1080. }, {});
  1081. const MAX_URL_LENGTH = 16e3 - 1200;
  1082. const possibleOptions = ["includePreviousRevision", "includeResult", "visibility", "effectFormat", "tag"];
  1083. const defaultOptions = {
  1084. includeResult: true
  1085. };
  1086. function _listen(query, params) {
  1087. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1088. const {
  1089. url,
  1090. token,
  1091. withCredentials,
  1092. requestTagPrefix
  1093. } = this.config();
  1094. const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
  1095. const options = {
  1096. ...defaults(opts, defaultOptions),
  1097. tag
  1098. };
  1099. const listenOpts = pick(options, possibleOptions);
  1100. const qs = encodeQueryString({
  1101. query,
  1102. params,
  1103. options: {
  1104. tag,
  1105. ...listenOpts
  1106. }
  1107. });
  1108. const uri = "".concat(url).concat(_getDataUrl(this, "listen", qs));
  1109. if (uri.length > MAX_URL_LENGTH) {
  1110. return new Observable(observer => observer.error(new Error("Query too large for listener")));
  1111. }
  1112. const listenFor = options.events ? options.events : ["mutation"];
  1113. const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
  1114. const esOptions = {};
  1115. if (token || withCredentials) {
  1116. esOptions.withCredentials = true;
  1117. }
  1118. if (token) {
  1119. esOptions.headers = {
  1120. Authorization: "Bearer ".concat(token)
  1121. };
  1122. }
  1123. return new Observable(observer => {
  1124. let es;
  1125. getEventSource().then(eventSource => {
  1126. es = eventSource;
  1127. }).catch(reason => {
  1128. observer.error(reason);
  1129. stop();
  1130. });
  1131. let reconnectTimer;
  1132. let stopped = false;
  1133. function onError() {
  1134. if (stopped) {
  1135. return;
  1136. }
  1137. emitReconnect();
  1138. if (stopped) {
  1139. return;
  1140. }
  1141. if (es.readyState === es.CLOSED) {
  1142. unsubscribe();
  1143. clearTimeout(reconnectTimer);
  1144. reconnectTimer = setTimeout(open, 100);
  1145. }
  1146. }
  1147. function onChannelError(err) {
  1148. observer.error(cooerceError(err));
  1149. }
  1150. function onMessage(evt) {
  1151. const event = parseEvent(evt);
  1152. return event instanceof Error ? observer.error(event) : observer.next(event);
  1153. }
  1154. function onDisconnect() {
  1155. stopped = true;
  1156. unsubscribe();
  1157. observer.complete();
  1158. }
  1159. function unsubscribe() {
  1160. if (!es) return;
  1161. es.removeEventListener("error", onError);
  1162. es.removeEventListener("channelError", onChannelError);
  1163. es.removeEventListener("disconnect", onDisconnect);
  1164. listenFor.forEach(type => es.removeEventListener(type, onMessage));
  1165. es.close();
  1166. }
  1167. function emitReconnect() {
  1168. if (shouldEmitReconnect) {
  1169. observer.next({
  1170. type: "reconnect"
  1171. });
  1172. }
  1173. }
  1174. async function getEventSource() {
  1175. const {
  1176. default: EventSource
  1177. } = await import('@sanity/eventsource');
  1178. const evs = new EventSource(uri, esOptions);
  1179. evs.addEventListener("error", onError);
  1180. evs.addEventListener("channelError", onChannelError);
  1181. evs.addEventListener("disconnect", onDisconnect);
  1182. listenFor.forEach(type => evs.addEventListener(type, onMessage));
  1183. return evs;
  1184. }
  1185. function open() {
  1186. getEventSource().then(eventSource => {
  1187. es = eventSource;
  1188. }).catch(reason => {
  1189. observer.error(reason);
  1190. stop();
  1191. });
  1192. }
  1193. function stop() {
  1194. stopped = true;
  1195. unsubscribe();
  1196. }
  1197. return stop;
  1198. });
  1199. }
  1200. function parseEvent(event) {
  1201. try {
  1202. const data = event.data && JSON.parse(event.data) || {};
  1203. return Object.assign({
  1204. type: event.type
  1205. }, data);
  1206. } catch (err) {
  1207. return err;
  1208. }
  1209. }
  1210. function cooerceError(err) {
  1211. if (err instanceof Error) {
  1212. return err;
  1213. }
  1214. const evt = parseEvent(err);
  1215. return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
  1216. }
  1217. function extractErrorMessage(err) {
  1218. if (!err.error) {
  1219. return err.message || "Unknown listener error";
  1220. }
  1221. if (err.error.description) {
  1222. return err.error.description;
  1223. }
  1224. return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
  1225. }
  1226. var __accessCheck$3 = (obj, member, msg) => {
  1227. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  1228. };
  1229. var __privateGet$3 = (obj, member, getter) => {
  1230. __accessCheck$3(obj, member, "read from private field");
  1231. return getter ? getter.call(obj) : member.get(obj);
  1232. };
  1233. var __privateAdd$3 = (obj, member, value) => {
  1234. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  1235. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  1236. };
  1237. var __privateSet$3 = (obj, member, value, setter) => {
  1238. __accessCheck$3(obj, member, "write to private field");
  1239. setter ? setter.call(obj, value) : member.set(obj, value);
  1240. return value;
  1241. };
  1242. var _client$2, _httpRequest$3, _client2$2, _httpRequest2$3;
  1243. class ObservableDatasetsClient {
  1244. constructor(client, httpRequest) {
  1245. __privateAdd$3(this, _client$2, void 0);
  1246. __privateAdd$3(this, _httpRequest$3, void 0);
  1247. __privateSet$3(this, _client$2, client);
  1248. __privateSet$3(this, _httpRequest$3, httpRequest);
  1249. }
  1250. /**
  1251. * Create a new dataset with the given name
  1252. *
  1253. * @param name - Name of the dataset to create
  1254. * @param options - Options for the dataset
  1255. */
  1256. create(name, options) {
  1257. return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name, options);
  1258. }
  1259. /**
  1260. * Edit a dataset with the given name
  1261. *
  1262. * @param name - Name of the dataset to edit
  1263. * @param options - New options for the dataset
  1264. */
  1265. edit(name, options) {
  1266. return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name, options);
  1267. }
  1268. /**
  1269. * Delete a dataset with the given name
  1270. *
  1271. * @param name - Name of the dataset to delete
  1272. */
  1273. delete(name) {
  1274. return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name);
  1275. }
  1276. /**
  1277. * Fetch a list of datasets for the configured project
  1278. */
  1279. list() {
  1280. return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
  1281. uri: "/datasets"
  1282. });
  1283. }
  1284. }
  1285. _client$2 = new WeakMap();
  1286. _httpRequest$3 = new WeakMap();
  1287. class DatasetsClient {
  1288. constructor(client, httpRequest) {
  1289. __privateAdd$3(this, _client2$2, void 0);
  1290. __privateAdd$3(this, _httpRequest2$3, void 0);
  1291. __privateSet$3(this, _client2$2, client);
  1292. __privateSet$3(this, _httpRequest2$3, httpRequest);
  1293. }
  1294. /**
  1295. * Create a new dataset with the given name
  1296. *
  1297. * @param name - Name of the dataset to create
  1298. * @param options - Options for the dataset
  1299. */
  1300. create(name, options) {
  1301. return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name, options));
  1302. }
  1303. /**
  1304. * Edit a dataset with the given name
  1305. *
  1306. * @param name - Name of the dataset to edit
  1307. * @param options - New options for the dataset
  1308. */
  1309. edit(name, options) {
  1310. return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name, options));
  1311. }
  1312. /**
  1313. * Delete a dataset with the given name
  1314. *
  1315. * @param name - Name of the dataset to delete
  1316. */
  1317. delete(name) {
  1318. return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name));
  1319. }
  1320. /**
  1321. * Fetch a list of datasets for the configured project
  1322. */
  1323. list() {
  1324. return lastValueFrom(_request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), {
  1325. uri: "/datasets"
  1326. }));
  1327. }
  1328. }
  1329. _client2$2 = new WeakMap();
  1330. _httpRequest2$3 = new WeakMap();
  1331. function _modify(client, httpRequest, method, name, options) {
  1332. dataset(name);
  1333. return _request(client, httpRequest, {
  1334. method,
  1335. uri: "/datasets/".concat(name),
  1336. body: options
  1337. });
  1338. }
  1339. var __accessCheck$2 = (obj, member, msg) => {
  1340. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  1341. };
  1342. var __privateGet$2 = (obj, member, getter) => {
  1343. __accessCheck$2(obj, member, "read from private field");
  1344. return getter ? getter.call(obj) : member.get(obj);
  1345. };
  1346. var __privateAdd$2 = (obj, member, value) => {
  1347. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  1348. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  1349. };
  1350. var __privateSet$2 = (obj, member, value, setter) => {
  1351. __accessCheck$2(obj, member, "write to private field");
  1352. setter ? setter.call(obj, value) : member.set(obj, value);
  1353. return value;
  1354. };
  1355. var _client$1, _httpRequest$2, _client2$1, _httpRequest2$2;
  1356. class ObservableProjectsClient {
  1357. constructor(client, httpRequest) {
  1358. __privateAdd$2(this, _client$1, void 0);
  1359. __privateAdd$2(this, _httpRequest$2, void 0);
  1360. __privateSet$2(this, _client$1, client);
  1361. __privateSet$2(this, _httpRequest$2, httpRequest);
  1362. }
  1363. /**
  1364. * Fetch a list of projects the authenticated user has access to
  1365. */
  1366. list() {
  1367. return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
  1368. uri: "/projects"
  1369. });
  1370. }
  1371. /**
  1372. * Fetch a project by project ID
  1373. *
  1374. * @param projectId - ID of the project to fetch
  1375. */
  1376. getById(projectId) {
  1377. return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
  1378. uri: "/projects/".concat(projectId)
  1379. });
  1380. }
  1381. }
  1382. _client$1 = new WeakMap();
  1383. _httpRequest$2 = new WeakMap();
  1384. class ProjectsClient {
  1385. constructor(client, httpRequest) {
  1386. __privateAdd$2(this, _client2$1, void 0);
  1387. __privateAdd$2(this, _httpRequest2$2, void 0);
  1388. __privateSet$2(this, _client2$1, client);
  1389. __privateSet$2(this, _httpRequest2$2, httpRequest);
  1390. }
  1391. /**
  1392. * Fetch a list of projects the authenticated user has access to
  1393. */
  1394. list() {
  1395. return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
  1396. uri: "/projects"
  1397. }));
  1398. }
  1399. /**
  1400. * Fetch a project by project ID
  1401. *
  1402. * @param projectId - ID of the project to fetch
  1403. */
  1404. getById(projectId) {
  1405. return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
  1406. uri: "/projects/".concat(projectId)
  1407. }));
  1408. }
  1409. }
  1410. _client2$1 = new WeakMap();
  1411. _httpRequest2$2 = new WeakMap();
  1412. var __accessCheck$1 = (obj, member, msg) => {
  1413. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  1414. };
  1415. var __privateGet$1 = (obj, member, getter) => {
  1416. __accessCheck$1(obj, member, "read from private field");
  1417. return getter ? getter.call(obj) : member.get(obj);
  1418. };
  1419. var __privateAdd$1 = (obj, member, value) => {
  1420. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  1421. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  1422. };
  1423. var __privateSet$1 = (obj, member, value, setter) => {
  1424. __accessCheck$1(obj, member, "write to private field");
  1425. setter ? setter.call(obj, value) : member.set(obj, value);
  1426. return value;
  1427. };
  1428. var _client, _httpRequest$1, _client2, _httpRequest2$1;
  1429. class ObservableUsersClient {
  1430. constructor(client, httpRequest) {
  1431. __privateAdd$1(this, _client, void 0);
  1432. __privateAdd$1(this, _httpRequest$1, void 0);
  1433. __privateSet$1(this, _client, client);
  1434. __privateSet$1(this, _httpRequest$1, httpRequest);
  1435. }
  1436. /**
  1437. * Fetch a user by user ID
  1438. *
  1439. * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
  1440. */
  1441. getById(id) {
  1442. return _request(__privateGet$1(this, _client), __privateGet$1(this, _httpRequest$1), {
  1443. uri: "/users/".concat(id)
  1444. });
  1445. }
  1446. }
  1447. _client = new WeakMap();
  1448. _httpRequest$1 = new WeakMap();
  1449. class UsersClient {
  1450. constructor(client, httpRequest) {
  1451. __privateAdd$1(this, _client2, void 0);
  1452. __privateAdd$1(this, _httpRequest2$1, void 0);
  1453. __privateSet$1(this, _client2, client);
  1454. __privateSet$1(this, _httpRequest2$1, httpRequest);
  1455. }
  1456. /**
  1457. * Fetch a user by user ID
  1458. *
  1459. * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
  1460. */
  1461. getById(id) {
  1462. return lastValueFrom(_request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
  1463. uri: "/users/".concat(id)
  1464. }));
  1465. }
  1466. }
  1467. _client2 = new WeakMap();
  1468. _httpRequest2$1 = new WeakMap();
  1469. var __accessCheck = (obj, member, msg) => {
  1470. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  1471. };
  1472. var __privateGet = (obj, member, getter) => {
  1473. __accessCheck(obj, member, "read from private field");
  1474. return getter ? getter.call(obj) : member.get(obj);
  1475. };
  1476. var __privateAdd = (obj, member, value) => {
  1477. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  1478. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  1479. };
  1480. var __privateSet = (obj, member, value, setter) => {
  1481. __accessCheck(obj, member, "write to private field");
  1482. setter ? setter.call(obj, value) : member.set(obj, value);
  1483. return value;
  1484. };
  1485. var _clientConfig, _httpRequest, _clientConfig2, _httpRequest2;
  1486. const _ObservableSanityClient = class {
  1487. constructor(httpRequest) {
  1488. let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
  1489. /**
  1490. * Private properties
  1491. */
  1492. __privateAdd(this, _clientConfig, void 0);
  1493. __privateAdd(this, _httpRequest, void 0);
  1494. /**
  1495. * Instance properties
  1496. */
  1497. this.listen = _listen;
  1498. this.config(config);
  1499. __privateSet(this, _httpRequest, httpRequest);
  1500. this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest));
  1501. this.datasets = new ObservableDatasetsClient(this, __privateGet(this, _httpRequest));
  1502. this.projects = new ObservableProjectsClient(this, __privateGet(this, _httpRequest));
  1503. this.users = new ObservableUsersClient(this, __privateGet(this, _httpRequest));
  1504. }
  1505. /**
  1506. * Clone the client - returns a new instance
  1507. */
  1508. clone() {
  1509. return new _ObservableSanityClient(__privateGet(this, _httpRequest), this.config());
  1510. }
  1511. config(newConfig) {
  1512. if (newConfig === void 0) {
  1513. return {
  1514. ...__privateGet(this, _clientConfig)
  1515. };
  1516. }
  1517. if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === false) {
  1518. throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
  1519. }
  1520. __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {}));
  1521. return this;
  1522. }
  1523. /**
  1524. * Clone the client with a new (partial) configuration.
  1525. *
  1526. * @param newConfig - New client configuration properties, shallowly merged with existing configuration
  1527. */
  1528. withConfig(newConfig) {
  1529. return new _ObservableSanityClient(__privateGet(this, _httpRequest), {
  1530. ...this.config(),
  1531. ...newConfig
  1532. });
  1533. }
  1534. fetch(query, params) {
  1535. let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1536. return _fetch(this, __privateGet(this, _httpRequest), query, params, options);
  1537. }
  1538. /**
  1539. * Fetch a single document with the given ID.
  1540. *
  1541. * @param id - Document ID to fetch
  1542. * @param options - Request options
  1543. */
  1544. getDocument(id, options) {
  1545. return _getDocument(this, __privateGet(this, _httpRequest), id, options);
  1546. }
  1547. /**
  1548. * Fetch multiple documents in one request.
  1549. * Should be used sparingly - performing a query is usually a better option.
  1550. * The order/position of documents is preserved based on the original array of IDs.
  1551. * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
  1552. *
  1553. * @param ids - Document IDs to fetch
  1554. * @param options - Request options
  1555. */
  1556. getDocuments(ids, options) {
  1557. return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
  1558. }
  1559. create(document, options) {
  1560. return _create(this, __privateGet(this, _httpRequest), document, "create", options);
  1561. }
  1562. createIfNotExists(document, options) {
  1563. return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
  1564. }
  1565. createOrReplace(document, options) {
  1566. return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
  1567. }
  1568. delete(selection, options) {
  1569. return _delete(this, __privateGet(this, _httpRequest), selection, options);
  1570. }
  1571. mutate(operations, options) {
  1572. return _mutate(this, __privateGet(this, _httpRequest), operations, options);
  1573. }
  1574. /**
  1575. * Create a new buildable patch of operations to perform
  1576. *
  1577. * @param documentId - Document ID(s) to patch
  1578. * @param operations - Optional object of patch operations to initialize the patch instance with
  1579. */
  1580. patch(documentId, operations) {
  1581. return new ObservablePatch(documentId, operations, this);
  1582. }
  1583. /**
  1584. * Create a new transaction of mutations
  1585. *
  1586. * @param operations - Optional array of mutation operations to initialize the transaction instance with
  1587. */
  1588. transaction(operations) {
  1589. return new ObservableTransaction(operations, this);
  1590. }
  1591. /**
  1592. * DEPRECATED: Perform an HTTP request against the Sanity API
  1593. *
  1594. * @deprecated Use your own request library!
  1595. * @param options - Request options
  1596. */
  1597. request(options) {
  1598. return _request(this, __privateGet(this, _httpRequest), options);
  1599. }
  1600. /**
  1601. * Get a Sanity API URL for the URI provided
  1602. *
  1603. * @param uri - URI/path to build URL for
  1604. * @param canUseCdn - Whether or not to allow using the API CDN for this route
  1605. */
  1606. getUrl(uri, canUseCdn) {
  1607. return _getUrl(this, uri, canUseCdn);
  1608. }
  1609. /**
  1610. * Get a Sanity API URL for the data operation and path provided
  1611. *
  1612. * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
  1613. * @param path - Path to append after the operation
  1614. */
  1615. getDataUrl(operation, path) {
  1616. return _getDataUrl(this, operation, path);
  1617. }
  1618. };
  1619. let ObservableSanityClient = _ObservableSanityClient;
  1620. _clientConfig = new WeakMap();
  1621. _httpRequest = new WeakMap();
  1622. const _SanityClient = class {
  1623. constructor(httpRequest) {
  1624. let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
  1625. /**
  1626. * Private properties
  1627. */
  1628. __privateAdd(this, _clientConfig2, void 0);
  1629. __privateAdd(this, _httpRequest2, void 0);
  1630. /**
  1631. * Instance properties
  1632. */
  1633. this.listen = _listen;
  1634. this.config(config);
  1635. __privateSet(this, _httpRequest2, httpRequest);
  1636. this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2));
  1637. this.datasets = new DatasetsClient(this, __privateGet(this, _httpRequest2));
  1638. this.projects = new ProjectsClient(this, __privateGet(this, _httpRequest2));
  1639. this.users = new UsersClient(this, __privateGet(this, _httpRequest2));
  1640. this.observable = new ObservableSanityClient(httpRequest, config);
  1641. }
  1642. /**
  1643. * Clone the client - returns a new instance
  1644. */
  1645. clone() {
  1646. return new _SanityClient(__privateGet(this, _httpRequest2), this.config());
  1647. }
  1648. config(newConfig) {
  1649. if (newConfig === void 0) {
  1650. return {
  1651. ...__privateGet(this, _clientConfig2)
  1652. };
  1653. }
  1654. if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === false) {
  1655. throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
  1656. }
  1657. if (this.observable) {
  1658. this.observable.config(newConfig);
  1659. }
  1660. __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {}));
  1661. return this;
  1662. }
  1663. /**
  1664. * Clone the client with a new (partial) configuration.
  1665. *
  1666. * @param newConfig - New client configuration properties, shallowly merged with existing configuration
  1667. */
  1668. withConfig(newConfig) {
  1669. return new _SanityClient(__privateGet(this, _httpRequest2), {
  1670. ...this.config(),
  1671. ...newConfig
  1672. });
  1673. }
  1674. fetch(query, params) {
  1675. let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1676. return lastValueFrom(_fetch(this, __privateGet(this, _httpRequest2), query, params, options));
  1677. }
  1678. /**
  1679. * Fetch a single document with the given ID.
  1680. *
  1681. * @param id - Document ID to fetch
  1682. * @param options - Request options
  1683. */
  1684. getDocument(id, options) {
  1685. return lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
  1686. }
  1687. /**
  1688. * Fetch multiple documents in one request.
  1689. * Should be used sparingly - performing a query is usually a better option.
  1690. * The order/position of documents is preserved based on the original array of IDs.
  1691. * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
  1692. *
  1693. * @param ids - Document IDs to fetch
  1694. * @param options - Request options
  1695. */
  1696. getDocuments(ids, options) {
  1697. return lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
  1698. }
  1699. create(document, options) {
  1700. return lastValueFrom(_create(this, __privateGet(this, _httpRequest2), document, "create", options));
  1701. }
  1702. createIfNotExists(document, options) {
  1703. return lastValueFrom(_createIfNotExists(this, __privateGet(this, _httpRequest2), document, options));
  1704. }
  1705. createOrReplace(document, options) {
  1706. return lastValueFrom(_createOrReplace(this, __privateGet(this, _httpRequest2), document, options));
  1707. }
  1708. delete(selection, options) {
  1709. return lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
  1710. }
  1711. mutate(operations, options) {
  1712. return lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
  1713. }
  1714. /**
  1715. * Create a new buildable patch of operations to perform
  1716. *
  1717. * @param documentId - Document ID(s)to patch
  1718. * @param operations - Optional object of patch operations to initialize the patch instance with
  1719. */
  1720. patch(documentId, operations) {
  1721. return new Patch(documentId, operations, this);
  1722. }
  1723. /**
  1724. * Create a new transaction of mutations
  1725. *
  1726. * @param operations - Optional array of mutation operations to initialize the transaction instance with
  1727. */
  1728. transaction(operations) {
  1729. return new Transaction(operations, this);
  1730. }
  1731. /**
  1732. * DEPRECATED: Perform an HTTP request against the Sanity API
  1733. *
  1734. * @deprecated Use your own request library!
  1735. * @param options - Request options
  1736. */
  1737. request(options) {
  1738. return lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
  1739. }
  1740. /**
  1741. * DEPRECATED: Perform an HTTP request a `/data` sub-endpoint
  1742. *
  1743. * @deprecated Use your own request library!
  1744. * @param endpoint - Endpoint to hit (mutate, query etc)
  1745. * @param body - Request body
  1746. * @param options - Request options
  1747. */
  1748. dataRequest(endpoint, body, options) {
  1749. return lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
  1750. }
  1751. /**
  1752. * Get a Sanity API URL for the URI provided
  1753. *
  1754. * @param uri - URI/path to build URL for
  1755. * @param canUseCdn - Whether or not to allow using the API CDN for this route
  1756. */
  1757. getUrl(uri, canUseCdn) {
  1758. return _getUrl(this, uri, canUseCdn);
  1759. }
  1760. /**
  1761. * Get a Sanity API URL for the data operation and path provided
  1762. *
  1763. * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
  1764. * @param path - Path to append after the operation
  1765. */
  1766. getDataUrl(operation, path) {
  1767. return _getDataUrl(this, operation, path);
  1768. }
  1769. };
  1770. let SanityClient = _SanityClient;
  1771. _clientConfig2 = new WeakMap();
  1772. _httpRequest2 = new WeakMap();
  1773. const httpRequest = defineHttpRequest(middleware);
  1774. const requester = httpRequest.defaultRequester;
  1775. const createClient = config => new SanityClient(httpRequest, config);
  1776. function deprecatedCreateClient(config) {
  1777. printNoDefaultExport();
  1778. return new SanityClient(httpRequest, config);
  1779. }
  1780. export { BasePatch, BaseTransaction, ClientError, ObservablePatch, ObservableSanityClient, ObservableTransaction, Patch, SanityClient, ServerError, Transaction, createClient, deprecatedCreateClient as default, requester };
  1781. //# sourceMappingURL=index.js.map