index.browser.js 62 KB

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