12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.SanityClient = {}));
- })(this, (function (exports) { 'use strict';
- function _mergeNamespaces(n, m) {
- m.forEach(function (e) {
- e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
- if (k !== 'default' && !(k in n)) {
- var d = Object.getOwnPropertyDescriptor(e, k);
- Object.defineProperty(n, k, d.get ? d : {
- enumerable: true,
- get: function () { return e[k]; }
- });
- }
- });
- });
- return Object.freeze(n);
- }
- const isReactNative = typeof navigator === "undefined" ? false : navigator.product === "ReactNative";
- const defaultOptions$1 = {
- timeout: isReactNative ? 6e4 : 12e4
- };
- function processOptions(opts) {
- const options = typeof opts === "string" ? Object.assign({
- url: opts
- }, defaultOptions$1) : Object.assign({}, defaultOptions$1, opts);
- const url = new URL(options.url, "http://localhost");
- options.timeout = normalizeTimeout(options.timeout);
- if (options.query) {
- for (const [key, value] of Object.entries(options.query)) {
- if (value !== void 0) {
- if (Array.isArray(value)) {
- for (const v of value) {
- url.searchParams.append(key, v);
- }
- } else {
- url.searchParams.append(key, value);
- }
- }
- }
- }
- options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase();
- options.url = url.origin === "http://localhost" ? "".concat(url.pathname, "?").concat(url.searchParams) : url.toString();
- return options;
- }
- function normalizeTimeout(time) {
- if (time === false || time === 0) {
- return false;
- }
- if (time.connect || time.socket) {
- return time;
- }
- const delay = Number(time);
- if (isNaN(delay)) {
- return normalizeTimeout(defaultOptions$1.timeout);
- }
- return {
- connect: delay,
- socket: delay
- };
- }
- const validUrl = /^https?:\/\//i;
- function validateOptions(options) {
- if (!validUrl.test(options.url)) {
- throw new Error("\"".concat(options.url, "\" is not a valid URL"));
- }
- }
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
- var trim = function(string) {
- return string.replace(/^\s+|\s+$/g, '');
- }
- , isArray = function(arg) {
- return Object.prototype.toString.call(arg) === '[object Array]';
- };
- var parseHeaders = function (headers) {
- if (!headers)
- return {}
- var result = {};
- var headersArr = trim(headers).split('\n');
- for (var i = 0; i < headersArr.length; i++) {
- var row = headersArr[i];
- var index = row.indexOf(':')
- , key = trim(row.slice(0, index)).toLowerCase()
- , value = trim(row.slice(index + 1));
- if (typeof(result[key]) === 'undefined') {
- result[key] = value;
- } else if (isArray(result[key])) {
- result[key].push(value);
- } else {
- result[key] = [ result[key], value ];
- }
- }
- return result
- };
- var middlewareReducer = middleware => {
- const applyMiddleware = function (hook, defaultValue) {
- const bailEarly = hook === "onError";
- let value = defaultValue;
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
- args[_key - 2] = arguments[_key];
- }
- for (let i = 0; i < middleware[hook].length; i++) {
- const handler = middleware[hook][i];
- value = handler(value, ...args);
- if (bailEarly && !value) {
- break;
- }
- }
- return value;
- };
- return applyMiddleware;
- };
- function createPubSub() {
- const subscribers = /* @__PURE__ */Object.create(null);
- let nextId = 0;
- function subscribe(subscriber) {
- const id = nextId++;
- subscribers[id] = subscriber;
- return function unsubscribe() {
- delete subscribers[id];
- };
- }
- function publish(event) {
- for (const id in subscribers) {
- subscribers[id](event);
- }
- }
- return {
- publish,
- subscribe
- };
- }
- const channelNames = ["request", "response", "progress", "error", "abort"];
- const middlehooks = ["processOptions", "validateOptions", "interceptRequest", "finalizeOptions", "onRequest", "onResponse", "onError", "onReturn", "onHeaders"];
- function createRequester(initMiddleware, httpRequest) {
- const loadedMiddleware = [];
- const middleware = middlehooks.reduce((ware, name) => {
- ware[name] = ware[name] || [];
- return ware;
- }, {
- processOptions: [processOptions],
- validateOptions: [validateOptions]
- });
- function request(opts) {
- const channels = channelNames.reduce((target, name) => {
- target[name] = createPubSub();
- return target;
- }, {});
- const applyMiddleware = middlewareReducer(middleware);
- const options = applyMiddleware("processOptions", opts);
- applyMiddleware("validateOptions", options);
- const context = {
- options,
- channels,
- applyMiddleware
- };
- let ongoingRequest = null;
- const unsubscribe = channels.request.subscribe(ctx => {
- ongoingRequest = httpRequest(ctx, (err, res) => onResponse(err, res, ctx));
- });
- channels.abort.subscribe(() => {
- unsubscribe();
- if (ongoingRequest) {
- ongoingRequest.abort();
- }
- });
- const returnValue = applyMiddleware("onReturn", channels, context);
- if (returnValue === channels) {
- channels.request.publish(context);
- }
- return returnValue;
- function onResponse(reqErr, res, ctx) {
- let error = reqErr;
- let response = res;
- if (!error) {
- try {
- response = applyMiddleware("onResponse", res, ctx);
- } catch (err) {
- response = null;
- error = err;
- }
- }
- error = error && applyMiddleware("onError", error, ctx);
- if (error) {
- channels.error.publish(error);
- } else if (response) {
- channels.response.publish(response);
- }
- }
- }
- request.use = function use(newMiddleware) {
- if (!newMiddleware) {
- throw new Error("Tried to add middleware that resolved to falsey value");
- }
- if (typeof newMiddleware === "function") {
- throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");
- }
- if (newMiddleware.onReturn && middleware.onReturn.length > 0) {
- throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");
- }
- middlehooks.forEach(key => {
- if (newMiddleware[key]) {
- middleware[key].push(newMiddleware[key]);
- }
- });
- loadedMiddleware.push(newMiddleware);
- return request;
- };
- request.clone = function clone() {
- return createRequester(loadedMiddleware, httpRequest);
- };
- initMiddleware.forEach(request.use);
- return request;
- }
- var __accessCheck$7 = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet$7 = (obj, member, getter) => {
- __accessCheck$7(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd$7 = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet$7 = (obj, member, value, setter) => {
- __accessCheck$7(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _method, _url, _resHeaders, _headers, _controller;
- class FetchXhr {
- constructor() {
- /**
- * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
- */
- this.readyState = 0;
- this.responseType = "";
- /**
- * Private implementation details
- */
- __privateAdd$7(this, _method, void 0);
- __privateAdd$7(this, _url, void 0);
- __privateAdd$7(this, _resHeaders, void 0);
- __privateAdd$7(this, _headers, {});
- __privateAdd$7(this, _controller, void 0);
- }
- // eslint-disable-next-line @typescript-eslint/no-unused-vars -- _async is only declared for typings compatibility
- open(method, url, _async) {
- __privateSet$7(this, _method, method);
- __privateSet$7(this, _url, url);
- __privateSet$7(this, _resHeaders, "");
- this.readyState = 1;
- this.onreadystatechange();
- __privateSet$7(this, _controller, void 0);
- }
- abort() {
- if (__privateGet$7(this, _controller)) {
- __privateGet$7(this, _controller).abort();
- }
- }
- getAllResponseHeaders() {
- return __privateGet$7(this, _resHeaders);
- }
- setRequestHeader(name, value) {
- __privateGet$7(this, _headers)[name] = value;
- }
- send(body) {
- const textBody = this.responseType !== "arraybuffer";
- const options = {
- method: __privateGet$7(this, _method),
- headers: __privateGet$7(this, _headers),
- body
- };
- if (typeof AbortController === "function") {
- __privateSet$7(this, _controller, new AbortController());
- if (typeof EventTarget !== "undefined" && __privateGet$7(this, _controller).signal instanceof EventTarget) {
- options.signal = __privateGet$7(this, _controller).signal;
- }
- }
- if (typeof document !== "undefined") {
- options.credentials = this.withCredentials ? "include" : "omit";
- }
- fetch(__privateGet$7(this, _url), options).then(res => {
- res.headers.forEach((value, key) => {
- __privateSet$7(this, _resHeaders, __privateGet$7(this, _resHeaders) + "".concat(key, ": ").concat(value, "\r\n"));
- });
- this.status = res.status;
- this.statusText = res.statusText;
- this.readyState = 3;
- return textBody ? res.text() : res.arrayBuffer();
- }).then(resBody => {
- if (typeof resBody === "string") {
- this.responseText = resBody;
- } else {
- this.response = resBody;
- }
- this.readyState = 4;
- this.onreadystatechange();
- }).catch(err => {
- var _a;
- if (err.name === "AbortError") {
- this.onabort();
- return;
- }
- (_a = this.onerror) == null ? void 0 : _a.call(this, err);
- });
- }
- }
- _method = new WeakMap();
- _url = new WeakMap();
- _resHeaders = new WeakMap();
- _headers = new WeakMap();
- _controller = new WeakMap();
- const adapter = typeof XMLHttpRequest === "function" ? "xhr" : "fetch";
- const XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr;
- var httpRequester = (context, callback) => {
- const opts = context.options;
- const options = context.applyMiddleware("finalizeOptions", opts);
- const timers = {};
- const injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
- adapter,
- context
- });
- if (injectedResponse) {
- const cbTimer = setTimeout(callback, 0, null, injectedResponse);
- const cancel = () => clearTimeout(cbTimer);
- return {
- abort: cancel
- };
- }
- let xhr = new XmlHttpRequest();
- const headers = options.headers;
- const delays = options.timeout;
- let aborted = false;
- let loaded = false;
- let timedOut = false;
- xhr.onerror = onError;
- xhr.ontimeout = onError;
- xhr.onabort = () => {
- stopTimers(true);
- aborted = true;
- };
- xhr.onreadystatechange = () => {
- resetTimers();
- if (aborted || xhr.readyState !== 4) {
- return;
- }
- if (xhr.status === 0) {
- return;
- }
- onLoad();
- };
- xhr.open(options.method, options.url, true
- // Always async
- );
- xhr.withCredentials = !!options.withCredentials;
- if (headers && xhr.setRequestHeader) {
- for (const key in headers) {
- if (headers.hasOwnProperty(key)) {
- xhr.setRequestHeader(key, headers[key]);
- }
- }
- }
- if (options.rawBody) {
- xhr.responseType = "arraybuffer";
- }
- context.applyMiddleware("onRequest", {
- options,
- adapter,
- request: xhr,
- context
- });
- xhr.send(options.body || null);
- if (delays) {
- timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect);
- }
- return {
- abort
- };
- function abort() {
- aborted = true;
- if (xhr) {
- xhr.abort();
- }
- }
- function timeoutRequest(code) {
- timedOut = true;
- xhr.abort();
- const error = new Error(code === "ESOCKETTIMEDOUT" ? "Socket timed out on request to ".concat(options.url) : "Connection timed out on request to ".concat(options.url));
- error.code = code;
- context.channels.error.publish(error);
- }
- function resetTimers() {
- if (!delays) {
- return;
- }
- stopTimers();
- timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket);
- }
- function stopTimers(force) {
- if (force || aborted || xhr.readyState >= 2 && timers.connect) {
- clearTimeout(timers.connect);
- }
- if (timers.socket) {
- clearTimeout(timers.socket);
- }
- }
- function onError(error) {
- if (loaded) {
- return;
- }
- stopTimers(true);
- loaded = true;
- xhr = null;
- const err = error || new Error("Network error while attempting to reach ".concat(options.url));
- err.isNetworkError = true;
- err.request = options;
- callback(err);
- }
- function reduceResponse() {
- return {
- body: xhr.response || (xhr.responseType === "" || xhr.responseType === "text" ? xhr.responseText : ""),
- url: options.url,
- method: options.method,
- headers: parseHeaders(xhr.getAllResponseHeaders()),
- statusCode: xhr.status,
- statusMessage: xhr.statusText
- };
- }
- function onLoad() {
- if (aborted || loaded || timedOut) {
- return;
- }
- if (xhr.status === 0) {
- onError(new Error("Unknown XHR error"));
- return;
- }
- stopTimers();
- loaded = true;
- callback(null, reduceResponse());
- }
- };
- const getIt = function () {
- let initMiddleware = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
- let httpRequest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : httpRequester;
- return createRequester(initMiddleware, httpRequest);
- };
- const environment = "browser";
- var browserExports = {};
- var browser$2 = {
- get exports(){ return browserExports; },
- set exports(v){ browserExports = v; },
- };
- /**
- * Helpers.
- */
- var ms;
- var hasRequiredMs;
- function requireMs () {
- if (hasRequiredMs) return ms;
- hasRequiredMs = 1;
- var s = 1000;
- var m = s * 60;
- var h = m * 60;
- var d = h * 24;
- var w = d * 7;
- var y = d * 365.25;
- /**
- * Parse or format the given `val`.
- *
- * Options:
- *
- * - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} [options]
- * @throws {Error} throw an error if val is not a non-empty string or a number
- * @return {String|Number}
- * @api public
- */
- ms = function(val, options) {
- options = options || {};
- var type = typeof val;
- if (type === 'string' && val.length > 0) {
- return parse(val);
- } else if (type === 'number' && isFinite(val)) {
- return options.long ? fmtLong(val) : fmtShort(val);
- }
- throw new Error(
- 'val is not a non-empty string or a valid number. val=' +
- JSON.stringify(val)
- );
- };
- /**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
- function parse(str) {
- str = String(str);
- if (str.length > 100) {
- return;
- }
- 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(
- str
- );
- if (!match) {
- return;
- }
- var n = parseFloat(match[1]);
- var type = (match[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'yrs':
- case 'yr':
- case 'y':
- return n * y;
- case 'weeks':
- case 'week':
- case 'w':
- return n * w;
- case 'days':
- case 'day':
- case 'd':
- return n * d;
- case 'hours':
- case 'hour':
- case 'hrs':
- case 'hr':
- case 'h':
- return n * h;
- case 'minutes':
- case 'minute':
- case 'mins':
- case 'min':
- case 'm':
- return n * m;
- case 'seconds':
- case 'second':
- case 'secs':
- case 'sec':
- case 's':
- return n * s;
- case 'milliseconds':
- case 'millisecond':
- case 'msecs':
- case 'msec':
- case 'ms':
- return n;
- default:
- return undefined;
- }
- }
- /**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
- function fmtShort(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return Math.round(ms / d) + 'd';
- }
- if (msAbs >= h) {
- return Math.round(ms / h) + 'h';
- }
- if (msAbs >= m) {
- return Math.round(ms / m) + 'm';
- }
- if (msAbs >= s) {
- return Math.round(ms / s) + 's';
- }
- return ms + 'ms';
- }
- /**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
- function fmtLong(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return plural(ms, msAbs, d, 'day');
- }
- if (msAbs >= h) {
- return plural(ms, msAbs, h, 'hour');
- }
- if (msAbs >= m) {
- return plural(ms, msAbs, m, 'minute');
- }
- if (msAbs >= s) {
- return plural(ms, msAbs, s, 'second');
- }
- return ms + ' ms';
- }
- /**
- * Pluralization helper.
- */
- function plural(ms, msAbs, n, name) {
- var isPlural = msAbs >= n * 1.5;
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
- }
- return ms;
- }
- /**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
- */
- function setup(env) {
- createDebug.debug = createDebug;
- createDebug.default = createDebug;
- createDebug.coerce = coerce;
- createDebug.disable = disable;
- createDebug.enable = enable;
- createDebug.enabled = enabled;
- createDebug.humanize = requireMs();
- createDebug.destroy = destroy;
- Object.keys(env).forEach(key => {
- createDebug[key] = env[key];
- });
- /**
- * The currently active debug mode names, and names to skip.
- */
- createDebug.names = [];
- createDebug.skips = [];
- /**
- * Map of special "%n" handling functions, for the debug "format" argument.
- *
- * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
- */
- createDebug.formatters = {};
- /**
- * Selects a color for a debug namespace
- * @param {String} namespace The namespace string for the debug instance to be colored
- * @return {Number|String} An ANSI color code for the given namespace
- * @api private
- */
- function selectColor(namespace) {
- let hash = 0;
- for (let i = 0; i < namespace.length; i++) {
- hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
- hash |= 0; // Convert to 32bit integer
- }
- return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
- }
- createDebug.selectColor = selectColor;
- /**
- * Create a debugger with the given `namespace`.
- *
- * @param {String} namespace
- * @return {Function}
- * @api public
- */
- function createDebug(namespace) {
- let prevTime;
- let enableOverride = null;
- let namespacesCache;
- let enabledCache;
- function debug(...args) {
- // Disabled?
- if (!debug.enabled) {
- return;
- }
- const self = debug;
- // Set `diff` timestamp
- const curr = Number(new Date());
- const ms = curr - (prevTime || curr);
- self.diff = ms;
- self.prev = prevTime;
- self.curr = curr;
- prevTime = curr;
- args[0] = createDebug.coerce(args[0]);
- if (typeof args[0] !== 'string') {
- // Anything else let's inspect with %O
- args.unshift('%O');
- }
- // Apply any `formatters` transformations
- let index = 0;
- args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
- // If we encounter an escaped % then don't increase the array index
- if (match === '%%') {
- return '%';
- }
- index++;
- const formatter = createDebug.formatters[format];
- if (typeof formatter === 'function') {
- const val = args[index];
- match = formatter.call(self, val);
- // Now we need to remove `args[index]` since it's inlined in the `format`
- args.splice(index, 1);
- index--;
- }
- return match;
- });
- // Apply env-specific formatting (colors, etc.)
- createDebug.formatArgs.call(self, args);
- const logFn = self.log || createDebug.log;
- logFn.apply(self, args);
- }
- debug.namespace = namespace;
- debug.useColors = createDebug.useColors();
- debug.color = createDebug.selectColor(namespace);
- debug.extend = extend;
- debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
- Object.defineProperty(debug, 'enabled', {
- enumerable: true,
- configurable: false,
- get: () => {
- if (enableOverride !== null) {
- return enableOverride;
- }
- if (namespacesCache !== createDebug.namespaces) {
- namespacesCache = createDebug.namespaces;
- enabledCache = createDebug.enabled(namespace);
- }
- return enabledCache;
- },
- set: v => {
- enableOverride = v;
- }
- });
- // Env-specific initialization logic for debug instances
- if (typeof createDebug.init === 'function') {
- createDebug.init(debug);
- }
- return debug;
- }
- function extend(namespace, delimiter) {
- const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
- newDebug.log = this.log;
- return newDebug;
- }
- /**
- * Enables a debug mode by namespaces. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} namespaces
- * @api public
- */
- function enable(namespaces) {
- createDebug.save(namespaces);
- createDebug.namespaces = namespaces;
- createDebug.names = [];
- createDebug.skips = [];
- let i;
- const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
- const len = split.length;
- for (i = 0; i < len; i++) {
- if (!split[i]) {
- // ignore empty strings
- continue;
- }
- namespaces = split[i].replace(/\*/g, '.*?');
- if (namespaces[0] === '-') {
- createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
- } else {
- createDebug.names.push(new RegExp('^' + namespaces + '$'));
- }
- }
- }
- /**
- * Disable debug output.
- *
- * @return {String} namespaces
- * @api public
- */
- function disable() {
- const namespaces = [
- ...createDebug.names.map(toNamespace),
- ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
- ].join(',');
- createDebug.enable('');
- return namespaces;
- }
- /**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
- function enabled(name) {
- if (name[name.length - 1] === '*') {
- return true;
- }
- let i;
- let len;
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
- if (createDebug.skips[i].test(name)) {
- return false;
- }
- }
- for (i = 0, len = createDebug.names.length; i < len; i++) {
- if (createDebug.names[i].test(name)) {
- return true;
- }
- }
- return false;
- }
- /**
- * Convert regexp to namespace
- *
- * @param {RegExp} regxep
- * @return {String} namespace
- * @api private
- */
- function toNamespace(regexp) {
- return regexp.toString()
- .substring(2, regexp.toString().length - 2)
- .replace(/\.\*\?$/, '*');
- }
- /**
- * Coerce `val`.
- *
- * @param {Mixed} val
- * @return {Mixed}
- * @api private
- */
- function coerce(val) {
- if (val instanceof Error) {
- return val.stack || val.message;
- }
- return val;
- }
- /**
- * XXX DO NOT USE. This is a temporary stub function.
- * XXX It WILL be removed in the next major release.
- */
- function destroy() {
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
- }
- createDebug.enable(createDebug.load());
- return createDebug;
- }
- var common = setup;
- /* eslint-env browser */
- (function (module, exports) {
- /**
- * This is the web browser implementation of `debug()`.
- */
- exports.formatArgs = formatArgs;
- exports.save = save;
- exports.load = load;
- exports.useColors = useColors;
- exports.storage = localstorage();
- exports.destroy = (() => {
- let warned = false;
- return () => {
- if (!warned) {
- warned = true;
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
- }
- };
- })();
- /**
- * Colors.
- */
- exports.colors = [
- '#0000CC',
- '#0000FF',
- '#0033CC',
- '#0033FF',
- '#0066CC',
- '#0066FF',
- '#0099CC',
- '#0099FF',
- '#00CC00',
- '#00CC33',
- '#00CC66',
- '#00CC99',
- '#00CCCC',
- '#00CCFF',
- '#3300CC',
- '#3300FF',
- '#3333CC',
- '#3333FF',
- '#3366CC',
- '#3366FF',
- '#3399CC',
- '#3399FF',
- '#33CC00',
- '#33CC33',
- '#33CC66',
- '#33CC99',
- '#33CCCC',
- '#33CCFF',
- '#6600CC',
- '#6600FF',
- '#6633CC',
- '#6633FF',
- '#66CC00',
- '#66CC33',
- '#9900CC',
- '#9900FF',
- '#9933CC',
- '#9933FF',
- '#99CC00',
- '#99CC33',
- '#CC0000',
- '#CC0033',
- '#CC0066',
- '#CC0099',
- '#CC00CC',
- '#CC00FF',
- '#CC3300',
- '#CC3333',
- '#CC3366',
- '#CC3399',
- '#CC33CC',
- '#CC33FF',
- '#CC6600',
- '#CC6633',
- '#CC9900',
- '#CC9933',
- '#CCCC00',
- '#CCCC33',
- '#FF0000',
- '#FF0033',
- '#FF0066',
- '#FF0099',
- '#FF00CC',
- '#FF00FF',
- '#FF3300',
- '#FF3333',
- '#FF3366',
- '#FF3399',
- '#FF33CC',
- '#FF33FF',
- '#FF6600',
- '#FF6633',
- '#FF9900',
- '#FF9933',
- '#FFCC00',
- '#FFCC33'
- ];
- /**
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
- * and the Firebug extension (any Firefox version) are known
- * to support "%c" CSS customizations.
- *
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
- */
- // eslint-disable-next-line complexity
- function useColors() {
- // NB: In an Electron preload script, document will be defined but not fully
- // initialized. Since we know we're in Chrome, we'll just detect this case
- // explicitly
- if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
- return true;
- }
- // Internet Explorer and Edge do not support colors.
- if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
- return false;
- }
- // Is webkit? http://stackoverflow.com/a/16459606/376773
- // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
- return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
- // Is firebug? http://stackoverflow.com/a/398120/376773
- (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
- // Is firefox >= v31?
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
- // Double check webkit in userAgent just in case we are in a worker
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
- }
- /**
- * Colorize log arguments if enabled.
- *
- * @api public
- */
- function formatArgs(args) {
- args[0] = (this.useColors ? '%c' : '') +
- this.namespace +
- (this.useColors ? ' %c' : ' ') +
- args[0] +
- (this.useColors ? '%c ' : ' ') +
- '+' + module.exports.humanize(this.diff);
- if (!this.useColors) {
- return;
- }
- const c = 'color: ' + this.color;
- args.splice(1, 0, c, 'color: inherit');
- // The final "%c" is somewhat tricky, because there could be other
- // arguments passed either before or after the %c, so we need to
- // figure out the correct index to insert the CSS into
- let index = 0;
- let lastC = 0;
- args[0].replace(/%[a-zA-Z%]/g, match => {
- if (match === '%%') {
- return;
- }
- index++;
- if (match === '%c') {
- // We only are interested in the *last* %c
- // (the user may have provided their own)
- lastC = index;
- }
- });
- args.splice(lastC, 0, c);
- }
- /**
- * Invokes `console.debug()` when available.
- * No-op when `console.debug` is not a "function".
- * If `console.debug` is not available, falls back
- * to `console.log`.
- *
- * @api public
- */
- exports.log = console.debug || console.log || (() => {});
- /**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
- function save(namespaces) {
- try {
- if (namespaces) {
- exports.storage.setItem('debug', namespaces);
- } else {
- exports.storage.removeItem('debug');
- }
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
- }
- /**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
- function load() {
- let r;
- try {
- r = exports.storage.getItem('debug');
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
- // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
- if (!r && typeof process !== 'undefined' && 'env' in process) {
- r = process.env.DEBUG;
- }
- return r;
- }
- /**
- * Localstorage attempts to return the localstorage.
- *
- * This is necessary because safari throws
- * when a user disables cookies/localstorage
- * and you attempt to access it.
- *
- * @return {LocalStorage}
- * @api private
- */
- function localstorage() {
- try {
- // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
- // The Browser also has localStorage in the global context.
- return localStorage;
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
- }
- module.exports = common(exports);
- const {formatters} = module.exports;
- /**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
- */
- formatters.j = function (v) {
- try {
- return JSON.stringify(v);
- } catch (error) {
- return '[UnexpectedJSONParseError]: ' + error.message;
- }
- };
- } (browser$2, browserExports));
- /*!
- * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
- *
- * Copyright (c) 2014-2017, Jon Schlinkert.
- * Released under the MIT License.
- */
- function isObject(o) {
- return Object.prototype.toString.call(o) === '[object Object]';
- }
- function isPlainObject$1(o) {
- var ctor,prot;
- if (isObject(o) === false) return false;
- // If has modified constructor
- ctor = o.constructor;
- if (ctor === undefined) return true;
- // If has modified prototype
- prot = ctor.prototype;
- if (isObject(prot) === false) return false;
- // If constructor does not have an Object-specific method
- if (prot.hasOwnProperty('isPrototypeOf') === false) {
- return false;
- }
- // Most likely a plain Object
- return true;
- }
- const isBuffer = typeof Buffer === "undefined" ? () => false : obj => Buffer.isBuffer(obj);
- const serializeTypes = ["boolean", "string", "number"];
- function jsonRequest() {
- return {
- processOptions: options => {
- const body = options.body;
- if (!body) {
- return options;
- }
- const isStream = typeof body.pipe === "function";
- const shouldSerialize = !isStream && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject$1(body));
- if (!shouldSerialize) {
- return options;
- }
- return Object.assign({}, options, {
- body: JSON.stringify(options.body),
- headers: Object.assign({}, options.headers, {
- "Content-Type": "application/json"
- })
- });
- }
- };
- }
- function jsonResponse(opts) {
- return {
- onResponse: response => {
- const contentType = response.headers["content-type"] || "";
- const shouldDecode = opts && opts.force || contentType.indexOf("application/json") !== -1;
- if (!response.body || !contentType || !shouldDecode) {
- return response;
- }
- return Object.assign({}, response, {
- body: tryParse(response.body)
- });
- },
- processOptions: options => Object.assign({}, options, {
- headers: Object.assign({
- Accept: "application/json"
- }, options.headers)
- })
- };
- function tryParse(body) {
- try {
- return JSON.parse(body);
- } catch (err) {
- err.message = "Failed to parsed response body as JSON: ".concat(err.message);
- throw err;
- }
- }
- }
- let actualGlobal;
- if (typeof globalThis !== "undefined") {
- actualGlobal = globalThis;
- } else if (typeof window !== "undefined") {
- actualGlobal = window;
- } else if (typeof global !== "undefined") {
- actualGlobal = global;
- } else if (typeof self !== "undefined") {
- actualGlobal = self;
- } else {
- actualGlobal = {};
- }
- var global$1 = actualGlobal;
- function observable$1() {
- let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- const Observable = opts.implementation || global$1.Observable;
- if (!Observable) {
- throw new Error("`Observable` is not available in global scope, and no implementation was passed");
- }
- return {
- onReturn: (channels, context) => new Observable(observer => {
- channels.error.subscribe(err => observer.error(err));
- channels.progress.subscribe(event => observer.next(Object.assign({
- type: "progress"
- }, event)));
- channels.response.subscribe(response => {
- observer.next(Object.assign({
- type: "response"
- }, response));
- observer.complete();
- });
- channels.request.publish(context);
- return () => channels.abort.publish();
- })
- };
- }
- function progress() {
- return {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- onRequest: evt => {
- if (evt.adapter !== "xhr") {
- return;
- }
- const xhr = evt.request;
- const context = evt.context;
- if ("upload" in xhr && "onprogress" in xhr.upload) {
- xhr.upload.onprogress = handleProgress("upload");
- }
- if ("onprogress" in xhr) {
- xhr.onprogress = handleProgress("download");
- }
- function handleProgress(stage) {
- return event => {
- const percent = event.lengthComputable ? event.loaded / event.total * 100 : -1;
- context.channels.progress.publish({
- stage,
- percent,
- total: event.total,
- loaded: event.loaded,
- lengthComputable: event.lengthComputable
- });
- };
- }
- }
- };
- }
- class Cancel {
- constructor(message) {
- this.__CANCEL__ = true;
- this.message = message;
- }
- toString() {
- return "Cancel".concat(this.message ? ": ".concat(this.message) : "");
- }
- }
- const _CancelToken = class {
- constructor(executor) {
- if (typeof executor !== "function") {
- throw new TypeError("executor must be a function.");
- }
- let resolvePromise = null;
- this.promise = new Promise(resolve => {
- resolvePromise = resolve;
- });
- executor(message => {
- if (this.reason) {
- return;
- }
- this.reason = new Cancel(message);
- resolvePromise(this.reason);
- });
- }
- };
- let CancelToken = _CancelToken;
- CancelToken.source = () => {
- let cancel;
- const token = new _CancelToken(can => {
- cancel = can;
- });
- return {
- token,
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- we know from the implementation that it's assigned during `constructor`
- cancel
- };
- };
- /******************************************************************************
- Copyright (c) Microsoft Corporation.
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- /* global Reflect, Promise */
- var extendStatics = function(d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- function __extends(d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
- function __values(o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
- }
- function __read(o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
- }
- function __spreadArray(to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
- }
- function isFunction(value) {
- return typeof value === 'function';
- }
- function createErrorClass(createImpl) {
- var _super = function (instance) {
- Error.call(instance);
- instance.stack = new Error().stack;
- };
- var ctorFunc = createImpl(_super);
- ctorFunc.prototype = Object.create(Error.prototype);
- ctorFunc.prototype.constructor = ctorFunc;
- return ctorFunc;
- }
- var UnsubscriptionError = createErrorClass(function (_super) {
- return function UnsubscriptionErrorImpl(errors) {
- _super(this);
- this.message = errors
- ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
- : '';
- this.name = 'UnsubscriptionError';
- this.errors = errors;
- };
- });
- function arrRemove(arr, item) {
- if (arr) {
- var index = arr.indexOf(item);
- 0 <= index && arr.splice(index, 1);
- }
- }
- var Subscription = (function () {
- function Subscription(initialTeardown) {
- this.initialTeardown = initialTeardown;
- this.closed = false;
- this._parentage = null;
- this._finalizers = null;
- }
- Subscription.prototype.unsubscribe = function () {
- var e_1, _a, e_2, _b;
- var errors;
- if (!this.closed) {
- this.closed = true;
- var _parentage = this._parentage;
- if (_parentage) {
- this._parentage = null;
- if (Array.isArray(_parentage)) {
- try {
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
- var parent_1 = _parentage_1_1.value;
- parent_1.remove(this);
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
- }
- finally { if (e_1) throw e_1.error; }
- }
- }
- else {
- _parentage.remove(this);
- }
- }
- var initialFinalizer = this.initialTeardown;
- if (isFunction(initialFinalizer)) {
- try {
- initialFinalizer();
- }
- catch (e) {
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
- }
- }
- var _finalizers = this._finalizers;
- if (_finalizers) {
- this._finalizers = null;
- try {
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
- var finalizer = _finalizers_1_1.value;
- try {
- execFinalizer(finalizer);
- }
- catch (err) {
- errors = errors !== null && errors !== void 0 ? errors : [];
- if (err instanceof UnsubscriptionError) {
- errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
- }
- else {
- errors.push(err);
- }
- }
- }
- }
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
- finally {
- try {
- if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
- }
- finally { if (e_2) throw e_2.error; }
- }
- }
- if (errors) {
- throw new UnsubscriptionError(errors);
- }
- }
- };
- Subscription.prototype.add = function (teardown) {
- var _a;
- if (teardown && teardown !== this) {
- if (this.closed) {
- execFinalizer(teardown);
- }
- else {
- if (teardown instanceof Subscription) {
- if (teardown.closed || teardown._hasParent(this)) {
- return;
- }
- teardown._addParent(this);
- }
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
- }
- }
- };
- Subscription.prototype._hasParent = function (parent) {
- var _parentage = this._parentage;
- return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
- };
- Subscription.prototype._addParent = function (parent) {
- var _parentage = this._parentage;
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
- };
- Subscription.prototype._removeParent = function (parent) {
- var _parentage = this._parentage;
- if (_parentage === parent) {
- this._parentage = null;
- }
- else if (Array.isArray(_parentage)) {
- arrRemove(_parentage, parent);
- }
- };
- Subscription.prototype.remove = function (teardown) {
- var _finalizers = this._finalizers;
- _finalizers && arrRemove(_finalizers, teardown);
- if (teardown instanceof Subscription) {
- teardown._removeParent(this);
- }
- };
- Subscription.EMPTY = (function () {
- var empty = new Subscription();
- empty.closed = true;
- return empty;
- })();
- return Subscription;
- }());
- Subscription.EMPTY;
- function isSubscription(value) {
- return (value instanceof Subscription ||
- (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
- }
- function execFinalizer(finalizer) {
- if (isFunction(finalizer)) {
- finalizer();
- }
- else {
- finalizer.unsubscribe();
- }
- }
- var config = {
- onUnhandledError: null,
- onStoppedNotification: null,
- Promise: undefined,
- useDeprecatedSynchronousErrorHandling: false,
- useDeprecatedNextContext: false,
- };
- var timeoutProvider = {
- setTimeout: function (handler, timeout) {
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
- }
- var delegate = timeoutProvider.delegate;
- if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
- return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
- }
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
- },
- clearTimeout: function (handle) {
- var delegate = timeoutProvider.delegate;
- return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
- },
- delegate: undefined,
- };
- function reportUnhandledError(err) {
- timeoutProvider.setTimeout(function () {
- {
- throw err;
- }
- });
- }
- function noop() { }
- function errorContext(cb) {
- {
- cb();
- }
- }
- var Subscriber = (function (_super) {
- __extends(Subscriber, _super);
- function Subscriber(destination) {
- var _this = _super.call(this) || this;
- _this.isStopped = false;
- if (destination) {
- _this.destination = destination;
- if (isSubscription(destination)) {
- destination.add(_this);
- }
- }
- else {
- _this.destination = EMPTY_OBSERVER;
- }
- return _this;
- }
- Subscriber.create = function (next, error, complete) {
- return new SafeSubscriber(next, error, complete);
- };
- Subscriber.prototype.next = function (value) {
- if (this.isStopped) ;
- else {
- this._next(value);
- }
- };
- Subscriber.prototype.error = function (err) {
- if (this.isStopped) ;
- else {
- this.isStopped = true;
- this._error(err);
- }
- };
- Subscriber.prototype.complete = function () {
- if (this.isStopped) ;
- else {
- this.isStopped = true;
- this._complete();
- }
- };
- Subscriber.prototype.unsubscribe = function () {
- if (!this.closed) {
- this.isStopped = true;
- _super.prototype.unsubscribe.call(this);
- this.destination = null;
- }
- };
- Subscriber.prototype._next = function (value) {
- this.destination.next(value);
- };
- Subscriber.prototype._error = function (err) {
- try {
- this.destination.error(err);
- }
- finally {
- this.unsubscribe();
- }
- };
- Subscriber.prototype._complete = function () {
- try {
- this.destination.complete();
- }
- finally {
- this.unsubscribe();
- }
- };
- return Subscriber;
- }(Subscription));
- var _bind = Function.prototype.bind;
- function bind(fn, thisArg) {
- return _bind.call(fn, thisArg);
- }
- var ConsumerObserver = (function () {
- function ConsumerObserver(partialObserver) {
- this.partialObserver = partialObserver;
- }
- ConsumerObserver.prototype.next = function (value) {
- var partialObserver = this.partialObserver;
- if (partialObserver.next) {
- try {
- partialObserver.next(value);
- }
- catch (error) {
- handleUnhandledError(error);
- }
- }
- };
- ConsumerObserver.prototype.error = function (err) {
- var partialObserver = this.partialObserver;
- if (partialObserver.error) {
- try {
- partialObserver.error(err);
- }
- catch (error) {
- handleUnhandledError(error);
- }
- }
- else {
- handleUnhandledError(err);
- }
- };
- ConsumerObserver.prototype.complete = function () {
- var partialObserver = this.partialObserver;
- if (partialObserver.complete) {
- try {
- partialObserver.complete();
- }
- catch (error) {
- handleUnhandledError(error);
- }
- }
- };
- return ConsumerObserver;
- }());
- var SafeSubscriber = (function (_super) {
- __extends(SafeSubscriber, _super);
- function SafeSubscriber(observerOrNext, error, complete) {
- var _this = _super.call(this) || this;
- var partialObserver;
- if (isFunction(observerOrNext) || !observerOrNext) {
- partialObserver = {
- next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),
- error: error !== null && error !== void 0 ? error : undefined,
- complete: complete !== null && complete !== void 0 ? complete : undefined,
- };
- }
- else {
- var context_1;
- if (_this && config.useDeprecatedNextContext) {
- context_1 = Object.create(observerOrNext);
- context_1.unsubscribe = function () { return _this.unsubscribe(); };
- partialObserver = {
- next: observerOrNext.next && bind(observerOrNext.next, context_1),
- error: observerOrNext.error && bind(observerOrNext.error, context_1),
- complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
- };
- }
- else {
- partialObserver = observerOrNext;
- }
- }
- _this.destination = new ConsumerObserver(partialObserver);
- return _this;
- }
- return SafeSubscriber;
- }(Subscriber));
- function handleUnhandledError(error) {
- {
- reportUnhandledError(error);
- }
- }
- function defaultErrorHandler(err) {
- throw err;
- }
- var EMPTY_OBSERVER = {
- closed: true,
- next: noop,
- error: defaultErrorHandler,
- complete: noop,
- };
- var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
- function identity(x) {
- return x;
- }
- function pipeFromArray(fns) {
- if (fns.length === 0) {
- return identity;
- }
- if (fns.length === 1) {
- return fns[0];
- }
- return function piped(input) {
- return fns.reduce(function (prev, fn) { return fn(prev); }, input);
- };
- }
- var Observable = (function () {
- function Observable(subscribe) {
- if (subscribe) {
- this._subscribe = subscribe;
- }
- }
- Observable.prototype.lift = function (operator) {
- var observable = new Observable();
- observable.source = this;
- observable.operator = operator;
- return observable;
- };
- Observable.prototype.subscribe = function (observerOrNext, error, complete) {
- var _this = this;
- var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
- errorContext(function () {
- var _a = _this, operator = _a.operator, source = _a.source;
- subscriber.add(operator
- ?
- operator.call(subscriber, source)
- : source
- ?
- _this._subscribe(subscriber)
- :
- _this._trySubscribe(subscriber));
- });
- return subscriber;
- };
- Observable.prototype._trySubscribe = function (sink) {
- try {
- return this._subscribe(sink);
- }
- catch (err) {
- sink.error(err);
- }
- };
- Observable.prototype.forEach = function (next, promiseCtor) {
- var _this = this;
- promiseCtor = getPromiseCtor(promiseCtor);
- return new promiseCtor(function (resolve, reject) {
- var subscriber = new SafeSubscriber({
- next: function (value) {
- try {
- next(value);
- }
- catch (err) {
- reject(err);
- subscriber.unsubscribe();
- }
- },
- error: reject,
- complete: resolve,
- });
- _this.subscribe(subscriber);
- });
- };
- Observable.prototype._subscribe = function (subscriber) {
- var _a;
- return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
- };
- Observable.prototype[observable] = function () {
- return this;
- };
- Observable.prototype.pipe = function () {
- var operations = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- operations[_i] = arguments[_i];
- }
- return pipeFromArray(operations)(this);
- };
- Observable.prototype.toPromise = function (promiseCtor) {
- var _this = this;
- promiseCtor = getPromiseCtor(promiseCtor);
- return new promiseCtor(function (resolve, reject) {
- var value;
- _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
- });
- };
- Observable.create = function (subscribe) {
- return new Observable(subscribe);
- };
- return Observable;
- }());
- function getPromiseCtor(promiseCtor) {
- var _a;
- return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
- }
- function isObserver(value) {
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
- }
- function isSubscriber(value) {
- return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
- }
- function hasLift(source) {
- return isFunction(source === null || source === void 0 ? void 0 : source.lift);
- }
- function operate(init) {
- return function (source) {
- if (hasLift(source)) {
- return source.lift(function (liftedSource) {
- try {
- return init(liftedSource, this);
- }
- catch (err) {
- this.error(err);
- }
- });
- }
- throw new TypeError('Unable to lift unknown Observable type');
- };
- }
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
- }
- var OperatorSubscriber = (function (_super) {
- __extends(OperatorSubscriber, _super);
- function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
- var _this = _super.call(this, destination) || this;
- _this.onFinalize = onFinalize;
- _this.shouldUnsubscribe = shouldUnsubscribe;
- _this._next = onNext
- ? function (value) {
- try {
- onNext(value);
- }
- catch (err) {
- destination.error(err);
- }
- }
- : _super.prototype._next;
- _this._error = onError
- ? function (err) {
- try {
- onError(err);
- }
- catch (err) {
- destination.error(err);
- }
- finally {
- this.unsubscribe();
- }
- }
- : _super.prototype._error;
- _this._complete = onComplete
- ? function () {
- try {
- onComplete();
- }
- catch (err) {
- destination.error(err);
- }
- finally {
- this.unsubscribe();
- }
- }
- : _super.prototype._complete;
- return _this;
- }
- OperatorSubscriber.prototype.unsubscribe = function () {
- var _a;
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
- var closed_1 = this.closed;
- _super.prototype.unsubscribe.call(this);
- !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
- }
- };
- return OperatorSubscriber;
- }(Subscriber));
- var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
- _super(this);
- this.name = 'EmptyError';
- this.message = 'no elements in sequence';
- }; });
- function lastValueFrom(source, config) {
- var hasConfig = typeof config === 'object';
- return new Promise(function (resolve, reject) {
- var _hasValue = false;
- var _value;
- source.subscribe({
- next: function (value) {
- _value = value;
- _hasValue = true;
- },
- error: reject,
- complete: function () {
- if (_hasValue) {
- resolve(_value);
- }
- else if (hasConfig) {
- resolve(config.defaultValue);
- }
- else {
- reject(new EmptyError());
- }
- },
- });
- });
- }
- function map(project, thisArg) {
- return operate(function (source, subscriber) {
- var index = 0;
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
- subscriber.next(project.call(thisArg, value, index++));
- }));
- });
- }
- function filter(predicate, thisArg) {
- return operate(function (source, subscriber) {
- var index = 0;
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
- });
- }
- var envMiddleware = [];
- const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
- class ClientError extends Error {
- constructor(res) {
- const props = extractErrorProps(res);
- super(props.message);
- this.statusCode = 400;
- Object.assign(this, props);
- }
- }
- class ServerError extends Error {
- constructor(res) {
- const props = extractErrorProps(res);
- super(props.message);
- this.statusCode = 500;
- Object.assign(this, props);
- }
- }
- function extractErrorProps(res) {
- const body = res.body;
- const props = {
- response: res,
- statusCode: res.statusCode,
- responseBody: stringifyBody(body, res),
- message: "",
- details: void 0
- };
- if (body.error && body.message) {
- props.message = "".concat(body.error, " - ").concat(body.message);
- return props;
- }
- if (isMutationError(body)) {
- const allItems = body.error.items || [];
- const items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map(item => {
- var _a;
- return (_a = item.error) == null ? void 0 : _a.description;
- }).filter(Boolean);
- let itemsStr = items.length ? ":\n- ".concat(items.join("\n- ")) : "";
- if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {
- itemsStr += "\n...and ".concat(allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE, " more");
- }
- props.message = "".concat(body.error.description).concat(itemsStr);
- props.details = body.error;
- return props;
- }
- if (body.error && body.error.description) {
- props.message = body.error.description;
- props.details = body.error;
- return props;
- }
- props.message = body.error || body.message || httpErrorMessage(res);
- return props;
- }
- function isMutationError(body) {
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description === "string";
- }
- function isPlainObject(obj) {
- return typeof obj === "object" && obj !== null && !Array.isArray(obj);
- }
- function httpErrorMessage(res) {
- const statusMessage = res.statusMessage ? " ".concat(res.statusMessage) : "";
- return "".concat(res.method, "-request to ").concat(res.url, " resulted in HTTP ").concat(res.statusCode).concat(statusMessage);
- }
- function stringifyBody(body, res) {
- const contentType = (res.headers["content-type"] || "").toLowerCase();
- const isJson = contentType.indexOf("application/json") !== -1;
- return isJson ? JSON.stringify(body, null, 2) : body;
- }
- const httpError = {
- onResponse: res => {
- if (res.statusCode >= 500) {
- throw new ServerError(res);
- } else if (res.statusCode >= 400) {
- throw new ClientError(res);
- }
- return res;
- }
- };
- const printWarnings = {
- onResponse: res => {
- const warn = res.headers["x-sanity-warning"];
- const warnings = Array.isArray(warn) ? warn : [warn];
- warnings.filter(Boolean).forEach(msg => console.warn(msg));
- return res;
- }
- };
- function defineHttpRequest(envMiddleware) {
- const request = getIt([...envMiddleware, printWarnings, jsonRequest(), jsonResponse(), progress(), httpError, observable$1({
- implementation: Observable
- })]);
- function httpRequest(options) {
- let requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : request;
- return requester({
- maxRedirects: 0,
- ...options
- });
- }
- httpRequest.defaultRequester = request;
- return httpRequest;
- }
- const projectHeader = "X-Sanity-Project-ID";
- function requestOptions(config) {
- let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- const headers = {};
- const token = overrides.token || config.token;
- if (token) {
- headers.Authorization = "Bearer ".concat(token);
- }
- if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
- headers[projectHeader] = config.projectId;
- }
- const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
- const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
- return Object.assign({}, overrides, {
- headers: Object.assign({}, headers, overrides.headers || {}),
- timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
- proxy: overrides.proxy || config.proxy,
- json: true,
- withCredentials
- });
- }
- function getSelection(sel) {
- if (typeof sel === "string" || Array.isArray(sel)) {
- return {
- id: sel
- };
- }
- if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
- return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
- query: sel.query,
- params: sel.params
- } : {
- query: sel.query
- };
- }
- const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
- throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
- }
- const VALID_ASSET_TYPES = ["image", "file"];
- const VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
- const dataset = name => {
- if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
- throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
- }
- };
- const projectId = id => {
- if (!/^[-a-z0-9]+$/i.test(id)) {
- throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
- }
- };
- const validateAssetType = type => {
- if (VALID_ASSET_TYPES.indexOf(type) === -1) {
- throw new Error("Invalid asset type: ".concat(type, ". Must be one of ").concat(VALID_ASSET_TYPES.join(", ")));
- }
- };
- const validateObject = (op, val) => {
- if (val === null || typeof val !== "object" || Array.isArray(val)) {
- throw new Error("".concat(op, "() takes an object of properties"));
- }
- };
- const validateDocumentId = (op, id) => {
- if (typeof id !== "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes("..")) {
- throw new Error("".concat(op, "(): \"").concat(id, "\" is not a valid document ID"));
- }
- };
- const requireDocumentId = (op, doc) => {
- if (!doc._id) {
- throw new Error("".concat(op, "() requires that the document contains an ID (\"_id\" property)"));
- }
- validateDocumentId(op, doc._id);
- };
- const validateInsert = (at, selector, items) => {
- const signature = "insert(at, selector, items)";
- if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
- const valid = VALID_INSERT_LOCATIONS.map(loc => "\"".concat(loc, "\"")).join(", ");
- throw new Error("".concat(signature, " takes an \"at\"-argument which is one of: ").concat(valid));
- }
- if (typeof selector !== "string") {
- throw new Error("".concat(signature, " takes a \"selector\"-argument which must be a string"));
- }
- if (!Array.isArray(items)) {
- throw new Error("".concat(signature, " takes an \"items\"-argument which must be an array"));
- }
- };
- const hasDataset = config => {
- if (!config.dataset) {
- throw new Error("`dataset` must be provided to perform queries");
- }
- return config.dataset || "";
- };
- const requestTag = tag => {
- if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
- throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
- }
- return tag;
- };
- const encodeQueryString = _ref => {
- let {
- query,
- params = {},
- options = {}
- } = _ref;
- const searchParams = new URLSearchParams();
- const {
- tag,
- ...opts
- } = options;
- if (tag) searchParams.set("tag", tag);
- searchParams.set("query", query);
- for (const [key, value] of Object.entries(params)) {
- searchParams.set("$".concat(key), JSON.stringify(value));
- }
- for (const [key, value] of Object.entries(opts)) {
- if (value) searchParams.set(key, "".concat(value));
- }
- return "?".concat(searchParams);
- };
- var __accessCheck$6 = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet$6 = (obj, member, getter) => {
- __accessCheck$6(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd$6 = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet$6 = (obj, member, value, setter) => {
- __accessCheck$6(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _client$5, _client2$5;
- class BasePatch {
- constructor(selection) {
- let operations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- this.selection = selection;
- this.operations = operations;
- }
- /**
- * Sets the given attributes to the document. Does NOT merge objects.
- * The operation is added to the current patch, ready to be commited by `commit()`
- *
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
- */
- set(attrs) {
- return this._assign("set", attrs);
- }
- /**
- * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
- * The operation is added to the current patch, ready to be commited by `commit()`
- *
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
- */
- setIfMissing(attrs) {
- return this._assign("setIfMissing", attrs);
- }
- /**
- * Performs a "diff-match-patch" operation on the string attributes provided.
- * The operation is added to the current patch, ready to be commited by `commit()`
- *
- * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
- */
- diffMatchPatch(attrs) {
- validateObject("diffMatchPatch", attrs);
- return this._assign("diffMatchPatch", attrs);
- }
- /**
- * Unsets the attribute paths provided.
- * The operation is added to the current patch, ready to be commited by `commit()`
- *
- * @param attrs - Attribute paths to unset.
- */
- unset(attrs) {
- if (!Array.isArray(attrs)) {
- throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
- }
- this.operations = Object.assign({}, this.operations, {
- unset: attrs
- });
- return this;
- }
- /**
- * 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.
- *
- * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
- */
- inc(attrs) {
- return this._assign("inc", attrs);
- }
- /**
- * 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.
- *
- * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
- */
- dec(attrs) {
- return this._assign("dec", attrs);
- }
- /**
- * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
- *
- * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
- * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
- * @param items - Array of items to insert/replace
- */
- insert(at, selector, items) {
- validateInsert(at, selector, items);
- return this._assign("insert", {
- [at]: selector,
- items
- });
- }
- /**
- * Append the given items to the array at the given JSONPath
- *
- * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
- * @param items - Array of items to append to the array
- */
- append(selector, items) {
- return this.insert("after", "".concat(selector, "[-1]"), items);
- }
- /**
- * Prepend the given items to the array at the given JSONPath
- *
- * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
- * @param items - Array of items to prepend to the array
- */
- prepend(selector, items) {
- return this.insert("before", "".concat(selector, "[0]"), items);
- }
- /**
- * Change the contents of an array by removing existing elements and/or adding new elements.
- *
- * @param selector - Attribute or JSONPath expression for array
- * @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
- * @param deleteCount - An integer indicating the number of old array elements to remove.
- * @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.
- */
- splice(selector, start, deleteCount, items) {
- const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
- const startIndex = start < 0 ? start - 1 : start;
- const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
- const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
- const rangeSelector = "".concat(selector, "[").concat(startIndex, ":").concat(delRange, "]");
- return this.insert("replace", rangeSelector, items || []);
- }
- /**
- * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
- *
- * @param rev - Revision to lock the patch to
- */
- ifRevisionId(rev) {
- this.operations.ifRevisionID = rev;
- return this;
- }
- /**
- * Return a plain JSON representation of the patch
- */
- serialize() {
- return {
- ...getSelection(this.selection),
- ...this.operations
- };
- }
- /**
- * Return a plain JSON representation of the patch
- */
- toJSON() {
- return this.serialize();
- }
- /**
- * Clears the patch of all operations
- */
- reset() {
- this.operations = {};
- return this;
- }
- _assign(op, props) {
- let merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
- validateObject(op, props);
- this.operations = Object.assign({}, this.operations, {
- [op]: Object.assign({}, merge && this.operations[op] || {}, props)
- });
- return this;
- }
- _set(op, props) {
- return this._assign(op, props, false);
- }
- }
- const _ObservablePatch = class extends BasePatch {
- constructor(selection, operations, client) {
- super(selection, operations);
- __privateAdd$6(this, _client$5, void 0);
- __privateSet$6(this, _client$5, client);
- }
- /**
- * Clones the patch
- */
- clone() {
- return new _ObservablePatch(this.selection, {
- ...this.operations
- }, __privateGet$6(this, _client$5));
- }
- commit(options) {
- if (!__privateGet$6(this, _client$5)) {
- throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
- }
- const returnFirst = typeof this.selection === "string";
- const opts = Object.assign({
- returnFirst,
- returnDocuments: true
- }, options);
- return __privateGet$6(this, _client$5).mutate({
- patch: this.serialize()
- }, opts);
- }
- };
- let ObservablePatch = _ObservablePatch;
- _client$5 = new WeakMap();
- const _Patch = class extends BasePatch {
- constructor(selection, operations, client) {
- super(selection, operations);
- __privateAdd$6(this, _client2$5, void 0);
- __privateSet$6(this, _client2$5, client);
- }
- /**
- * Clones the patch
- */
- clone() {
- return new _Patch(this.selection, {
- ...this.operations
- }, __privateGet$6(this, _client2$5));
- }
- commit(options) {
- if (!__privateGet$6(this, _client2$5)) {
- throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
- }
- const returnFirst = typeof this.selection === "string";
- const opts = Object.assign({
- returnFirst,
- returnDocuments: true
- }, options);
- return __privateGet$6(this, _client2$5).mutate({
- patch: this.serialize()
- }, opts);
- }
- };
- let Patch = _Patch;
- _client2$5 = new WeakMap();
- var __accessCheck$5 = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet$5 = (obj, member, getter) => {
- __accessCheck$5(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd$5 = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet$5 = (obj, member, value, setter) => {
- __accessCheck$5(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _client$4, _client2$4;
- const defaultMutateOptions = {
- returnDocuments: false
- };
- class BaseTransaction {
- constructor() {
- let operations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
- let transactionId = arguments.length > 1 ? arguments[1] : undefined;
- this.operations = operations;
- this.trxId = transactionId;
- }
- /**
- * 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.
- * The operation is added to the current transaction, ready to be commited by `commit()`
- *
- * @param doc - Document to create. Requires a `_type` property.
- */
- create(doc) {
- validateObject("create", doc);
- return this._add({
- create: doc
- });
- }
- /**
- * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
- * The operation is added to the current transaction, ready to be commited by `commit()`
- *
- * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
- */
- createIfNotExists(doc) {
- const op = "createIfNotExists";
- validateObject(op, doc);
- requireDocumentId(op, doc);
- return this._add({
- [op]: doc
- });
- }
- /**
- * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
- * The operation is added to the current transaction, ready to be commited by `commit()`
- *
- * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
- */
- createOrReplace(doc) {
- const op = "createOrReplace";
- validateObject(op, doc);
- requireDocumentId(op, doc);
- return this._add({
- [op]: doc
- });
- }
- /**
- * Deletes the document with the given document ID
- * The operation is added to the current transaction, ready to be commited by `commit()`
- *
- * @param documentId - Document ID to delete
- */
- delete(documentId) {
- validateDocumentId("delete", documentId);
- return this._add({
- delete: {
- id: documentId
- }
- });
- }
- transactionId(id) {
- if (!id) {
- return this.trxId;
- }
- this.trxId = id;
- return this;
- }
- /**
- * Return a plain JSON representation of the transaction
- */
- serialize() {
- return [...this.operations];
- }
- /**
- * Return a plain JSON representation of the transaction
- */
- toJSON() {
- return this.serialize();
- }
- /**
- * Clears the transaction of all operations
- */
- reset() {
- this.operations = [];
- return this;
- }
- _add(mut) {
- this.operations.push(mut);
- return this;
- }
- }
- const _Transaction = class extends BaseTransaction {
- constructor(operations, client, transactionId) {
- super(operations, transactionId);
- __privateAdd$5(this, _client$4, void 0);
- __privateSet$5(this, _client$4, client);
- }
- /**
- * Clones the transaction
- */
- clone() {
- return new _Transaction([...this.operations], __privateGet$5(this, _client$4), this.trxId);
- }
- commit(options) {
- if (!__privateGet$5(this, _client$4)) {
- throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
- }
- return __privateGet$5(this, _client$4).mutate(this.serialize(), Object.assign({
- transactionId: this.trxId
- }, defaultMutateOptions, options || {}));
- }
- patch(patchOrDocumentId, patchOps) {
- const isBuilder = typeof patchOps === "function";
- const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof Patch;
- if (isPatch) {
- return this._add({
- patch: patchOrDocumentId.serialize()
- });
- }
- if (isBuilder) {
- const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$5(this, _client$4)));
- if (!(patch instanceof Patch)) {
- throw new Error("function passed to `patch()` must return the patch");
- }
- return this._add({
- patch: patch.serialize()
- });
- }
- return this._add({
- patch: {
- id: patchOrDocumentId,
- ...patchOps
- }
- });
- }
- };
- let Transaction = _Transaction;
- _client$4 = new WeakMap();
- const _ObservableTransaction = class extends BaseTransaction {
- constructor(operations, client, transactionId) {
- super(operations, transactionId);
- __privateAdd$5(this, _client2$4, void 0);
- __privateSet$5(this, _client2$4, client);
- }
- /**
- * Clones the transaction
- */
- clone() {
- return new _ObservableTransaction([...this.operations], __privateGet$5(this, _client2$4), this.trxId);
- }
- commit(options) {
- if (!__privateGet$5(this, _client2$4)) {
- throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
- }
- return __privateGet$5(this, _client2$4).mutate(this.serialize(), Object.assign({
- transactionId: this.trxId
- }, defaultMutateOptions, options || {}));
- }
- patch(patchOrDocumentId, patchOps) {
- const isBuilder = typeof patchOps === "function";
- const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof ObservablePatch;
- if (isPatch) {
- return this._add({
- patch: patchOrDocumentId.serialize()
- });
- }
- if (isBuilder) {
- const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$5(this, _client2$4)));
- if (!(patch instanceof ObservablePatch)) {
- throw new Error("function passed to `patch()` must return the patch");
- }
- return this._add({
- patch: patch.serialize()
- });
- }
- return this._add({
- patch: {
- id: patchOrDocumentId,
- ...patchOps
- }
- });
- }
- };
- let ObservableTransaction = _ObservableTransaction;
- _client2$4 = new WeakMap();
- const excludeFalsey = (param, defValue) => {
- const value = typeof param === "undefined" ? defValue : param;
- return param === false ? void 0 : value;
- };
- const getMutationQuery = function () {
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- return {
- dryRun: options.dryRun,
- returnIds: true,
- returnDocuments: excludeFalsey(options.returnDocuments, true),
- visibility: options.visibility || "sync",
- autoGenerateArrayKeys: options.autoGenerateArrayKeys,
- skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
- };
- };
- const isResponse = event => event.type === "response";
- const getBody = event => event.body;
- const indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
- indexed[attr(doc)] = doc;
- return indexed;
- }, /* @__PURE__ */Object.create(null));
- const getQuerySizeLimit = 11264;
- function _fetch(client, httpRequest, query, params) {
- let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
- const mapResponse = options.filterResponse === false ? res => res : res => res.result;
- return _dataRequest(client, httpRequest, "query", {
- query,
- params
- }, options).pipe(map(mapResponse));
- }
- function _getDocument(client, httpRequest, id) {
- let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
- const options = {
- uri: _getDataUrl(client, "doc", id),
- json: true,
- tag: opts.tag
- };
- return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => event.body.documents && event.body.documents[0]));
- }
- function _getDocuments(client, httpRequest, ids) {
- let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
- const options = {
- uri: _getDataUrl(client, "doc", ids.join(",")),
- json: true,
- tag: opts.tag
- };
- return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => {
- const indexed = indexBy(event.body.documents || [], doc => doc._id);
- return ids.map(id => indexed[id] || null);
- }));
- }
- function _createIfNotExists(client, httpRequest, doc, options) {
- requireDocumentId("createIfNotExists", doc);
- return _create(client, httpRequest, doc, "createIfNotExists", options);
- }
- function _createOrReplace(client, httpRequest, doc, options) {
- requireDocumentId("createOrReplace", doc);
- return _create(client, httpRequest, doc, "createOrReplace", options);
- }
- function _delete(client, httpRequest, selection, options) {
- return _dataRequest(client, httpRequest, "mutate", {
- mutations: [{
- delete: getSelection(selection)
- }]
- }, options);
- }
- function _mutate(client, httpRequest, mutations, options) {
- let mut;
- if (mutations instanceof Patch || mutations instanceof ObservablePatch) {
- mut = {
- patch: mutations.serialize()
- };
- } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {
- mut = mutations.serialize();
- } else {
- mut = mutations;
- }
- const muts = Array.isArray(mut) ? mut : [mut];
- const transactionId = options && options.transactionId || void 0;
- return _dataRequest(client, httpRequest, "mutate", {
- mutations: muts,
- transactionId
- }, options);
- }
- function _dataRequest(client, httpRequest, endpoint, body) {
- let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
- const isMutation = endpoint === "mutate";
- const isQuery = endpoint === "query";
- const strQuery = isMutation ? "" : encodeQueryString(body);
- const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
- const stringQuery = useGet ? strQuery : "";
- const returnFirst = options.returnFirst;
- const {
- timeout,
- token,
- tag,
- headers
- } = options;
- const uri = _getDataUrl(client, endpoint, stringQuery);
- const reqOptions = {
- method: useGet ? "GET" : "POST",
- uri,
- json: true,
- body: useGet ? void 0 : body,
- query: isMutation && getMutationQuery(options),
- timeout,
- headers,
- token,
- tag,
- canUseCdn: isQuery,
- signal: options.signal
- };
- return _requestObservable(client, httpRequest, reqOptions).pipe(filter(isResponse), map(getBody), map(res => {
- if (!isMutation) {
- return res;
- }
- const results = res.results || [];
- if (options.returnDocuments) {
- return returnFirst ? results[0] && results[0].document : results.map(mut => mut.document);
- }
- const key = returnFirst ? "documentId" : "documentIds";
- const ids = returnFirst ? results[0] && results[0].id : results.map(mut => mut.id);
- return {
- transactionId: res.transactionId,
- results,
- [key]: ids
- };
- }));
- }
- function _create(client, httpRequest, doc, op) {
- let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
- const mutation = {
- [op]: doc
- };
- const opts = Object.assign({
- returnFirst: true,
- returnDocuments: true
- }, options);
- return _dataRequest(client, httpRequest, "mutate", {
- mutations: [mutation]
- }, opts);
- }
- function _requestObservable(client, httpRequest, options) {
- const uri = options.url || options.uri;
- const config = client.config();
- const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
- const useCdn = config.useCdn && canUseCdn;
- const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
- if (tag) {
- options.query = {
- tag: requestTag(tag),
- ...options.query
- };
- }
- const reqOptions = requestOptions(config, Object.assign({}, options, {
- url: _getUrl(client, uri, useCdn)
- }));
- const request = new Observable(subscriber =>
- // 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
- httpRequest(reqOptions, config.requester).subscribe(subscriber));
- return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
- }
- function _request(client, httpRequest, options) {
- const observable = _requestObservable(client, httpRequest, options).pipe(filter(event => event.type === "response"), map(event => event.body));
- return observable;
- }
- function _getDataUrl(client, operation, path) {
- const config = client.config();
- const catalog = hasDataset(config);
- const baseUri = "/".concat(operation, "/").concat(catalog);
- const uri = path ? "".concat(baseUri, "/").concat(path) : baseUri;
- return "/data".concat(uri).replace(/\/($|\?)/, "$1");
- }
- function _getUrl(client, uri) {
- let canUseCdn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
- const {
- url,
- cdnUrl
- } = client.config();
- const base = canUseCdn ? cdnUrl : url;
- return "".concat(base, "/").concat(uri.replace(/^\//, ""));
- }
- function _withAbortSignal(signal) {
- return input => {
- return new Observable(observer => {
- const abort = () => observer.error(_createAbortError(signal));
- if (signal && signal.aborted) {
- abort();
- return;
- }
- const subscription = input.subscribe(observer);
- signal.addEventListener("abort", abort);
- return () => {
- signal.removeEventListener("abort", abort);
- subscription.unsubscribe();
- };
- });
- };
- }
- const isDomExceptionSupported = Boolean(globalThis.DOMException);
- function _createAbortError(signal) {
- var _a, _b;
- if (isDomExceptionSupported) {
- return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
- }
- const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
- error.name = "AbortError";
- return error;
- }
- var __accessCheck$4 = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet$4 = (obj, member, getter) => {
- __accessCheck$4(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd$4 = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet$4 = (obj, member, value, setter) => {
- __accessCheck$4(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _client$3, _httpRequest$4, _client2$3, _httpRequest2$4;
- class ObservableAssetsClient {
- constructor(client, httpRequest) {
- __privateAdd$4(this, _client$3, void 0);
- __privateAdd$4(this, _httpRequest$4, void 0);
- __privateSet$4(this, _client$3, client);
- __privateSet$4(this, _httpRequest$4, httpRequest);
- }
- upload(assetType, body, options) {
- return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
- }
- }
- _client$3 = new WeakMap();
- _httpRequest$4 = new WeakMap();
- class AssetsClient {
- constructor(client, httpRequest) {
- __privateAdd$4(this, _client2$3, void 0);
- __privateAdd$4(this, _httpRequest2$4, void 0);
- __privateSet$4(this, _client2$3, client);
- __privateSet$4(this, _httpRequest2$4, httpRequest);
- }
- upload(assetType, body, options) {
- const observable = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
- return lastValueFrom(observable.pipe(filter(event => event.type === "response"), map(event => event.body.document)));
- }
- }
- _client2$3 = new WeakMap();
- _httpRequest2$4 = new WeakMap();
- function _upload(client, httpRequest, assetType, body) {
- let opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
- validateAssetType(assetType);
- let meta = opts.extract || void 0;
- if (meta && !meta.length) {
- meta = ["none"];
- }
- const dataset = hasDataset(client.config());
- const assetEndpoint = assetType === "image" ? "images" : "files";
- const options = optionsFromFile(opts, body);
- const {
- tag,
- label,
- title,
- description,
- creditLine,
- filename,
- source
- } = options;
- const query = {
- label,
- title,
- description,
- filename,
- meta,
- creditLine
- };
- if (source) {
- query.sourceId = source.id;
- query.sourceName = source.name;
- query.sourceUrl = source.url;
- }
- return _requestObservable(client, httpRequest, {
- tag,
- method: "POST",
- timeout: options.timeout || 0,
- uri: "/assets/".concat(assetEndpoint, "/").concat(dataset),
- headers: options.contentType ? {
- "Content-Type": options.contentType
- } : {},
- query,
- body
- });
- }
- function optionsFromFile(opts, file) {
- if (typeof File === "undefined" || !(file instanceof File)) {
- return opts;
- }
- return Object.assign({
- filename: opts.preserveFilename === false ? void 0 : file.name,
- contentType: file.type
- }, opts);
- }
- const BASE_URL = "https://www.sanity.io/help/";
- function generateHelpUrl(slug) {
- return BASE_URL + slug;
- }
- function once(fn) {
- let didCall = false;
- let returnValue;
- return function () {
- if (didCall) {
- return returnValue;
- }
- returnValue = fn(...arguments);
- didCall = true;
- return returnValue;
- };
- }
- const createWarningPrinter = message =>
- // eslint-disable-next-line no-console
- once(function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- return console.warn(message.join(" "), ...args);
- });
- 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."]);
- 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.")]);
- const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
- const printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead"]);
- const defaultCdnHost = "apicdn.sanity.io";
- const defaultConfig = {
- apiHost: "https://api.sanity.io",
- apiVersion: "1",
- useProjectHostname: true
- };
- const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
- const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
- const validateApiVersion = function validateApiVersion2(apiVersion) {
- if (apiVersion === "1" || apiVersion === "X") {
- return;
- }
- const apiDate = new Date(apiVersion);
- const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
- if (!apiVersionValid) {
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
- }
- };
- const initConfig = (config, prevConfig) => {
- const specifiedConfig = Object.assign({}, prevConfig, config);
- if (!specifiedConfig.apiVersion) {
- printNoApiVersionSpecifiedWarning();
- }
- const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
- const projectBased = newConfig.useProjectHostname;
- if (typeof Promise === "undefined") {
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
- throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
- }
- if (projectBased && !newConfig.projectId) {
- throw new Error("Configuration must contain `projectId`");
- }
- const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
- const isLocalhost = isBrowser && isLocal(window.location.hostname);
- if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
- printBrowserTokenWarning();
- } else if (typeof newConfig.useCdn === "undefined") {
- printCdnWarning();
- }
- if (projectBased) {
- projectId(newConfig.projectId);
- }
- if (newConfig.dataset) {
- dataset(newConfig.dataset);
- }
- if ("requestTagPrefix" in newConfig) {
- newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
- }
- newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
- newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
- newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
- validateApiVersion(newConfig.apiVersion);
- const hostParts = newConfig.apiHost.split("://", 2);
- const protocol = hostParts[0];
- const host = hostParts[1];
- const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
- if (newConfig.useProjectHostname) {
- newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
- newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
- } else {
- newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
- newConfig.cdnUrl = newConfig.url;
- }
- return newConfig;
- };
- var defaults = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
- target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
- return target;
- }, {});
- const pick = (obj, props) => props.reduce((selection, prop) => {
- if (typeof obj[prop] === "undefined") {
- return selection;
- }
- selection[prop] = obj[prop];
- return selection;
- }, {});
- const MAX_URL_LENGTH = 16e3 - 1200;
- const possibleOptions = ["includePreviousRevision", "includeResult", "visibility", "effectFormat", "tag"];
- const defaultOptions = {
- includeResult: true
- };
- function _listen(query, params) {
- let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- const {
- url,
- token,
- withCredentials,
- requestTagPrefix
- } = this.config();
- const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
- const options = {
- ...defaults(opts, defaultOptions),
- tag
- };
- const listenOpts = pick(options, possibleOptions);
- const qs = encodeQueryString({
- query,
- params,
- options: {
- tag,
- ...listenOpts
- }
- });
- const uri = "".concat(url).concat(_getDataUrl(this, "listen", qs));
- if (uri.length > MAX_URL_LENGTH) {
- return new Observable(observer => observer.error(new Error("Query too large for listener")));
- }
- const listenFor = options.events ? options.events : ["mutation"];
- const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
- const esOptions = {};
- if (token || withCredentials) {
- esOptions.withCredentials = true;
- }
- if (token) {
- esOptions.headers = {
- Authorization: "Bearer ".concat(token)
- };
- }
- return new Observable(observer => {
- let es;
- getEventSource().then(eventSource => {
- es = eventSource;
- }).catch(reason => {
- observer.error(reason);
- stop();
- });
- let reconnectTimer;
- let stopped = false;
- function onError() {
- if (stopped) {
- return;
- }
- emitReconnect();
- if (stopped) {
- return;
- }
- if (es.readyState === es.CLOSED) {
- unsubscribe();
- clearTimeout(reconnectTimer);
- reconnectTimer = setTimeout(open, 100);
- }
- }
- function onChannelError(err) {
- observer.error(cooerceError(err));
- }
- function onMessage(evt) {
- const event = parseEvent(evt);
- return event instanceof Error ? observer.error(event) : observer.next(event);
- }
- function onDisconnect() {
- stopped = true;
- unsubscribe();
- observer.complete();
- }
- function unsubscribe() {
- if (!es) return;
- es.removeEventListener("error", onError);
- es.removeEventListener("channelError", onChannelError);
- es.removeEventListener("disconnect", onDisconnect);
- listenFor.forEach(type => es.removeEventListener(type, onMessage));
- es.close();
- }
- function emitReconnect() {
- if (shouldEmitReconnect) {
- observer.next({
- type: "reconnect"
- });
- }
- }
- async function getEventSource() {
- const {
- default: EventSource
- } = await Promise.resolve().then(function () { return browser$1; });
- const evs = new EventSource(uri, esOptions);
- evs.addEventListener("error", onError);
- evs.addEventListener("channelError", onChannelError);
- evs.addEventListener("disconnect", onDisconnect);
- listenFor.forEach(type => evs.addEventListener(type, onMessage));
- return evs;
- }
- function open() {
- getEventSource().then(eventSource => {
- es = eventSource;
- }).catch(reason => {
- observer.error(reason);
- stop();
- });
- }
- function stop() {
- stopped = true;
- unsubscribe();
- }
- return stop;
- });
- }
- function parseEvent(event) {
- try {
- const data = event.data && JSON.parse(event.data) || {};
- return Object.assign({
- type: event.type
- }, data);
- } catch (err) {
- return err;
- }
- }
- function cooerceError(err) {
- if (err instanceof Error) {
- return err;
- }
- const evt = parseEvent(err);
- return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
- }
- function extractErrorMessage(err) {
- if (!err.error) {
- return err.message || "Unknown listener error";
- }
- if (err.error.description) {
- return err.error.description;
- }
- return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
- }
- var __accessCheck$3 = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet$3 = (obj, member, getter) => {
- __accessCheck$3(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd$3 = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet$3 = (obj, member, value, setter) => {
- __accessCheck$3(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _client$2, _httpRequest$3, _client2$2, _httpRequest2$3;
- class ObservableDatasetsClient {
- constructor(client, httpRequest) {
- __privateAdd$3(this, _client$2, void 0);
- __privateAdd$3(this, _httpRequest$3, void 0);
- __privateSet$3(this, _client$2, client);
- __privateSet$3(this, _httpRequest$3, httpRequest);
- }
- /**
- * Create a new dataset with the given name
- *
- * @param name - Name of the dataset to create
- * @param options - Options for the dataset
- */
- create(name, options) {
- return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name, options);
- }
- /**
- * Edit a dataset with the given name
- *
- * @param name - Name of the dataset to edit
- * @param options - New options for the dataset
- */
- edit(name, options) {
- return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name, options);
- }
- /**
- * Delete a dataset with the given name
- *
- * @param name - Name of the dataset to delete
- */
- delete(name) {
- return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name);
- }
- /**
- * Fetch a list of datasets for the configured project
- */
- list() {
- return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
- uri: "/datasets"
- });
- }
- }
- _client$2 = new WeakMap();
- _httpRequest$3 = new WeakMap();
- class DatasetsClient {
- constructor(client, httpRequest) {
- __privateAdd$3(this, _client2$2, void 0);
- __privateAdd$3(this, _httpRequest2$3, void 0);
- __privateSet$3(this, _client2$2, client);
- __privateSet$3(this, _httpRequest2$3, httpRequest);
- }
- /**
- * Create a new dataset with the given name
- *
- * @param name - Name of the dataset to create
- * @param options - Options for the dataset
- */
- create(name, options) {
- return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name, options));
- }
- /**
- * Edit a dataset with the given name
- *
- * @param name - Name of the dataset to edit
- * @param options - New options for the dataset
- */
- edit(name, options) {
- return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name, options));
- }
- /**
- * Delete a dataset with the given name
- *
- * @param name - Name of the dataset to delete
- */
- delete(name) {
- return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name));
- }
- /**
- * Fetch a list of datasets for the configured project
- */
- list() {
- return lastValueFrom(_request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), {
- uri: "/datasets"
- }));
- }
- }
- _client2$2 = new WeakMap();
- _httpRequest2$3 = new WeakMap();
- function _modify(client, httpRequest, method, name, options) {
- dataset(name);
- return _request(client, httpRequest, {
- method,
- uri: "/datasets/".concat(name),
- body: options
- });
- }
- var __accessCheck$2 = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet$2 = (obj, member, getter) => {
- __accessCheck$2(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd$2 = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet$2 = (obj, member, value, setter) => {
- __accessCheck$2(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _client$1, _httpRequest$2, _client2$1, _httpRequest2$2;
- class ObservableProjectsClient {
- constructor(client, httpRequest) {
- __privateAdd$2(this, _client$1, void 0);
- __privateAdd$2(this, _httpRequest$2, void 0);
- __privateSet$2(this, _client$1, client);
- __privateSet$2(this, _httpRequest$2, httpRequest);
- }
- /**
- * Fetch a list of projects the authenticated user has access to
- */
- list() {
- return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
- uri: "/projects"
- });
- }
- /**
- * Fetch a project by project ID
- *
- * @param projectId - ID of the project to fetch
- */
- getById(projectId) {
- return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
- uri: "/projects/".concat(projectId)
- });
- }
- }
- _client$1 = new WeakMap();
- _httpRequest$2 = new WeakMap();
- class ProjectsClient {
- constructor(client, httpRequest) {
- __privateAdd$2(this, _client2$1, void 0);
- __privateAdd$2(this, _httpRequest2$2, void 0);
- __privateSet$2(this, _client2$1, client);
- __privateSet$2(this, _httpRequest2$2, httpRequest);
- }
- /**
- * Fetch a list of projects the authenticated user has access to
- */
- list() {
- return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
- uri: "/projects"
- }));
- }
- /**
- * Fetch a project by project ID
- *
- * @param projectId - ID of the project to fetch
- */
- getById(projectId) {
- return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
- uri: "/projects/".concat(projectId)
- }));
- }
- }
- _client2$1 = new WeakMap();
- _httpRequest2$2 = new WeakMap();
- var __accessCheck$1 = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet$1 = (obj, member, getter) => {
- __accessCheck$1(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd$1 = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet$1 = (obj, member, value, setter) => {
- __accessCheck$1(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _client, _httpRequest$1, _client2, _httpRequest2$1;
- class ObservableUsersClient {
- constructor(client, httpRequest) {
- __privateAdd$1(this, _client, void 0);
- __privateAdd$1(this, _httpRequest$1, void 0);
- __privateSet$1(this, _client, client);
- __privateSet$1(this, _httpRequest$1, httpRequest);
- }
- /**
- * Fetch a user by user ID
- *
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
- */
- getById(id) {
- return _request(__privateGet$1(this, _client), __privateGet$1(this, _httpRequest$1), {
- uri: "/users/".concat(id)
- });
- }
- }
- _client = new WeakMap();
- _httpRequest$1 = new WeakMap();
- class UsersClient {
- constructor(client, httpRequest) {
- __privateAdd$1(this, _client2, void 0);
- __privateAdd$1(this, _httpRequest2$1, void 0);
- __privateSet$1(this, _client2, client);
- __privateSet$1(this, _httpRequest2$1, httpRequest);
- }
- /**
- * Fetch a user by user ID
- *
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
- */
- getById(id) {
- return lastValueFrom(_request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
- uri: "/users/".concat(id)
- }));
- }
- }
- _client2 = new WeakMap();
- _httpRequest2$1 = new WeakMap();
- var __accessCheck = (obj, member, msg) => {
- if (!member.has(obj)) throw TypeError("Cannot " + msg);
- };
- var __privateGet = (obj, member, getter) => {
- __accessCheck(obj, member, "read from private field");
- return getter ? getter.call(obj) : member.get(obj);
- };
- var __privateAdd = (obj, member, value) => {
- if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- };
- var __privateSet = (obj, member, value, setter) => {
- __accessCheck(obj, member, "write to private field");
- setter ? setter.call(obj, value) : member.set(obj, value);
- return value;
- };
- var _clientConfig, _httpRequest, _clientConfig2, _httpRequest2;
- const _ObservableSanityClient = class {
- constructor(httpRequest) {
- let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
- /**
- * Private properties
- */
- __privateAdd(this, _clientConfig, void 0);
- __privateAdd(this, _httpRequest, void 0);
- /**
- * Instance properties
- */
- this.listen = _listen;
- this.config(config);
- __privateSet(this, _httpRequest, httpRequest);
- this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest));
- this.datasets = new ObservableDatasetsClient(this, __privateGet(this, _httpRequest));
- this.projects = new ObservableProjectsClient(this, __privateGet(this, _httpRequest));
- this.users = new ObservableUsersClient(this, __privateGet(this, _httpRequest));
- }
- /**
- * Clone the client - returns a new instance
- */
- clone() {
- return new _ObservableSanityClient(__privateGet(this, _httpRequest), this.config());
- }
- config(newConfig) {
- if (newConfig === void 0) {
- return {
- ...__privateGet(this, _clientConfig)
- };
- }
- if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === false) {
- throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
- }
- __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {}));
- return this;
- }
- /**
- * Clone the client with a new (partial) configuration.
- *
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
- */
- withConfig(newConfig) {
- return new _ObservableSanityClient(__privateGet(this, _httpRequest), {
- ...this.config(),
- ...newConfig
- });
- }
- fetch(query, params) {
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- return _fetch(this, __privateGet(this, _httpRequest), query, params, options);
- }
- /**
- * Fetch a single document with the given ID.
- *
- * @param id - Document ID to fetch
- * @param options - Request options
- */
- getDocument(id, options) {
- return _getDocument(this, __privateGet(this, _httpRequest), id, options);
- }
- /**
- * Fetch multiple documents in one request.
- * Should be used sparingly - performing a query is usually a better option.
- * The order/position of documents is preserved based on the original array of IDs.
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
- *
- * @param ids - Document IDs to fetch
- * @param options - Request options
- */
- getDocuments(ids, options) {
- return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
- }
- create(document, options) {
- return _create(this, __privateGet(this, _httpRequest), document, "create", options);
- }
- createIfNotExists(document, options) {
- return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
- }
- createOrReplace(document, options) {
- return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
- }
- delete(selection, options) {
- return _delete(this, __privateGet(this, _httpRequest), selection, options);
- }
- mutate(operations, options) {
- return _mutate(this, __privateGet(this, _httpRequest), operations, options);
- }
- /**
- * Create a new buildable patch of operations to perform
- *
- * @param documentId - Document ID(s) to patch
- * @param operations - Optional object of patch operations to initialize the patch instance with
- */
- patch(documentId, operations) {
- return new ObservablePatch(documentId, operations, this);
- }
- /**
- * Create a new transaction of mutations
- *
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
- */
- transaction(operations) {
- return new ObservableTransaction(operations, this);
- }
- /**
- * DEPRECATED: Perform an HTTP request against the Sanity API
- *
- * @deprecated Use your own request library!
- * @param options - Request options
- */
- request(options) {
- return _request(this, __privateGet(this, _httpRequest), options);
- }
- /**
- * Get a Sanity API URL for the URI provided
- *
- * @param uri - URI/path to build URL for
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
- */
- getUrl(uri, canUseCdn) {
- return _getUrl(this, uri, canUseCdn);
- }
- /**
- * Get a Sanity API URL for the data operation and path provided
- *
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
- * @param path - Path to append after the operation
- */
- getDataUrl(operation, path) {
- return _getDataUrl(this, operation, path);
- }
- };
- let ObservableSanityClient = _ObservableSanityClient;
- _clientConfig = new WeakMap();
- _httpRequest = new WeakMap();
- const _SanityClient = class {
- constructor(httpRequest) {
- let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
- /**
- * Private properties
- */
- __privateAdd(this, _clientConfig2, void 0);
- __privateAdd(this, _httpRequest2, void 0);
- /**
- * Instance properties
- */
- this.listen = _listen;
- this.config(config);
- __privateSet(this, _httpRequest2, httpRequest);
- this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2));
- this.datasets = new DatasetsClient(this, __privateGet(this, _httpRequest2));
- this.projects = new ProjectsClient(this, __privateGet(this, _httpRequest2));
- this.users = new UsersClient(this, __privateGet(this, _httpRequest2));
- this.observable = new ObservableSanityClient(httpRequest, config);
- }
- /**
- * Clone the client - returns a new instance
- */
- clone() {
- return new _SanityClient(__privateGet(this, _httpRequest2), this.config());
- }
- config(newConfig) {
- if (newConfig === void 0) {
- return {
- ...__privateGet(this, _clientConfig2)
- };
- }
- if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === false) {
- throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
- }
- if (this.observable) {
- this.observable.config(newConfig);
- }
- __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {}));
- return this;
- }
- /**
- * Clone the client with a new (partial) configuration.
- *
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
- */
- withConfig(newConfig) {
- return new _SanityClient(__privateGet(this, _httpRequest2), {
- ...this.config(),
- ...newConfig
- });
- }
- fetch(query, params) {
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- return lastValueFrom(_fetch(this, __privateGet(this, _httpRequest2), query, params, options));
- }
- /**
- * Fetch a single document with the given ID.
- *
- * @param id - Document ID to fetch
- * @param options - Request options
- */
- getDocument(id, options) {
- return lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
- }
- /**
- * Fetch multiple documents in one request.
- * Should be used sparingly - performing a query is usually a better option.
- * The order/position of documents is preserved based on the original array of IDs.
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
- *
- * @param ids - Document IDs to fetch
- * @param options - Request options
- */
- getDocuments(ids, options) {
- return lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
- }
- create(document, options) {
- return lastValueFrom(_create(this, __privateGet(this, _httpRequest2), document, "create", options));
- }
- createIfNotExists(document, options) {
- return lastValueFrom(_createIfNotExists(this, __privateGet(this, _httpRequest2), document, options));
- }
- createOrReplace(document, options) {
- return lastValueFrom(_createOrReplace(this, __privateGet(this, _httpRequest2), document, options));
- }
- delete(selection, options) {
- return lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
- }
- mutate(operations, options) {
- return lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
- }
- /**
- * Create a new buildable patch of operations to perform
- *
- * @param documentId - Document ID(s)to patch
- * @param operations - Optional object of patch operations to initialize the patch instance with
- */
- patch(documentId, operations) {
- return new Patch(documentId, operations, this);
- }
- /**
- * Create a new transaction of mutations
- *
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
- */
- transaction(operations) {
- return new Transaction(operations, this);
- }
- /**
- * DEPRECATED: Perform an HTTP request against the Sanity API
- *
- * @deprecated Use your own request library!
- * @param options - Request options
- */
- request(options) {
- return lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
- }
- /**
- * DEPRECATED: Perform an HTTP request a `/data` sub-endpoint
- *
- * @deprecated Use your own request library!
- * @param endpoint - Endpoint to hit (mutate, query etc)
- * @param body - Request body
- * @param options - Request options
- */
- dataRequest(endpoint, body, options) {
- return lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
- }
- /**
- * Get a Sanity API URL for the URI provided
- *
- * @param uri - URI/path to build URL for
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
- */
- getUrl(uri, canUseCdn) {
- return _getUrl(this, uri, canUseCdn);
- }
- /**
- * Get a Sanity API URL for the data operation and path provided
- *
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
- * @param path - Path to append after the operation
- */
- getDataUrl(operation, path) {
- return _getDataUrl(this, operation, path);
- }
- };
- let SanityClient = _SanityClient;
- _clientConfig2 = new WeakMap();
- _httpRequest2 = new WeakMap();
- const httpRequest = defineHttpRequest(envMiddleware);
- const requester = httpRequest.defaultRequester;
- const createClient = config => new SanityClient(httpRequest, config);
- function deprecatedCreateClient(config) {
- printNoDefaultExport();
- return new SanityClient(httpRequest, config);
- }
- var eventsourceExports = {};
- var eventsource = {
- get exports(){ return eventsourceExports; },
- set exports(v){ eventsourceExports = v; },
- };
- /** @license
- * eventsource.js
- * Available under MIT License (MIT)
- * https://github.com/Yaffle/EventSource/
- */
- (function (module, exports) {
- /*jslint indent: 2, vars: true, plusplus: true */
- /*global setTimeout, clearTimeout */
- (function (global) {
- var setTimeout = global.setTimeout;
- var clearTimeout = global.clearTimeout;
- var XMLHttpRequest = global.XMLHttpRequest;
- var XDomainRequest = global.XDomainRequest;
- var ActiveXObject = global.ActiveXObject;
- var NativeEventSource = global.EventSource;
- var document = global.document;
- var Promise = global.Promise;
- var fetch = global.fetch;
- var Response = global.Response;
- var TextDecoder = global.TextDecoder;
- var TextEncoder = global.TextEncoder;
- var AbortController = global.AbortController;
- if (typeof window !== "undefined" && typeof document !== "undefined" && !("readyState" in document) && document.body == null) { // Firefox 2
- document.readyState = "loading";
- window.addEventListener("load", function (event) {
- document.readyState = "complete";
- }, false);
- }
- if (XMLHttpRequest == null && ActiveXObject != null) { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6
- XMLHttpRequest = function () {
- return new ActiveXObject("Microsoft.XMLHTTP");
- };
- }
- if (Object.create == undefined) {
- Object.create = function (C) {
- function F(){}
- F.prototype = C;
- return new F();
- };
- }
- if (!Date.now) {
- Date.now = function now() {
- return new Date().getTime();
- };
- }
- // see #118 (Promise#finally with polyfilled Promise)
- // see #123 (data URLs crash Edge)
- // see #125 (CSP violations)
- // see pull/#138
- // => No way to polyfill Promise#finally
- if (AbortController == undefined) {
- var originalFetch2 = fetch;
- fetch = function (url, options) {
- var signal = options.signal;
- return originalFetch2(url, {headers: options.headers, credentials: options.credentials, cache: options.cache}).then(function (response) {
- var reader = response.body.getReader();
- signal._reader = reader;
- if (signal._aborted) {
- signal._reader.cancel();
- }
- return {
- status: response.status,
- statusText: response.statusText,
- headers: response.headers,
- body: {
- getReader: function () {
- return reader;
- }
- }
- };
- });
- };
- AbortController = function () {
- this.signal = {
- _reader: null,
- _aborted: false
- };
- this.abort = function () {
- if (this.signal._reader != null) {
- this.signal._reader.cancel();
- }
- this.signal._aborted = true;
- };
- };
- }
- function TextDecoderPolyfill() {
- this.bitsNeeded = 0;
- this.codePoint = 0;
- }
- TextDecoderPolyfill.prototype.decode = function (octets) {
- function valid(codePoint, shift, octetsCount) {
- if (octetsCount === 1) {
- return codePoint >= 0x0080 >> shift && codePoint << shift <= 0x07FF;
- }
- if (octetsCount === 2) {
- return codePoint >= 0x0800 >> shift && codePoint << shift <= 0xD7FF || codePoint >= 0xE000 >> shift && codePoint << shift <= 0xFFFF;
- }
- if (octetsCount === 3) {
- return codePoint >= 0x010000 >> shift && codePoint << shift <= 0x10FFFF;
- }
- throw new Error();
- }
- function octetsCount(bitsNeeded, codePoint) {
- if (bitsNeeded === 6 * 1) {
- return codePoint >> 6 > 15 ? 3 : codePoint > 31 ? 2 : 1;
- }
- if (bitsNeeded === 6 * 2) {
- return codePoint > 15 ? 3 : 2;
- }
- if (bitsNeeded === 6 * 3) {
- return 3;
- }
- throw new Error();
- }
- var REPLACER = 0xFFFD;
- var string = "";
- var bitsNeeded = this.bitsNeeded;
- var codePoint = this.codePoint;
- for (var i = 0; i < octets.length; i += 1) {
- var octet = octets[i];
- if (bitsNeeded !== 0) {
- if (octet < 128 || octet > 191 || !valid(codePoint << 6 | octet & 63, bitsNeeded - 6, octetsCount(bitsNeeded, codePoint))) {
- bitsNeeded = 0;
- codePoint = REPLACER;
- string += String.fromCharCode(codePoint);
- }
- }
- if (bitsNeeded === 0) {
- if (octet >= 0 && octet <= 127) {
- bitsNeeded = 0;
- codePoint = octet;
- } else if (octet >= 192 && octet <= 223) {
- bitsNeeded = 6 * 1;
- codePoint = octet & 31;
- } else if (octet >= 224 && octet <= 239) {
- bitsNeeded = 6 * 2;
- codePoint = octet & 15;
- } else if (octet >= 240 && octet <= 247) {
- bitsNeeded = 6 * 3;
- codePoint = octet & 7;
- } else {
- bitsNeeded = 0;
- codePoint = REPLACER;
- }
- if (bitsNeeded !== 0 && !valid(codePoint, bitsNeeded, octetsCount(bitsNeeded, codePoint))) {
- bitsNeeded = 0;
- codePoint = REPLACER;
- }
- } else {
- bitsNeeded -= 6;
- codePoint = codePoint << 6 | octet & 63;
- }
- if (bitsNeeded === 0) {
- if (codePoint <= 0xFFFF) {
- string += String.fromCharCode(codePoint);
- } else {
- string += String.fromCharCode(0xD800 + (codePoint - 0xFFFF - 1 >> 10));
- string += String.fromCharCode(0xDC00 + (codePoint - 0xFFFF - 1 & 0x3FF));
- }
- }
- }
- this.bitsNeeded = bitsNeeded;
- this.codePoint = codePoint;
- return string;
- };
- // Firefox < 38 throws an error with stream option
- var supportsStreamOption = function () {
- try {
- return new TextDecoder().decode(new TextEncoder().encode("test"), {stream: true}) === "test";
- } catch (error) {
- console.debug("TextDecoder does not support streaming option. Using polyfill instead: " + error);
- }
- return false;
- };
- // IE, Edge
- if (TextDecoder == undefined || TextEncoder == undefined || !supportsStreamOption()) {
- TextDecoder = TextDecoderPolyfill;
- }
- var k = function () {
- };
- function XHRWrapper(xhr) {
- this.withCredentials = false;
- this.readyState = 0;
- this.status = 0;
- this.statusText = "";
- this.responseText = "";
- this.onprogress = k;
- this.onload = k;
- this.onerror = k;
- this.onreadystatechange = k;
- this._contentType = "";
- this._xhr = xhr;
- this._sendTimeout = 0;
- this._abort = k;
- }
- XHRWrapper.prototype.open = function (method, url) {
- this._abort(true);
- var that = this;
- var xhr = this._xhr;
- var state = 1;
- var timeout = 0;
- this._abort = function (silent) {
- if (that._sendTimeout !== 0) {
- clearTimeout(that._sendTimeout);
- that._sendTimeout = 0;
- }
- if (state === 1 || state === 2 || state === 3) {
- state = 4;
- xhr.onload = k;
- xhr.onerror = k;
- xhr.onabort = k;
- xhr.onprogress = k;
- xhr.onreadystatechange = k;
- // IE 8 - 9: XDomainRequest#abort() does not fire any event
- // Opera < 10: XMLHttpRequest#abort() does not fire any event
- xhr.abort();
- if (timeout !== 0) {
- clearTimeout(timeout);
- timeout = 0;
- }
- if (!silent) {
- that.readyState = 4;
- that.onabort(null);
- that.onreadystatechange();
- }
- }
- state = 0;
- };
- var onStart = function () {
- if (state === 1) {
- //state = 2;
- var status = 0;
- var statusText = "";
- var contentType = undefined;
- if (!("contentType" in xhr)) {
- try {
- status = xhr.status;
- statusText = xhr.statusText;
- contentType = xhr.getResponseHeader("Content-Type");
- } catch (error) {
- // IE < 10 throws exception for `xhr.status` when xhr.readyState === 2 || xhr.readyState === 3
- // Opera < 11 throws exception for `xhr.status` when xhr.readyState === 2
- // https://bugs.webkit.org/show_bug.cgi?id=29121
- status = 0;
- statusText = "";
- contentType = undefined;
- // Firefox < 14, Chrome ?, Safari ?
- // https://bugs.webkit.org/show_bug.cgi?id=29658
- // https://bugs.webkit.org/show_bug.cgi?id=77854
- }
- } else {
- status = 200;
- statusText = "OK";
- contentType = xhr.contentType;
- }
- if (status !== 0) {
- state = 2;
- that.readyState = 2;
- that.status = status;
- that.statusText = statusText;
- that._contentType = contentType;
- that.onreadystatechange();
- }
- }
- };
- var onProgress = function () {
- onStart();
- if (state === 2 || state === 3) {
- state = 3;
- var responseText = "";
- try {
- responseText = xhr.responseText;
- } catch (error) {
- // IE 8 - 9 with XMLHttpRequest
- }
- that.readyState = 3;
- that.responseText = responseText;
- that.onprogress();
- }
- };
- var onFinish = function (type, event) {
- if (event == null || event.preventDefault == null) {
- event = {
- preventDefault: k
- };
- }
- // Firefox 52 fires "readystatechange" (xhr.readyState === 4) without final "readystatechange" (xhr.readyState === 3)
- // IE 8 fires "onload" without "onprogress"
- onProgress();
- if (state === 1 || state === 2 || state === 3) {
- state = 4;
- if (timeout !== 0) {
- clearTimeout(timeout);
- timeout = 0;
- }
- that.readyState = 4;
- if (type === "load") {
- that.onload(event);
- } else if (type === "error") {
- that.onerror(event);
- } else if (type === "abort") {
- that.onabort(event);
- } else {
- throw new TypeError();
- }
- that.onreadystatechange();
- }
- };
- var onReadyStateChange = function (event) {
- if (xhr != undefined) { // Opera 12
- if (xhr.readyState === 4) {
- if (!("onload" in xhr) || !("onerror" in xhr) || !("onabort" in xhr)) {
- onFinish(xhr.responseText === "" ? "error" : "load", event);
- }
- } else if (xhr.readyState === 3) {
- if (!("onprogress" in xhr)) { // testing XMLHttpRequest#responseText too many times is too slow in IE 11
- // and in Firefox 3.6
- onProgress();
- }
- } else if (xhr.readyState === 2) {
- onStart();
- }
- }
- };
- var onTimeout = function () {
- timeout = setTimeout(function () {
- onTimeout();
- }, 500);
- if (xhr.readyState === 3) {
- onProgress();
- }
- };
- // XDomainRequest#abort removes onprogress, onerror, onload
- if ("onload" in xhr) {
- xhr.onload = function (event) {
- onFinish("load", event);
- };
- }
- if ("onerror" in xhr) {
- xhr.onerror = function (event) {
- onFinish("error", event);
- };
- }
- // improper fix to match Firefox behaviour, but it is better than just ignore abort
- // see https://bugzilla.mozilla.org/show_bug.cgi?id=768596
- // https://bugzilla.mozilla.org/show_bug.cgi?id=880200
- // https://code.google.com/p/chromium/issues/detail?id=153570
- // IE 8 fires "onload" without "onprogress
- if ("onabort" in xhr) {
- xhr.onabort = function (event) {
- onFinish("abort", event);
- };
- }
- if ("onprogress" in xhr) {
- xhr.onprogress = onProgress;
- }
- // IE 8 - 9 (XMLHTTPRequest)
- // Opera < 12
- // Firefox < 3.5
- // Firefox 3.5 - 3.6 - ? < 9.0
- // onprogress is not fired sometimes or delayed
- // see also #64 (significant lag in IE 11)
- if ("onreadystatechange" in xhr) {
- xhr.onreadystatechange = function (event) {
- onReadyStateChange(event);
- };
- }
- if ("contentType" in xhr || !("ontimeout" in XMLHttpRequest.prototype)) {
- url += (url.indexOf("?") === -1 ? "?" : "&") + "padding=true";
- }
- xhr.open(method, url, true);
- if ("readyState" in xhr) {
- // workaround for Opera 12 issue with "progress" events
- // #91 (XMLHttpRequest onprogress not fired for streaming response in Edge 14-15-?)
- timeout = setTimeout(function () {
- onTimeout();
- }, 0);
- }
- };
- XHRWrapper.prototype.abort = function () {
- this._abort(false);
- };
- XHRWrapper.prototype.getResponseHeader = function (name) {
- return this._contentType;
- };
- XHRWrapper.prototype.setRequestHeader = function (name, value) {
- var xhr = this._xhr;
- if ("setRequestHeader" in xhr) {
- xhr.setRequestHeader(name, value);
- }
- };
- XHRWrapper.prototype.getAllResponseHeaders = function () {
- // XMLHttpRequest#getAllResponseHeaders returns null for CORS requests in Firefox 3.6.28
- return this._xhr.getAllResponseHeaders != undefined ? this._xhr.getAllResponseHeaders() || "" : "";
- };
- XHRWrapper.prototype.send = function () {
- // loading indicator in Safari < ? (6), Chrome < 14, Firefox
- // https://bugzilla.mozilla.org/show_bug.cgi?id=736723
- if ((!("ontimeout" in XMLHttpRequest.prototype) || (!("sendAsBinary" in XMLHttpRequest.prototype) && !("mozAnon" in XMLHttpRequest.prototype))) &&
- document != undefined &&
- document.readyState != undefined &&
- document.readyState !== "complete") {
- var that = this;
- that._sendTimeout = setTimeout(function () {
- that._sendTimeout = 0;
- that.send();
- }, 4);
- return;
- }
- var xhr = this._xhr;
- // withCredentials should be set after "open" for Safari and Chrome (< 19 ?)
- if ("withCredentials" in xhr) {
- xhr.withCredentials = this.withCredentials;
- }
- try {
- // xhr.send(); throws "Not enough arguments" in Firefox 3.0
- xhr.send(undefined);
- } catch (error1) {
- // Safari 5.1.7, Opera 12
- throw error1;
- }
- };
- function toLowerCase(name) {
- return name.replace(/[A-Z]/g, function (c) {
- return String.fromCharCode(c.charCodeAt(0) + 0x20);
- });
- }
- function HeadersPolyfill(all) {
- // Get headers: implemented according to mozilla's example code: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#Example
- var map = Object.create(null);
- var array = all.split("\r\n");
- for (var i = 0; i < array.length; i += 1) {
- var line = array[i];
- var parts = line.split(": ");
- var name = parts.shift();
- var value = parts.join(": ");
- map[toLowerCase(name)] = value;
- }
- this._map = map;
- }
- HeadersPolyfill.prototype.get = function (name) {
- return this._map[toLowerCase(name)];
- };
- if (XMLHttpRequest != null && XMLHttpRequest.HEADERS_RECEIVED == null) { // IE < 9, Firefox 3.6
- XMLHttpRequest.HEADERS_RECEIVED = 2;
- }
- function XHRTransport() {
- }
- XHRTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
- xhr.open("GET", url);
- var offset = 0;
- xhr.onprogress = function () {
- var responseText = xhr.responseText;
- var chunk = responseText.slice(offset);
- offset += chunk.length;
- onProgressCallback(chunk);
- };
- xhr.onerror = function (event) {
- event.preventDefault();
- onFinishCallback(new Error("NetworkError"));
- };
- xhr.onload = function () {
- onFinishCallback(null);
- };
- xhr.onabort = function () {
- onFinishCallback(null);
- };
- xhr.onreadystatechange = function () {
- if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
- var status = xhr.status;
- var statusText = xhr.statusText;
- var contentType = xhr.getResponseHeader("Content-Type");
- var headers = xhr.getAllResponseHeaders();
- onStartCallback(status, statusText, contentType, new HeadersPolyfill(headers));
- }
- };
- xhr.withCredentials = withCredentials;
- for (var name in headers) {
- if (Object.prototype.hasOwnProperty.call(headers, name)) {
- xhr.setRequestHeader(name, headers[name]);
- }
- }
- xhr.send();
- return xhr;
- };
- function HeadersWrapper(headers) {
- this._headers = headers;
- }
- HeadersWrapper.prototype.get = function (name) {
- return this._headers.get(name);
- };
- function FetchTransport() {
- }
- FetchTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
- var reader = null;
- var controller = new AbortController();
- var signal = controller.signal;
- var textDecoder = new TextDecoder();
- fetch(url, {
- headers: headers,
- credentials: withCredentials ? "include" : "same-origin",
- signal: signal,
- cache: "no-store"
- }).then(function (response) {
- reader = response.body.getReader();
- onStartCallback(response.status, response.statusText, response.headers.get("Content-Type"), new HeadersWrapper(response.headers));
- // see https://github.com/promises-aplus/promises-spec/issues/179
- return new Promise(function (resolve, reject) {
- var readNextChunk = function () {
- reader.read().then(function (result) {
- if (result.done) {
- //Note: bytes in textDecoder are ignored
- resolve(undefined);
- } else {
- var chunk = textDecoder.decode(result.value, {stream: true});
- onProgressCallback(chunk);
- readNextChunk();
- }
- })["catch"](function (error) {
- reject(error);
- });
- };
- readNextChunk();
- });
- })["catch"](function (error) {
- if (error.name === "AbortError") {
- return undefined;
- } else {
- return error;
- }
- }).then(function (error) {
- onFinishCallback(error);
- });
- return {
- abort: function () {
- if (reader != null) {
- reader.cancel(); // https://bugzilla.mozilla.org/show_bug.cgi?id=1583815
- }
- controller.abort();
- }
- };
- };
- function EventTarget() {
- this._listeners = Object.create(null);
- }
- function throwError(e) {
- setTimeout(function () {
- throw e;
- }, 0);
- }
- EventTarget.prototype.dispatchEvent = function (event) {
- event.target = this;
- var typeListeners = this._listeners[event.type];
- if (typeListeners != undefined) {
- var length = typeListeners.length;
- for (var i = 0; i < length; i += 1) {
- var listener = typeListeners[i];
- try {
- if (typeof listener.handleEvent === "function") {
- listener.handleEvent(event);
- } else {
- listener.call(this, event);
- }
- } catch (e) {
- throwError(e);
- }
- }
- }
- };
- EventTarget.prototype.addEventListener = function (type, listener) {
- type = String(type);
- var listeners = this._listeners;
- var typeListeners = listeners[type];
- if (typeListeners == undefined) {
- typeListeners = [];
- listeners[type] = typeListeners;
- }
- var found = false;
- for (var i = 0; i < typeListeners.length; i += 1) {
- if (typeListeners[i] === listener) {
- found = true;
- }
- }
- if (!found) {
- typeListeners.push(listener);
- }
- };
- EventTarget.prototype.removeEventListener = function (type, listener) {
- type = String(type);
- var listeners = this._listeners;
- var typeListeners = listeners[type];
- if (typeListeners != undefined) {
- var filtered = [];
- for (var i = 0; i < typeListeners.length; i += 1) {
- if (typeListeners[i] !== listener) {
- filtered.push(typeListeners[i]);
- }
- }
- if (filtered.length === 0) {
- delete listeners[type];
- } else {
- listeners[type] = filtered;
- }
- }
- };
- function Event(type) {
- this.type = type;
- this.target = undefined;
- }
- function MessageEvent(type, options) {
- Event.call(this, type);
- this.data = options.data;
- this.lastEventId = options.lastEventId;
- }
- MessageEvent.prototype = Object.create(Event.prototype);
- function ConnectionEvent(type, options) {
- Event.call(this, type);
- this.status = options.status;
- this.statusText = options.statusText;
- this.headers = options.headers;
- }
- ConnectionEvent.prototype = Object.create(Event.prototype);
- function ErrorEvent(type, options) {
- Event.call(this, type);
- this.error = options.error;
- }
- ErrorEvent.prototype = Object.create(Event.prototype);
- var WAITING = -1;
- var CONNECTING = 0;
- var OPEN = 1;
- var CLOSED = 2;
- var AFTER_CR = -1;
- var FIELD_START = 0;
- var FIELD = 1;
- var VALUE_START = 2;
- var VALUE = 3;
- var contentTypeRegExp = /^text\/event\-stream(;.*)?$/i;
- var MINIMUM_DURATION = 1000;
- var MAXIMUM_DURATION = 18000000;
- var parseDuration = function (value, def) {
- var n = value == null ? def : parseInt(value, 10);
- if (n !== n) {
- n = def;
- }
- return clampDuration(n);
- };
- var clampDuration = function (n) {
- return Math.min(Math.max(n, MINIMUM_DURATION), MAXIMUM_DURATION);
- };
- var fire = function (that, f, event) {
- try {
- if (typeof f === "function") {
- f.call(that, event);
- }
- } catch (e) {
- throwError(e);
- }
- };
- function EventSourcePolyfill(url, options) {
- EventTarget.call(this);
- options = options || {};
- this.onopen = undefined;
- this.onmessage = undefined;
- this.onerror = undefined;
- this.url = undefined;
- this.readyState = undefined;
- this.withCredentials = undefined;
- this.headers = undefined;
- this._close = undefined;
- start(this, url, options);
- }
- function getBestXHRTransport() {
- return (XMLHttpRequest != undefined && ("withCredentials" in XMLHttpRequest.prototype)) || XDomainRequest == undefined
- ? new XMLHttpRequest()
- : new XDomainRequest();
- }
- var isFetchSupported = fetch != undefined && Response != undefined && "body" in Response.prototype;
- function start(es, url, options) {
- url = String(url);
- var withCredentials = Boolean(options.withCredentials);
- var lastEventIdQueryParameterName = options.lastEventIdQueryParameterName || "lastEventId";
- var initialRetry = clampDuration(1000);
- var heartbeatTimeout = parseDuration(options.heartbeatTimeout, 45000);
- var lastEventId = "";
- var retry = initialRetry;
- var wasActivity = false;
- var textLength = 0;
- var headers = options.headers || {};
- var TransportOption = options.Transport;
- var xhr = isFetchSupported && TransportOption == undefined ? undefined : new XHRWrapper(TransportOption != undefined ? new TransportOption() : getBestXHRTransport());
- var transport = TransportOption != null && typeof TransportOption !== "string" ? new TransportOption() : (xhr == undefined ? new FetchTransport() : new XHRTransport());
- var abortController = undefined;
- var timeout = 0;
- var currentState = WAITING;
- var dataBuffer = "";
- var lastEventIdBuffer = "";
- var eventTypeBuffer = "";
- var textBuffer = "";
- var state = FIELD_START;
- var fieldStart = 0;
- var valueStart = 0;
- var onStart = function (status, statusText, contentType, headers) {
- if (currentState === CONNECTING) {
- if (status === 200 && contentType != undefined && contentTypeRegExp.test(contentType)) {
- currentState = OPEN;
- wasActivity = Date.now();
- retry = initialRetry;
- es.readyState = OPEN;
- var event = new ConnectionEvent("open", {
- status: status,
- statusText: statusText,
- headers: headers
- });
- es.dispatchEvent(event);
- fire(es, es.onopen, event);
- } else {
- var message = "";
- if (status !== 200) {
- if (statusText) {
- statusText = statusText.replace(/\s+/g, " ");
- }
- message = "EventSource's response has a status " + status + " " + statusText + " that is not 200. Aborting the connection.";
- } else {
- message = "EventSource's response has a Content-Type specifying an unsupported type: " + (contentType == undefined ? "-" : contentType.replace(/\s+/g, " ")) + ". Aborting the connection.";
- }
- close();
- var event = new ConnectionEvent("error", {
- status: status,
- statusText: statusText,
- headers: headers
- });
- es.dispatchEvent(event);
- fire(es, es.onerror, event);
- console.error(message);
- }
- }
- };
- var onProgress = function (textChunk) {
- if (currentState === OPEN) {
- var n = -1;
- for (var i = 0; i < textChunk.length; i += 1) {
- var c = textChunk.charCodeAt(i);
- if (c === "\n".charCodeAt(0) || c === "\r".charCodeAt(0)) {
- n = i;
- }
- }
- var chunk = (n !== -1 ? textBuffer : "") + textChunk.slice(0, n + 1);
- textBuffer = (n === -1 ? textBuffer : "") + textChunk.slice(n + 1);
- if (textChunk !== "") {
- wasActivity = Date.now();
- textLength += textChunk.length;
- }
- for (var position = 0; position < chunk.length; position += 1) {
- var c = chunk.charCodeAt(position);
- if (state === AFTER_CR && c === "\n".charCodeAt(0)) {
- state = FIELD_START;
- } else {
- if (state === AFTER_CR) {
- state = FIELD_START;
- }
- if (c === "\r".charCodeAt(0) || c === "\n".charCodeAt(0)) {
- if (state !== FIELD_START) {
- if (state === FIELD) {
- valueStart = position + 1;
- }
- var field = chunk.slice(fieldStart, valueStart - 1);
- var value = chunk.slice(valueStart + (valueStart < position && chunk.charCodeAt(valueStart) === " ".charCodeAt(0) ? 1 : 0), position);
- if (field === "data") {
- dataBuffer += "\n";
- dataBuffer += value;
- } else if (field === "id") {
- lastEventIdBuffer = value;
- } else if (field === "event") {
- eventTypeBuffer = value;
- } else if (field === "retry") {
- initialRetry = parseDuration(value, initialRetry);
- retry = initialRetry;
- } else if (field === "heartbeatTimeout") {
- heartbeatTimeout = parseDuration(value, heartbeatTimeout);
- if (timeout !== 0) {
- clearTimeout(timeout);
- timeout = setTimeout(function () {
- onTimeout();
- }, heartbeatTimeout);
- }
- }
- }
- if (state === FIELD_START) {
- if (dataBuffer !== "") {
- lastEventId = lastEventIdBuffer;
- if (eventTypeBuffer === "") {
- eventTypeBuffer = "message";
- }
- var event = new MessageEvent(eventTypeBuffer, {
- data: dataBuffer.slice(1),
- lastEventId: lastEventIdBuffer
- });
- es.dispatchEvent(event);
- if (eventTypeBuffer === "open") {
- fire(es, es.onopen, event);
- } else if (eventTypeBuffer === "message") {
- fire(es, es.onmessage, event);
- } else if (eventTypeBuffer === "error") {
- fire(es, es.onerror, event);
- }
- if (currentState === CLOSED) {
- return;
- }
- }
- dataBuffer = "";
- eventTypeBuffer = "";
- }
- state = c === "\r".charCodeAt(0) ? AFTER_CR : FIELD_START;
- } else {
- if (state === FIELD_START) {
- fieldStart = position;
- state = FIELD;
- }
- if (state === FIELD) {
- if (c === ":".charCodeAt(0)) {
- valueStart = position + 1;
- state = VALUE_START;
- }
- } else if (state === VALUE_START) {
- state = VALUE;
- }
- }
- }
- }
- }
- };
- var onFinish = function (error) {
- if (currentState === OPEN || currentState === CONNECTING) {
- currentState = WAITING;
- if (timeout !== 0) {
- clearTimeout(timeout);
- timeout = 0;
- }
- timeout = setTimeout(function () {
- onTimeout();
- }, retry);
- retry = clampDuration(Math.min(initialRetry * 16, retry * 2));
- es.readyState = CONNECTING;
- var event = new ErrorEvent("error", {error: error});
- es.dispatchEvent(event);
- fire(es, es.onerror, event);
- if (error != undefined) {
- console.error(error);
- }
- }
- };
- var close = function () {
- currentState = CLOSED;
- if (abortController != undefined) {
- abortController.abort();
- abortController = undefined;
- }
- if (timeout !== 0) {
- clearTimeout(timeout);
- timeout = 0;
- }
- es.readyState = CLOSED;
- };
- var onTimeout = function () {
- timeout = 0;
- if (currentState !== WAITING) {
- if (!wasActivity && abortController != undefined) {
- onFinish(new Error("No activity within " + heartbeatTimeout + " milliseconds." + " " + (currentState === CONNECTING ? "No response received." : textLength + " chars received.") + " " + "Reconnecting."));
- if (abortController != undefined) {
- abortController.abort();
- abortController = undefined;
- }
- } else {
- var nextHeartbeat = Math.max((wasActivity || Date.now()) + heartbeatTimeout - Date.now(), 1);
- wasActivity = false;
- timeout = setTimeout(function () {
- onTimeout();
- }, nextHeartbeat);
- }
- return;
- }
- wasActivity = false;
- textLength = 0;
- timeout = setTimeout(function () {
- onTimeout();
- }, heartbeatTimeout);
- currentState = CONNECTING;
- dataBuffer = "";
- eventTypeBuffer = "";
- lastEventIdBuffer = lastEventId;
- textBuffer = "";
- fieldStart = 0;
- valueStart = 0;
- state = FIELD_START;
- // https://bugzilla.mozilla.org/show_bug.cgi?id=428916
- // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
- var requestURL = url;
- if (url.slice(0, 5) !== "data:" && url.slice(0, 5) !== "blob:") {
- if (lastEventId !== "") {
- // Remove the lastEventId parameter if it's already part of the request URL.
- var i = url.indexOf("?");
- requestURL = i === -1 ? url : url.slice(0, i + 1) + url.slice(i + 1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g, function (p, paramName) {
- return paramName === lastEventIdQueryParameterName ? '' : p;
- });
- // Append the current lastEventId to the request URL.
- requestURL += (url.indexOf("?") === -1 ? "?" : "&") + lastEventIdQueryParameterName +"=" + encodeURIComponent(lastEventId);
- }
- }
- var withCredentials = es.withCredentials;
- var requestHeaders = {};
- requestHeaders["Accept"] = "text/event-stream";
- var headers = es.headers;
- if (headers != undefined) {
- for (var name in headers) {
- if (Object.prototype.hasOwnProperty.call(headers, name)) {
- requestHeaders[name] = headers[name];
- }
- }
- }
- try {
- abortController = transport.open(xhr, onStart, onProgress, onFinish, requestURL, withCredentials, requestHeaders);
- } catch (error) {
- close();
- throw error;
- }
- };
- es.url = url;
- es.readyState = CONNECTING;
- es.withCredentials = withCredentials;
- es.headers = headers;
- es._close = close;
- onTimeout();
- }
- EventSourcePolyfill.prototype = Object.create(EventTarget.prototype);
- EventSourcePolyfill.prototype.CONNECTING = CONNECTING;
- EventSourcePolyfill.prototype.OPEN = OPEN;
- EventSourcePolyfill.prototype.CLOSED = CLOSED;
- EventSourcePolyfill.prototype.close = function () {
- this._close();
- };
- EventSourcePolyfill.CONNECTING = CONNECTING;
- EventSourcePolyfill.OPEN = OPEN;
- EventSourcePolyfill.CLOSED = CLOSED;
- EventSourcePolyfill.prototype.withCredentials = undefined;
- var R = NativeEventSource;
- if (XMLHttpRequest != undefined && (NativeEventSource == undefined || !("withCredentials" in NativeEventSource.prototype))) {
- // Why replace a native EventSource ?
- // https://bugzilla.mozilla.org/show_bug.cgi?id=444328
- // https://bugzilla.mozilla.org/show_bug.cgi?id=831392
- // https://code.google.com/p/chromium/issues/detail?id=260144
- // https://code.google.com/p/chromium/issues/detail?id=225654
- // ...
- R = EventSourcePolyfill;
- }
- (function (factory) {
- {
- var v = factory(exports);
- if (v !== undefined) module.exports = v;
- }
- })(function (exports) {
- exports.EventSourcePolyfill = EventSourcePolyfill;
- exports.NativeEventSource = NativeEventSource;
- exports.EventSource = R;
- });
- }(typeof globalThis === 'undefined' ? (typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal) : globalThis));
- } (eventsource, eventsourceExports));
- var browser = eventsourceExports.EventSourcePolyfill;
- var browser$1 = /*#__PURE__*/_mergeNamespaces({
- __proto__: null,
- default: browser
- }, [browser]);
- exports.BasePatch = BasePatch;
- exports.BaseTransaction = BaseTransaction;
- exports.ClientError = ClientError;
- exports.ObservablePatch = ObservablePatch;
- exports.ObservableSanityClient = ObservableSanityClient;
- exports.ObservableTransaction = ObservableTransaction;
- exports.Patch = Patch;
- exports.SanityClient = SanityClient;
- exports.ServerError = ServerError;
- exports.Transaction = Transaction;
- exports.createClient = createClient;
- exports.default = deprecatedCreateClient;
- exports.requester = requester;
- exports.unstable__adapter = adapter;
- exports.unstable__environment = environment;
- Object.defineProperty(exports, '__esModule', { value: true });
- }));
|