sanityClient.js 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.SanityClient = {}));
  5. })(this, (function (exports) { 'use strict';
  6. function _mergeNamespaces(n, m) {
  7. m.forEach(function (e) {
  8. e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
  9. if (k !== 'default' && !(k in n)) {
  10. var d = Object.getOwnPropertyDescriptor(e, k);
  11. Object.defineProperty(n, k, d.get ? d : {
  12. enumerable: true,
  13. get: function () { return e[k]; }
  14. });
  15. }
  16. });
  17. });
  18. return Object.freeze(n);
  19. }
  20. const isReactNative = typeof navigator === "undefined" ? false : navigator.product === "ReactNative";
  21. const defaultOptions$1 = {
  22. timeout: isReactNative ? 6e4 : 12e4
  23. };
  24. function processOptions(opts) {
  25. const options = typeof opts === "string" ? Object.assign({
  26. url: opts
  27. }, defaultOptions$1) : Object.assign({}, defaultOptions$1, opts);
  28. const url = new URL(options.url, "http://localhost");
  29. options.timeout = normalizeTimeout(options.timeout);
  30. if (options.query) {
  31. for (const [key, value] of Object.entries(options.query)) {
  32. if (value !== void 0) {
  33. if (Array.isArray(value)) {
  34. for (const v of value) {
  35. url.searchParams.append(key, v);
  36. }
  37. } else {
  38. url.searchParams.append(key, value);
  39. }
  40. }
  41. }
  42. }
  43. options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase();
  44. options.url = url.origin === "http://localhost" ? "".concat(url.pathname, "?").concat(url.searchParams) : url.toString();
  45. return options;
  46. }
  47. function normalizeTimeout(time) {
  48. if (time === false || time === 0) {
  49. return false;
  50. }
  51. if (time.connect || time.socket) {
  52. return time;
  53. }
  54. const delay = Number(time);
  55. if (isNaN(delay)) {
  56. return normalizeTimeout(defaultOptions$1.timeout);
  57. }
  58. return {
  59. connect: delay,
  60. socket: delay
  61. };
  62. }
  63. const validUrl = /^https?:\/\//i;
  64. function validateOptions(options) {
  65. if (!validUrl.test(options.url)) {
  66. throw new Error("\"".concat(options.url, "\" is not a valid URL"));
  67. }
  68. }
  69. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  70. var trim = function(string) {
  71. return string.replace(/^\s+|\s+$/g, '');
  72. }
  73. , isArray = function(arg) {
  74. return Object.prototype.toString.call(arg) === '[object Array]';
  75. };
  76. var parseHeaders = function (headers) {
  77. if (!headers)
  78. return {}
  79. var result = {};
  80. var headersArr = trim(headers).split('\n');
  81. for (var i = 0; i < headersArr.length; i++) {
  82. var row = headersArr[i];
  83. var index = row.indexOf(':')
  84. , key = trim(row.slice(0, index)).toLowerCase()
  85. , value = trim(row.slice(index + 1));
  86. if (typeof(result[key]) === 'undefined') {
  87. result[key] = value;
  88. } else if (isArray(result[key])) {
  89. result[key].push(value);
  90. } else {
  91. result[key] = [ result[key], value ];
  92. }
  93. }
  94. return result
  95. };
  96. var middlewareReducer = middleware => {
  97. const applyMiddleware = function (hook, defaultValue) {
  98. const bailEarly = hook === "onError";
  99. let value = defaultValue;
  100. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  101. args[_key - 2] = arguments[_key];
  102. }
  103. for (let i = 0; i < middleware[hook].length; i++) {
  104. const handler = middleware[hook][i];
  105. value = handler(value, ...args);
  106. if (bailEarly && !value) {
  107. break;
  108. }
  109. }
  110. return value;
  111. };
  112. return applyMiddleware;
  113. };
  114. function createPubSub() {
  115. const subscribers = /* @__PURE__ */Object.create(null);
  116. let nextId = 0;
  117. function subscribe(subscriber) {
  118. const id = nextId++;
  119. subscribers[id] = subscriber;
  120. return function unsubscribe() {
  121. delete subscribers[id];
  122. };
  123. }
  124. function publish(event) {
  125. for (const id in subscribers) {
  126. subscribers[id](event);
  127. }
  128. }
  129. return {
  130. publish,
  131. subscribe
  132. };
  133. }
  134. const channelNames = ["request", "response", "progress", "error", "abort"];
  135. const middlehooks = ["processOptions", "validateOptions", "interceptRequest", "finalizeOptions", "onRequest", "onResponse", "onError", "onReturn", "onHeaders"];
  136. function createRequester(initMiddleware, httpRequest) {
  137. const loadedMiddleware = [];
  138. const middleware = middlehooks.reduce((ware, name) => {
  139. ware[name] = ware[name] || [];
  140. return ware;
  141. }, {
  142. processOptions: [processOptions],
  143. validateOptions: [validateOptions]
  144. });
  145. function request(opts) {
  146. const channels = channelNames.reduce((target, name) => {
  147. target[name] = createPubSub();
  148. return target;
  149. }, {});
  150. const applyMiddleware = middlewareReducer(middleware);
  151. const options = applyMiddleware("processOptions", opts);
  152. applyMiddleware("validateOptions", options);
  153. const context = {
  154. options,
  155. channels,
  156. applyMiddleware
  157. };
  158. let ongoingRequest = null;
  159. const unsubscribe = channels.request.subscribe(ctx => {
  160. ongoingRequest = httpRequest(ctx, (err, res) => onResponse(err, res, ctx));
  161. });
  162. channels.abort.subscribe(() => {
  163. unsubscribe();
  164. if (ongoingRequest) {
  165. ongoingRequest.abort();
  166. }
  167. });
  168. const returnValue = applyMiddleware("onReturn", channels, context);
  169. if (returnValue === channels) {
  170. channels.request.publish(context);
  171. }
  172. return returnValue;
  173. function onResponse(reqErr, res, ctx) {
  174. let error = reqErr;
  175. let response = res;
  176. if (!error) {
  177. try {
  178. response = applyMiddleware("onResponse", res, ctx);
  179. } catch (err) {
  180. response = null;
  181. error = err;
  182. }
  183. }
  184. error = error && applyMiddleware("onError", error, ctx);
  185. if (error) {
  186. channels.error.publish(error);
  187. } else if (response) {
  188. channels.response.publish(response);
  189. }
  190. }
  191. }
  192. request.use = function use(newMiddleware) {
  193. if (!newMiddleware) {
  194. throw new Error("Tried to add middleware that resolved to falsey value");
  195. }
  196. if (typeof newMiddleware === "function") {
  197. throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");
  198. }
  199. if (newMiddleware.onReturn && middleware.onReturn.length > 0) {
  200. throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");
  201. }
  202. middlehooks.forEach(key => {
  203. if (newMiddleware[key]) {
  204. middleware[key].push(newMiddleware[key]);
  205. }
  206. });
  207. loadedMiddleware.push(newMiddleware);
  208. return request;
  209. };
  210. request.clone = function clone() {
  211. return createRequester(loadedMiddleware, httpRequest);
  212. };
  213. initMiddleware.forEach(request.use);
  214. return request;
  215. }
  216. var __accessCheck$7 = (obj, member, msg) => {
  217. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  218. };
  219. var __privateGet$7 = (obj, member, getter) => {
  220. __accessCheck$7(obj, member, "read from private field");
  221. return getter ? getter.call(obj) : member.get(obj);
  222. };
  223. var __privateAdd$7 = (obj, member, value) => {
  224. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  225. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  226. };
  227. var __privateSet$7 = (obj, member, value, setter) => {
  228. __accessCheck$7(obj, member, "write to private field");
  229. setter ? setter.call(obj, value) : member.set(obj, value);
  230. return value;
  231. };
  232. var _method, _url, _resHeaders, _headers, _controller;
  233. class FetchXhr {
  234. constructor() {
  235. /**
  236. * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
  237. */
  238. this.readyState = 0;
  239. this.responseType = "";
  240. /**
  241. * Private implementation details
  242. */
  243. __privateAdd$7(this, _method, void 0);
  244. __privateAdd$7(this, _url, void 0);
  245. __privateAdd$7(this, _resHeaders, void 0);
  246. __privateAdd$7(this, _headers, {});
  247. __privateAdd$7(this, _controller, void 0);
  248. }
  249. // eslint-disable-next-line @typescript-eslint/no-unused-vars -- _async is only declared for typings compatibility
  250. open(method, url, _async) {
  251. __privateSet$7(this, _method, method);
  252. __privateSet$7(this, _url, url);
  253. __privateSet$7(this, _resHeaders, "");
  254. this.readyState = 1;
  255. this.onreadystatechange();
  256. __privateSet$7(this, _controller, void 0);
  257. }
  258. abort() {
  259. if (__privateGet$7(this, _controller)) {
  260. __privateGet$7(this, _controller).abort();
  261. }
  262. }
  263. getAllResponseHeaders() {
  264. return __privateGet$7(this, _resHeaders);
  265. }
  266. setRequestHeader(name, value) {
  267. __privateGet$7(this, _headers)[name] = value;
  268. }
  269. send(body) {
  270. const textBody = this.responseType !== "arraybuffer";
  271. const options = {
  272. method: __privateGet$7(this, _method),
  273. headers: __privateGet$7(this, _headers),
  274. body
  275. };
  276. if (typeof AbortController === "function") {
  277. __privateSet$7(this, _controller, new AbortController());
  278. if (typeof EventTarget !== "undefined" && __privateGet$7(this, _controller).signal instanceof EventTarget) {
  279. options.signal = __privateGet$7(this, _controller).signal;
  280. }
  281. }
  282. if (typeof document !== "undefined") {
  283. options.credentials = this.withCredentials ? "include" : "omit";
  284. }
  285. fetch(__privateGet$7(this, _url), options).then(res => {
  286. res.headers.forEach((value, key) => {
  287. __privateSet$7(this, _resHeaders, __privateGet$7(this, _resHeaders) + "".concat(key, ": ").concat(value, "\r\n"));
  288. });
  289. this.status = res.status;
  290. this.statusText = res.statusText;
  291. this.readyState = 3;
  292. return textBody ? res.text() : res.arrayBuffer();
  293. }).then(resBody => {
  294. if (typeof resBody === "string") {
  295. this.responseText = resBody;
  296. } else {
  297. this.response = resBody;
  298. }
  299. this.readyState = 4;
  300. this.onreadystatechange();
  301. }).catch(err => {
  302. var _a;
  303. if (err.name === "AbortError") {
  304. this.onabort();
  305. return;
  306. }
  307. (_a = this.onerror) == null ? void 0 : _a.call(this, err);
  308. });
  309. }
  310. }
  311. _method = new WeakMap();
  312. _url = new WeakMap();
  313. _resHeaders = new WeakMap();
  314. _headers = new WeakMap();
  315. _controller = new WeakMap();
  316. const adapter = typeof XMLHttpRequest === "function" ? "xhr" : "fetch";
  317. const XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr;
  318. var httpRequester = (context, callback) => {
  319. const opts = context.options;
  320. const options = context.applyMiddleware("finalizeOptions", opts);
  321. const timers = {};
  322. const injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
  323. adapter,
  324. context
  325. });
  326. if (injectedResponse) {
  327. const cbTimer = setTimeout(callback, 0, null, injectedResponse);
  328. const cancel = () => clearTimeout(cbTimer);
  329. return {
  330. abort: cancel
  331. };
  332. }
  333. let xhr = new XmlHttpRequest();
  334. const headers = options.headers;
  335. const delays = options.timeout;
  336. let aborted = false;
  337. let loaded = false;
  338. let timedOut = false;
  339. xhr.onerror = onError;
  340. xhr.ontimeout = onError;
  341. xhr.onabort = () => {
  342. stopTimers(true);
  343. aborted = true;
  344. };
  345. xhr.onreadystatechange = () => {
  346. resetTimers();
  347. if (aborted || xhr.readyState !== 4) {
  348. return;
  349. }
  350. if (xhr.status === 0) {
  351. return;
  352. }
  353. onLoad();
  354. };
  355. xhr.open(options.method, options.url, true
  356. // Always async
  357. );
  358. xhr.withCredentials = !!options.withCredentials;
  359. if (headers && xhr.setRequestHeader) {
  360. for (const key in headers) {
  361. if (headers.hasOwnProperty(key)) {
  362. xhr.setRequestHeader(key, headers[key]);
  363. }
  364. }
  365. }
  366. if (options.rawBody) {
  367. xhr.responseType = "arraybuffer";
  368. }
  369. context.applyMiddleware("onRequest", {
  370. options,
  371. adapter,
  372. request: xhr,
  373. context
  374. });
  375. xhr.send(options.body || null);
  376. if (delays) {
  377. timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect);
  378. }
  379. return {
  380. abort
  381. };
  382. function abort() {
  383. aborted = true;
  384. if (xhr) {
  385. xhr.abort();
  386. }
  387. }
  388. function timeoutRequest(code) {
  389. timedOut = true;
  390. xhr.abort();
  391. const error = new Error(code === "ESOCKETTIMEDOUT" ? "Socket timed out on request to ".concat(options.url) : "Connection timed out on request to ".concat(options.url));
  392. error.code = code;
  393. context.channels.error.publish(error);
  394. }
  395. function resetTimers() {
  396. if (!delays) {
  397. return;
  398. }
  399. stopTimers();
  400. timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket);
  401. }
  402. function stopTimers(force) {
  403. if (force || aborted || xhr.readyState >= 2 && timers.connect) {
  404. clearTimeout(timers.connect);
  405. }
  406. if (timers.socket) {
  407. clearTimeout(timers.socket);
  408. }
  409. }
  410. function onError(error) {
  411. if (loaded) {
  412. return;
  413. }
  414. stopTimers(true);
  415. loaded = true;
  416. xhr = null;
  417. const err = error || new Error("Network error while attempting to reach ".concat(options.url));
  418. err.isNetworkError = true;
  419. err.request = options;
  420. callback(err);
  421. }
  422. function reduceResponse() {
  423. return {
  424. body: xhr.response || (xhr.responseType === "" || xhr.responseType === "text" ? xhr.responseText : ""),
  425. url: options.url,
  426. method: options.method,
  427. headers: parseHeaders(xhr.getAllResponseHeaders()),
  428. statusCode: xhr.status,
  429. statusMessage: xhr.statusText
  430. };
  431. }
  432. function onLoad() {
  433. if (aborted || loaded || timedOut) {
  434. return;
  435. }
  436. if (xhr.status === 0) {
  437. onError(new Error("Unknown XHR error"));
  438. return;
  439. }
  440. stopTimers();
  441. loaded = true;
  442. callback(null, reduceResponse());
  443. }
  444. };
  445. const getIt = function () {
  446. let initMiddleware = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  447. let httpRequest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : httpRequester;
  448. return createRequester(initMiddleware, httpRequest);
  449. };
  450. const environment = "browser";
  451. var browserExports = {};
  452. var browser$2 = {
  453. get exports(){ return browserExports; },
  454. set exports(v){ browserExports = v; },
  455. };
  456. /**
  457. * Helpers.
  458. */
  459. var ms;
  460. var hasRequiredMs;
  461. function requireMs () {
  462. if (hasRequiredMs) return ms;
  463. hasRequiredMs = 1;
  464. var s = 1000;
  465. var m = s * 60;
  466. var h = m * 60;
  467. var d = h * 24;
  468. var w = d * 7;
  469. var y = d * 365.25;
  470. /**
  471. * Parse or format the given `val`.
  472. *
  473. * Options:
  474. *
  475. * - `long` verbose formatting [false]
  476. *
  477. * @param {String|Number} val
  478. * @param {Object} [options]
  479. * @throws {Error} throw an error if val is not a non-empty string or a number
  480. * @return {String|Number}
  481. * @api public
  482. */
  483. ms = function(val, options) {
  484. options = options || {};
  485. var type = typeof val;
  486. if (type === 'string' && val.length > 0) {
  487. return parse(val);
  488. } else if (type === 'number' && isFinite(val)) {
  489. return options.long ? fmtLong(val) : fmtShort(val);
  490. }
  491. throw new Error(
  492. 'val is not a non-empty string or a valid number. val=' +
  493. JSON.stringify(val)
  494. );
  495. };
  496. /**
  497. * Parse the given `str` and return milliseconds.
  498. *
  499. * @param {String} str
  500. * @return {Number}
  501. * @api private
  502. */
  503. function parse(str) {
  504. str = String(str);
  505. if (str.length > 100) {
  506. return;
  507. }
  508. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  509. str
  510. );
  511. if (!match) {
  512. return;
  513. }
  514. var n = parseFloat(match[1]);
  515. var type = (match[2] || 'ms').toLowerCase();
  516. switch (type) {
  517. case 'years':
  518. case 'year':
  519. case 'yrs':
  520. case 'yr':
  521. case 'y':
  522. return n * y;
  523. case 'weeks':
  524. case 'week':
  525. case 'w':
  526. return n * w;
  527. case 'days':
  528. case 'day':
  529. case 'd':
  530. return n * d;
  531. case 'hours':
  532. case 'hour':
  533. case 'hrs':
  534. case 'hr':
  535. case 'h':
  536. return n * h;
  537. case 'minutes':
  538. case 'minute':
  539. case 'mins':
  540. case 'min':
  541. case 'm':
  542. return n * m;
  543. case 'seconds':
  544. case 'second':
  545. case 'secs':
  546. case 'sec':
  547. case 's':
  548. return n * s;
  549. case 'milliseconds':
  550. case 'millisecond':
  551. case 'msecs':
  552. case 'msec':
  553. case 'ms':
  554. return n;
  555. default:
  556. return undefined;
  557. }
  558. }
  559. /**
  560. * Short format for `ms`.
  561. *
  562. * @param {Number} ms
  563. * @return {String}
  564. * @api private
  565. */
  566. function fmtShort(ms) {
  567. var msAbs = Math.abs(ms);
  568. if (msAbs >= d) {
  569. return Math.round(ms / d) + 'd';
  570. }
  571. if (msAbs >= h) {
  572. return Math.round(ms / h) + 'h';
  573. }
  574. if (msAbs >= m) {
  575. return Math.round(ms / m) + 'm';
  576. }
  577. if (msAbs >= s) {
  578. return Math.round(ms / s) + 's';
  579. }
  580. return ms + 'ms';
  581. }
  582. /**
  583. * Long format for `ms`.
  584. *
  585. * @param {Number} ms
  586. * @return {String}
  587. * @api private
  588. */
  589. function fmtLong(ms) {
  590. var msAbs = Math.abs(ms);
  591. if (msAbs >= d) {
  592. return plural(ms, msAbs, d, 'day');
  593. }
  594. if (msAbs >= h) {
  595. return plural(ms, msAbs, h, 'hour');
  596. }
  597. if (msAbs >= m) {
  598. return plural(ms, msAbs, m, 'minute');
  599. }
  600. if (msAbs >= s) {
  601. return plural(ms, msAbs, s, 'second');
  602. }
  603. return ms + ' ms';
  604. }
  605. /**
  606. * Pluralization helper.
  607. */
  608. function plural(ms, msAbs, n, name) {
  609. var isPlural = msAbs >= n * 1.5;
  610. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  611. }
  612. return ms;
  613. }
  614. /**
  615. * This is the common logic for both the Node.js and web browser
  616. * implementations of `debug()`.
  617. */
  618. function setup(env) {
  619. createDebug.debug = createDebug;
  620. createDebug.default = createDebug;
  621. createDebug.coerce = coerce;
  622. createDebug.disable = disable;
  623. createDebug.enable = enable;
  624. createDebug.enabled = enabled;
  625. createDebug.humanize = requireMs();
  626. createDebug.destroy = destroy;
  627. Object.keys(env).forEach(key => {
  628. createDebug[key] = env[key];
  629. });
  630. /**
  631. * The currently active debug mode names, and names to skip.
  632. */
  633. createDebug.names = [];
  634. createDebug.skips = [];
  635. /**
  636. * Map of special "%n" handling functions, for the debug "format" argument.
  637. *
  638. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  639. */
  640. createDebug.formatters = {};
  641. /**
  642. * Selects a color for a debug namespace
  643. * @param {String} namespace The namespace string for the debug instance to be colored
  644. * @return {Number|String} An ANSI color code for the given namespace
  645. * @api private
  646. */
  647. function selectColor(namespace) {
  648. let hash = 0;
  649. for (let i = 0; i < namespace.length; i++) {
  650. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  651. hash |= 0; // Convert to 32bit integer
  652. }
  653. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  654. }
  655. createDebug.selectColor = selectColor;
  656. /**
  657. * Create a debugger with the given `namespace`.
  658. *
  659. * @param {String} namespace
  660. * @return {Function}
  661. * @api public
  662. */
  663. function createDebug(namespace) {
  664. let prevTime;
  665. let enableOverride = null;
  666. let namespacesCache;
  667. let enabledCache;
  668. function debug(...args) {
  669. // Disabled?
  670. if (!debug.enabled) {
  671. return;
  672. }
  673. const self = debug;
  674. // Set `diff` timestamp
  675. const curr = Number(new Date());
  676. const ms = curr - (prevTime || curr);
  677. self.diff = ms;
  678. self.prev = prevTime;
  679. self.curr = curr;
  680. prevTime = curr;
  681. args[0] = createDebug.coerce(args[0]);
  682. if (typeof args[0] !== 'string') {
  683. // Anything else let's inspect with %O
  684. args.unshift('%O');
  685. }
  686. // Apply any `formatters` transformations
  687. let index = 0;
  688. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  689. // If we encounter an escaped % then don't increase the array index
  690. if (match === '%%') {
  691. return '%';
  692. }
  693. index++;
  694. const formatter = createDebug.formatters[format];
  695. if (typeof formatter === 'function') {
  696. const val = args[index];
  697. match = formatter.call(self, val);
  698. // Now we need to remove `args[index]` since it's inlined in the `format`
  699. args.splice(index, 1);
  700. index--;
  701. }
  702. return match;
  703. });
  704. // Apply env-specific formatting (colors, etc.)
  705. createDebug.formatArgs.call(self, args);
  706. const logFn = self.log || createDebug.log;
  707. logFn.apply(self, args);
  708. }
  709. debug.namespace = namespace;
  710. debug.useColors = createDebug.useColors();
  711. debug.color = createDebug.selectColor(namespace);
  712. debug.extend = extend;
  713. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  714. Object.defineProperty(debug, 'enabled', {
  715. enumerable: true,
  716. configurable: false,
  717. get: () => {
  718. if (enableOverride !== null) {
  719. return enableOverride;
  720. }
  721. if (namespacesCache !== createDebug.namespaces) {
  722. namespacesCache = createDebug.namespaces;
  723. enabledCache = createDebug.enabled(namespace);
  724. }
  725. return enabledCache;
  726. },
  727. set: v => {
  728. enableOverride = v;
  729. }
  730. });
  731. // Env-specific initialization logic for debug instances
  732. if (typeof createDebug.init === 'function') {
  733. createDebug.init(debug);
  734. }
  735. return debug;
  736. }
  737. function extend(namespace, delimiter) {
  738. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  739. newDebug.log = this.log;
  740. return newDebug;
  741. }
  742. /**
  743. * Enables a debug mode by namespaces. This can include modes
  744. * separated by a colon and wildcards.
  745. *
  746. * @param {String} namespaces
  747. * @api public
  748. */
  749. function enable(namespaces) {
  750. createDebug.save(namespaces);
  751. createDebug.namespaces = namespaces;
  752. createDebug.names = [];
  753. createDebug.skips = [];
  754. let i;
  755. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  756. const len = split.length;
  757. for (i = 0; i < len; i++) {
  758. if (!split[i]) {
  759. // ignore empty strings
  760. continue;
  761. }
  762. namespaces = split[i].replace(/\*/g, '.*?');
  763. if (namespaces[0] === '-') {
  764. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  765. } else {
  766. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  767. }
  768. }
  769. }
  770. /**
  771. * Disable debug output.
  772. *
  773. * @return {String} namespaces
  774. * @api public
  775. */
  776. function disable() {
  777. const namespaces = [
  778. ...createDebug.names.map(toNamespace),
  779. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  780. ].join(',');
  781. createDebug.enable('');
  782. return namespaces;
  783. }
  784. /**
  785. * Returns true if the given mode name is enabled, false otherwise.
  786. *
  787. * @param {String} name
  788. * @return {Boolean}
  789. * @api public
  790. */
  791. function enabled(name) {
  792. if (name[name.length - 1] === '*') {
  793. return true;
  794. }
  795. let i;
  796. let len;
  797. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  798. if (createDebug.skips[i].test(name)) {
  799. return false;
  800. }
  801. }
  802. for (i = 0, len = createDebug.names.length; i < len; i++) {
  803. if (createDebug.names[i].test(name)) {
  804. return true;
  805. }
  806. }
  807. return false;
  808. }
  809. /**
  810. * Convert regexp to namespace
  811. *
  812. * @param {RegExp} regxep
  813. * @return {String} namespace
  814. * @api private
  815. */
  816. function toNamespace(regexp) {
  817. return regexp.toString()
  818. .substring(2, regexp.toString().length - 2)
  819. .replace(/\.\*\?$/, '*');
  820. }
  821. /**
  822. * Coerce `val`.
  823. *
  824. * @param {Mixed} val
  825. * @return {Mixed}
  826. * @api private
  827. */
  828. function coerce(val) {
  829. if (val instanceof Error) {
  830. return val.stack || val.message;
  831. }
  832. return val;
  833. }
  834. /**
  835. * XXX DO NOT USE. This is a temporary stub function.
  836. * XXX It WILL be removed in the next major release.
  837. */
  838. function destroy() {
  839. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  840. }
  841. createDebug.enable(createDebug.load());
  842. return createDebug;
  843. }
  844. var common = setup;
  845. /* eslint-env browser */
  846. (function (module, exports) {
  847. /**
  848. * This is the web browser implementation of `debug()`.
  849. */
  850. exports.formatArgs = formatArgs;
  851. exports.save = save;
  852. exports.load = load;
  853. exports.useColors = useColors;
  854. exports.storage = localstorage();
  855. exports.destroy = (() => {
  856. let warned = false;
  857. return () => {
  858. if (!warned) {
  859. warned = true;
  860. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  861. }
  862. };
  863. })();
  864. /**
  865. * Colors.
  866. */
  867. exports.colors = [
  868. '#0000CC',
  869. '#0000FF',
  870. '#0033CC',
  871. '#0033FF',
  872. '#0066CC',
  873. '#0066FF',
  874. '#0099CC',
  875. '#0099FF',
  876. '#00CC00',
  877. '#00CC33',
  878. '#00CC66',
  879. '#00CC99',
  880. '#00CCCC',
  881. '#00CCFF',
  882. '#3300CC',
  883. '#3300FF',
  884. '#3333CC',
  885. '#3333FF',
  886. '#3366CC',
  887. '#3366FF',
  888. '#3399CC',
  889. '#3399FF',
  890. '#33CC00',
  891. '#33CC33',
  892. '#33CC66',
  893. '#33CC99',
  894. '#33CCCC',
  895. '#33CCFF',
  896. '#6600CC',
  897. '#6600FF',
  898. '#6633CC',
  899. '#6633FF',
  900. '#66CC00',
  901. '#66CC33',
  902. '#9900CC',
  903. '#9900FF',
  904. '#9933CC',
  905. '#9933FF',
  906. '#99CC00',
  907. '#99CC33',
  908. '#CC0000',
  909. '#CC0033',
  910. '#CC0066',
  911. '#CC0099',
  912. '#CC00CC',
  913. '#CC00FF',
  914. '#CC3300',
  915. '#CC3333',
  916. '#CC3366',
  917. '#CC3399',
  918. '#CC33CC',
  919. '#CC33FF',
  920. '#CC6600',
  921. '#CC6633',
  922. '#CC9900',
  923. '#CC9933',
  924. '#CCCC00',
  925. '#CCCC33',
  926. '#FF0000',
  927. '#FF0033',
  928. '#FF0066',
  929. '#FF0099',
  930. '#FF00CC',
  931. '#FF00FF',
  932. '#FF3300',
  933. '#FF3333',
  934. '#FF3366',
  935. '#FF3399',
  936. '#FF33CC',
  937. '#FF33FF',
  938. '#FF6600',
  939. '#FF6633',
  940. '#FF9900',
  941. '#FF9933',
  942. '#FFCC00',
  943. '#FFCC33'
  944. ];
  945. /**
  946. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  947. * and the Firebug extension (any Firefox version) are known
  948. * to support "%c" CSS customizations.
  949. *
  950. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  951. */
  952. // eslint-disable-next-line complexity
  953. function useColors() {
  954. // NB: In an Electron preload script, document will be defined but not fully
  955. // initialized. Since we know we're in Chrome, we'll just detect this case
  956. // explicitly
  957. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  958. return true;
  959. }
  960. // Internet Explorer and Edge do not support colors.
  961. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  962. return false;
  963. }
  964. // Is webkit? http://stackoverflow.com/a/16459606/376773
  965. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  966. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  967. // Is firebug? http://stackoverflow.com/a/398120/376773
  968. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  969. // Is firefox >= v31?
  970. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  971. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  972. // Double check webkit in userAgent just in case we are in a worker
  973. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  974. }
  975. /**
  976. * Colorize log arguments if enabled.
  977. *
  978. * @api public
  979. */
  980. function formatArgs(args) {
  981. args[0] = (this.useColors ? '%c' : '') +
  982. this.namespace +
  983. (this.useColors ? ' %c' : ' ') +
  984. args[0] +
  985. (this.useColors ? '%c ' : ' ') +
  986. '+' + module.exports.humanize(this.diff);
  987. if (!this.useColors) {
  988. return;
  989. }
  990. const c = 'color: ' + this.color;
  991. args.splice(1, 0, c, 'color: inherit');
  992. // The final "%c" is somewhat tricky, because there could be other
  993. // arguments passed either before or after the %c, so we need to
  994. // figure out the correct index to insert the CSS into
  995. let index = 0;
  996. let lastC = 0;
  997. args[0].replace(/%[a-zA-Z%]/g, match => {
  998. if (match === '%%') {
  999. return;
  1000. }
  1001. index++;
  1002. if (match === '%c') {
  1003. // We only are interested in the *last* %c
  1004. // (the user may have provided their own)
  1005. lastC = index;
  1006. }
  1007. });
  1008. args.splice(lastC, 0, c);
  1009. }
  1010. /**
  1011. * Invokes `console.debug()` when available.
  1012. * No-op when `console.debug` is not a "function".
  1013. * If `console.debug` is not available, falls back
  1014. * to `console.log`.
  1015. *
  1016. * @api public
  1017. */
  1018. exports.log = console.debug || console.log || (() => {});
  1019. /**
  1020. * Save `namespaces`.
  1021. *
  1022. * @param {String} namespaces
  1023. * @api private
  1024. */
  1025. function save(namespaces) {
  1026. try {
  1027. if (namespaces) {
  1028. exports.storage.setItem('debug', namespaces);
  1029. } else {
  1030. exports.storage.removeItem('debug');
  1031. }
  1032. } catch (error) {
  1033. // Swallow
  1034. // XXX (@Qix-) should we be logging these?
  1035. }
  1036. }
  1037. /**
  1038. * Load `namespaces`.
  1039. *
  1040. * @return {String} returns the previously persisted debug modes
  1041. * @api private
  1042. */
  1043. function load() {
  1044. let r;
  1045. try {
  1046. r = exports.storage.getItem('debug');
  1047. } catch (error) {
  1048. // Swallow
  1049. // XXX (@Qix-) should we be logging these?
  1050. }
  1051. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  1052. if (!r && typeof process !== 'undefined' && 'env' in process) {
  1053. r = process.env.DEBUG;
  1054. }
  1055. return r;
  1056. }
  1057. /**
  1058. * Localstorage attempts to return the localstorage.
  1059. *
  1060. * This is necessary because safari throws
  1061. * when a user disables cookies/localstorage
  1062. * and you attempt to access it.
  1063. *
  1064. * @return {LocalStorage}
  1065. * @api private
  1066. */
  1067. function localstorage() {
  1068. try {
  1069. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  1070. // The Browser also has localStorage in the global context.
  1071. return localStorage;
  1072. } catch (error) {
  1073. // Swallow
  1074. // XXX (@Qix-) should we be logging these?
  1075. }
  1076. }
  1077. module.exports = common(exports);
  1078. const {formatters} = module.exports;
  1079. /**
  1080. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1081. */
  1082. formatters.j = function (v) {
  1083. try {
  1084. return JSON.stringify(v);
  1085. } catch (error) {
  1086. return '[UnexpectedJSONParseError]: ' + error.message;
  1087. }
  1088. };
  1089. } (browser$2, browserExports));
  1090. /*!
  1091. * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
  1092. *
  1093. * Copyright (c) 2014-2017, Jon Schlinkert.
  1094. * Released under the MIT License.
  1095. */
  1096. function isObject(o) {
  1097. return Object.prototype.toString.call(o) === '[object Object]';
  1098. }
  1099. function isPlainObject$1(o) {
  1100. var ctor,prot;
  1101. if (isObject(o) === false) return false;
  1102. // If has modified constructor
  1103. ctor = o.constructor;
  1104. if (ctor === undefined) return true;
  1105. // If has modified prototype
  1106. prot = ctor.prototype;
  1107. if (isObject(prot) === false) return false;
  1108. // If constructor does not have an Object-specific method
  1109. if (prot.hasOwnProperty('isPrototypeOf') === false) {
  1110. return false;
  1111. }
  1112. // Most likely a plain Object
  1113. return true;
  1114. }
  1115. const isBuffer = typeof Buffer === "undefined" ? () => false : obj => Buffer.isBuffer(obj);
  1116. const serializeTypes = ["boolean", "string", "number"];
  1117. function jsonRequest() {
  1118. return {
  1119. processOptions: options => {
  1120. const body = options.body;
  1121. if (!body) {
  1122. return options;
  1123. }
  1124. const isStream = typeof body.pipe === "function";
  1125. const shouldSerialize = !isStream && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject$1(body));
  1126. if (!shouldSerialize) {
  1127. return options;
  1128. }
  1129. return Object.assign({}, options, {
  1130. body: JSON.stringify(options.body),
  1131. headers: Object.assign({}, options.headers, {
  1132. "Content-Type": "application/json"
  1133. })
  1134. });
  1135. }
  1136. };
  1137. }
  1138. function jsonResponse(opts) {
  1139. return {
  1140. onResponse: response => {
  1141. const contentType = response.headers["content-type"] || "";
  1142. const shouldDecode = opts && opts.force || contentType.indexOf("application/json") !== -1;
  1143. if (!response.body || !contentType || !shouldDecode) {
  1144. return response;
  1145. }
  1146. return Object.assign({}, response, {
  1147. body: tryParse(response.body)
  1148. });
  1149. },
  1150. processOptions: options => Object.assign({}, options, {
  1151. headers: Object.assign({
  1152. Accept: "application/json"
  1153. }, options.headers)
  1154. })
  1155. };
  1156. function tryParse(body) {
  1157. try {
  1158. return JSON.parse(body);
  1159. } catch (err) {
  1160. err.message = "Failed to parsed response body as JSON: ".concat(err.message);
  1161. throw err;
  1162. }
  1163. }
  1164. }
  1165. let actualGlobal;
  1166. if (typeof globalThis !== "undefined") {
  1167. actualGlobal = globalThis;
  1168. } else if (typeof window !== "undefined") {
  1169. actualGlobal = window;
  1170. } else if (typeof global !== "undefined") {
  1171. actualGlobal = global;
  1172. } else if (typeof self !== "undefined") {
  1173. actualGlobal = self;
  1174. } else {
  1175. actualGlobal = {};
  1176. }
  1177. var global$1 = actualGlobal;
  1178. function observable$1() {
  1179. let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1180. const Observable = opts.implementation || global$1.Observable;
  1181. if (!Observable) {
  1182. throw new Error("`Observable` is not available in global scope, and no implementation was passed");
  1183. }
  1184. return {
  1185. onReturn: (channels, context) => new Observable(observer => {
  1186. channels.error.subscribe(err => observer.error(err));
  1187. channels.progress.subscribe(event => observer.next(Object.assign({
  1188. type: "progress"
  1189. }, event)));
  1190. channels.response.subscribe(response => {
  1191. observer.next(Object.assign({
  1192. type: "response"
  1193. }, response));
  1194. observer.complete();
  1195. });
  1196. channels.request.publish(context);
  1197. return () => channels.abort.publish();
  1198. })
  1199. };
  1200. }
  1201. function progress() {
  1202. return {
  1203. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1204. onRequest: evt => {
  1205. if (evt.adapter !== "xhr") {
  1206. return;
  1207. }
  1208. const xhr = evt.request;
  1209. const context = evt.context;
  1210. if ("upload" in xhr && "onprogress" in xhr.upload) {
  1211. xhr.upload.onprogress = handleProgress("upload");
  1212. }
  1213. if ("onprogress" in xhr) {
  1214. xhr.onprogress = handleProgress("download");
  1215. }
  1216. function handleProgress(stage) {
  1217. return event => {
  1218. const percent = event.lengthComputable ? event.loaded / event.total * 100 : -1;
  1219. context.channels.progress.publish({
  1220. stage,
  1221. percent,
  1222. total: event.total,
  1223. loaded: event.loaded,
  1224. lengthComputable: event.lengthComputable
  1225. });
  1226. };
  1227. }
  1228. }
  1229. };
  1230. }
  1231. class Cancel {
  1232. constructor(message) {
  1233. this.__CANCEL__ = true;
  1234. this.message = message;
  1235. }
  1236. toString() {
  1237. return "Cancel".concat(this.message ? ": ".concat(this.message) : "");
  1238. }
  1239. }
  1240. const _CancelToken = class {
  1241. constructor(executor) {
  1242. if (typeof executor !== "function") {
  1243. throw new TypeError("executor must be a function.");
  1244. }
  1245. let resolvePromise = null;
  1246. this.promise = new Promise(resolve => {
  1247. resolvePromise = resolve;
  1248. });
  1249. executor(message => {
  1250. if (this.reason) {
  1251. return;
  1252. }
  1253. this.reason = new Cancel(message);
  1254. resolvePromise(this.reason);
  1255. });
  1256. }
  1257. };
  1258. let CancelToken = _CancelToken;
  1259. CancelToken.source = () => {
  1260. let cancel;
  1261. const token = new _CancelToken(can => {
  1262. cancel = can;
  1263. });
  1264. return {
  1265. token,
  1266. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- we know from the implementation that it's assigned during `constructor`
  1267. cancel
  1268. };
  1269. };
  1270. /******************************************************************************
  1271. Copyright (c) Microsoft Corporation.
  1272. Permission to use, copy, modify, and/or distribute this software for any
  1273. purpose with or without fee is hereby granted.
  1274. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  1275. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  1276. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  1277. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  1278. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  1279. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  1280. PERFORMANCE OF THIS SOFTWARE.
  1281. ***************************************************************************** */
  1282. /* global Reflect, Promise */
  1283. var extendStatics = function(d, b) {
  1284. extendStatics = Object.setPrototypeOf ||
  1285. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1286. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  1287. return extendStatics(d, b);
  1288. };
  1289. function __extends(d, b) {
  1290. if (typeof b !== "function" && b !== null)
  1291. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  1292. extendStatics(d, b);
  1293. function __() { this.constructor = d; }
  1294. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1295. }
  1296. function __values(o) {
  1297. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  1298. if (m) return m.call(o);
  1299. if (o && typeof o.length === "number") return {
  1300. next: function () {
  1301. if (o && i >= o.length) o = void 0;
  1302. return { value: o && o[i++], done: !o };
  1303. }
  1304. };
  1305. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  1306. }
  1307. function __read(o, n) {
  1308. var m = typeof Symbol === "function" && o[Symbol.iterator];
  1309. if (!m) return o;
  1310. var i = m.call(o), r, ar = [], e;
  1311. try {
  1312. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  1313. }
  1314. catch (error) { e = { error: error }; }
  1315. finally {
  1316. try {
  1317. if (r && !r.done && (m = i["return"])) m.call(i);
  1318. }
  1319. finally { if (e) throw e.error; }
  1320. }
  1321. return ar;
  1322. }
  1323. function __spreadArray(to, from, pack) {
  1324. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  1325. if (ar || !(i in from)) {
  1326. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  1327. ar[i] = from[i];
  1328. }
  1329. }
  1330. return to.concat(ar || Array.prototype.slice.call(from));
  1331. }
  1332. function isFunction(value) {
  1333. return typeof value === 'function';
  1334. }
  1335. function createErrorClass(createImpl) {
  1336. var _super = function (instance) {
  1337. Error.call(instance);
  1338. instance.stack = new Error().stack;
  1339. };
  1340. var ctorFunc = createImpl(_super);
  1341. ctorFunc.prototype = Object.create(Error.prototype);
  1342. ctorFunc.prototype.constructor = ctorFunc;
  1343. return ctorFunc;
  1344. }
  1345. var UnsubscriptionError = createErrorClass(function (_super) {
  1346. return function UnsubscriptionErrorImpl(errors) {
  1347. _super(this);
  1348. this.message = errors
  1349. ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
  1350. : '';
  1351. this.name = 'UnsubscriptionError';
  1352. this.errors = errors;
  1353. };
  1354. });
  1355. function arrRemove(arr, item) {
  1356. if (arr) {
  1357. var index = arr.indexOf(item);
  1358. 0 <= index && arr.splice(index, 1);
  1359. }
  1360. }
  1361. var Subscription = (function () {
  1362. function Subscription(initialTeardown) {
  1363. this.initialTeardown = initialTeardown;
  1364. this.closed = false;
  1365. this._parentage = null;
  1366. this._finalizers = null;
  1367. }
  1368. Subscription.prototype.unsubscribe = function () {
  1369. var e_1, _a, e_2, _b;
  1370. var errors;
  1371. if (!this.closed) {
  1372. this.closed = true;
  1373. var _parentage = this._parentage;
  1374. if (_parentage) {
  1375. this._parentage = null;
  1376. if (Array.isArray(_parentage)) {
  1377. try {
  1378. for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
  1379. var parent_1 = _parentage_1_1.value;
  1380. parent_1.remove(this);
  1381. }
  1382. }
  1383. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1384. finally {
  1385. try {
  1386. if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
  1387. }
  1388. finally { if (e_1) throw e_1.error; }
  1389. }
  1390. }
  1391. else {
  1392. _parentage.remove(this);
  1393. }
  1394. }
  1395. var initialFinalizer = this.initialTeardown;
  1396. if (isFunction(initialFinalizer)) {
  1397. try {
  1398. initialFinalizer();
  1399. }
  1400. catch (e) {
  1401. errors = e instanceof UnsubscriptionError ? e.errors : [e];
  1402. }
  1403. }
  1404. var _finalizers = this._finalizers;
  1405. if (_finalizers) {
  1406. this._finalizers = null;
  1407. try {
  1408. for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
  1409. var finalizer = _finalizers_1_1.value;
  1410. try {
  1411. execFinalizer(finalizer);
  1412. }
  1413. catch (err) {
  1414. errors = errors !== null && errors !== void 0 ? errors : [];
  1415. if (err instanceof UnsubscriptionError) {
  1416. errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
  1417. }
  1418. else {
  1419. errors.push(err);
  1420. }
  1421. }
  1422. }
  1423. }
  1424. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  1425. finally {
  1426. try {
  1427. if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
  1428. }
  1429. finally { if (e_2) throw e_2.error; }
  1430. }
  1431. }
  1432. if (errors) {
  1433. throw new UnsubscriptionError(errors);
  1434. }
  1435. }
  1436. };
  1437. Subscription.prototype.add = function (teardown) {
  1438. var _a;
  1439. if (teardown && teardown !== this) {
  1440. if (this.closed) {
  1441. execFinalizer(teardown);
  1442. }
  1443. else {
  1444. if (teardown instanceof Subscription) {
  1445. if (teardown.closed || teardown._hasParent(this)) {
  1446. return;
  1447. }
  1448. teardown._addParent(this);
  1449. }
  1450. (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
  1451. }
  1452. }
  1453. };
  1454. Subscription.prototype._hasParent = function (parent) {
  1455. var _parentage = this._parentage;
  1456. return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
  1457. };
  1458. Subscription.prototype._addParent = function (parent) {
  1459. var _parentage = this._parentage;
  1460. this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
  1461. };
  1462. Subscription.prototype._removeParent = function (parent) {
  1463. var _parentage = this._parentage;
  1464. if (_parentage === parent) {
  1465. this._parentage = null;
  1466. }
  1467. else if (Array.isArray(_parentage)) {
  1468. arrRemove(_parentage, parent);
  1469. }
  1470. };
  1471. Subscription.prototype.remove = function (teardown) {
  1472. var _finalizers = this._finalizers;
  1473. _finalizers && arrRemove(_finalizers, teardown);
  1474. if (teardown instanceof Subscription) {
  1475. teardown._removeParent(this);
  1476. }
  1477. };
  1478. Subscription.EMPTY = (function () {
  1479. var empty = new Subscription();
  1480. empty.closed = true;
  1481. return empty;
  1482. })();
  1483. return Subscription;
  1484. }());
  1485. Subscription.EMPTY;
  1486. function isSubscription(value) {
  1487. return (value instanceof Subscription ||
  1488. (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
  1489. }
  1490. function execFinalizer(finalizer) {
  1491. if (isFunction(finalizer)) {
  1492. finalizer();
  1493. }
  1494. else {
  1495. finalizer.unsubscribe();
  1496. }
  1497. }
  1498. var config = {
  1499. onUnhandledError: null,
  1500. onStoppedNotification: null,
  1501. Promise: undefined,
  1502. useDeprecatedSynchronousErrorHandling: false,
  1503. useDeprecatedNextContext: false,
  1504. };
  1505. var timeoutProvider = {
  1506. setTimeout: function (handler, timeout) {
  1507. var args = [];
  1508. for (var _i = 2; _i < arguments.length; _i++) {
  1509. args[_i - 2] = arguments[_i];
  1510. }
  1511. var delegate = timeoutProvider.delegate;
  1512. if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
  1513. return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
  1514. }
  1515. return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
  1516. },
  1517. clearTimeout: function (handle) {
  1518. var delegate = timeoutProvider.delegate;
  1519. return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
  1520. },
  1521. delegate: undefined,
  1522. };
  1523. function reportUnhandledError(err) {
  1524. timeoutProvider.setTimeout(function () {
  1525. {
  1526. throw err;
  1527. }
  1528. });
  1529. }
  1530. function noop() { }
  1531. function errorContext(cb) {
  1532. {
  1533. cb();
  1534. }
  1535. }
  1536. var Subscriber = (function (_super) {
  1537. __extends(Subscriber, _super);
  1538. function Subscriber(destination) {
  1539. var _this = _super.call(this) || this;
  1540. _this.isStopped = false;
  1541. if (destination) {
  1542. _this.destination = destination;
  1543. if (isSubscription(destination)) {
  1544. destination.add(_this);
  1545. }
  1546. }
  1547. else {
  1548. _this.destination = EMPTY_OBSERVER;
  1549. }
  1550. return _this;
  1551. }
  1552. Subscriber.create = function (next, error, complete) {
  1553. return new SafeSubscriber(next, error, complete);
  1554. };
  1555. Subscriber.prototype.next = function (value) {
  1556. if (this.isStopped) ;
  1557. else {
  1558. this._next(value);
  1559. }
  1560. };
  1561. Subscriber.prototype.error = function (err) {
  1562. if (this.isStopped) ;
  1563. else {
  1564. this.isStopped = true;
  1565. this._error(err);
  1566. }
  1567. };
  1568. Subscriber.prototype.complete = function () {
  1569. if (this.isStopped) ;
  1570. else {
  1571. this.isStopped = true;
  1572. this._complete();
  1573. }
  1574. };
  1575. Subscriber.prototype.unsubscribe = function () {
  1576. if (!this.closed) {
  1577. this.isStopped = true;
  1578. _super.prototype.unsubscribe.call(this);
  1579. this.destination = null;
  1580. }
  1581. };
  1582. Subscriber.prototype._next = function (value) {
  1583. this.destination.next(value);
  1584. };
  1585. Subscriber.prototype._error = function (err) {
  1586. try {
  1587. this.destination.error(err);
  1588. }
  1589. finally {
  1590. this.unsubscribe();
  1591. }
  1592. };
  1593. Subscriber.prototype._complete = function () {
  1594. try {
  1595. this.destination.complete();
  1596. }
  1597. finally {
  1598. this.unsubscribe();
  1599. }
  1600. };
  1601. return Subscriber;
  1602. }(Subscription));
  1603. var _bind = Function.prototype.bind;
  1604. function bind(fn, thisArg) {
  1605. return _bind.call(fn, thisArg);
  1606. }
  1607. var ConsumerObserver = (function () {
  1608. function ConsumerObserver(partialObserver) {
  1609. this.partialObserver = partialObserver;
  1610. }
  1611. ConsumerObserver.prototype.next = function (value) {
  1612. var partialObserver = this.partialObserver;
  1613. if (partialObserver.next) {
  1614. try {
  1615. partialObserver.next(value);
  1616. }
  1617. catch (error) {
  1618. handleUnhandledError(error);
  1619. }
  1620. }
  1621. };
  1622. ConsumerObserver.prototype.error = function (err) {
  1623. var partialObserver = this.partialObserver;
  1624. if (partialObserver.error) {
  1625. try {
  1626. partialObserver.error(err);
  1627. }
  1628. catch (error) {
  1629. handleUnhandledError(error);
  1630. }
  1631. }
  1632. else {
  1633. handleUnhandledError(err);
  1634. }
  1635. };
  1636. ConsumerObserver.prototype.complete = function () {
  1637. var partialObserver = this.partialObserver;
  1638. if (partialObserver.complete) {
  1639. try {
  1640. partialObserver.complete();
  1641. }
  1642. catch (error) {
  1643. handleUnhandledError(error);
  1644. }
  1645. }
  1646. };
  1647. return ConsumerObserver;
  1648. }());
  1649. var SafeSubscriber = (function (_super) {
  1650. __extends(SafeSubscriber, _super);
  1651. function SafeSubscriber(observerOrNext, error, complete) {
  1652. var _this = _super.call(this) || this;
  1653. var partialObserver;
  1654. if (isFunction(observerOrNext) || !observerOrNext) {
  1655. partialObserver = {
  1656. next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),
  1657. error: error !== null && error !== void 0 ? error : undefined,
  1658. complete: complete !== null && complete !== void 0 ? complete : undefined,
  1659. };
  1660. }
  1661. else {
  1662. var context_1;
  1663. if (_this && config.useDeprecatedNextContext) {
  1664. context_1 = Object.create(observerOrNext);
  1665. context_1.unsubscribe = function () { return _this.unsubscribe(); };
  1666. partialObserver = {
  1667. next: observerOrNext.next && bind(observerOrNext.next, context_1),
  1668. error: observerOrNext.error && bind(observerOrNext.error, context_1),
  1669. complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
  1670. };
  1671. }
  1672. else {
  1673. partialObserver = observerOrNext;
  1674. }
  1675. }
  1676. _this.destination = new ConsumerObserver(partialObserver);
  1677. return _this;
  1678. }
  1679. return SafeSubscriber;
  1680. }(Subscriber));
  1681. function handleUnhandledError(error) {
  1682. {
  1683. reportUnhandledError(error);
  1684. }
  1685. }
  1686. function defaultErrorHandler(err) {
  1687. throw err;
  1688. }
  1689. var EMPTY_OBSERVER = {
  1690. closed: true,
  1691. next: noop,
  1692. error: defaultErrorHandler,
  1693. complete: noop,
  1694. };
  1695. var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
  1696. function identity(x) {
  1697. return x;
  1698. }
  1699. function pipeFromArray(fns) {
  1700. if (fns.length === 0) {
  1701. return identity;
  1702. }
  1703. if (fns.length === 1) {
  1704. return fns[0];
  1705. }
  1706. return function piped(input) {
  1707. return fns.reduce(function (prev, fn) { return fn(prev); }, input);
  1708. };
  1709. }
  1710. var Observable = (function () {
  1711. function Observable(subscribe) {
  1712. if (subscribe) {
  1713. this._subscribe = subscribe;
  1714. }
  1715. }
  1716. Observable.prototype.lift = function (operator) {
  1717. var observable = new Observable();
  1718. observable.source = this;
  1719. observable.operator = operator;
  1720. return observable;
  1721. };
  1722. Observable.prototype.subscribe = function (observerOrNext, error, complete) {
  1723. var _this = this;
  1724. var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
  1725. errorContext(function () {
  1726. var _a = _this, operator = _a.operator, source = _a.source;
  1727. subscriber.add(operator
  1728. ?
  1729. operator.call(subscriber, source)
  1730. : source
  1731. ?
  1732. _this._subscribe(subscriber)
  1733. :
  1734. _this._trySubscribe(subscriber));
  1735. });
  1736. return subscriber;
  1737. };
  1738. Observable.prototype._trySubscribe = function (sink) {
  1739. try {
  1740. return this._subscribe(sink);
  1741. }
  1742. catch (err) {
  1743. sink.error(err);
  1744. }
  1745. };
  1746. Observable.prototype.forEach = function (next, promiseCtor) {
  1747. var _this = this;
  1748. promiseCtor = getPromiseCtor(promiseCtor);
  1749. return new promiseCtor(function (resolve, reject) {
  1750. var subscriber = new SafeSubscriber({
  1751. next: function (value) {
  1752. try {
  1753. next(value);
  1754. }
  1755. catch (err) {
  1756. reject(err);
  1757. subscriber.unsubscribe();
  1758. }
  1759. },
  1760. error: reject,
  1761. complete: resolve,
  1762. });
  1763. _this.subscribe(subscriber);
  1764. });
  1765. };
  1766. Observable.prototype._subscribe = function (subscriber) {
  1767. var _a;
  1768. return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
  1769. };
  1770. Observable.prototype[observable] = function () {
  1771. return this;
  1772. };
  1773. Observable.prototype.pipe = function () {
  1774. var operations = [];
  1775. for (var _i = 0; _i < arguments.length; _i++) {
  1776. operations[_i] = arguments[_i];
  1777. }
  1778. return pipeFromArray(operations)(this);
  1779. };
  1780. Observable.prototype.toPromise = function (promiseCtor) {
  1781. var _this = this;
  1782. promiseCtor = getPromiseCtor(promiseCtor);
  1783. return new promiseCtor(function (resolve, reject) {
  1784. var value;
  1785. _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
  1786. });
  1787. };
  1788. Observable.create = function (subscribe) {
  1789. return new Observable(subscribe);
  1790. };
  1791. return Observable;
  1792. }());
  1793. function getPromiseCtor(promiseCtor) {
  1794. var _a;
  1795. return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
  1796. }
  1797. function isObserver(value) {
  1798. return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
  1799. }
  1800. function isSubscriber(value) {
  1801. return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
  1802. }
  1803. function hasLift(source) {
  1804. return isFunction(source === null || source === void 0 ? void 0 : source.lift);
  1805. }
  1806. function operate(init) {
  1807. return function (source) {
  1808. if (hasLift(source)) {
  1809. return source.lift(function (liftedSource) {
  1810. try {
  1811. return init(liftedSource, this);
  1812. }
  1813. catch (err) {
  1814. this.error(err);
  1815. }
  1816. });
  1817. }
  1818. throw new TypeError('Unable to lift unknown Observable type');
  1819. };
  1820. }
  1821. function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
  1822. return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
  1823. }
  1824. var OperatorSubscriber = (function (_super) {
  1825. __extends(OperatorSubscriber, _super);
  1826. function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
  1827. var _this = _super.call(this, destination) || this;
  1828. _this.onFinalize = onFinalize;
  1829. _this.shouldUnsubscribe = shouldUnsubscribe;
  1830. _this._next = onNext
  1831. ? function (value) {
  1832. try {
  1833. onNext(value);
  1834. }
  1835. catch (err) {
  1836. destination.error(err);
  1837. }
  1838. }
  1839. : _super.prototype._next;
  1840. _this._error = onError
  1841. ? function (err) {
  1842. try {
  1843. onError(err);
  1844. }
  1845. catch (err) {
  1846. destination.error(err);
  1847. }
  1848. finally {
  1849. this.unsubscribe();
  1850. }
  1851. }
  1852. : _super.prototype._error;
  1853. _this._complete = onComplete
  1854. ? function () {
  1855. try {
  1856. onComplete();
  1857. }
  1858. catch (err) {
  1859. destination.error(err);
  1860. }
  1861. finally {
  1862. this.unsubscribe();
  1863. }
  1864. }
  1865. : _super.prototype._complete;
  1866. return _this;
  1867. }
  1868. OperatorSubscriber.prototype.unsubscribe = function () {
  1869. var _a;
  1870. if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
  1871. var closed_1 = this.closed;
  1872. _super.prototype.unsubscribe.call(this);
  1873. !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
  1874. }
  1875. };
  1876. return OperatorSubscriber;
  1877. }(Subscriber));
  1878. var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
  1879. _super(this);
  1880. this.name = 'EmptyError';
  1881. this.message = 'no elements in sequence';
  1882. }; });
  1883. function lastValueFrom(source, config) {
  1884. var hasConfig = typeof config === 'object';
  1885. return new Promise(function (resolve, reject) {
  1886. var _hasValue = false;
  1887. var _value;
  1888. source.subscribe({
  1889. next: function (value) {
  1890. _value = value;
  1891. _hasValue = true;
  1892. },
  1893. error: reject,
  1894. complete: function () {
  1895. if (_hasValue) {
  1896. resolve(_value);
  1897. }
  1898. else if (hasConfig) {
  1899. resolve(config.defaultValue);
  1900. }
  1901. else {
  1902. reject(new EmptyError());
  1903. }
  1904. },
  1905. });
  1906. });
  1907. }
  1908. function map(project, thisArg) {
  1909. return operate(function (source, subscriber) {
  1910. var index = 0;
  1911. source.subscribe(createOperatorSubscriber(subscriber, function (value) {
  1912. subscriber.next(project.call(thisArg, value, index++));
  1913. }));
  1914. });
  1915. }
  1916. function filter(predicate, thisArg) {
  1917. return operate(function (source, subscriber) {
  1918. var index = 0;
  1919. source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
  1920. });
  1921. }
  1922. var envMiddleware = [];
  1923. const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
  1924. class ClientError extends Error {
  1925. constructor(res) {
  1926. const props = extractErrorProps(res);
  1927. super(props.message);
  1928. this.statusCode = 400;
  1929. Object.assign(this, props);
  1930. }
  1931. }
  1932. class ServerError extends Error {
  1933. constructor(res) {
  1934. const props = extractErrorProps(res);
  1935. super(props.message);
  1936. this.statusCode = 500;
  1937. Object.assign(this, props);
  1938. }
  1939. }
  1940. function extractErrorProps(res) {
  1941. const body = res.body;
  1942. const props = {
  1943. response: res,
  1944. statusCode: res.statusCode,
  1945. responseBody: stringifyBody(body, res),
  1946. message: "",
  1947. details: void 0
  1948. };
  1949. if (body.error && body.message) {
  1950. props.message = "".concat(body.error, " - ").concat(body.message);
  1951. return props;
  1952. }
  1953. if (isMutationError(body)) {
  1954. const allItems = body.error.items || [];
  1955. const items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map(item => {
  1956. var _a;
  1957. return (_a = item.error) == null ? void 0 : _a.description;
  1958. }).filter(Boolean);
  1959. let itemsStr = items.length ? ":\n- ".concat(items.join("\n- ")) : "";
  1960. if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {
  1961. itemsStr += "\n...and ".concat(allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE, " more");
  1962. }
  1963. props.message = "".concat(body.error.description).concat(itemsStr);
  1964. props.details = body.error;
  1965. return props;
  1966. }
  1967. if (body.error && body.error.description) {
  1968. props.message = body.error.description;
  1969. props.details = body.error;
  1970. return props;
  1971. }
  1972. props.message = body.error || body.message || httpErrorMessage(res);
  1973. return props;
  1974. }
  1975. function isMutationError(body) {
  1976. return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description === "string";
  1977. }
  1978. function isPlainObject(obj) {
  1979. return typeof obj === "object" && obj !== null && !Array.isArray(obj);
  1980. }
  1981. function httpErrorMessage(res) {
  1982. const statusMessage = res.statusMessage ? " ".concat(res.statusMessage) : "";
  1983. return "".concat(res.method, "-request to ").concat(res.url, " resulted in HTTP ").concat(res.statusCode).concat(statusMessage);
  1984. }
  1985. function stringifyBody(body, res) {
  1986. const contentType = (res.headers["content-type"] || "").toLowerCase();
  1987. const isJson = contentType.indexOf("application/json") !== -1;
  1988. return isJson ? JSON.stringify(body, null, 2) : body;
  1989. }
  1990. const httpError = {
  1991. onResponse: res => {
  1992. if (res.statusCode >= 500) {
  1993. throw new ServerError(res);
  1994. } else if (res.statusCode >= 400) {
  1995. throw new ClientError(res);
  1996. }
  1997. return res;
  1998. }
  1999. };
  2000. const printWarnings = {
  2001. onResponse: res => {
  2002. const warn = res.headers["x-sanity-warning"];
  2003. const warnings = Array.isArray(warn) ? warn : [warn];
  2004. warnings.filter(Boolean).forEach(msg => console.warn(msg));
  2005. return res;
  2006. }
  2007. };
  2008. function defineHttpRequest(envMiddleware) {
  2009. const request = getIt([...envMiddleware, printWarnings, jsonRequest(), jsonResponse(), progress(), httpError, observable$1({
  2010. implementation: Observable
  2011. })]);
  2012. function httpRequest(options) {
  2013. let requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : request;
  2014. return requester({
  2015. maxRedirects: 0,
  2016. ...options
  2017. });
  2018. }
  2019. httpRequest.defaultRequester = request;
  2020. return httpRequest;
  2021. }
  2022. const projectHeader = "X-Sanity-Project-ID";
  2023. function requestOptions(config) {
  2024. let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2025. const headers = {};
  2026. const token = overrides.token || config.token;
  2027. if (token) {
  2028. headers.Authorization = "Bearer ".concat(token);
  2029. }
  2030. if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
  2031. headers[projectHeader] = config.projectId;
  2032. }
  2033. const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
  2034. const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
  2035. return Object.assign({}, overrides, {
  2036. headers: Object.assign({}, headers, overrides.headers || {}),
  2037. timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
  2038. proxy: overrides.proxy || config.proxy,
  2039. json: true,
  2040. withCredentials
  2041. });
  2042. }
  2043. function getSelection(sel) {
  2044. if (typeof sel === "string" || Array.isArray(sel)) {
  2045. return {
  2046. id: sel
  2047. };
  2048. }
  2049. if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
  2050. return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
  2051. query: sel.query,
  2052. params: sel.params
  2053. } : {
  2054. query: sel.query
  2055. };
  2056. }
  2057. const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
  2058. throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
  2059. }
  2060. const VALID_ASSET_TYPES = ["image", "file"];
  2061. const VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
  2062. const dataset = name => {
  2063. if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
  2064. throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
  2065. }
  2066. };
  2067. const projectId = id => {
  2068. if (!/^[-a-z0-9]+$/i.test(id)) {
  2069. throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
  2070. }
  2071. };
  2072. const validateAssetType = type => {
  2073. if (VALID_ASSET_TYPES.indexOf(type) === -1) {
  2074. throw new Error("Invalid asset type: ".concat(type, ". Must be one of ").concat(VALID_ASSET_TYPES.join(", ")));
  2075. }
  2076. };
  2077. const validateObject = (op, val) => {
  2078. if (val === null || typeof val !== "object" || Array.isArray(val)) {
  2079. throw new Error("".concat(op, "() takes an object of properties"));
  2080. }
  2081. };
  2082. const validateDocumentId = (op, id) => {
  2083. if (typeof id !== "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes("..")) {
  2084. throw new Error("".concat(op, "(): \"").concat(id, "\" is not a valid document ID"));
  2085. }
  2086. };
  2087. const requireDocumentId = (op, doc) => {
  2088. if (!doc._id) {
  2089. throw new Error("".concat(op, "() requires that the document contains an ID (\"_id\" property)"));
  2090. }
  2091. validateDocumentId(op, doc._id);
  2092. };
  2093. const validateInsert = (at, selector, items) => {
  2094. const signature = "insert(at, selector, items)";
  2095. if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
  2096. const valid = VALID_INSERT_LOCATIONS.map(loc => "\"".concat(loc, "\"")).join(", ");
  2097. throw new Error("".concat(signature, " takes an \"at\"-argument which is one of: ").concat(valid));
  2098. }
  2099. if (typeof selector !== "string") {
  2100. throw new Error("".concat(signature, " takes a \"selector\"-argument which must be a string"));
  2101. }
  2102. if (!Array.isArray(items)) {
  2103. throw new Error("".concat(signature, " takes an \"items\"-argument which must be an array"));
  2104. }
  2105. };
  2106. const hasDataset = config => {
  2107. if (!config.dataset) {
  2108. throw new Error("`dataset` must be provided to perform queries");
  2109. }
  2110. return config.dataset || "";
  2111. };
  2112. const requestTag = tag => {
  2113. if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
  2114. throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
  2115. }
  2116. return tag;
  2117. };
  2118. const encodeQueryString = _ref => {
  2119. let {
  2120. query,
  2121. params = {},
  2122. options = {}
  2123. } = _ref;
  2124. const searchParams = new URLSearchParams();
  2125. const {
  2126. tag,
  2127. ...opts
  2128. } = options;
  2129. if (tag) searchParams.set("tag", tag);
  2130. searchParams.set("query", query);
  2131. for (const [key, value] of Object.entries(params)) {
  2132. searchParams.set("$".concat(key), JSON.stringify(value));
  2133. }
  2134. for (const [key, value] of Object.entries(opts)) {
  2135. if (value) searchParams.set(key, "".concat(value));
  2136. }
  2137. return "?".concat(searchParams);
  2138. };
  2139. var __accessCheck$6 = (obj, member, msg) => {
  2140. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  2141. };
  2142. var __privateGet$6 = (obj, member, getter) => {
  2143. __accessCheck$6(obj, member, "read from private field");
  2144. return getter ? getter.call(obj) : member.get(obj);
  2145. };
  2146. var __privateAdd$6 = (obj, member, value) => {
  2147. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  2148. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  2149. };
  2150. var __privateSet$6 = (obj, member, value, setter) => {
  2151. __accessCheck$6(obj, member, "write to private field");
  2152. setter ? setter.call(obj, value) : member.set(obj, value);
  2153. return value;
  2154. };
  2155. var _client$5, _client2$5;
  2156. class BasePatch {
  2157. constructor(selection) {
  2158. let operations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2159. this.selection = selection;
  2160. this.operations = operations;
  2161. }
  2162. /**
  2163. * Sets the given attributes to the document. Does NOT merge objects.
  2164. * The operation is added to the current patch, ready to be commited by `commit()`
  2165. *
  2166. * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
  2167. */
  2168. set(attrs) {
  2169. return this._assign("set", attrs);
  2170. }
  2171. /**
  2172. * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
  2173. * The operation is added to the current patch, ready to be commited by `commit()`
  2174. *
  2175. * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
  2176. */
  2177. setIfMissing(attrs) {
  2178. return this._assign("setIfMissing", attrs);
  2179. }
  2180. /**
  2181. * Performs a "diff-match-patch" operation on the string attributes provided.
  2182. * The operation is added to the current patch, ready to be commited by `commit()`
  2183. *
  2184. * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
  2185. */
  2186. diffMatchPatch(attrs) {
  2187. validateObject("diffMatchPatch", attrs);
  2188. return this._assign("diffMatchPatch", attrs);
  2189. }
  2190. /**
  2191. * Unsets the attribute paths provided.
  2192. * The operation is added to the current patch, ready to be commited by `commit()`
  2193. *
  2194. * @param attrs - Attribute paths to unset.
  2195. */
  2196. unset(attrs) {
  2197. if (!Array.isArray(attrs)) {
  2198. throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
  2199. }
  2200. this.operations = Object.assign({}, this.operations, {
  2201. unset: attrs
  2202. });
  2203. return this;
  2204. }
  2205. /**
  2206. * 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.
  2207. *
  2208. * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
  2209. */
  2210. inc(attrs) {
  2211. return this._assign("inc", attrs);
  2212. }
  2213. /**
  2214. * 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.
  2215. *
  2216. * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
  2217. */
  2218. dec(attrs) {
  2219. return this._assign("dec", attrs);
  2220. }
  2221. /**
  2222. * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
  2223. *
  2224. * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
  2225. * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
  2226. * @param items - Array of items to insert/replace
  2227. */
  2228. insert(at, selector, items) {
  2229. validateInsert(at, selector, items);
  2230. return this._assign("insert", {
  2231. [at]: selector,
  2232. items
  2233. });
  2234. }
  2235. /**
  2236. * Append the given items to the array at the given JSONPath
  2237. *
  2238. * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
  2239. * @param items - Array of items to append to the array
  2240. */
  2241. append(selector, items) {
  2242. return this.insert("after", "".concat(selector, "[-1]"), items);
  2243. }
  2244. /**
  2245. * Prepend the given items to the array at the given JSONPath
  2246. *
  2247. * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
  2248. * @param items - Array of items to prepend to the array
  2249. */
  2250. prepend(selector, items) {
  2251. return this.insert("before", "".concat(selector, "[0]"), items);
  2252. }
  2253. /**
  2254. * Change the contents of an array by removing existing elements and/or adding new elements.
  2255. *
  2256. * @param selector - Attribute or JSONPath expression for array
  2257. * @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
  2258. * @param deleteCount - An integer indicating the number of old array elements to remove.
  2259. * @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.
  2260. */
  2261. splice(selector, start, deleteCount, items) {
  2262. const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
  2263. const startIndex = start < 0 ? start - 1 : start;
  2264. const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
  2265. const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
  2266. const rangeSelector = "".concat(selector, "[").concat(startIndex, ":").concat(delRange, "]");
  2267. return this.insert("replace", rangeSelector, items || []);
  2268. }
  2269. /**
  2270. * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
  2271. *
  2272. * @param rev - Revision to lock the patch to
  2273. */
  2274. ifRevisionId(rev) {
  2275. this.operations.ifRevisionID = rev;
  2276. return this;
  2277. }
  2278. /**
  2279. * Return a plain JSON representation of the patch
  2280. */
  2281. serialize() {
  2282. return {
  2283. ...getSelection(this.selection),
  2284. ...this.operations
  2285. };
  2286. }
  2287. /**
  2288. * Return a plain JSON representation of the patch
  2289. */
  2290. toJSON() {
  2291. return this.serialize();
  2292. }
  2293. /**
  2294. * Clears the patch of all operations
  2295. */
  2296. reset() {
  2297. this.operations = {};
  2298. return this;
  2299. }
  2300. _assign(op, props) {
  2301. let merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  2302. validateObject(op, props);
  2303. this.operations = Object.assign({}, this.operations, {
  2304. [op]: Object.assign({}, merge && this.operations[op] || {}, props)
  2305. });
  2306. return this;
  2307. }
  2308. _set(op, props) {
  2309. return this._assign(op, props, false);
  2310. }
  2311. }
  2312. const _ObservablePatch = class extends BasePatch {
  2313. constructor(selection, operations, client) {
  2314. super(selection, operations);
  2315. __privateAdd$6(this, _client$5, void 0);
  2316. __privateSet$6(this, _client$5, client);
  2317. }
  2318. /**
  2319. * Clones the patch
  2320. */
  2321. clone() {
  2322. return new _ObservablePatch(this.selection, {
  2323. ...this.operations
  2324. }, __privateGet$6(this, _client$5));
  2325. }
  2326. commit(options) {
  2327. if (!__privateGet$6(this, _client$5)) {
  2328. throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
  2329. }
  2330. const returnFirst = typeof this.selection === "string";
  2331. const opts = Object.assign({
  2332. returnFirst,
  2333. returnDocuments: true
  2334. }, options);
  2335. return __privateGet$6(this, _client$5).mutate({
  2336. patch: this.serialize()
  2337. }, opts);
  2338. }
  2339. };
  2340. let ObservablePatch = _ObservablePatch;
  2341. _client$5 = new WeakMap();
  2342. const _Patch = class extends BasePatch {
  2343. constructor(selection, operations, client) {
  2344. super(selection, operations);
  2345. __privateAdd$6(this, _client2$5, void 0);
  2346. __privateSet$6(this, _client2$5, client);
  2347. }
  2348. /**
  2349. * Clones the patch
  2350. */
  2351. clone() {
  2352. return new _Patch(this.selection, {
  2353. ...this.operations
  2354. }, __privateGet$6(this, _client2$5));
  2355. }
  2356. commit(options) {
  2357. if (!__privateGet$6(this, _client2$5)) {
  2358. throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
  2359. }
  2360. const returnFirst = typeof this.selection === "string";
  2361. const opts = Object.assign({
  2362. returnFirst,
  2363. returnDocuments: true
  2364. }, options);
  2365. return __privateGet$6(this, _client2$5).mutate({
  2366. patch: this.serialize()
  2367. }, opts);
  2368. }
  2369. };
  2370. let Patch = _Patch;
  2371. _client2$5 = new WeakMap();
  2372. var __accessCheck$5 = (obj, member, msg) => {
  2373. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  2374. };
  2375. var __privateGet$5 = (obj, member, getter) => {
  2376. __accessCheck$5(obj, member, "read from private field");
  2377. return getter ? getter.call(obj) : member.get(obj);
  2378. };
  2379. var __privateAdd$5 = (obj, member, value) => {
  2380. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  2381. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  2382. };
  2383. var __privateSet$5 = (obj, member, value, setter) => {
  2384. __accessCheck$5(obj, member, "write to private field");
  2385. setter ? setter.call(obj, value) : member.set(obj, value);
  2386. return value;
  2387. };
  2388. var _client$4, _client2$4;
  2389. const defaultMutateOptions = {
  2390. returnDocuments: false
  2391. };
  2392. class BaseTransaction {
  2393. constructor() {
  2394. let operations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  2395. let transactionId = arguments.length > 1 ? arguments[1] : undefined;
  2396. this.operations = operations;
  2397. this.trxId = transactionId;
  2398. }
  2399. /**
  2400. * 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.
  2401. * The operation is added to the current transaction, ready to be commited by `commit()`
  2402. *
  2403. * @param doc - Document to create. Requires a `_type` property.
  2404. */
  2405. create(doc) {
  2406. validateObject("create", doc);
  2407. return this._add({
  2408. create: doc
  2409. });
  2410. }
  2411. /**
  2412. * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
  2413. * The operation is added to the current transaction, ready to be commited by `commit()`
  2414. *
  2415. * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
  2416. */
  2417. createIfNotExists(doc) {
  2418. const op = "createIfNotExists";
  2419. validateObject(op, doc);
  2420. requireDocumentId(op, doc);
  2421. return this._add({
  2422. [op]: doc
  2423. });
  2424. }
  2425. /**
  2426. * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
  2427. * The operation is added to the current transaction, ready to be commited by `commit()`
  2428. *
  2429. * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
  2430. */
  2431. createOrReplace(doc) {
  2432. const op = "createOrReplace";
  2433. validateObject(op, doc);
  2434. requireDocumentId(op, doc);
  2435. return this._add({
  2436. [op]: doc
  2437. });
  2438. }
  2439. /**
  2440. * Deletes the document with the given document ID
  2441. * The operation is added to the current transaction, ready to be commited by `commit()`
  2442. *
  2443. * @param documentId - Document ID to delete
  2444. */
  2445. delete(documentId) {
  2446. validateDocumentId("delete", documentId);
  2447. return this._add({
  2448. delete: {
  2449. id: documentId
  2450. }
  2451. });
  2452. }
  2453. transactionId(id) {
  2454. if (!id) {
  2455. return this.trxId;
  2456. }
  2457. this.trxId = id;
  2458. return this;
  2459. }
  2460. /**
  2461. * Return a plain JSON representation of the transaction
  2462. */
  2463. serialize() {
  2464. return [...this.operations];
  2465. }
  2466. /**
  2467. * Return a plain JSON representation of the transaction
  2468. */
  2469. toJSON() {
  2470. return this.serialize();
  2471. }
  2472. /**
  2473. * Clears the transaction of all operations
  2474. */
  2475. reset() {
  2476. this.operations = [];
  2477. return this;
  2478. }
  2479. _add(mut) {
  2480. this.operations.push(mut);
  2481. return this;
  2482. }
  2483. }
  2484. const _Transaction = class extends BaseTransaction {
  2485. constructor(operations, client, transactionId) {
  2486. super(operations, transactionId);
  2487. __privateAdd$5(this, _client$4, void 0);
  2488. __privateSet$5(this, _client$4, client);
  2489. }
  2490. /**
  2491. * Clones the transaction
  2492. */
  2493. clone() {
  2494. return new _Transaction([...this.operations], __privateGet$5(this, _client$4), this.trxId);
  2495. }
  2496. commit(options) {
  2497. if (!__privateGet$5(this, _client$4)) {
  2498. throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
  2499. }
  2500. return __privateGet$5(this, _client$4).mutate(this.serialize(), Object.assign({
  2501. transactionId: this.trxId
  2502. }, defaultMutateOptions, options || {}));
  2503. }
  2504. patch(patchOrDocumentId, patchOps) {
  2505. const isBuilder = typeof patchOps === "function";
  2506. const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof Patch;
  2507. if (isPatch) {
  2508. return this._add({
  2509. patch: patchOrDocumentId.serialize()
  2510. });
  2511. }
  2512. if (isBuilder) {
  2513. const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$5(this, _client$4)));
  2514. if (!(patch instanceof Patch)) {
  2515. throw new Error("function passed to `patch()` must return the patch");
  2516. }
  2517. return this._add({
  2518. patch: patch.serialize()
  2519. });
  2520. }
  2521. return this._add({
  2522. patch: {
  2523. id: patchOrDocumentId,
  2524. ...patchOps
  2525. }
  2526. });
  2527. }
  2528. };
  2529. let Transaction = _Transaction;
  2530. _client$4 = new WeakMap();
  2531. const _ObservableTransaction = class extends BaseTransaction {
  2532. constructor(operations, client, transactionId) {
  2533. super(operations, transactionId);
  2534. __privateAdd$5(this, _client2$4, void 0);
  2535. __privateSet$5(this, _client2$4, client);
  2536. }
  2537. /**
  2538. * Clones the transaction
  2539. */
  2540. clone() {
  2541. return new _ObservableTransaction([...this.operations], __privateGet$5(this, _client2$4), this.trxId);
  2542. }
  2543. commit(options) {
  2544. if (!__privateGet$5(this, _client2$4)) {
  2545. throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
  2546. }
  2547. return __privateGet$5(this, _client2$4).mutate(this.serialize(), Object.assign({
  2548. transactionId: this.trxId
  2549. }, defaultMutateOptions, options || {}));
  2550. }
  2551. patch(patchOrDocumentId, patchOps) {
  2552. const isBuilder = typeof patchOps === "function";
  2553. const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof ObservablePatch;
  2554. if (isPatch) {
  2555. return this._add({
  2556. patch: patchOrDocumentId.serialize()
  2557. });
  2558. }
  2559. if (isBuilder) {
  2560. const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$5(this, _client2$4)));
  2561. if (!(patch instanceof ObservablePatch)) {
  2562. throw new Error("function passed to `patch()` must return the patch");
  2563. }
  2564. return this._add({
  2565. patch: patch.serialize()
  2566. });
  2567. }
  2568. return this._add({
  2569. patch: {
  2570. id: patchOrDocumentId,
  2571. ...patchOps
  2572. }
  2573. });
  2574. }
  2575. };
  2576. let ObservableTransaction = _ObservableTransaction;
  2577. _client2$4 = new WeakMap();
  2578. const excludeFalsey = (param, defValue) => {
  2579. const value = typeof param === "undefined" ? defValue : param;
  2580. return param === false ? void 0 : value;
  2581. };
  2582. const getMutationQuery = function () {
  2583. let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  2584. return {
  2585. dryRun: options.dryRun,
  2586. returnIds: true,
  2587. returnDocuments: excludeFalsey(options.returnDocuments, true),
  2588. visibility: options.visibility || "sync",
  2589. autoGenerateArrayKeys: options.autoGenerateArrayKeys,
  2590. skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
  2591. };
  2592. };
  2593. const isResponse = event => event.type === "response";
  2594. const getBody = event => event.body;
  2595. const indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
  2596. indexed[attr(doc)] = doc;
  2597. return indexed;
  2598. }, /* @__PURE__ */Object.create(null));
  2599. const getQuerySizeLimit = 11264;
  2600. function _fetch(client, httpRequest, query, params) {
  2601. let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  2602. const mapResponse = options.filterResponse === false ? res => res : res => res.result;
  2603. return _dataRequest(client, httpRequest, "query", {
  2604. query,
  2605. params
  2606. }, options).pipe(map(mapResponse));
  2607. }
  2608. function _getDocument(client, httpRequest, id) {
  2609. let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  2610. const options = {
  2611. uri: _getDataUrl(client, "doc", id),
  2612. json: true,
  2613. tag: opts.tag
  2614. };
  2615. return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => event.body.documents && event.body.documents[0]));
  2616. }
  2617. function _getDocuments(client, httpRequest, ids) {
  2618. let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  2619. const options = {
  2620. uri: _getDataUrl(client, "doc", ids.join(",")),
  2621. json: true,
  2622. tag: opts.tag
  2623. };
  2624. return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => {
  2625. const indexed = indexBy(event.body.documents || [], doc => doc._id);
  2626. return ids.map(id => indexed[id] || null);
  2627. }));
  2628. }
  2629. function _createIfNotExists(client, httpRequest, doc, options) {
  2630. requireDocumentId("createIfNotExists", doc);
  2631. return _create(client, httpRequest, doc, "createIfNotExists", options);
  2632. }
  2633. function _createOrReplace(client, httpRequest, doc, options) {
  2634. requireDocumentId("createOrReplace", doc);
  2635. return _create(client, httpRequest, doc, "createOrReplace", options);
  2636. }
  2637. function _delete(client, httpRequest, selection, options) {
  2638. return _dataRequest(client, httpRequest, "mutate", {
  2639. mutations: [{
  2640. delete: getSelection(selection)
  2641. }]
  2642. }, options);
  2643. }
  2644. function _mutate(client, httpRequest, mutations, options) {
  2645. let mut;
  2646. if (mutations instanceof Patch || mutations instanceof ObservablePatch) {
  2647. mut = {
  2648. patch: mutations.serialize()
  2649. };
  2650. } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {
  2651. mut = mutations.serialize();
  2652. } else {
  2653. mut = mutations;
  2654. }
  2655. const muts = Array.isArray(mut) ? mut : [mut];
  2656. const transactionId = options && options.transactionId || void 0;
  2657. return _dataRequest(client, httpRequest, "mutate", {
  2658. mutations: muts,
  2659. transactionId
  2660. }, options);
  2661. }
  2662. function _dataRequest(client, httpRequest, endpoint, body) {
  2663. let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  2664. const isMutation = endpoint === "mutate";
  2665. const isQuery = endpoint === "query";
  2666. const strQuery = isMutation ? "" : encodeQueryString(body);
  2667. const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
  2668. const stringQuery = useGet ? strQuery : "";
  2669. const returnFirst = options.returnFirst;
  2670. const {
  2671. timeout,
  2672. token,
  2673. tag,
  2674. headers
  2675. } = options;
  2676. const uri = _getDataUrl(client, endpoint, stringQuery);
  2677. const reqOptions = {
  2678. method: useGet ? "GET" : "POST",
  2679. uri,
  2680. json: true,
  2681. body: useGet ? void 0 : body,
  2682. query: isMutation && getMutationQuery(options),
  2683. timeout,
  2684. headers,
  2685. token,
  2686. tag,
  2687. canUseCdn: isQuery,
  2688. signal: options.signal
  2689. };
  2690. return _requestObservable(client, httpRequest, reqOptions).pipe(filter(isResponse), map(getBody), map(res => {
  2691. if (!isMutation) {
  2692. return res;
  2693. }
  2694. const results = res.results || [];
  2695. if (options.returnDocuments) {
  2696. return returnFirst ? results[0] && results[0].document : results.map(mut => mut.document);
  2697. }
  2698. const key = returnFirst ? "documentId" : "documentIds";
  2699. const ids = returnFirst ? results[0] && results[0].id : results.map(mut => mut.id);
  2700. return {
  2701. transactionId: res.transactionId,
  2702. results,
  2703. [key]: ids
  2704. };
  2705. }));
  2706. }
  2707. function _create(client, httpRequest, doc, op) {
  2708. let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  2709. const mutation = {
  2710. [op]: doc
  2711. };
  2712. const opts = Object.assign({
  2713. returnFirst: true,
  2714. returnDocuments: true
  2715. }, options);
  2716. return _dataRequest(client, httpRequest, "mutate", {
  2717. mutations: [mutation]
  2718. }, opts);
  2719. }
  2720. function _requestObservable(client, httpRequest, options) {
  2721. const uri = options.url || options.uri;
  2722. const config = client.config();
  2723. const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
  2724. const useCdn = config.useCdn && canUseCdn;
  2725. const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
  2726. if (tag) {
  2727. options.query = {
  2728. tag: requestTag(tag),
  2729. ...options.query
  2730. };
  2731. }
  2732. const reqOptions = requestOptions(config, Object.assign({}, options, {
  2733. url: _getUrl(client, uri, useCdn)
  2734. }));
  2735. const request = new Observable(subscriber =>
  2736. // 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
  2737. httpRequest(reqOptions, config.requester).subscribe(subscriber));
  2738. return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
  2739. }
  2740. function _request(client, httpRequest, options) {
  2741. const observable = _requestObservable(client, httpRequest, options).pipe(filter(event => event.type === "response"), map(event => event.body));
  2742. return observable;
  2743. }
  2744. function _getDataUrl(client, operation, path) {
  2745. const config = client.config();
  2746. const catalog = hasDataset(config);
  2747. const baseUri = "/".concat(operation, "/").concat(catalog);
  2748. const uri = path ? "".concat(baseUri, "/").concat(path) : baseUri;
  2749. return "/data".concat(uri).replace(/\/($|\?)/, "$1");
  2750. }
  2751. function _getUrl(client, uri) {
  2752. let canUseCdn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  2753. const {
  2754. url,
  2755. cdnUrl
  2756. } = client.config();
  2757. const base = canUseCdn ? cdnUrl : url;
  2758. return "".concat(base, "/").concat(uri.replace(/^\//, ""));
  2759. }
  2760. function _withAbortSignal(signal) {
  2761. return input => {
  2762. return new Observable(observer => {
  2763. const abort = () => observer.error(_createAbortError(signal));
  2764. if (signal && signal.aborted) {
  2765. abort();
  2766. return;
  2767. }
  2768. const subscription = input.subscribe(observer);
  2769. signal.addEventListener("abort", abort);
  2770. return () => {
  2771. signal.removeEventListener("abort", abort);
  2772. subscription.unsubscribe();
  2773. };
  2774. });
  2775. };
  2776. }
  2777. const isDomExceptionSupported = Boolean(globalThis.DOMException);
  2778. function _createAbortError(signal) {
  2779. var _a, _b;
  2780. if (isDomExceptionSupported) {
  2781. return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
  2782. }
  2783. const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
  2784. error.name = "AbortError";
  2785. return error;
  2786. }
  2787. var __accessCheck$4 = (obj, member, msg) => {
  2788. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  2789. };
  2790. var __privateGet$4 = (obj, member, getter) => {
  2791. __accessCheck$4(obj, member, "read from private field");
  2792. return getter ? getter.call(obj) : member.get(obj);
  2793. };
  2794. var __privateAdd$4 = (obj, member, value) => {
  2795. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  2796. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  2797. };
  2798. var __privateSet$4 = (obj, member, value, setter) => {
  2799. __accessCheck$4(obj, member, "write to private field");
  2800. setter ? setter.call(obj, value) : member.set(obj, value);
  2801. return value;
  2802. };
  2803. var _client$3, _httpRequest$4, _client2$3, _httpRequest2$4;
  2804. class ObservableAssetsClient {
  2805. constructor(client, httpRequest) {
  2806. __privateAdd$4(this, _client$3, void 0);
  2807. __privateAdd$4(this, _httpRequest$4, void 0);
  2808. __privateSet$4(this, _client$3, client);
  2809. __privateSet$4(this, _httpRequest$4, httpRequest);
  2810. }
  2811. upload(assetType, body, options) {
  2812. return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
  2813. }
  2814. }
  2815. _client$3 = new WeakMap();
  2816. _httpRequest$4 = new WeakMap();
  2817. class AssetsClient {
  2818. constructor(client, httpRequest) {
  2819. __privateAdd$4(this, _client2$3, void 0);
  2820. __privateAdd$4(this, _httpRequest2$4, void 0);
  2821. __privateSet$4(this, _client2$3, client);
  2822. __privateSet$4(this, _httpRequest2$4, httpRequest);
  2823. }
  2824. upload(assetType, body, options) {
  2825. const observable = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
  2826. return lastValueFrom(observable.pipe(filter(event => event.type === "response"), map(event => event.body.document)));
  2827. }
  2828. }
  2829. _client2$3 = new WeakMap();
  2830. _httpRequest2$4 = new WeakMap();
  2831. function _upload(client, httpRequest, assetType, body) {
  2832. let opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  2833. validateAssetType(assetType);
  2834. let meta = opts.extract || void 0;
  2835. if (meta && !meta.length) {
  2836. meta = ["none"];
  2837. }
  2838. const dataset = hasDataset(client.config());
  2839. const assetEndpoint = assetType === "image" ? "images" : "files";
  2840. const options = optionsFromFile(opts, body);
  2841. const {
  2842. tag,
  2843. label,
  2844. title,
  2845. description,
  2846. creditLine,
  2847. filename,
  2848. source
  2849. } = options;
  2850. const query = {
  2851. label,
  2852. title,
  2853. description,
  2854. filename,
  2855. meta,
  2856. creditLine
  2857. };
  2858. if (source) {
  2859. query.sourceId = source.id;
  2860. query.sourceName = source.name;
  2861. query.sourceUrl = source.url;
  2862. }
  2863. return _requestObservable(client, httpRequest, {
  2864. tag,
  2865. method: "POST",
  2866. timeout: options.timeout || 0,
  2867. uri: "/assets/".concat(assetEndpoint, "/").concat(dataset),
  2868. headers: options.contentType ? {
  2869. "Content-Type": options.contentType
  2870. } : {},
  2871. query,
  2872. body
  2873. });
  2874. }
  2875. function optionsFromFile(opts, file) {
  2876. if (typeof File === "undefined" || !(file instanceof File)) {
  2877. return opts;
  2878. }
  2879. return Object.assign({
  2880. filename: opts.preserveFilename === false ? void 0 : file.name,
  2881. contentType: file.type
  2882. }, opts);
  2883. }
  2884. const BASE_URL = "https://www.sanity.io/help/";
  2885. function generateHelpUrl(slug) {
  2886. return BASE_URL + slug;
  2887. }
  2888. function once(fn) {
  2889. let didCall = false;
  2890. let returnValue;
  2891. return function () {
  2892. if (didCall) {
  2893. return returnValue;
  2894. }
  2895. returnValue = fn(...arguments);
  2896. didCall = true;
  2897. return returnValue;
  2898. };
  2899. }
  2900. const createWarningPrinter = message =>
  2901. // eslint-disable-next-line no-console
  2902. once(function () {
  2903. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2904. args[_key] = arguments[_key];
  2905. }
  2906. return console.warn(message.join(" "), ...args);
  2907. });
  2908. 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."]);
  2909. 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.")]);
  2910. const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
  2911. const printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead"]);
  2912. const defaultCdnHost = "apicdn.sanity.io";
  2913. const defaultConfig = {
  2914. apiHost: "https://api.sanity.io",
  2915. apiVersion: "1",
  2916. useProjectHostname: true
  2917. };
  2918. const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
  2919. const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
  2920. const validateApiVersion = function validateApiVersion2(apiVersion) {
  2921. if (apiVersion === "1" || apiVersion === "X") {
  2922. return;
  2923. }
  2924. const apiDate = new Date(apiVersion);
  2925. const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
  2926. if (!apiVersionValid) {
  2927. throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
  2928. }
  2929. };
  2930. const initConfig = (config, prevConfig) => {
  2931. const specifiedConfig = Object.assign({}, prevConfig, config);
  2932. if (!specifiedConfig.apiVersion) {
  2933. printNoApiVersionSpecifiedWarning();
  2934. }
  2935. const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
  2936. const projectBased = newConfig.useProjectHostname;
  2937. if (typeof Promise === "undefined") {
  2938. const helpUrl = generateHelpUrl("js-client-promise-polyfill");
  2939. throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
  2940. }
  2941. if (projectBased && !newConfig.projectId) {
  2942. throw new Error("Configuration must contain `projectId`");
  2943. }
  2944. const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
  2945. const isLocalhost = isBrowser && isLocal(window.location.hostname);
  2946. if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
  2947. printBrowserTokenWarning();
  2948. } else if (typeof newConfig.useCdn === "undefined") {
  2949. printCdnWarning();
  2950. }
  2951. if (projectBased) {
  2952. projectId(newConfig.projectId);
  2953. }
  2954. if (newConfig.dataset) {
  2955. dataset(newConfig.dataset);
  2956. }
  2957. if ("requestTagPrefix" in newConfig) {
  2958. newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
  2959. }
  2960. newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
  2961. newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
  2962. newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
  2963. validateApiVersion(newConfig.apiVersion);
  2964. const hostParts = newConfig.apiHost.split("://", 2);
  2965. const protocol = hostParts[0];
  2966. const host = hostParts[1];
  2967. const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
  2968. if (newConfig.useProjectHostname) {
  2969. newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
  2970. newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
  2971. } else {
  2972. newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
  2973. newConfig.cdnUrl = newConfig.url;
  2974. }
  2975. return newConfig;
  2976. };
  2977. var defaults = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
  2978. target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
  2979. return target;
  2980. }, {});
  2981. const pick = (obj, props) => props.reduce((selection, prop) => {
  2982. if (typeof obj[prop] === "undefined") {
  2983. return selection;
  2984. }
  2985. selection[prop] = obj[prop];
  2986. return selection;
  2987. }, {});
  2988. const MAX_URL_LENGTH = 16e3 - 1200;
  2989. const possibleOptions = ["includePreviousRevision", "includeResult", "visibility", "effectFormat", "tag"];
  2990. const defaultOptions = {
  2991. includeResult: true
  2992. };
  2993. function _listen(query, params) {
  2994. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2995. const {
  2996. url,
  2997. token,
  2998. withCredentials,
  2999. requestTagPrefix
  3000. } = this.config();
  3001. const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
  3002. const options = {
  3003. ...defaults(opts, defaultOptions),
  3004. tag
  3005. };
  3006. const listenOpts = pick(options, possibleOptions);
  3007. const qs = encodeQueryString({
  3008. query,
  3009. params,
  3010. options: {
  3011. tag,
  3012. ...listenOpts
  3013. }
  3014. });
  3015. const uri = "".concat(url).concat(_getDataUrl(this, "listen", qs));
  3016. if (uri.length > MAX_URL_LENGTH) {
  3017. return new Observable(observer => observer.error(new Error("Query too large for listener")));
  3018. }
  3019. const listenFor = options.events ? options.events : ["mutation"];
  3020. const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
  3021. const esOptions = {};
  3022. if (token || withCredentials) {
  3023. esOptions.withCredentials = true;
  3024. }
  3025. if (token) {
  3026. esOptions.headers = {
  3027. Authorization: "Bearer ".concat(token)
  3028. };
  3029. }
  3030. return new Observable(observer => {
  3031. let es;
  3032. getEventSource().then(eventSource => {
  3033. es = eventSource;
  3034. }).catch(reason => {
  3035. observer.error(reason);
  3036. stop();
  3037. });
  3038. let reconnectTimer;
  3039. let stopped = false;
  3040. function onError() {
  3041. if (stopped) {
  3042. return;
  3043. }
  3044. emitReconnect();
  3045. if (stopped) {
  3046. return;
  3047. }
  3048. if (es.readyState === es.CLOSED) {
  3049. unsubscribe();
  3050. clearTimeout(reconnectTimer);
  3051. reconnectTimer = setTimeout(open, 100);
  3052. }
  3053. }
  3054. function onChannelError(err) {
  3055. observer.error(cooerceError(err));
  3056. }
  3057. function onMessage(evt) {
  3058. const event = parseEvent(evt);
  3059. return event instanceof Error ? observer.error(event) : observer.next(event);
  3060. }
  3061. function onDisconnect() {
  3062. stopped = true;
  3063. unsubscribe();
  3064. observer.complete();
  3065. }
  3066. function unsubscribe() {
  3067. if (!es) return;
  3068. es.removeEventListener("error", onError);
  3069. es.removeEventListener("channelError", onChannelError);
  3070. es.removeEventListener("disconnect", onDisconnect);
  3071. listenFor.forEach(type => es.removeEventListener(type, onMessage));
  3072. es.close();
  3073. }
  3074. function emitReconnect() {
  3075. if (shouldEmitReconnect) {
  3076. observer.next({
  3077. type: "reconnect"
  3078. });
  3079. }
  3080. }
  3081. async function getEventSource() {
  3082. const {
  3083. default: EventSource
  3084. } = await Promise.resolve().then(function () { return browser$1; });
  3085. const evs = new EventSource(uri, esOptions);
  3086. evs.addEventListener("error", onError);
  3087. evs.addEventListener("channelError", onChannelError);
  3088. evs.addEventListener("disconnect", onDisconnect);
  3089. listenFor.forEach(type => evs.addEventListener(type, onMessage));
  3090. return evs;
  3091. }
  3092. function open() {
  3093. getEventSource().then(eventSource => {
  3094. es = eventSource;
  3095. }).catch(reason => {
  3096. observer.error(reason);
  3097. stop();
  3098. });
  3099. }
  3100. function stop() {
  3101. stopped = true;
  3102. unsubscribe();
  3103. }
  3104. return stop;
  3105. });
  3106. }
  3107. function parseEvent(event) {
  3108. try {
  3109. const data = event.data && JSON.parse(event.data) || {};
  3110. return Object.assign({
  3111. type: event.type
  3112. }, data);
  3113. } catch (err) {
  3114. return err;
  3115. }
  3116. }
  3117. function cooerceError(err) {
  3118. if (err instanceof Error) {
  3119. return err;
  3120. }
  3121. const evt = parseEvent(err);
  3122. return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
  3123. }
  3124. function extractErrorMessage(err) {
  3125. if (!err.error) {
  3126. return err.message || "Unknown listener error";
  3127. }
  3128. if (err.error.description) {
  3129. return err.error.description;
  3130. }
  3131. return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
  3132. }
  3133. var __accessCheck$3 = (obj, member, msg) => {
  3134. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  3135. };
  3136. var __privateGet$3 = (obj, member, getter) => {
  3137. __accessCheck$3(obj, member, "read from private field");
  3138. return getter ? getter.call(obj) : member.get(obj);
  3139. };
  3140. var __privateAdd$3 = (obj, member, value) => {
  3141. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  3142. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  3143. };
  3144. var __privateSet$3 = (obj, member, value, setter) => {
  3145. __accessCheck$3(obj, member, "write to private field");
  3146. setter ? setter.call(obj, value) : member.set(obj, value);
  3147. return value;
  3148. };
  3149. var _client$2, _httpRequest$3, _client2$2, _httpRequest2$3;
  3150. class ObservableDatasetsClient {
  3151. constructor(client, httpRequest) {
  3152. __privateAdd$3(this, _client$2, void 0);
  3153. __privateAdd$3(this, _httpRequest$3, void 0);
  3154. __privateSet$3(this, _client$2, client);
  3155. __privateSet$3(this, _httpRequest$3, httpRequest);
  3156. }
  3157. /**
  3158. * Create a new dataset with the given name
  3159. *
  3160. * @param name - Name of the dataset to create
  3161. * @param options - Options for the dataset
  3162. */
  3163. create(name, options) {
  3164. return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name, options);
  3165. }
  3166. /**
  3167. * Edit a dataset with the given name
  3168. *
  3169. * @param name - Name of the dataset to edit
  3170. * @param options - New options for the dataset
  3171. */
  3172. edit(name, options) {
  3173. return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name, options);
  3174. }
  3175. /**
  3176. * Delete a dataset with the given name
  3177. *
  3178. * @param name - Name of the dataset to delete
  3179. */
  3180. delete(name) {
  3181. return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name);
  3182. }
  3183. /**
  3184. * Fetch a list of datasets for the configured project
  3185. */
  3186. list() {
  3187. return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
  3188. uri: "/datasets"
  3189. });
  3190. }
  3191. }
  3192. _client$2 = new WeakMap();
  3193. _httpRequest$3 = new WeakMap();
  3194. class DatasetsClient {
  3195. constructor(client, httpRequest) {
  3196. __privateAdd$3(this, _client2$2, void 0);
  3197. __privateAdd$3(this, _httpRequest2$3, void 0);
  3198. __privateSet$3(this, _client2$2, client);
  3199. __privateSet$3(this, _httpRequest2$3, httpRequest);
  3200. }
  3201. /**
  3202. * Create a new dataset with the given name
  3203. *
  3204. * @param name - Name of the dataset to create
  3205. * @param options - Options for the dataset
  3206. */
  3207. create(name, options) {
  3208. return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name, options));
  3209. }
  3210. /**
  3211. * Edit a dataset with the given name
  3212. *
  3213. * @param name - Name of the dataset to edit
  3214. * @param options - New options for the dataset
  3215. */
  3216. edit(name, options) {
  3217. return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name, options));
  3218. }
  3219. /**
  3220. * Delete a dataset with the given name
  3221. *
  3222. * @param name - Name of the dataset to delete
  3223. */
  3224. delete(name) {
  3225. return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name));
  3226. }
  3227. /**
  3228. * Fetch a list of datasets for the configured project
  3229. */
  3230. list() {
  3231. return lastValueFrom(_request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), {
  3232. uri: "/datasets"
  3233. }));
  3234. }
  3235. }
  3236. _client2$2 = new WeakMap();
  3237. _httpRequest2$3 = new WeakMap();
  3238. function _modify(client, httpRequest, method, name, options) {
  3239. dataset(name);
  3240. return _request(client, httpRequest, {
  3241. method,
  3242. uri: "/datasets/".concat(name),
  3243. body: options
  3244. });
  3245. }
  3246. var __accessCheck$2 = (obj, member, msg) => {
  3247. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  3248. };
  3249. var __privateGet$2 = (obj, member, getter) => {
  3250. __accessCheck$2(obj, member, "read from private field");
  3251. return getter ? getter.call(obj) : member.get(obj);
  3252. };
  3253. var __privateAdd$2 = (obj, member, value) => {
  3254. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  3255. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  3256. };
  3257. var __privateSet$2 = (obj, member, value, setter) => {
  3258. __accessCheck$2(obj, member, "write to private field");
  3259. setter ? setter.call(obj, value) : member.set(obj, value);
  3260. return value;
  3261. };
  3262. var _client$1, _httpRequest$2, _client2$1, _httpRequest2$2;
  3263. class ObservableProjectsClient {
  3264. constructor(client, httpRequest) {
  3265. __privateAdd$2(this, _client$1, void 0);
  3266. __privateAdd$2(this, _httpRequest$2, void 0);
  3267. __privateSet$2(this, _client$1, client);
  3268. __privateSet$2(this, _httpRequest$2, httpRequest);
  3269. }
  3270. /**
  3271. * Fetch a list of projects the authenticated user has access to
  3272. */
  3273. list() {
  3274. return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
  3275. uri: "/projects"
  3276. });
  3277. }
  3278. /**
  3279. * Fetch a project by project ID
  3280. *
  3281. * @param projectId - ID of the project to fetch
  3282. */
  3283. getById(projectId) {
  3284. return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
  3285. uri: "/projects/".concat(projectId)
  3286. });
  3287. }
  3288. }
  3289. _client$1 = new WeakMap();
  3290. _httpRequest$2 = new WeakMap();
  3291. class ProjectsClient {
  3292. constructor(client, httpRequest) {
  3293. __privateAdd$2(this, _client2$1, void 0);
  3294. __privateAdd$2(this, _httpRequest2$2, void 0);
  3295. __privateSet$2(this, _client2$1, client);
  3296. __privateSet$2(this, _httpRequest2$2, httpRequest);
  3297. }
  3298. /**
  3299. * Fetch a list of projects the authenticated user has access to
  3300. */
  3301. list() {
  3302. return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
  3303. uri: "/projects"
  3304. }));
  3305. }
  3306. /**
  3307. * Fetch a project by project ID
  3308. *
  3309. * @param projectId - ID of the project to fetch
  3310. */
  3311. getById(projectId) {
  3312. return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
  3313. uri: "/projects/".concat(projectId)
  3314. }));
  3315. }
  3316. }
  3317. _client2$1 = new WeakMap();
  3318. _httpRequest2$2 = new WeakMap();
  3319. var __accessCheck$1 = (obj, member, msg) => {
  3320. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  3321. };
  3322. var __privateGet$1 = (obj, member, getter) => {
  3323. __accessCheck$1(obj, member, "read from private field");
  3324. return getter ? getter.call(obj) : member.get(obj);
  3325. };
  3326. var __privateAdd$1 = (obj, member, value) => {
  3327. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  3328. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  3329. };
  3330. var __privateSet$1 = (obj, member, value, setter) => {
  3331. __accessCheck$1(obj, member, "write to private field");
  3332. setter ? setter.call(obj, value) : member.set(obj, value);
  3333. return value;
  3334. };
  3335. var _client, _httpRequest$1, _client2, _httpRequest2$1;
  3336. class ObservableUsersClient {
  3337. constructor(client, httpRequest) {
  3338. __privateAdd$1(this, _client, void 0);
  3339. __privateAdd$1(this, _httpRequest$1, void 0);
  3340. __privateSet$1(this, _client, client);
  3341. __privateSet$1(this, _httpRequest$1, httpRequest);
  3342. }
  3343. /**
  3344. * Fetch a user by user ID
  3345. *
  3346. * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
  3347. */
  3348. getById(id) {
  3349. return _request(__privateGet$1(this, _client), __privateGet$1(this, _httpRequest$1), {
  3350. uri: "/users/".concat(id)
  3351. });
  3352. }
  3353. }
  3354. _client = new WeakMap();
  3355. _httpRequest$1 = new WeakMap();
  3356. class UsersClient {
  3357. constructor(client, httpRequest) {
  3358. __privateAdd$1(this, _client2, void 0);
  3359. __privateAdd$1(this, _httpRequest2$1, void 0);
  3360. __privateSet$1(this, _client2, client);
  3361. __privateSet$1(this, _httpRequest2$1, httpRequest);
  3362. }
  3363. /**
  3364. * Fetch a user by user ID
  3365. *
  3366. * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
  3367. */
  3368. getById(id) {
  3369. return lastValueFrom(_request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
  3370. uri: "/users/".concat(id)
  3371. }));
  3372. }
  3373. }
  3374. _client2 = new WeakMap();
  3375. _httpRequest2$1 = new WeakMap();
  3376. var __accessCheck = (obj, member, msg) => {
  3377. if (!member.has(obj)) throw TypeError("Cannot " + msg);
  3378. };
  3379. var __privateGet = (obj, member, getter) => {
  3380. __accessCheck(obj, member, "read from private field");
  3381. return getter ? getter.call(obj) : member.get(obj);
  3382. };
  3383. var __privateAdd = (obj, member, value) => {
  3384. if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
  3385. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  3386. };
  3387. var __privateSet = (obj, member, value, setter) => {
  3388. __accessCheck(obj, member, "write to private field");
  3389. setter ? setter.call(obj, value) : member.set(obj, value);
  3390. return value;
  3391. };
  3392. var _clientConfig, _httpRequest, _clientConfig2, _httpRequest2;
  3393. const _ObservableSanityClient = class {
  3394. constructor(httpRequest) {
  3395. let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
  3396. /**
  3397. * Private properties
  3398. */
  3399. __privateAdd(this, _clientConfig, void 0);
  3400. __privateAdd(this, _httpRequest, void 0);
  3401. /**
  3402. * Instance properties
  3403. */
  3404. this.listen = _listen;
  3405. this.config(config);
  3406. __privateSet(this, _httpRequest, httpRequest);
  3407. this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest));
  3408. this.datasets = new ObservableDatasetsClient(this, __privateGet(this, _httpRequest));
  3409. this.projects = new ObservableProjectsClient(this, __privateGet(this, _httpRequest));
  3410. this.users = new ObservableUsersClient(this, __privateGet(this, _httpRequest));
  3411. }
  3412. /**
  3413. * Clone the client - returns a new instance
  3414. */
  3415. clone() {
  3416. return new _ObservableSanityClient(__privateGet(this, _httpRequest), this.config());
  3417. }
  3418. config(newConfig) {
  3419. if (newConfig === void 0) {
  3420. return {
  3421. ...__privateGet(this, _clientConfig)
  3422. };
  3423. }
  3424. if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === false) {
  3425. throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
  3426. }
  3427. __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {}));
  3428. return this;
  3429. }
  3430. /**
  3431. * Clone the client with a new (partial) configuration.
  3432. *
  3433. * @param newConfig - New client configuration properties, shallowly merged with existing configuration
  3434. */
  3435. withConfig(newConfig) {
  3436. return new _ObservableSanityClient(__privateGet(this, _httpRequest), {
  3437. ...this.config(),
  3438. ...newConfig
  3439. });
  3440. }
  3441. fetch(query, params) {
  3442. let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  3443. return _fetch(this, __privateGet(this, _httpRequest), query, params, options);
  3444. }
  3445. /**
  3446. * Fetch a single document with the given ID.
  3447. *
  3448. * @param id - Document ID to fetch
  3449. * @param options - Request options
  3450. */
  3451. getDocument(id, options) {
  3452. return _getDocument(this, __privateGet(this, _httpRequest), id, options);
  3453. }
  3454. /**
  3455. * Fetch multiple documents in one request.
  3456. * Should be used sparingly - performing a query is usually a better option.
  3457. * The order/position of documents is preserved based on the original array of IDs.
  3458. * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
  3459. *
  3460. * @param ids - Document IDs to fetch
  3461. * @param options - Request options
  3462. */
  3463. getDocuments(ids, options) {
  3464. return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
  3465. }
  3466. create(document, options) {
  3467. return _create(this, __privateGet(this, _httpRequest), document, "create", options);
  3468. }
  3469. createIfNotExists(document, options) {
  3470. return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
  3471. }
  3472. createOrReplace(document, options) {
  3473. return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
  3474. }
  3475. delete(selection, options) {
  3476. return _delete(this, __privateGet(this, _httpRequest), selection, options);
  3477. }
  3478. mutate(operations, options) {
  3479. return _mutate(this, __privateGet(this, _httpRequest), operations, options);
  3480. }
  3481. /**
  3482. * Create a new buildable patch of operations to perform
  3483. *
  3484. * @param documentId - Document ID(s) to patch
  3485. * @param operations - Optional object of patch operations to initialize the patch instance with
  3486. */
  3487. patch(documentId, operations) {
  3488. return new ObservablePatch(documentId, operations, this);
  3489. }
  3490. /**
  3491. * Create a new transaction of mutations
  3492. *
  3493. * @param operations - Optional array of mutation operations to initialize the transaction instance with
  3494. */
  3495. transaction(operations) {
  3496. return new ObservableTransaction(operations, this);
  3497. }
  3498. /**
  3499. * DEPRECATED: Perform an HTTP request against the Sanity API
  3500. *
  3501. * @deprecated Use your own request library!
  3502. * @param options - Request options
  3503. */
  3504. request(options) {
  3505. return _request(this, __privateGet(this, _httpRequest), options);
  3506. }
  3507. /**
  3508. * Get a Sanity API URL for the URI provided
  3509. *
  3510. * @param uri - URI/path to build URL for
  3511. * @param canUseCdn - Whether or not to allow using the API CDN for this route
  3512. */
  3513. getUrl(uri, canUseCdn) {
  3514. return _getUrl(this, uri, canUseCdn);
  3515. }
  3516. /**
  3517. * Get a Sanity API URL for the data operation and path provided
  3518. *
  3519. * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
  3520. * @param path - Path to append after the operation
  3521. */
  3522. getDataUrl(operation, path) {
  3523. return _getDataUrl(this, operation, path);
  3524. }
  3525. };
  3526. let ObservableSanityClient = _ObservableSanityClient;
  3527. _clientConfig = new WeakMap();
  3528. _httpRequest = new WeakMap();
  3529. const _SanityClient = class {
  3530. constructor(httpRequest) {
  3531. let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
  3532. /**
  3533. * Private properties
  3534. */
  3535. __privateAdd(this, _clientConfig2, void 0);
  3536. __privateAdd(this, _httpRequest2, void 0);
  3537. /**
  3538. * Instance properties
  3539. */
  3540. this.listen = _listen;
  3541. this.config(config);
  3542. __privateSet(this, _httpRequest2, httpRequest);
  3543. this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2));
  3544. this.datasets = new DatasetsClient(this, __privateGet(this, _httpRequest2));
  3545. this.projects = new ProjectsClient(this, __privateGet(this, _httpRequest2));
  3546. this.users = new UsersClient(this, __privateGet(this, _httpRequest2));
  3547. this.observable = new ObservableSanityClient(httpRequest, config);
  3548. }
  3549. /**
  3550. * Clone the client - returns a new instance
  3551. */
  3552. clone() {
  3553. return new _SanityClient(__privateGet(this, _httpRequest2), this.config());
  3554. }
  3555. config(newConfig) {
  3556. if (newConfig === void 0) {
  3557. return {
  3558. ...__privateGet(this, _clientConfig2)
  3559. };
  3560. }
  3561. if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === false) {
  3562. throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
  3563. }
  3564. if (this.observable) {
  3565. this.observable.config(newConfig);
  3566. }
  3567. __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {}));
  3568. return this;
  3569. }
  3570. /**
  3571. * Clone the client with a new (partial) configuration.
  3572. *
  3573. * @param newConfig - New client configuration properties, shallowly merged with existing configuration
  3574. */
  3575. withConfig(newConfig) {
  3576. return new _SanityClient(__privateGet(this, _httpRequest2), {
  3577. ...this.config(),
  3578. ...newConfig
  3579. });
  3580. }
  3581. fetch(query, params) {
  3582. let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  3583. return lastValueFrom(_fetch(this, __privateGet(this, _httpRequest2), query, params, options));
  3584. }
  3585. /**
  3586. * Fetch a single document with the given ID.
  3587. *
  3588. * @param id - Document ID to fetch
  3589. * @param options - Request options
  3590. */
  3591. getDocument(id, options) {
  3592. return lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
  3593. }
  3594. /**
  3595. * Fetch multiple documents in one request.
  3596. * Should be used sparingly - performing a query is usually a better option.
  3597. * The order/position of documents is preserved based on the original array of IDs.
  3598. * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
  3599. *
  3600. * @param ids - Document IDs to fetch
  3601. * @param options - Request options
  3602. */
  3603. getDocuments(ids, options) {
  3604. return lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
  3605. }
  3606. create(document, options) {
  3607. return lastValueFrom(_create(this, __privateGet(this, _httpRequest2), document, "create", options));
  3608. }
  3609. createIfNotExists(document, options) {
  3610. return lastValueFrom(_createIfNotExists(this, __privateGet(this, _httpRequest2), document, options));
  3611. }
  3612. createOrReplace(document, options) {
  3613. return lastValueFrom(_createOrReplace(this, __privateGet(this, _httpRequest2), document, options));
  3614. }
  3615. delete(selection, options) {
  3616. return lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
  3617. }
  3618. mutate(operations, options) {
  3619. return lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
  3620. }
  3621. /**
  3622. * Create a new buildable patch of operations to perform
  3623. *
  3624. * @param documentId - Document ID(s)to patch
  3625. * @param operations - Optional object of patch operations to initialize the patch instance with
  3626. */
  3627. patch(documentId, operations) {
  3628. return new Patch(documentId, operations, this);
  3629. }
  3630. /**
  3631. * Create a new transaction of mutations
  3632. *
  3633. * @param operations - Optional array of mutation operations to initialize the transaction instance with
  3634. */
  3635. transaction(operations) {
  3636. return new Transaction(operations, this);
  3637. }
  3638. /**
  3639. * DEPRECATED: Perform an HTTP request against the Sanity API
  3640. *
  3641. * @deprecated Use your own request library!
  3642. * @param options - Request options
  3643. */
  3644. request(options) {
  3645. return lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
  3646. }
  3647. /**
  3648. * DEPRECATED: Perform an HTTP request a `/data` sub-endpoint
  3649. *
  3650. * @deprecated Use your own request library!
  3651. * @param endpoint - Endpoint to hit (mutate, query etc)
  3652. * @param body - Request body
  3653. * @param options - Request options
  3654. */
  3655. dataRequest(endpoint, body, options) {
  3656. return lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
  3657. }
  3658. /**
  3659. * Get a Sanity API URL for the URI provided
  3660. *
  3661. * @param uri - URI/path to build URL for
  3662. * @param canUseCdn - Whether or not to allow using the API CDN for this route
  3663. */
  3664. getUrl(uri, canUseCdn) {
  3665. return _getUrl(this, uri, canUseCdn);
  3666. }
  3667. /**
  3668. * Get a Sanity API URL for the data operation and path provided
  3669. *
  3670. * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
  3671. * @param path - Path to append after the operation
  3672. */
  3673. getDataUrl(operation, path) {
  3674. return _getDataUrl(this, operation, path);
  3675. }
  3676. };
  3677. let SanityClient = _SanityClient;
  3678. _clientConfig2 = new WeakMap();
  3679. _httpRequest2 = new WeakMap();
  3680. const httpRequest = defineHttpRequest(envMiddleware);
  3681. const requester = httpRequest.defaultRequester;
  3682. const createClient = config => new SanityClient(httpRequest, config);
  3683. function deprecatedCreateClient(config) {
  3684. printNoDefaultExport();
  3685. return new SanityClient(httpRequest, config);
  3686. }
  3687. var eventsourceExports = {};
  3688. var eventsource = {
  3689. get exports(){ return eventsourceExports; },
  3690. set exports(v){ eventsourceExports = v; },
  3691. };
  3692. /** @license
  3693. * eventsource.js
  3694. * Available under MIT License (MIT)
  3695. * https://github.com/Yaffle/EventSource/
  3696. */
  3697. (function (module, exports) {
  3698. /*jslint indent: 2, vars: true, plusplus: true */
  3699. /*global setTimeout, clearTimeout */
  3700. (function (global) {
  3701. var setTimeout = global.setTimeout;
  3702. var clearTimeout = global.clearTimeout;
  3703. var XMLHttpRequest = global.XMLHttpRequest;
  3704. var XDomainRequest = global.XDomainRequest;
  3705. var ActiveXObject = global.ActiveXObject;
  3706. var NativeEventSource = global.EventSource;
  3707. var document = global.document;
  3708. var Promise = global.Promise;
  3709. var fetch = global.fetch;
  3710. var Response = global.Response;
  3711. var TextDecoder = global.TextDecoder;
  3712. var TextEncoder = global.TextEncoder;
  3713. var AbortController = global.AbortController;
  3714. if (typeof window !== "undefined" && typeof document !== "undefined" && !("readyState" in document) && document.body == null) { // Firefox 2
  3715. document.readyState = "loading";
  3716. window.addEventListener("load", function (event) {
  3717. document.readyState = "complete";
  3718. }, false);
  3719. }
  3720. if (XMLHttpRequest == null && ActiveXObject != null) { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6
  3721. XMLHttpRequest = function () {
  3722. return new ActiveXObject("Microsoft.XMLHTTP");
  3723. };
  3724. }
  3725. if (Object.create == undefined) {
  3726. Object.create = function (C) {
  3727. function F(){}
  3728. F.prototype = C;
  3729. return new F();
  3730. };
  3731. }
  3732. if (!Date.now) {
  3733. Date.now = function now() {
  3734. return new Date().getTime();
  3735. };
  3736. }
  3737. // see #118 (Promise#finally with polyfilled Promise)
  3738. // see #123 (data URLs crash Edge)
  3739. // see #125 (CSP violations)
  3740. // see pull/#138
  3741. // => No way to polyfill Promise#finally
  3742. if (AbortController == undefined) {
  3743. var originalFetch2 = fetch;
  3744. fetch = function (url, options) {
  3745. var signal = options.signal;
  3746. return originalFetch2(url, {headers: options.headers, credentials: options.credentials, cache: options.cache}).then(function (response) {
  3747. var reader = response.body.getReader();
  3748. signal._reader = reader;
  3749. if (signal._aborted) {
  3750. signal._reader.cancel();
  3751. }
  3752. return {
  3753. status: response.status,
  3754. statusText: response.statusText,
  3755. headers: response.headers,
  3756. body: {
  3757. getReader: function () {
  3758. return reader;
  3759. }
  3760. }
  3761. };
  3762. });
  3763. };
  3764. AbortController = function () {
  3765. this.signal = {
  3766. _reader: null,
  3767. _aborted: false
  3768. };
  3769. this.abort = function () {
  3770. if (this.signal._reader != null) {
  3771. this.signal._reader.cancel();
  3772. }
  3773. this.signal._aborted = true;
  3774. };
  3775. };
  3776. }
  3777. function TextDecoderPolyfill() {
  3778. this.bitsNeeded = 0;
  3779. this.codePoint = 0;
  3780. }
  3781. TextDecoderPolyfill.prototype.decode = function (octets) {
  3782. function valid(codePoint, shift, octetsCount) {
  3783. if (octetsCount === 1) {
  3784. return codePoint >= 0x0080 >> shift && codePoint << shift <= 0x07FF;
  3785. }
  3786. if (octetsCount === 2) {
  3787. return codePoint >= 0x0800 >> shift && codePoint << shift <= 0xD7FF || codePoint >= 0xE000 >> shift && codePoint << shift <= 0xFFFF;
  3788. }
  3789. if (octetsCount === 3) {
  3790. return codePoint >= 0x010000 >> shift && codePoint << shift <= 0x10FFFF;
  3791. }
  3792. throw new Error();
  3793. }
  3794. function octetsCount(bitsNeeded, codePoint) {
  3795. if (bitsNeeded === 6 * 1) {
  3796. return codePoint >> 6 > 15 ? 3 : codePoint > 31 ? 2 : 1;
  3797. }
  3798. if (bitsNeeded === 6 * 2) {
  3799. return codePoint > 15 ? 3 : 2;
  3800. }
  3801. if (bitsNeeded === 6 * 3) {
  3802. return 3;
  3803. }
  3804. throw new Error();
  3805. }
  3806. var REPLACER = 0xFFFD;
  3807. var string = "";
  3808. var bitsNeeded = this.bitsNeeded;
  3809. var codePoint = this.codePoint;
  3810. for (var i = 0; i < octets.length; i += 1) {
  3811. var octet = octets[i];
  3812. if (bitsNeeded !== 0) {
  3813. if (octet < 128 || octet > 191 || !valid(codePoint << 6 | octet & 63, bitsNeeded - 6, octetsCount(bitsNeeded, codePoint))) {
  3814. bitsNeeded = 0;
  3815. codePoint = REPLACER;
  3816. string += String.fromCharCode(codePoint);
  3817. }
  3818. }
  3819. if (bitsNeeded === 0) {
  3820. if (octet >= 0 && octet <= 127) {
  3821. bitsNeeded = 0;
  3822. codePoint = octet;
  3823. } else if (octet >= 192 && octet <= 223) {
  3824. bitsNeeded = 6 * 1;
  3825. codePoint = octet & 31;
  3826. } else if (octet >= 224 && octet <= 239) {
  3827. bitsNeeded = 6 * 2;
  3828. codePoint = octet & 15;
  3829. } else if (octet >= 240 && octet <= 247) {
  3830. bitsNeeded = 6 * 3;
  3831. codePoint = octet & 7;
  3832. } else {
  3833. bitsNeeded = 0;
  3834. codePoint = REPLACER;
  3835. }
  3836. if (bitsNeeded !== 0 && !valid(codePoint, bitsNeeded, octetsCount(bitsNeeded, codePoint))) {
  3837. bitsNeeded = 0;
  3838. codePoint = REPLACER;
  3839. }
  3840. } else {
  3841. bitsNeeded -= 6;
  3842. codePoint = codePoint << 6 | octet & 63;
  3843. }
  3844. if (bitsNeeded === 0) {
  3845. if (codePoint <= 0xFFFF) {
  3846. string += String.fromCharCode(codePoint);
  3847. } else {
  3848. string += String.fromCharCode(0xD800 + (codePoint - 0xFFFF - 1 >> 10));
  3849. string += String.fromCharCode(0xDC00 + (codePoint - 0xFFFF - 1 & 0x3FF));
  3850. }
  3851. }
  3852. }
  3853. this.bitsNeeded = bitsNeeded;
  3854. this.codePoint = codePoint;
  3855. return string;
  3856. };
  3857. // Firefox < 38 throws an error with stream option
  3858. var supportsStreamOption = function () {
  3859. try {
  3860. return new TextDecoder().decode(new TextEncoder().encode("test"), {stream: true}) === "test";
  3861. } catch (error) {
  3862. console.debug("TextDecoder does not support streaming option. Using polyfill instead: " + error);
  3863. }
  3864. return false;
  3865. };
  3866. // IE, Edge
  3867. if (TextDecoder == undefined || TextEncoder == undefined || !supportsStreamOption()) {
  3868. TextDecoder = TextDecoderPolyfill;
  3869. }
  3870. var k = function () {
  3871. };
  3872. function XHRWrapper(xhr) {
  3873. this.withCredentials = false;
  3874. this.readyState = 0;
  3875. this.status = 0;
  3876. this.statusText = "";
  3877. this.responseText = "";
  3878. this.onprogress = k;
  3879. this.onload = k;
  3880. this.onerror = k;
  3881. this.onreadystatechange = k;
  3882. this._contentType = "";
  3883. this._xhr = xhr;
  3884. this._sendTimeout = 0;
  3885. this._abort = k;
  3886. }
  3887. XHRWrapper.prototype.open = function (method, url) {
  3888. this._abort(true);
  3889. var that = this;
  3890. var xhr = this._xhr;
  3891. var state = 1;
  3892. var timeout = 0;
  3893. this._abort = function (silent) {
  3894. if (that._sendTimeout !== 0) {
  3895. clearTimeout(that._sendTimeout);
  3896. that._sendTimeout = 0;
  3897. }
  3898. if (state === 1 || state === 2 || state === 3) {
  3899. state = 4;
  3900. xhr.onload = k;
  3901. xhr.onerror = k;
  3902. xhr.onabort = k;
  3903. xhr.onprogress = k;
  3904. xhr.onreadystatechange = k;
  3905. // IE 8 - 9: XDomainRequest#abort() does not fire any event
  3906. // Opera < 10: XMLHttpRequest#abort() does not fire any event
  3907. xhr.abort();
  3908. if (timeout !== 0) {
  3909. clearTimeout(timeout);
  3910. timeout = 0;
  3911. }
  3912. if (!silent) {
  3913. that.readyState = 4;
  3914. that.onabort(null);
  3915. that.onreadystatechange();
  3916. }
  3917. }
  3918. state = 0;
  3919. };
  3920. var onStart = function () {
  3921. if (state === 1) {
  3922. //state = 2;
  3923. var status = 0;
  3924. var statusText = "";
  3925. var contentType = undefined;
  3926. if (!("contentType" in xhr)) {
  3927. try {
  3928. status = xhr.status;
  3929. statusText = xhr.statusText;
  3930. contentType = xhr.getResponseHeader("Content-Type");
  3931. } catch (error) {
  3932. // IE < 10 throws exception for `xhr.status` when xhr.readyState === 2 || xhr.readyState === 3
  3933. // Opera < 11 throws exception for `xhr.status` when xhr.readyState === 2
  3934. // https://bugs.webkit.org/show_bug.cgi?id=29121
  3935. status = 0;
  3936. statusText = "";
  3937. contentType = undefined;
  3938. // Firefox < 14, Chrome ?, Safari ?
  3939. // https://bugs.webkit.org/show_bug.cgi?id=29658
  3940. // https://bugs.webkit.org/show_bug.cgi?id=77854
  3941. }
  3942. } else {
  3943. status = 200;
  3944. statusText = "OK";
  3945. contentType = xhr.contentType;
  3946. }
  3947. if (status !== 0) {
  3948. state = 2;
  3949. that.readyState = 2;
  3950. that.status = status;
  3951. that.statusText = statusText;
  3952. that._contentType = contentType;
  3953. that.onreadystatechange();
  3954. }
  3955. }
  3956. };
  3957. var onProgress = function () {
  3958. onStart();
  3959. if (state === 2 || state === 3) {
  3960. state = 3;
  3961. var responseText = "";
  3962. try {
  3963. responseText = xhr.responseText;
  3964. } catch (error) {
  3965. // IE 8 - 9 with XMLHttpRequest
  3966. }
  3967. that.readyState = 3;
  3968. that.responseText = responseText;
  3969. that.onprogress();
  3970. }
  3971. };
  3972. var onFinish = function (type, event) {
  3973. if (event == null || event.preventDefault == null) {
  3974. event = {
  3975. preventDefault: k
  3976. };
  3977. }
  3978. // Firefox 52 fires "readystatechange" (xhr.readyState === 4) without final "readystatechange" (xhr.readyState === 3)
  3979. // IE 8 fires "onload" without "onprogress"
  3980. onProgress();
  3981. if (state === 1 || state === 2 || state === 3) {
  3982. state = 4;
  3983. if (timeout !== 0) {
  3984. clearTimeout(timeout);
  3985. timeout = 0;
  3986. }
  3987. that.readyState = 4;
  3988. if (type === "load") {
  3989. that.onload(event);
  3990. } else if (type === "error") {
  3991. that.onerror(event);
  3992. } else if (type === "abort") {
  3993. that.onabort(event);
  3994. } else {
  3995. throw new TypeError();
  3996. }
  3997. that.onreadystatechange();
  3998. }
  3999. };
  4000. var onReadyStateChange = function (event) {
  4001. if (xhr != undefined) { // Opera 12
  4002. if (xhr.readyState === 4) {
  4003. if (!("onload" in xhr) || !("onerror" in xhr) || !("onabort" in xhr)) {
  4004. onFinish(xhr.responseText === "" ? "error" : "load", event);
  4005. }
  4006. } else if (xhr.readyState === 3) {
  4007. if (!("onprogress" in xhr)) { // testing XMLHttpRequest#responseText too many times is too slow in IE 11
  4008. // and in Firefox 3.6
  4009. onProgress();
  4010. }
  4011. } else if (xhr.readyState === 2) {
  4012. onStart();
  4013. }
  4014. }
  4015. };
  4016. var onTimeout = function () {
  4017. timeout = setTimeout(function () {
  4018. onTimeout();
  4019. }, 500);
  4020. if (xhr.readyState === 3) {
  4021. onProgress();
  4022. }
  4023. };
  4024. // XDomainRequest#abort removes onprogress, onerror, onload
  4025. if ("onload" in xhr) {
  4026. xhr.onload = function (event) {
  4027. onFinish("load", event);
  4028. };
  4029. }
  4030. if ("onerror" in xhr) {
  4031. xhr.onerror = function (event) {
  4032. onFinish("error", event);
  4033. };
  4034. }
  4035. // improper fix to match Firefox behaviour, but it is better than just ignore abort
  4036. // see https://bugzilla.mozilla.org/show_bug.cgi?id=768596
  4037. // https://bugzilla.mozilla.org/show_bug.cgi?id=880200
  4038. // https://code.google.com/p/chromium/issues/detail?id=153570
  4039. // IE 8 fires "onload" without "onprogress
  4040. if ("onabort" in xhr) {
  4041. xhr.onabort = function (event) {
  4042. onFinish("abort", event);
  4043. };
  4044. }
  4045. if ("onprogress" in xhr) {
  4046. xhr.onprogress = onProgress;
  4047. }
  4048. // IE 8 - 9 (XMLHTTPRequest)
  4049. // Opera < 12
  4050. // Firefox < 3.5
  4051. // Firefox 3.5 - 3.6 - ? < 9.0
  4052. // onprogress is not fired sometimes or delayed
  4053. // see also #64 (significant lag in IE 11)
  4054. if ("onreadystatechange" in xhr) {
  4055. xhr.onreadystatechange = function (event) {
  4056. onReadyStateChange(event);
  4057. };
  4058. }
  4059. if ("contentType" in xhr || !("ontimeout" in XMLHttpRequest.prototype)) {
  4060. url += (url.indexOf("?") === -1 ? "?" : "&") + "padding=true";
  4061. }
  4062. xhr.open(method, url, true);
  4063. if ("readyState" in xhr) {
  4064. // workaround for Opera 12 issue with "progress" events
  4065. // #91 (XMLHttpRequest onprogress not fired for streaming response in Edge 14-15-?)
  4066. timeout = setTimeout(function () {
  4067. onTimeout();
  4068. }, 0);
  4069. }
  4070. };
  4071. XHRWrapper.prototype.abort = function () {
  4072. this._abort(false);
  4073. };
  4074. XHRWrapper.prototype.getResponseHeader = function (name) {
  4075. return this._contentType;
  4076. };
  4077. XHRWrapper.prototype.setRequestHeader = function (name, value) {
  4078. var xhr = this._xhr;
  4079. if ("setRequestHeader" in xhr) {
  4080. xhr.setRequestHeader(name, value);
  4081. }
  4082. };
  4083. XHRWrapper.prototype.getAllResponseHeaders = function () {
  4084. // XMLHttpRequest#getAllResponseHeaders returns null for CORS requests in Firefox 3.6.28
  4085. return this._xhr.getAllResponseHeaders != undefined ? this._xhr.getAllResponseHeaders() || "" : "";
  4086. };
  4087. XHRWrapper.prototype.send = function () {
  4088. // loading indicator in Safari < ? (6), Chrome < 14, Firefox
  4089. // https://bugzilla.mozilla.org/show_bug.cgi?id=736723
  4090. if ((!("ontimeout" in XMLHttpRequest.prototype) || (!("sendAsBinary" in XMLHttpRequest.prototype) && !("mozAnon" in XMLHttpRequest.prototype))) &&
  4091. document != undefined &&
  4092. document.readyState != undefined &&
  4093. document.readyState !== "complete") {
  4094. var that = this;
  4095. that._sendTimeout = setTimeout(function () {
  4096. that._sendTimeout = 0;
  4097. that.send();
  4098. }, 4);
  4099. return;
  4100. }
  4101. var xhr = this._xhr;
  4102. // withCredentials should be set after "open" for Safari and Chrome (< 19 ?)
  4103. if ("withCredentials" in xhr) {
  4104. xhr.withCredentials = this.withCredentials;
  4105. }
  4106. try {
  4107. // xhr.send(); throws "Not enough arguments" in Firefox 3.0
  4108. xhr.send(undefined);
  4109. } catch (error1) {
  4110. // Safari 5.1.7, Opera 12
  4111. throw error1;
  4112. }
  4113. };
  4114. function toLowerCase(name) {
  4115. return name.replace(/[A-Z]/g, function (c) {
  4116. return String.fromCharCode(c.charCodeAt(0) + 0x20);
  4117. });
  4118. }
  4119. function HeadersPolyfill(all) {
  4120. // Get headers: implemented according to mozilla's example code: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#Example
  4121. var map = Object.create(null);
  4122. var array = all.split("\r\n");
  4123. for (var i = 0; i < array.length; i += 1) {
  4124. var line = array[i];
  4125. var parts = line.split(": ");
  4126. var name = parts.shift();
  4127. var value = parts.join(": ");
  4128. map[toLowerCase(name)] = value;
  4129. }
  4130. this._map = map;
  4131. }
  4132. HeadersPolyfill.prototype.get = function (name) {
  4133. return this._map[toLowerCase(name)];
  4134. };
  4135. if (XMLHttpRequest != null && XMLHttpRequest.HEADERS_RECEIVED == null) { // IE < 9, Firefox 3.6
  4136. XMLHttpRequest.HEADERS_RECEIVED = 2;
  4137. }
  4138. function XHRTransport() {
  4139. }
  4140. XHRTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
  4141. xhr.open("GET", url);
  4142. var offset = 0;
  4143. xhr.onprogress = function () {
  4144. var responseText = xhr.responseText;
  4145. var chunk = responseText.slice(offset);
  4146. offset += chunk.length;
  4147. onProgressCallback(chunk);
  4148. };
  4149. xhr.onerror = function (event) {
  4150. event.preventDefault();
  4151. onFinishCallback(new Error("NetworkError"));
  4152. };
  4153. xhr.onload = function () {
  4154. onFinishCallback(null);
  4155. };
  4156. xhr.onabort = function () {
  4157. onFinishCallback(null);
  4158. };
  4159. xhr.onreadystatechange = function () {
  4160. if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
  4161. var status = xhr.status;
  4162. var statusText = xhr.statusText;
  4163. var contentType = xhr.getResponseHeader("Content-Type");
  4164. var headers = xhr.getAllResponseHeaders();
  4165. onStartCallback(status, statusText, contentType, new HeadersPolyfill(headers));
  4166. }
  4167. };
  4168. xhr.withCredentials = withCredentials;
  4169. for (var name in headers) {
  4170. if (Object.prototype.hasOwnProperty.call(headers, name)) {
  4171. xhr.setRequestHeader(name, headers[name]);
  4172. }
  4173. }
  4174. xhr.send();
  4175. return xhr;
  4176. };
  4177. function HeadersWrapper(headers) {
  4178. this._headers = headers;
  4179. }
  4180. HeadersWrapper.prototype.get = function (name) {
  4181. return this._headers.get(name);
  4182. };
  4183. function FetchTransport() {
  4184. }
  4185. FetchTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
  4186. var reader = null;
  4187. var controller = new AbortController();
  4188. var signal = controller.signal;
  4189. var textDecoder = new TextDecoder();
  4190. fetch(url, {
  4191. headers: headers,
  4192. credentials: withCredentials ? "include" : "same-origin",
  4193. signal: signal,
  4194. cache: "no-store"
  4195. }).then(function (response) {
  4196. reader = response.body.getReader();
  4197. onStartCallback(response.status, response.statusText, response.headers.get("Content-Type"), new HeadersWrapper(response.headers));
  4198. // see https://github.com/promises-aplus/promises-spec/issues/179
  4199. return new Promise(function (resolve, reject) {
  4200. var readNextChunk = function () {
  4201. reader.read().then(function (result) {
  4202. if (result.done) {
  4203. //Note: bytes in textDecoder are ignored
  4204. resolve(undefined);
  4205. } else {
  4206. var chunk = textDecoder.decode(result.value, {stream: true});
  4207. onProgressCallback(chunk);
  4208. readNextChunk();
  4209. }
  4210. })["catch"](function (error) {
  4211. reject(error);
  4212. });
  4213. };
  4214. readNextChunk();
  4215. });
  4216. })["catch"](function (error) {
  4217. if (error.name === "AbortError") {
  4218. return undefined;
  4219. } else {
  4220. return error;
  4221. }
  4222. }).then(function (error) {
  4223. onFinishCallback(error);
  4224. });
  4225. return {
  4226. abort: function () {
  4227. if (reader != null) {
  4228. reader.cancel(); // https://bugzilla.mozilla.org/show_bug.cgi?id=1583815
  4229. }
  4230. controller.abort();
  4231. }
  4232. };
  4233. };
  4234. function EventTarget() {
  4235. this._listeners = Object.create(null);
  4236. }
  4237. function throwError(e) {
  4238. setTimeout(function () {
  4239. throw e;
  4240. }, 0);
  4241. }
  4242. EventTarget.prototype.dispatchEvent = function (event) {
  4243. event.target = this;
  4244. var typeListeners = this._listeners[event.type];
  4245. if (typeListeners != undefined) {
  4246. var length = typeListeners.length;
  4247. for (var i = 0; i < length; i += 1) {
  4248. var listener = typeListeners[i];
  4249. try {
  4250. if (typeof listener.handleEvent === "function") {
  4251. listener.handleEvent(event);
  4252. } else {
  4253. listener.call(this, event);
  4254. }
  4255. } catch (e) {
  4256. throwError(e);
  4257. }
  4258. }
  4259. }
  4260. };
  4261. EventTarget.prototype.addEventListener = function (type, listener) {
  4262. type = String(type);
  4263. var listeners = this._listeners;
  4264. var typeListeners = listeners[type];
  4265. if (typeListeners == undefined) {
  4266. typeListeners = [];
  4267. listeners[type] = typeListeners;
  4268. }
  4269. var found = false;
  4270. for (var i = 0; i < typeListeners.length; i += 1) {
  4271. if (typeListeners[i] === listener) {
  4272. found = true;
  4273. }
  4274. }
  4275. if (!found) {
  4276. typeListeners.push(listener);
  4277. }
  4278. };
  4279. EventTarget.prototype.removeEventListener = function (type, listener) {
  4280. type = String(type);
  4281. var listeners = this._listeners;
  4282. var typeListeners = listeners[type];
  4283. if (typeListeners != undefined) {
  4284. var filtered = [];
  4285. for (var i = 0; i < typeListeners.length; i += 1) {
  4286. if (typeListeners[i] !== listener) {
  4287. filtered.push(typeListeners[i]);
  4288. }
  4289. }
  4290. if (filtered.length === 0) {
  4291. delete listeners[type];
  4292. } else {
  4293. listeners[type] = filtered;
  4294. }
  4295. }
  4296. };
  4297. function Event(type) {
  4298. this.type = type;
  4299. this.target = undefined;
  4300. }
  4301. function MessageEvent(type, options) {
  4302. Event.call(this, type);
  4303. this.data = options.data;
  4304. this.lastEventId = options.lastEventId;
  4305. }
  4306. MessageEvent.prototype = Object.create(Event.prototype);
  4307. function ConnectionEvent(type, options) {
  4308. Event.call(this, type);
  4309. this.status = options.status;
  4310. this.statusText = options.statusText;
  4311. this.headers = options.headers;
  4312. }
  4313. ConnectionEvent.prototype = Object.create(Event.prototype);
  4314. function ErrorEvent(type, options) {
  4315. Event.call(this, type);
  4316. this.error = options.error;
  4317. }
  4318. ErrorEvent.prototype = Object.create(Event.prototype);
  4319. var WAITING = -1;
  4320. var CONNECTING = 0;
  4321. var OPEN = 1;
  4322. var CLOSED = 2;
  4323. var AFTER_CR = -1;
  4324. var FIELD_START = 0;
  4325. var FIELD = 1;
  4326. var VALUE_START = 2;
  4327. var VALUE = 3;
  4328. var contentTypeRegExp = /^text\/event\-stream(;.*)?$/i;
  4329. var MINIMUM_DURATION = 1000;
  4330. var MAXIMUM_DURATION = 18000000;
  4331. var parseDuration = function (value, def) {
  4332. var n = value == null ? def : parseInt(value, 10);
  4333. if (n !== n) {
  4334. n = def;
  4335. }
  4336. return clampDuration(n);
  4337. };
  4338. var clampDuration = function (n) {
  4339. return Math.min(Math.max(n, MINIMUM_DURATION), MAXIMUM_DURATION);
  4340. };
  4341. var fire = function (that, f, event) {
  4342. try {
  4343. if (typeof f === "function") {
  4344. f.call(that, event);
  4345. }
  4346. } catch (e) {
  4347. throwError(e);
  4348. }
  4349. };
  4350. function EventSourcePolyfill(url, options) {
  4351. EventTarget.call(this);
  4352. options = options || {};
  4353. this.onopen = undefined;
  4354. this.onmessage = undefined;
  4355. this.onerror = undefined;
  4356. this.url = undefined;
  4357. this.readyState = undefined;
  4358. this.withCredentials = undefined;
  4359. this.headers = undefined;
  4360. this._close = undefined;
  4361. start(this, url, options);
  4362. }
  4363. function getBestXHRTransport() {
  4364. return (XMLHttpRequest != undefined && ("withCredentials" in XMLHttpRequest.prototype)) || XDomainRequest == undefined
  4365. ? new XMLHttpRequest()
  4366. : new XDomainRequest();
  4367. }
  4368. var isFetchSupported = fetch != undefined && Response != undefined && "body" in Response.prototype;
  4369. function start(es, url, options) {
  4370. url = String(url);
  4371. var withCredentials = Boolean(options.withCredentials);
  4372. var lastEventIdQueryParameterName = options.lastEventIdQueryParameterName || "lastEventId";
  4373. var initialRetry = clampDuration(1000);
  4374. var heartbeatTimeout = parseDuration(options.heartbeatTimeout, 45000);
  4375. var lastEventId = "";
  4376. var retry = initialRetry;
  4377. var wasActivity = false;
  4378. var textLength = 0;
  4379. var headers = options.headers || {};
  4380. var TransportOption = options.Transport;
  4381. var xhr = isFetchSupported && TransportOption == undefined ? undefined : new XHRWrapper(TransportOption != undefined ? new TransportOption() : getBestXHRTransport());
  4382. var transport = TransportOption != null && typeof TransportOption !== "string" ? new TransportOption() : (xhr == undefined ? new FetchTransport() : new XHRTransport());
  4383. var abortController = undefined;
  4384. var timeout = 0;
  4385. var currentState = WAITING;
  4386. var dataBuffer = "";
  4387. var lastEventIdBuffer = "";
  4388. var eventTypeBuffer = "";
  4389. var textBuffer = "";
  4390. var state = FIELD_START;
  4391. var fieldStart = 0;
  4392. var valueStart = 0;
  4393. var onStart = function (status, statusText, contentType, headers) {
  4394. if (currentState === CONNECTING) {
  4395. if (status === 200 && contentType != undefined && contentTypeRegExp.test(contentType)) {
  4396. currentState = OPEN;
  4397. wasActivity = Date.now();
  4398. retry = initialRetry;
  4399. es.readyState = OPEN;
  4400. var event = new ConnectionEvent("open", {
  4401. status: status,
  4402. statusText: statusText,
  4403. headers: headers
  4404. });
  4405. es.dispatchEvent(event);
  4406. fire(es, es.onopen, event);
  4407. } else {
  4408. var message = "";
  4409. if (status !== 200) {
  4410. if (statusText) {
  4411. statusText = statusText.replace(/\s+/g, " ");
  4412. }
  4413. message = "EventSource's response has a status " + status + " " + statusText + " that is not 200. Aborting the connection.";
  4414. } else {
  4415. message = "EventSource's response has a Content-Type specifying an unsupported type: " + (contentType == undefined ? "-" : contentType.replace(/\s+/g, " ")) + ". Aborting the connection.";
  4416. }
  4417. close();
  4418. var event = new ConnectionEvent("error", {
  4419. status: status,
  4420. statusText: statusText,
  4421. headers: headers
  4422. });
  4423. es.dispatchEvent(event);
  4424. fire(es, es.onerror, event);
  4425. console.error(message);
  4426. }
  4427. }
  4428. };
  4429. var onProgress = function (textChunk) {
  4430. if (currentState === OPEN) {
  4431. var n = -1;
  4432. for (var i = 0; i < textChunk.length; i += 1) {
  4433. var c = textChunk.charCodeAt(i);
  4434. if (c === "\n".charCodeAt(0) || c === "\r".charCodeAt(0)) {
  4435. n = i;
  4436. }
  4437. }
  4438. var chunk = (n !== -1 ? textBuffer : "") + textChunk.slice(0, n + 1);
  4439. textBuffer = (n === -1 ? textBuffer : "") + textChunk.slice(n + 1);
  4440. if (textChunk !== "") {
  4441. wasActivity = Date.now();
  4442. textLength += textChunk.length;
  4443. }
  4444. for (var position = 0; position < chunk.length; position += 1) {
  4445. var c = chunk.charCodeAt(position);
  4446. if (state === AFTER_CR && c === "\n".charCodeAt(0)) {
  4447. state = FIELD_START;
  4448. } else {
  4449. if (state === AFTER_CR) {
  4450. state = FIELD_START;
  4451. }
  4452. if (c === "\r".charCodeAt(0) || c === "\n".charCodeAt(0)) {
  4453. if (state !== FIELD_START) {
  4454. if (state === FIELD) {
  4455. valueStart = position + 1;
  4456. }
  4457. var field = chunk.slice(fieldStart, valueStart - 1);
  4458. var value = chunk.slice(valueStart + (valueStart < position && chunk.charCodeAt(valueStart) === " ".charCodeAt(0) ? 1 : 0), position);
  4459. if (field === "data") {
  4460. dataBuffer += "\n";
  4461. dataBuffer += value;
  4462. } else if (field === "id") {
  4463. lastEventIdBuffer = value;
  4464. } else if (field === "event") {
  4465. eventTypeBuffer = value;
  4466. } else if (field === "retry") {
  4467. initialRetry = parseDuration(value, initialRetry);
  4468. retry = initialRetry;
  4469. } else if (field === "heartbeatTimeout") {
  4470. heartbeatTimeout = parseDuration(value, heartbeatTimeout);
  4471. if (timeout !== 0) {
  4472. clearTimeout(timeout);
  4473. timeout = setTimeout(function () {
  4474. onTimeout();
  4475. }, heartbeatTimeout);
  4476. }
  4477. }
  4478. }
  4479. if (state === FIELD_START) {
  4480. if (dataBuffer !== "") {
  4481. lastEventId = lastEventIdBuffer;
  4482. if (eventTypeBuffer === "") {
  4483. eventTypeBuffer = "message";
  4484. }
  4485. var event = new MessageEvent(eventTypeBuffer, {
  4486. data: dataBuffer.slice(1),
  4487. lastEventId: lastEventIdBuffer
  4488. });
  4489. es.dispatchEvent(event);
  4490. if (eventTypeBuffer === "open") {
  4491. fire(es, es.onopen, event);
  4492. } else if (eventTypeBuffer === "message") {
  4493. fire(es, es.onmessage, event);
  4494. } else if (eventTypeBuffer === "error") {
  4495. fire(es, es.onerror, event);
  4496. }
  4497. if (currentState === CLOSED) {
  4498. return;
  4499. }
  4500. }
  4501. dataBuffer = "";
  4502. eventTypeBuffer = "";
  4503. }
  4504. state = c === "\r".charCodeAt(0) ? AFTER_CR : FIELD_START;
  4505. } else {
  4506. if (state === FIELD_START) {
  4507. fieldStart = position;
  4508. state = FIELD;
  4509. }
  4510. if (state === FIELD) {
  4511. if (c === ":".charCodeAt(0)) {
  4512. valueStart = position + 1;
  4513. state = VALUE_START;
  4514. }
  4515. } else if (state === VALUE_START) {
  4516. state = VALUE;
  4517. }
  4518. }
  4519. }
  4520. }
  4521. }
  4522. };
  4523. var onFinish = function (error) {
  4524. if (currentState === OPEN || currentState === CONNECTING) {
  4525. currentState = WAITING;
  4526. if (timeout !== 0) {
  4527. clearTimeout(timeout);
  4528. timeout = 0;
  4529. }
  4530. timeout = setTimeout(function () {
  4531. onTimeout();
  4532. }, retry);
  4533. retry = clampDuration(Math.min(initialRetry * 16, retry * 2));
  4534. es.readyState = CONNECTING;
  4535. var event = new ErrorEvent("error", {error: error});
  4536. es.dispatchEvent(event);
  4537. fire(es, es.onerror, event);
  4538. if (error != undefined) {
  4539. console.error(error);
  4540. }
  4541. }
  4542. };
  4543. var close = function () {
  4544. currentState = CLOSED;
  4545. if (abortController != undefined) {
  4546. abortController.abort();
  4547. abortController = undefined;
  4548. }
  4549. if (timeout !== 0) {
  4550. clearTimeout(timeout);
  4551. timeout = 0;
  4552. }
  4553. es.readyState = CLOSED;
  4554. };
  4555. var onTimeout = function () {
  4556. timeout = 0;
  4557. if (currentState !== WAITING) {
  4558. if (!wasActivity && abortController != undefined) {
  4559. onFinish(new Error("No activity within " + heartbeatTimeout + " milliseconds." + " " + (currentState === CONNECTING ? "No response received." : textLength + " chars received.") + " " + "Reconnecting."));
  4560. if (abortController != undefined) {
  4561. abortController.abort();
  4562. abortController = undefined;
  4563. }
  4564. } else {
  4565. var nextHeartbeat = Math.max((wasActivity || Date.now()) + heartbeatTimeout - Date.now(), 1);
  4566. wasActivity = false;
  4567. timeout = setTimeout(function () {
  4568. onTimeout();
  4569. }, nextHeartbeat);
  4570. }
  4571. return;
  4572. }
  4573. wasActivity = false;
  4574. textLength = 0;
  4575. timeout = setTimeout(function () {
  4576. onTimeout();
  4577. }, heartbeatTimeout);
  4578. currentState = CONNECTING;
  4579. dataBuffer = "";
  4580. eventTypeBuffer = "";
  4581. lastEventIdBuffer = lastEventId;
  4582. textBuffer = "";
  4583. fieldStart = 0;
  4584. valueStart = 0;
  4585. state = FIELD_START;
  4586. // https://bugzilla.mozilla.org/show_bug.cgi?id=428916
  4587. // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
  4588. var requestURL = url;
  4589. if (url.slice(0, 5) !== "data:" && url.slice(0, 5) !== "blob:") {
  4590. if (lastEventId !== "") {
  4591. // Remove the lastEventId parameter if it's already part of the request URL.
  4592. var i = url.indexOf("?");
  4593. requestURL = i === -1 ? url : url.slice(0, i + 1) + url.slice(i + 1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g, function (p, paramName) {
  4594. return paramName === lastEventIdQueryParameterName ? '' : p;
  4595. });
  4596. // Append the current lastEventId to the request URL.
  4597. requestURL += (url.indexOf("?") === -1 ? "?" : "&") + lastEventIdQueryParameterName +"=" + encodeURIComponent(lastEventId);
  4598. }
  4599. }
  4600. var withCredentials = es.withCredentials;
  4601. var requestHeaders = {};
  4602. requestHeaders["Accept"] = "text/event-stream";
  4603. var headers = es.headers;
  4604. if (headers != undefined) {
  4605. for (var name in headers) {
  4606. if (Object.prototype.hasOwnProperty.call(headers, name)) {
  4607. requestHeaders[name] = headers[name];
  4608. }
  4609. }
  4610. }
  4611. try {
  4612. abortController = transport.open(xhr, onStart, onProgress, onFinish, requestURL, withCredentials, requestHeaders);
  4613. } catch (error) {
  4614. close();
  4615. throw error;
  4616. }
  4617. };
  4618. es.url = url;
  4619. es.readyState = CONNECTING;
  4620. es.withCredentials = withCredentials;
  4621. es.headers = headers;
  4622. es._close = close;
  4623. onTimeout();
  4624. }
  4625. EventSourcePolyfill.prototype = Object.create(EventTarget.prototype);
  4626. EventSourcePolyfill.prototype.CONNECTING = CONNECTING;
  4627. EventSourcePolyfill.prototype.OPEN = OPEN;
  4628. EventSourcePolyfill.prototype.CLOSED = CLOSED;
  4629. EventSourcePolyfill.prototype.close = function () {
  4630. this._close();
  4631. };
  4632. EventSourcePolyfill.CONNECTING = CONNECTING;
  4633. EventSourcePolyfill.OPEN = OPEN;
  4634. EventSourcePolyfill.CLOSED = CLOSED;
  4635. EventSourcePolyfill.prototype.withCredentials = undefined;
  4636. var R = NativeEventSource;
  4637. if (XMLHttpRequest != undefined && (NativeEventSource == undefined || !("withCredentials" in NativeEventSource.prototype))) {
  4638. // Why replace a native EventSource ?
  4639. // https://bugzilla.mozilla.org/show_bug.cgi?id=444328
  4640. // https://bugzilla.mozilla.org/show_bug.cgi?id=831392
  4641. // https://code.google.com/p/chromium/issues/detail?id=260144
  4642. // https://code.google.com/p/chromium/issues/detail?id=225654
  4643. // ...
  4644. R = EventSourcePolyfill;
  4645. }
  4646. (function (factory) {
  4647. {
  4648. var v = factory(exports);
  4649. if (v !== undefined) module.exports = v;
  4650. }
  4651. })(function (exports) {
  4652. exports.EventSourcePolyfill = EventSourcePolyfill;
  4653. exports.NativeEventSource = NativeEventSource;
  4654. exports.EventSource = R;
  4655. });
  4656. }(typeof globalThis === 'undefined' ? (typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal) : globalThis));
  4657. } (eventsource, eventsourceExports));
  4658. var browser = eventsourceExports.EventSourcePolyfill;
  4659. var browser$1 = /*#__PURE__*/_mergeNamespaces({
  4660. __proto__: null,
  4661. default: browser
  4662. }, [browser]);
  4663. exports.BasePatch = BasePatch;
  4664. exports.BaseTransaction = BaseTransaction;
  4665. exports.ClientError = ClientError;
  4666. exports.ObservablePatch = ObservablePatch;
  4667. exports.ObservableSanityClient = ObservableSanityClient;
  4668. exports.ObservableTransaction = ObservableTransaction;
  4669. exports.Patch = Patch;
  4670. exports.SanityClient = SanityClient;
  4671. exports.ServerError = ServerError;
  4672. exports.Transaction = Transaction;
  4673. exports.createClient = createClient;
  4674. exports.default = deprecatedCreateClient;
  4675. exports.requester = requester;
  4676. exports.unstable__adapter = adapter;
  4677. exports.unstable__environment = environment;
  4678. Object.defineProperty(exports, '__esModule', { value: true });
  4679. }));