ParseObject.js 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  3. var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map");
  4. var _Array$isArray2 = require("@babel/runtime-corejs3/core-js-stable/array/is-array");
  5. var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");
  6. var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");
  7. var _sliceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/slice");
  8. var _reverseInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/reverse");
  9. var _Promise2 = require("@babel/runtime-corejs3/core-js-stable/promise");
  10. var _Object$setPrototypeOf = require("@babel/runtime-corejs3/core-js-stable/object/set-prototype-of");
  11. var _typeof3 = require("@babel/runtime-corejs3/helpers/typeof");
  12. var _Object$getPrototypeOf2 = require("@babel/runtime-corejs3/core-js-stable/object/get-prototype-of");
  13. var _Object$create2 = require("@babel/runtime-corejs3/core-js-stable/object/create");
  14. var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");
  15. var _Object$defineProperty2 = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
  16. var _Object$defineProperties = require("@babel/runtime-corejs3/core-js-stable/object/define-properties");
  17. var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors");
  18. var _forEachInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/for-each");
  19. var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
  20. var _filterInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/filter");
  21. var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols");
  22. var _Object$keys2 = require("@babel/runtime-corejs3/core-js-stable/object/keys");
  23. _Object$defineProperty2(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.default = void 0;
  27. var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
  28. var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find"));
  29. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/define-property"));
  30. var _create = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/create"));
  31. var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
  32. var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
  33. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));
  34. var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
  35. var _getPrototypeOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/get-prototype-of"));
  36. var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/includes"));
  37. var _stringify = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/json/stringify"));
  38. var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
  39. var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
  40. var _freeze = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/freeze"));
  41. var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));
  42. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/classCallCheck"));
  43. var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/createClass"));
  44. var _defineProperty3 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
  45. var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
  46. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  47. var _canBeSerialized = _interopRequireDefault(require("./canBeSerialized"));
  48. var _decode = _interopRequireDefault(require("./decode"));
  49. var _encode = _interopRequireDefault(require("./encode"));
  50. var _escape2 = _interopRequireDefault(require("./escape"));
  51. var _EventuallyQueue = _interopRequireDefault(require("./EventuallyQueue"));
  52. var _ParseACL = _interopRequireDefault(require("./ParseACL"));
  53. var _parseDate = _interopRequireDefault(require("./parseDate"));
  54. var _ParseError = _interopRequireDefault(require("./ParseError"));
  55. var _ParseFile = _interopRequireDefault(require("./ParseFile"));
  56. var _promiseUtils = require("./promiseUtils");
  57. var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
  58. var _ParseOp = require("./ParseOp");
  59. var _ParseQuery = _interopRequireDefault(require("./ParseQuery"));
  60. var _ParseRelation = _interopRequireDefault(require("./ParseRelation"));
  61. var SingleInstanceStateController = _interopRequireWildcard(require("./SingleInstanceStateController"));
  62. var _unique = _interopRequireDefault(require("./unique"));
  63. var UniqueInstanceStateController = _interopRequireWildcard(require("./UniqueInstanceStateController"));
  64. var _unsavedChildren = _interopRequireDefault(require("./unsavedChildren"));
  65. function _getRequireWildcardCache(nodeInterop) {
  66. if (typeof _WeakMap !== "function") return null;
  67. var cacheBabelInterop = new _WeakMap();
  68. var cacheNodeInterop = new _WeakMap();
  69. return (_getRequireWildcardCache = function (nodeInterop) {
  70. return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  71. })(nodeInterop);
  72. }
  73. function _interopRequireWildcard(obj, nodeInterop) {
  74. if (!nodeInterop && obj && obj.__esModule) {
  75. return obj;
  76. }
  77. if (obj === null || _typeof3(obj) !== "object" && typeof obj !== "function") {
  78. return {
  79. default: obj
  80. };
  81. }
  82. var cache = _getRequireWildcardCache(nodeInterop);
  83. if (cache && cache.has(obj)) {
  84. return cache.get(obj);
  85. }
  86. var newObj = {};
  87. for (var key in obj) {
  88. if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
  89. var desc = _Object$defineProperty2 && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : null;
  90. if (desc && (desc.get || desc.set)) {
  91. _Object$defineProperty2(newObj, key, desc);
  92. } else {
  93. newObj[key] = obj[key];
  94. }
  95. }
  96. }
  97. newObj.default = obj;
  98. if (cache) {
  99. cache.set(obj, newObj);
  100. }
  101. return newObj;
  102. }
  103. function _createForOfIteratorHelper(o, allowArrayLike) {
  104. var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"];
  105. if (!it) {
  106. if (_Array$isArray2(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  107. if (it) o = it;
  108. var i = 0;
  109. var F = function () {};
  110. return {
  111. s: F,
  112. n: function () {
  113. if (i >= o.length) return {
  114. done: true
  115. };
  116. return {
  117. done: false,
  118. value: o[i++]
  119. };
  120. },
  121. e: function (_e) {
  122. throw _e;
  123. },
  124. f: F
  125. };
  126. }
  127. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  128. }
  129. var normalCompletion = true,
  130. didErr = false,
  131. err;
  132. return {
  133. s: function () {
  134. it = it.call(o);
  135. },
  136. n: function () {
  137. var step = it.next();
  138. normalCompletion = step.done;
  139. return step;
  140. },
  141. e: function (_e2) {
  142. didErr = true;
  143. err = _e2;
  144. },
  145. f: function () {
  146. try {
  147. if (!normalCompletion && it.return != null) it.return();
  148. } finally {
  149. if (didErr) throw err;
  150. }
  151. }
  152. };
  153. }
  154. function _unsupportedIterableToArray(o, minLen) {
  155. var _context20;
  156. if (!o) return;
  157. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  158. var n = _sliceInstanceProperty(_context20 = Object.prototype.toString.call(o)).call(_context20, 8, -1);
  159. if (n === "Object" && o.constructor) n = o.constructor.name;
  160. if (n === "Map" || n === "Set") return _Array$from(o);
  161. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  162. }
  163. function _arrayLikeToArray(arr, len) {
  164. if (len == null || len > arr.length) len = arr.length;
  165. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  166. arr2[i] = arr[i];
  167. }
  168. return arr2;
  169. }
  170. function _regeneratorRuntime() {
  171. "use strict";
  172. /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  173. _regeneratorRuntime = function () {
  174. return exports;
  175. };
  176. var exports = {},
  177. Op = Object.prototype,
  178. hasOwn = Op.hasOwnProperty,
  179. $Symbol = "function" == typeof _Symbol ? _Symbol : {},
  180. iteratorSymbol = $Symbol.iterator || "@@iterator",
  181. asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
  182. toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  183. function define(obj, key, value) {
  184. return _Object$defineProperty2(obj, key, {
  185. value: value,
  186. enumerable: !0,
  187. configurable: !0,
  188. writable: !0
  189. }), obj[key];
  190. }
  191. try {
  192. define({}, "");
  193. } catch (err) {
  194. define = function (obj, key, value) {
  195. return obj[key] = value;
  196. };
  197. }
  198. function wrap(innerFn, outerFn, self, tryLocsList) {
  199. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
  200. generator = _Object$create2(protoGenerator.prototype),
  201. context = new Context(tryLocsList || []);
  202. return generator._invoke = function (innerFn, self, context) {
  203. var state = "suspendedStart";
  204. return function (method, arg) {
  205. if ("executing" === state) throw new Error("Generator is already running");
  206. if ("completed" === state) {
  207. if ("throw" === method) throw arg;
  208. return doneResult();
  209. }
  210. for (context.method = method, context.arg = arg;;) {
  211. var delegate = context.delegate;
  212. if (delegate) {
  213. var delegateResult = maybeInvokeDelegate(delegate, context);
  214. if (delegateResult) {
  215. if (delegateResult === ContinueSentinel) continue;
  216. return delegateResult;
  217. }
  218. }
  219. if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
  220. if ("suspendedStart" === state) throw state = "completed", context.arg;
  221. context.dispatchException(context.arg);
  222. } else "return" === context.method && context.abrupt("return", context.arg);
  223. state = "executing";
  224. var record = tryCatch(innerFn, self, context);
  225. if ("normal" === record.type) {
  226. if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
  227. return {
  228. value: record.arg,
  229. done: context.done
  230. };
  231. }
  232. "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
  233. }
  234. };
  235. }(innerFn, self, context), generator;
  236. }
  237. function tryCatch(fn, obj, arg) {
  238. try {
  239. return {
  240. type: "normal",
  241. arg: fn.call(obj, arg)
  242. };
  243. } catch (err) {
  244. return {
  245. type: "throw",
  246. arg: err
  247. };
  248. }
  249. }
  250. exports.wrap = wrap;
  251. var ContinueSentinel = {};
  252. function Generator() {}
  253. function GeneratorFunction() {}
  254. function GeneratorFunctionPrototype() {}
  255. var IteratorPrototype = {};
  256. define(IteratorPrototype, iteratorSymbol, function () {
  257. return this;
  258. });
  259. var getProto = _Object$getPrototypeOf2,
  260. NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  261. NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
  262. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = _Object$create2(IteratorPrototype);
  263. function defineIteratorMethods(prototype) {
  264. var _context18;
  265. _forEachInstanceProperty2(_context18 = ["next", "throw", "return"]).call(_context18, function (method) {
  266. define(prototype, method, function (arg) {
  267. return this._invoke(method, arg);
  268. });
  269. });
  270. }
  271. function AsyncIterator(generator, PromiseImpl) {
  272. function invoke(method, arg, resolve, reject) {
  273. var record = tryCatch(generator[method], generator, arg);
  274. if ("throw" !== record.type) {
  275. var result = record.arg,
  276. value = result.value;
  277. return value && "object" == _typeof3(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
  278. invoke("next", value, resolve, reject);
  279. }, function (err) {
  280. invoke("throw", err, resolve, reject);
  281. }) : PromiseImpl.resolve(value).then(function (unwrapped) {
  282. result.value = unwrapped, resolve(result);
  283. }, function (error) {
  284. return invoke("throw", error, resolve, reject);
  285. });
  286. }
  287. reject(record.arg);
  288. }
  289. var previousPromise;
  290. this._invoke = function (method, arg) {
  291. function callInvokeWithMethodAndArg() {
  292. return new PromiseImpl(function (resolve, reject) {
  293. invoke(method, arg, resolve, reject);
  294. });
  295. }
  296. return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  297. };
  298. }
  299. function maybeInvokeDelegate(delegate, context) {
  300. var method = delegate.iterator[context.method];
  301. if (undefined === method) {
  302. if (context.delegate = null, "throw" === context.method) {
  303. if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
  304. context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
  305. }
  306. return ContinueSentinel;
  307. }
  308. var record = tryCatch(method, delegate.iterator, context.arg);
  309. if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
  310. var info = record.arg;
  311. return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
  312. }
  313. function pushTryEntry(locs) {
  314. var entry = {
  315. tryLoc: locs[0]
  316. };
  317. 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
  318. }
  319. function resetTryEntry(entry) {
  320. var record = entry.completion || {};
  321. record.type = "normal", delete record.arg, entry.completion = record;
  322. }
  323. function Context(tryLocsList) {
  324. this.tryEntries = [{
  325. tryLoc: "root"
  326. }], _forEachInstanceProperty2(tryLocsList).call(tryLocsList, pushTryEntry, this), this.reset(!0);
  327. }
  328. function values(iterable) {
  329. if (iterable) {
  330. var iteratorMethod = iterable[iteratorSymbol];
  331. if (iteratorMethod) return iteratorMethod.call(iterable);
  332. if ("function" == typeof iterable.next) return iterable;
  333. if (!isNaN(iterable.length)) {
  334. var i = -1,
  335. next = function next() {
  336. for (; ++i < iterable.length;) {
  337. if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
  338. }
  339. return next.value = undefined, next.done = !0, next;
  340. };
  341. return next.next = next;
  342. }
  343. }
  344. return {
  345. next: doneResult
  346. };
  347. }
  348. function doneResult() {
  349. return {
  350. value: undefined,
  351. done: !0
  352. };
  353. }
  354. return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
  355. var ctor = "function" == typeof genFun && genFun.constructor;
  356. return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
  357. }, exports.mark = function (genFun) {
  358. return _Object$setPrototypeOf ? _Object$setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = _Object$create2(Gp), genFun;
  359. }, exports.awrap = function (arg) {
  360. return {
  361. __await: arg
  362. };
  363. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
  364. return this;
  365. }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  366. void 0 === PromiseImpl && (PromiseImpl = _Promise2);
  367. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  368. return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
  369. return result.done ? result.value : iter.next();
  370. });
  371. }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
  372. return this;
  373. }), define(Gp, "toString", function () {
  374. return "[object Generator]";
  375. }), exports.keys = function (object) {
  376. var keys = [];
  377. for (var key in object) {
  378. keys.push(key);
  379. }
  380. return _reverseInstanceProperty(keys).call(keys), function next() {
  381. for (; keys.length;) {
  382. var key = keys.pop();
  383. if (key in object) return next.value = key, next.done = !1, next;
  384. }
  385. return next.done = !0, next;
  386. };
  387. }, exports.values = values, Context.prototype = {
  388. constructor: Context,
  389. reset: function (skipTempReset) {
  390. var _context19;
  391. if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, _forEachInstanceProperty2(_context19 = this.tryEntries).call(_context19, resetTryEntry), !skipTempReset) for (var name in this) {
  392. "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+_sliceInstanceProperty(name).call(name, 1)) && (this[name] = undefined);
  393. }
  394. },
  395. stop: function () {
  396. this.done = !0;
  397. var rootRecord = this.tryEntries[0].completion;
  398. if ("throw" === rootRecord.type) throw rootRecord.arg;
  399. return this.rval;
  400. },
  401. dispatchException: function (exception) {
  402. if (this.done) throw exception;
  403. var context = this;
  404. function handle(loc, caught) {
  405. return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
  406. }
  407. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  408. var entry = this.tryEntries[i],
  409. record = entry.completion;
  410. if ("root" === entry.tryLoc) return handle("end");
  411. if (entry.tryLoc <= this.prev) {
  412. var hasCatch = hasOwn.call(entry, "catchLoc"),
  413. hasFinally = hasOwn.call(entry, "finallyLoc");
  414. if (hasCatch && hasFinally) {
  415. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  416. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  417. } else if (hasCatch) {
  418. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  419. } else {
  420. if (!hasFinally) throw new Error("try statement without catch or finally");
  421. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  422. }
  423. }
  424. }
  425. },
  426. abrupt: function (type, arg) {
  427. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  428. var entry = this.tryEntries[i];
  429. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  430. var finallyEntry = entry;
  431. break;
  432. }
  433. }
  434. finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
  435. var record = finallyEntry ? finallyEntry.completion : {};
  436. return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
  437. },
  438. complete: function (record, afterLoc) {
  439. if ("throw" === record.type) throw record.arg;
  440. return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
  441. },
  442. finish: function (finallyLoc) {
  443. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  444. var entry = this.tryEntries[i];
  445. if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
  446. }
  447. },
  448. catch: function (tryLoc) {
  449. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  450. var entry = this.tryEntries[i];
  451. if (entry.tryLoc === tryLoc) {
  452. var record = entry.completion;
  453. if ("throw" === record.type) {
  454. var thrown = record.arg;
  455. resetTryEntry(entry);
  456. }
  457. return thrown;
  458. }
  459. }
  460. throw new Error("illegal catch attempt");
  461. },
  462. delegateYield: function (iterable, resultName, nextLoc) {
  463. return this.delegate = {
  464. iterator: values(iterable),
  465. resultName: resultName,
  466. nextLoc: nextLoc
  467. }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
  468. }
  469. }, exports;
  470. }
  471. function ownKeys(object, enumerableOnly) {
  472. var keys = _Object$keys2(object);
  473. if (_Object$getOwnPropertySymbols) {
  474. var symbols = _Object$getOwnPropertySymbols(object);
  475. enumerableOnly && (symbols = _filterInstanceProperty(symbols).call(symbols, function (sym) {
  476. return _Object$getOwnPropertyDescriptor(object, sym).enumerable;
  477. })), keys.push.apply(keys, symbols);
  478. }
  479. return keys;
  480. }
  481. function _objectSpread(target) {
  482. for (var i = 1; i < arguments.length; i++) {
  483. var _context16, _context17;
  484. var source = null != arguments[i] ? arguments[i] : {};
  485. i % 2 ? _forEachInstanceProperty2(_context16 = ownKeys(Object(source), !0)).call(_context16, function (key) {
  486. (0, _defineProperty3.default)(target, key, source[key]);
  487. }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(target, _Object$getOwnPropertyDescriptors(source)) : _forEachInstanceProperty2(_context17 = ownKeys(Object(source))).call(_context17, function (key) {
  488. _Object$defineProperty2(target, key, _Object$getOwnPropertyDescriptor(source, key));
  489. });
  490. }
  491. return target;
  492. }
  493. var uuidv4 = require('./uuid');
  494. /*:: export type Pointer = {
  495. __type: string,
  496. className: string,
  497. objectId: string,
  498. };*/
  499. /*:: type SaveParams = {
  500. method: string,
  501. path: string,
  502. body: AttributeMap,
  503. };*/
  504. /*:: export type SaveOptions = FullOptions & {
  505. cascadeSave?: boolean,
  506. context?: AttributeMap,
  507. };*/
  508. // Mapping of class names to constructors, so we can populate objects from the
  509. // server with appropriate subclasses of ParseObject
  510. var classMap = {}; // Global counter for generating unique Ids for non-single-instance objects
  511. var objectCount = 0; // On web clients, objects are single-instance: any two objects with the same Id
  512. // will have the same attributes. However, this may be dangerous default
  513. // behavior in a server scenario
  514. var singleInstance = !_CoreManager.default.get('IS_NODE');
  515. if (singleInstance) {
  516. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  517. } else {
  518. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  519. }
  520. function getServerUrlPath() {
  521. var serverUrl = _CoreManager.default.get('SERVER_URL');
  522. if (serverUrl[serverUrl.length - 1] !== '/') {
  523. serverUrl += '/';
  524. }
  525. var url = serverUrl.replace(/https?:\/\//, '');
  526. return url.substr((0, _indexOf.default)(url).call(url, '/'));
  527. }
  528. /**
  529. * Creates a new model with defined attributes.
  530. *
  531. * <p>You won't normally call this method directly. It is recommended that
  532. * you use a subclass of <code>Parse.Object</code> instead, created by calling
  533. * <code>extend</code>.</p>
  534. *
  535. * <p>However, if you don't want to use a subclass, or aren't sure which
  536. * subclass is appropriate, you can use this form:<pre>
  537. * var object = new Parse.Object("ClassName");
  538. * </pre>
  539. * That is basically equivalent to:<pre>
  540. * var MyClass = Parse.Object.extend("ClassName");
  541. * var object = new MyClass();
  542. * </pre></p>
  543. *
  544. * @alias Parse.Object
  545. */
  546. var ParseObject = /*#__PURE__*/function () {
  547. /**
  548. * @param {string} className The class name for the object
  549. * @param {object} attributes The initial set of data to store in the object.
  550. * @param {object} options The options for this object instance.
  551. */
  552. function ParseObject(className
  553. /*: ?string | { className: string, [attr: string]: mixed }*/
  554. , attributes
  555. /*:: ?: { [attr: string]: mixed }*/
  556. , options
  557. /*:: ?: { ignoreValidation: boolean }*/
  558. ) {
  559. (0, _classCallCheck2.default)(this, ParseObject);
  560. (0, _defineProperty3.default)(this, "id", void 0);
  561. (0, _defineProperty3.default)(this, "_localId", void 0);
  562. (0, _defineProperty3.default)(this, "_objCount", void 0);
  563. (0, _defineProperty3.default)(this, "className", void 0); // Enable legacy initializers
  564. if (typeof this.initialize === 'function') {
  565. this.initialize.apply(this, arguments);
  566. }
  567. var toSet = null;
  568. this._objCount = objectCount++;
  569. if (typeof className === 'string') {
  570. this.className = className;
  571. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  572. toSet = attributes;
  573. }
  574. } else if (className && (0, _typeof2.default)(className) === 'object') {
  575. this.className = className.className;
  576. toSet = {};
  577. for (var _attr in className) {
  578. if (_attr !== 'className') {
  579. toSet[_attr] = className[_attr];
  580. }
  581. }
  582. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  583. options = attributes;
  584. }
  585. }
  586. if (toSet && !this.set(toSet, options)) {
  587. throw new Error("Can't create an invalid Parse Object");
  588. }
  589. }
  590. /**
  591. * The ID of this object, unique within its class.
  592. *
  593. * @property {string} id
  594. */
  595. (0, _createClass2.default)(ParseObject, [{
  596. key: "attributes",
  597. get:
  598. /** Prototype getters / setters **/
  599. function ()
  600. /*: AttributeMap*/
  601. {
  602. var stateController = _CoreManager.default.getObjectStateController();
  603. return (0, _freeze.default)(stateController.estimateAttributes(this._getStateIdentifier()));
  604. }
  605. /**
  606. * The first time this object was saved on the server.
  607. *
  608. * @property {Date} createdAt
  609. * @returns {Date}
  610. */
  611. }, {
  612. key: "createdAt",
  613. get: function ()
  614. /*: ?Date*/
  615. {
  616. return this._getServerData().createdAt;
  617. }
  618. /**
  619. * The last time this object was updated on the server.
  620. *
  621. * @property {Date} updatedAt
  622. * @returns {Date}
  623. */
  624. }, {
  625. key: "updatedAt",
  626. get: function ()
  627. /*: ?Date*/
  628. {
  629. return this._getServerData().updatedAt;
  630. }
  631. /** Private methods **/
  632. /**
  633. * Returns a local or server Id used uniquely identify this object
  634. *
  635. * @returns {string}
  636. */
  637. }, {
  638. key: "_getId",
  639. value: function ()
  640. /*: string*/
  641. {
  642. if (typeof this.id === 'string') {
  643. return this.id;
  644. }
  645. if (typeof this._localId === 'string') {
  646. return this._localId;
  647. }
  648. var localId = 'local' + uuidv4();
  649. this._localId = localId;
  650. return localId;
  651. }
  652. /**
  653. * Returns a unique identifier used to pull data from the State Controller.
  654. *
  655. * @returns {Parse.Object|object}
  656. */
  657. }, {
  658. key: "_getStateIdentifier",
  659. value: function ()
  660. /*: ParseObject | { id: string, className: string }*/
  661. {
  662. if (singleInstance) {
  663. var id = this.id;
  664. if (!id) {
  665. id = this._getId();
  666. }
  667. return {
  668. id: id,
  669. className: this.className
  670. };
  671. } else {
  672. return this;
  673. }
  674. }
  675. }, {
  676. key: "_getServerData",
  677. value: function ()
  678. /*: AttributeMap*/
  679. {
  680. var stateController = _CoreManager.default.getObjectStateController();
  681. return stateController.getServerData(this._getStateIdentifier());
  682. }
  683. }, {
  684. key: "_clearServerData",
  685. value: function () {
  686. var serverData = this._getServerData();
  687. var unset = {};
  688. for (var _attr2 in serverData) {
  689. unset[_attr2] = undefined;
  690. }
  691. var stateController = _CoreManager.default.getObjectStateController();
  692. stateController.setServerData(this._getStateIdentifier(), unset);
  693. }
  694. }, {
  695. key: "_getPendingOps",
  696. value: function ()
  697. /*: Array<OpsMap>*/
  698. {
  699. var stateController = _CoreManager.default.getObjectStateController();
  700. return stateController.getPendingOps(this._getStateIdentifier());
  701. }
  702. /**
  703. * @param {Array<string>} [keysToClear] - if specified, only ops matching
  704. * these fields will be cleared
  705. */
  706. }, {
  707. key: "_clearPendingOps",
  708. value: function (keysToClear
  709. /*:: ?: Array<string>*/
  710. ) {
  711. var pending = this._getPendingOps();
  712. var latest = pending[pending.length - 1];
  713. var keys = keysToClear || (0, _keys.default)(latest);
  714. (0, _forEach.default)(keys).call(keys, function (key) {
  715. delete latest[key];
  716. });
  717. }
  718. }, {
  719. key: "_getDirtyObjectAttributes",
  720. value: function ()
  721. /*: AttributeMap*/
  722. {
  723. var attributes = this.attributes;
  724. var stateController = _CoreManager.default.getObjectStateController();
  725. var objectCache = stateController.getObjectCache(this._getStateIdentifier());
  726. var dirty = {};
  727. for (var _attr3 in attributes) {
  728. var val = attributes[_attr3];
  729. if (val && (0, _typeof2.default)(val) === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
  730. // Due to the way browsers construct maps, the key order will not change
  731. // unless the object is changed
  732. try {
  733. var json = (0, _encode.default)(val, false, true);
  734. var stringified = (0, _stringify.default)(json);
  735. if (objectCache[_attr3] !== stringified) {
  736. dirty[_attr3] = val;
  737. }
  738. } catch (e) {
  739. // Error occurred, possibly by a nested unsaved pointer in a mutable container
  740. // No matter how it happened, it indicates a change in the attribute
  741. dirty[_attr3] = val;
  742. }
  743. }
  744. }
  745. return dirty;
  746. }
  747. }, {
  748. key: "_toFullJSON",
  749. value: function (seen
  750. /*:: ?: Array<any>*/
  751. , offline
  752. /*:: ?: boolean*/
  753. )
  754. /*: AttributeMap*/
  755. {
  756. var json
  757. /*: { [key: string]: mixed }*/
  758. = this.toJSON(seen, offline);
  759. json.__type = 'Object';
  760. json.className = this.className;
  761. return json;
  762. }
  763. }, {
  764. key: "_getSaveJSON",
  765. value: function ()
  766. /*: AttributeMap*/
  767. {
  768. var pending = this._getPendingOps();
  769. var dirtyObjects = this._getDirtyObjectAttributes();
  770. var json = {};
  771. for (var attr in dirtyObjects) {
  772. var isDotNotation = false;
  773. for (var i = 0; i < pending.length; i += 1) {
  774. for (var field in pending[i]) {
  775. // Dot notation operations are handled later
  776. if ((0, _includes.default)(field).call(field, '.')) {
  777. var fieldName = field.split('.')[0];
  778. if (fieldName === attr) {
  779. isDotNotation = true;
  780. break;
  781. }
  782. }
  783. }
  784. }
  785. if (!isDotNotation) {
  786. json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
  787. }
  788. }
  789. for (attr in pending[0]) {
  790. json[attr] = pending[0][attr].toJSON();
  791. }
  792. return json;
  793. }
  794. }, {
  795. key: "_getSaveParams",
  796. value: function ()
  797. /*: SaveParams*/
  798. {
  799. var method = this.id ? 'PUT' : 'POST';
  800. var body = this._getSaveJSON();
  801. var path = 'classes/' + this.className;
  802. if (_CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID')) {
  803. if (!this.createdAt) {
  804. method = 'POST';
  805. body.objectId = this.id;
  806. } else {
  807. method = 'PUT';
  808. path += '/' + this.id;
  809. }
  810. } else if (this.id) {
  811. path += '/' + this.id;
  812. } else if (this.className === '_User') {
  813. path = 'users';
  814. }
  815. return {
  816. method: method,
  817. body: body,
  818. path: path
  819. };
  820. }
  821. }, {
  822. key: "_finishFetch",
  823. value: function (serverData
  824. /*: AttributeMap*/
  825. ) {
  826. if (!this.id && serverData.objectId) {
  827. this.id = serverData.objectId;
  828. }
  829. var stateController = _CoreManager.default.getObjectStateController();
  830. stateController.initializeState(this._getStateIdentifier());
  831. var decoded = {};
  832. for (var _attr4 in serverData) {
  833. if (_attr4 === 'ACL') {
  834. decoded[_attr4] = new _ParseACL.default(serverData[_attr4]);
  835. } else if (_attr4 !== 'objectId') {
  836. decoded[_attr4] = (0, _decode.default)(serverData[_attr4]);
  837. if (decoded[_attr4] instanceof _ParseRelation.default) {
  838. decoded[_attr4]._ensureParentAndKey(this, _attr4);
  839. }
  840. }
  841. }
  842. if (decoded.createdAt && typeof decoded.createdAt === 'string') {
  843. decoded.createdAt = (0, _parseDate.default)(decoded.createdAt);
  844. }
  845. if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
  846. decoded.updatedAt = (0, _parseDate.default)(decoded.updatedAt);
  847. }
  848. if (!decoded.updatedAt && decoded.createdAt) {
  849. decoded.updatedAt = decoded.createdAt;
  850. }
  851. stateController.commitServerChanges(this._getStateIdentifier(), decoded);
  852. }
  853. }, {
  854. key: "_setExisted",
  855. value: function (existed
  856. /*: boolean*/
  857. ) {
  858. var stateController = _CoreManager.default.getObjectStateController();
  859. var state = stateController.getState(this._getStateIdentifier());
  860. if (state) {
  861. state.existed = existed;
  862. }
  863. }
  864. }, {
  865. key: "_migrateId",
  866. value: function (serverId
  867. /*: string*/
  868. ) {
  869. if (this._localId && serverId) {
  870. if (singleInstance) {
  871. var stateController = _CoreManager.default.getObjectStateController();
  872. var oldState = stateController.removeState(this._getStateIdentifier());
  873. this.id = serverId;
  874. delete this._localId;
  875. if (oldState) {
  876. stateController.initializeState(this._getStateIdentifier(), oldState);
  877. }
  878. } else {
  879. this.id = serverId;
  880. delete this._localId;
  881. }
  882. }
  883. }
  884. }, {
  885. key: "_handleSaveResponse",
  886. value: function (response
  887. /*: AttributeMap*/
  888. , status
  889. /*: number*/
  890. ) {
  891. var changes = {};
  892. var stateController = _CoreManager.default.getObjectStateController();
  893. var pending = stateController.popPendingState(this._getStateIdentifier());
  894. for (var attr in pending) {
  895. if (pending[attr] instanceof _ParseOp.RelationOp) {
  896. changes[attr] = pending[attr].applyTo(undefined, this, attr);
  897. } else if (!(attr in response)) {
  898. // Only SetOps and UnsetOps should not come back with results
  899. changes[attr] = pending[attr].applyTo(undefined);
  900. }
  901. }
  902. for (attr in response) {
  903. if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
  904. changes[attr] = (0, _parseDate.default)(response[attr]);
  905. } else if (attr === 'ACL') {
  906. changes[attr] = new _ParseACL.default(response[attr]);
  907. } else if (attr !== 'objectId') {
  908. var val = (0, _decode.default)(response[attr]);
  909. if (val && (0, _getPrototypeOf.default)(val) === Object.prototype) {
  910. changes[attr] = _objectSpread(_objectSpread({}, this.attributes[attr]), val);
  911. } else {
  912. changes[attr] = val;
  913. }
  914. if (changes[attr] instanceof _ParseOp.UnsetOp) {
  915. changes[attr] = undefined;
  916. }
  917. }
  918. }
  919. if (changes.createdAt && !changes.updatedAt) {
  920. changes.updatedAt = changes.createdAt;
  921. }
  922. this._migrateId(response.objectId);
  923. if (status !== 201) {
  924. this._setExisted(true);
  925. }
  926. stateController.commitServerChanges(this._getStateIdentifier(), changes);
  927. }
  928. }, {
  929. key: "_handleSaveError",
  930. value: function () {
  931. var stateController = _CoreManager.default.getObjectStateController();
  932. stateController.mergeFirstPendingState(this._getStateIdentifier());
  933. }
  934. }, {
  935. key: "initialize",
  936. value:
  937. /** Public methods **/
  938. function () {// NOOP
  939. }
  940. /**
  941. * Returns a JSON version of the object suitable for saving to Parse.
  942. *
  943. * @param seen
  944. * @param offline
  945. * @returns {object}
  946. */
  947. }, {
  948. key: "toJSON",
  949. value: function (seen
  950. /*: Array<any> | void*/
  951. , offline
  952. /*:: ?: boolean*/
  953. )
  954. /*: AttributeMap*/
  955. {
  956. var seenEntry = this.id ? this.className + ':' + this.id : this;
  957. seen = seen || [seenEntry];
  958. var json = {};
  959. var attrs = this.attributes;
  960. for (var _attr5 in attrs) {
  961. if ((_attr5 === 'createdAt' || _attr5 === 'updatedAt') && attrs[_attr5].toJSON) {
  962. json[_attr5] = attrs[_attr5].toJSON();
  963. } else {
  964. json[_attr5] = (0, _encode.default)(attrs[_attr5], false, false, seen, offline);
  965. }
  966. }
  967. var pending = this._getPendingOps();
  968. for (var _attr6 in pending[0]) {
  969. json[_attr6] = pending[0][_attr6].toJSON(offline);
  970. }
  971. if (this.id) {
  972. json.objectId = this.id;
  973. }
  974. return json;
  975. }
  976. /**
  977. * Determines whether this ParseObject is equal to another ParseObject
  978. *
  979. * @param {object} other - An other object ot compare
  980. * @returns {boolean}
  981. */
  982. }, {
  983. key: "equals",
  984. value: function (other
  985. /*: mixed*/
  986. )
  987. /*: boolean*/
  988. {
  989. if (this === other) {
  990. return true;
  991. }
  992. return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
  993. }
  994. /**
  995. * Returns true if this object has been modified since its last
  996. * save/refresh. If an attribute is specified, it returns true only if that
  997. * particular attribute has been modified since the last save/refresh.
  998. *
  999. * @param {string} attr An attribute name (optional).
  1000. * @returns {boolean}
  1001. */
  1002. }, {
  1003. key: "dirty",
  1004. value: function (attr
  1005. /*:: ?: string*/
  1006. )
  1007. /*: boolean*/
  1008. {
  1009. if (!this.id) {
  1010. return true;
  1011. }
  1012. var pendingOps = this._getPendingOps();
  1013. var dirtyObjects = this._getDirtyObjectAttributes();
  1014. if (attr) {
  1015. if (dirtyObjects.hasOwnProperty(attr)) {
  1016. return true;
  1017. }
  1018. for (var i = 0; i < pendingOps.length; i++) {
  1019. if (pendingOps[i].hasOwnProperty(attr)) {
  1020. return true;
  1021. }
  1022. }
  1023. return false;
  1024. }
  1025. if ((0, _keys.default)(pendingOps[0]).length !== 0) {
  1026. return true;
  1027. }
  1028. if ((0, _keys.default)(dirtyObjects).length !== 0) {
  1029. return true;
  1030. }
  1031. return false;
  1032. }
  1033. /**
  1034. * Returns an array of keys that have been modified since last save/refresh
  1035. *
  1036. * @returns {string[]}
  1037. */
  1038. }, {
  1039. key: "dirtyKeys",
  1040. value: function ()
  1041. /*: Array<string>*/
  1042. {
  1043. var pendingOps = this._getPendingOps();
  1044. var keys = {};
  1045. for (var i = 0; i < pendingOps.length; i++) {
  1046. for (var _attr7 in pendingOps[i]) {
  1047. keys[_attr7] = true;
  1048. }
  1049. }
  1050. var dirtyObjects = this._getDirtyObjectAttributes();
  1051. for (var _attr8 in dirtyObjects) {
  1052. keys[_attr8] = true;
  1053. }
  1054. return (0, _keys.default)(keys);
  1055. }
  1056. /**
  1057. * Returns true if the object has been fetched.
  1058. *
  1059. * @returns {boolean}
  1060. */
  1061. }, {
  1062. key: "isDataAvailable",
  1063. value: function ()
  1064. /*: boolean*/
  1065. {
  1066. var serverData = this._getServerData();
  1067. return !!(0, _keys.default)(serverData).length;
  1068. }
  1069. /**
  1070. * Gets a Pointer referencing this Object.
  1071. *
  1072. * @returns {Pointer}
  1073. */
  1074. }, {
  1075. key: "toPointer",
  1076. value: function ()
  1077. /*: Pointer*/
  1078. {
  1079. if (!this.id) {
  1080. throw new Error('Cannot create a pointer to an unsaved ParseObject');
  1081. }
  1082. return {
  1083. __type: 'Pointer',
  1084. className: this.className,
  1085. objectId: this.id
  1086. };
  1087. }
  1088. /**
  1089. * Gets a Pointer referencing this Object.
  1090. *
  1091. * @returns {Pointer}
  1092. */
  1093. }, {
  1094. key: "toOfflinePointer",
  1095. value: function ()
  1096. /*: Pointer*/
  1097. {
  1098. if (!this._localId) {
  1099. throw new Error('Cannot create a offline pointer to a saved ParseObject');
  1100. }
  1101. return {
  1102. __type: 'Object',
  1103. className: this.className,
  1104. _localId: this._localId
  1105. };
  1106. }
  1107. /**
  1108. * Gets the value of an attribute.
  1109. *
  1110. * @param {string} attr The string name of an attribute.
  1111. * @returns {*}
  1112. */
  1113. }, {
  1114. key: "get",
  1115. value: function (attr
  1116. /*: string*/
  1117. )
  1118. /*: mixed*/
  1119. {
  1120. return this.attributes[attr];
  1121. }
  1122. /**
  1123. * Gets a relation on the given class for the attribute.
  1124. *
  1125. * @param {string} attr The attribute to get the relation for.
  1126. * @returns {Parse.Relation}
  1127. */
  1128. }, {
  1129. key: "relation",
  1130. value: function (attr
  1131. /*: string*/
  1132. )
  1133. /*: ParseRelation*/
  1134. {
  1135. var value = this.get(attr);
  1136. if (value) {
  1137. if (!(value instanceof _ParseRelation.default)) {
  1138. throw new Error('Called relation() on non-relation field ' + attr);
  1139. }
  1140. value._ensureParentAndKey(this, attr);
  1141. return value;
  1142. }
  1143. return new _ParseRelation.default(this, attr);
  1144. }
  1145. /**
  1146. * Gets the HTML-escaped value of an attribute.
  1147. *
  1148. * @param {string} attr The string name of an attribute.
  1149. * @returns {string}
  1150. */
  1151. }, {
  1152. key: "escape",
  1153. value: function (attr
  1154. /*: string*/
  1155. )
  1156. /*: string*/
  1157. {
  1158. var val = this.attributes[attr];
  1159. if (val == null) {
  1160. return '';
  1161. }
  1162. if (typeof val !== 'string') {
  1163. if (typeof val.toString !== 'function') {
  1164. return '';
  1165. }
  1166. val = val.toString();
  1167. }
  1168. return (0, _escape2.default)(val);
  1169. }
  1170. /**
  1171. * Returns <code>true</code> if the attribute contains a value that is not
  1172. * null or undefined.
  1173. *
  1174. * @param {string} attr The string name of the attribute.
  1175. * @returns {boolean}
  1176. */
  1177. }, {
  1178. key: "has",
  1179. value: function (attr
  1180. /*: string*/
  1181. )
  1182. /*: boolean*/
  1183. {
  1184. var attributes = this.attributes;
  1185. if (attributes.hasOwnProperty(attr)) {
  1186. return attributes[attr] != null;
  1187. }
  1188. return false;
  1189. }
  1190. /**
  1191. * Sets a hash of model attributes on the object.
  1192. *
  1193. * <p>You can call it with an object containing keys and values, with one
  1194. * key and value, or dot notation. For example:<pre>
  1195. * gameTurn.set({
  1196. * player: player1,
  1197. * diceRoll: 2
  1198. * }, {
  1199. * error: function(gameTurnAgain, error) {
  1200. * // The set failed validation.
  1201. * }
  1202. * });
  1203. *
  1204. * game.set("currentPlayer", player2, {
  1205. * error: function(gameTurnAgain, error) {
  1206. * // The set failed validation.
  1207. * }
  1208. * });
  1209. *
  1210. * game.set("finished", true);</pre></p>
  1211. *
  1212. * game.set("player.score", 10);</pre></p>
  1213. *
  1214. * @param {(string|object)} key The key to set.
  1215. * @param {(string|object)} value The value to give it.
  1216. * @param {object} options A set of options for the set.
  1217. * The only supported option is <code>error</code>.
  1218. * @returns {(ParseObject|boolean)} true if the set succeeded.
  1219. */
  1220. }, {
  1221. key: "set",
  1222. value: function (key
  1223. /*: mixed*/
  1224. , value
  1225. /*: mixed*/
  1226. , options
  1227. /*:: ?: mixed*/
  1228. )
  1229. /*: ParseObject | boolean*/
  1230. {
  1231. var changes = {};
  1232. var newOps = {};
  1233. if (key && (0, _typeof2.default)(key) === 'object') {
  1234. changes = key;
  1235. options = value;
  1236. } else if (typeof key === 'string') {
  1237. changes[key] = value;
  1238. } else {
  1239. return this;
  1240. }
  1241. options = options || {};
  1242. var readonly = [];
  1243. if (typeof this.constructor.readOnlyAttributes === 'function') {
  1244. readonly = (0, _concat.default)(readonly).call(readonly, this.constructor.readOnlyAttributes());
  1245. }
  1246. for (var k in changes) {
  1247. if (k === 'createdAt' || k === 'updatedAt') {
  1248. // This property is read-only, but for legacy reasons we silently
  1249. // ignore it
  1250. continue;
  1251. }
  1252. if ((0, _indexOf.default)(readonly).call(readonly, k) > -1) {
  1253. throw new Error('Cannot modify readonly attribute: ' + k);
  1254. }
  1255. if (options.unset) {
  1256. newOps[k] = new _ParseOp.UnsetOp();
  1257. } else if (changes[k] instanceof _ParseOp.Op) {
  1258. newOps[k] = changes[k];
  1259. } else if (changes[k] && (0, _typeof2.default)(changes[k]) === 'object' && typeof changes[k].__op === 'string') {
  1260. newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
  1261. } else if (k === 'objectId' || k === 'id') {
  1262. if (typeof changes[k] === 'string') {
  1263. this.id = changes[k];
  1264. }
  1265. } else if (k === 'ACL' && (0, _typeof2.default)(changes[k]) === 'object' && !(changes[k] instanceof _ParseACL.default)) {
  1266. newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
  1267. } else if (changes[k] instanceof _ParseRelation.default) {
  1268. var relation = new _ParseRelation.default(this, k);
  1269. relation.targetClassName = changes[k].targetClassName;
  1270. newOps[k] = new _ParseOp.SetOp(relation);
  1271. } else {
  1272. newOps[k] = new _ParseOp.SetOp(changes[k]);
  1273. }
  1274. }
  1275. var currentAttributes = this.attributes; // Calculate new values
  1276. var newValues = {};
  1277. for (var _attr9 in newOps) {
  1278. if (newOps[_attr9] instanceof _ParseOp.RelationOp) {
  1279. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9], this, _attr9);
  1280. } else if (!(newOps[_attr9] instanceof _ParseOp.UnsetOp)) {
  1281. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9]);
  1282. }
  1283. } // Validate changes
  1284. if (!options.ignoreValidation) {
  1285. var validation = this.validate(newValues);
  1286. if (validation) {
  1287. if (typeof options.error === 'function') {
  1288. options.error(this, validation);
  1289. }
  1290. return false;
  1291. }
  1292. } // Consolidate Ops
  1293. var pendingOps = this._getPendingOps();
  1294. var last = pendingOps.length - 1;
  1295. var stateController = _CoreManager.default.getObjectStateController();
  1296. for (var _attr10 in newOps) {
  1297. var nextOp = newOps[_attr10].mergeWith(pendingOps[last][_attr10]);
  1298. stateController.setPendingOp(this._getStateIdentifier(), _attr10, nextOp);
  1299. }
  1300. return this;
  1301. }
  1302. /**
  1303. * Remove an attribute from the model. This is a noop if the attribute doesn't
  1304. * exist.
  1305. *
  1306. * @param {string} attr The string name of an attribute.
  1307. * @param options
  1308. * @returns {(ParseObject | boolean)}
  1309. */
  1310. }, {
  1311. key: "unset",
  1312. value: function (attr
  1313. /*: string*/
  1314. , options
  1315. /*:: ?: { [opt: string]: mixed }*/
  1316. )
  1317. /*: ParseObject | boolean*/
  1318. {
  1319. options = options || {};
  1320. options.unset = true;
  1321. return this.set(attr, null, options);
  1322. }
  1323. /**
  1324. * Atomically increments the value of the given attribute the next time the
  1325. * object is saved. If no amount is specified, 1 is used by default.
  1326. *
  1327. * @param attr {String} The key.
  1328. * @param amount {Number} The amount to increment by (optional).
  1329. * @returns {(ParseObject|boolean)}
  1330. */
  1331. }, {
  1332. key: "increment",
  1333. value: function (attr
  1334. /*: string*/
  1335. , amount
  1336. /*:: ?: number*/
  1337. )
  1338. /*: ParseObject | boolean*/
  1339. {
  1340. if (typeof amount === 'undefined') {
  1341. amount = 1;
  1342. }
  1343. if (typeof amount !== 'number') {
  1344. throw new Error('Cannot increment by a non-numeric amount.');
  1345. }
  1346. return this.set(attr, new _ParseOp.IncrementOp(amount));
  1347. }
  1348. /**
  1349. * Atomically decrements the value of the given attribute the next time the
  1350. * object is saved. If no amount is specified, 1 is used by default.
  1351. *
  1352. * @param attr {String} The key.
  1353. * @param amount {Number} The amount to decrement by (optional).
  1354. * @returns {(ParseObject | boolean)}
  1355. */
  1356. }, {
  1357. key: "decrement",
  1358. value: function (attr
  1359. /*: string*/
  1360. , amount
  1361. /*:: ?: number*/
  1362. )
  1363. /*: ParseObject | boolean*/
  1364. {
  1365. if (typeof amount === 'undefined') {
  1366. amount = 1;
  1367. }
  1368. if (typeof amount !== 'number') {
  1369. throw new Error('Cannot decrement by a non-numeric amount.');
  1370. }
  1371. return this.set(attr, new _ParseOp.IncrementOp(amount * -1));
  1372. }
  1373. /**
  1374. * Atomically add an object to the end of the array associated with a given
  1375. * key.
  1376. *
  1377. * @param attr {String} The key.
  1378. * @param item {} The item to add.
  1379. * @returns {(ParseObject | boolean)}
  1380. */
  1381. }, {
  1382. key: "add",
  1383. value: function (attr
  1384. /*: string*/
  1385. , item
  1386. /*: mixed*/
  1387. )
  1388. /*: ParseObject | boolean*/
  1389. {
  1390. return this.set(attr, new _ParseOp.AddOp([item]));
  1391. }
  1392. /**
  1393. * Atomically add the objects to the end of the array associated with a given
  1394. * key.
  1395. *
  1396. * @param attr {String} The key.
  1397. * @param items {Object[]} The items to add.
  1398. * @returns {(ParseObject | boolean)}
  1399. */
  1400. }, {
  1401. key: "addAll",
  1402. value: function (attr
  1403. /*: string*/
  1404. , items
  1405. /*: Array<mixed>*/
  1406. )
  1407. /*: ParseObject | boolean*/
  1408. {
  1409. return this.set(attr, new _ParseOp.AddOp(items));
  1410. }
  1411. /**
  1412. * Atomically add an object to the array associated with a given key, only
  1413. * if it is not already present in the array. The position of the insert is
  1414. * not guaranteed.
  1415. *
  1416. * @param attr {String} The key.
  1417. * @param item {} The object to add.
  1418. * @returns {(ParseObject | boolean)}
  1419. */
  1420. }, {
  1421. key: "addUnique",
  1422. value: function (attr
  1423. /*: string*/
  1424. , item
  1425. /*: mixed*/
  1426. )
  1427. /*: ParseObject | boolean*/
  1428. {
  1429. return this.set(attr, new _ParseOp.AddUniqueOp([item]));
  1430. }
  1431. /**
  1432. * Atomically add the objects to the array associated with a given key, only
  1433. * if it is not already present in the array. The position of the insert is
  1434. * not guaranteed.
  1435. *
  1436. * @param attr {String} The key.
  1437. * @param items {Object[]} The objects to add.
  1438. * @returns {(ParseObject | boolean)}
  1439. */
  1440. }, {
  1441. key: "addAllUnique",
  1442. value: function (attr
  1443. /*: string*/
  1444. , items
  1445. /*: Array<mixed>*/
  1446. )
  1447. /*: ParseObject | boolean*/
  1448. {
  1449. return this.set(attr, new _ParseOp.AddUniqueOp(items));
  1450. }
  1451. /**
  1452. * Atomically remove all instances of an object from the array associated
  1453. * with a given key.
  1454. *
  1455. * @param attr {String} The key.
  1456. * @param item {} The object to remove.
  1457. * @returns {(ParseObject | boolean)}
  1458. */
  1459. }, {
  1460. key: "remove",
  1461. value: function (attr
  1462. /*: string*/
  1463. , item
  1464. /*: mixed*/
  1465. )
  1466. /*: ParseObject | boolean*/
  1467. {
  1468. return this.set(attr, new _ParseOp.RemoveOp([item]));
  1469. }
  1470. /**
  1471. * Atomically remove all instances of the objects from the array associated
  1472. * with a given key.
  1473. *
  1474. * @param attr {String} The key.
  1475. * @param items {Object[]} The object to remove.
  1476. * @returns {(ParseObject | boolean)}
  1477. */
  1478. }, {
  1479. key: "removeAll",
  1480. value: function (attr
  1481. /*: string*/
  1482. , items
  1483. /*: Array<mixed>*/
  1484. )
  1485. /*: ParseObject | boolean*/
  1486. {
  1487. return this.set(attr, new _ParseOp.RemoveOp(items));
  1488. }
  1489. /**
  1490. * Returns an instance of a subclass of Parse.Op describing what kind of
  1491. * modification has been performed on this field since the last time it was
  1492. * saved. For example, after calling object.increment("x"), calling
  1493. * object.op("x") would return an instance of Parse.Op.Increment.
  1494. *
  1495. * @param attr {String} The key.
  1496. * @returns {Parse.Op} The operation, or undefined if none.
  1497. */
  1498. }, {
  1499. key: "op",
  1500. value: function (attr
  1501. /*: string*/
  1502. )
  1503. /*: ?Op*/
  1504. {
  1505. var pending = this._getPendingOps();
  1506. for (var i = pending.length; i--;) {
  1507. if (pending[i][attr]) {
  1508. return pending[i][attr];
  1509. }
  1510. }
  1511. }
  1512. /**
  1513. * Creates a new model with identical attributes to this one.
  1514. *
  1515. * @returns {Parse.Object}
  1516. */
  1517. }, {
  1518. key: "clone",
  1519. value: function clone()
  1520. /*: any*/
  1521. {
  1522. var clone = new this.constructor(this.className);
  1523. var attributes = this.attributes;
  1524. if (typeof this.constructor.readOnlyAttributes === 'function') {
  1525. var readonly = this.constructor.readOnlyAttributes() || []; // Attributes are frozen, so we have to rebuild an object,
  1526. // rather than delete readonly keys
  1527. var copy = {};
  1528. for (var a in attributes) {
  1529. if ((0, _indexOf.default)(readonly).call(readonly, a) < 0) {
  1530. copy[a] = attributes[a];
  1531. }
  1532. }
  1533. attributes = copy;
  1534. }
  1535. if (clone.set) {
  1536. clone.set(attributes);
  1537. }
  1538. return clone;
  1539. }
  1540. /**
  1541. * Creates a new instance of this object. Not to be confused with clone()
  1542. *
  1543. * @returns {Parse.Object}
  1544. */
  1545. }, {
  1546. key: "newInstance",
  1547. value: function ()
  1548. /*: any*/
  1549. {
  1550. var clone = new this.constructor(this.className);
  1551. clone.id = this.id;
  1552. if (singleInstance) {
  1553. // Just return an object with the right id
  1554. return clone;
  1555. }
  1556. var stateController = _CoreManager.default.getObjectStateController();
  1557. if (stateController) {
  1558. stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
  1559. }
  1560. return clone;
  1561. }
  1562. /**
  1563. * Returns true if this object has never been saved to Parse.
  1564. *
  1565. * @returns {boolean}
  1566. */
  1567. }, {
  1568. key: "isNew",
  1569. value: function ()
  1570. /*: boolean*/
  1571. {
  1572. return !this.id;
  1573. }
  1574. /**
  1575. * Returns true if this object was created by the Parse server when the
  1576. * object might have already been there (e.g. in the case of a Facebook
  1577. * login)
  1578. *
  1579. * @returns {boolean}
  1580. */
  1581. }, {
  1582. key: "existed",
  1583. value: function ()
  1584. /*: boolean*/
  1585. {
  1586. if (!this.id) {
  1587. return false;
  1588. }
  1589. var stateController = _CoreManager.default.getObjectStateController();
  1590. var state = stateController.getState(this._getStateIdentifier());
  1591. if (state) {
  1592. return state.existed;
  1593. }
  1594. return false;
  1595. }
  1596. /**
  1597. * Returns true if this object exists on the Server
  1598. *
  1599. * @param {object} options
  1600. * Valid options are:<ul>
  1601. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1602. * be used for this request.
  1603. * <li>sessionToken: A valid session token, used for making a request on
  1604. * behalf of a specific user.
  1605. * </ul>
  1606. * @returns {Promise<boolean>} A boolean promise that is fulfilled if object exists.
  1607. */
  1608. }, {
  1609. key: "exists",
  1610. value: function () {
  1611. var _exists = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(options
  1612. /*:: ?: RequestOptions*/
  1613. ) {
  1614. var query;
  1615. return _regeneratorRuntime().wrap(function _callee$(_context) {
  1616. while (1) {
  1617. switch (_context.prev = _context.next) {
  1618. case 0:
  1619. if (this.id) {
  1620. _context.next = 2;
  1621. break;
  1622. }
  1623. return _context.abrupt("return", false);
  1624. case 2:
  1625. _context.prev = 2;
  1626. query = new _ParseQuery.default(this.className);
  1627. _context.next = 6;
  1628. return query.get(this.id, options);
  1629. case 6:
  1630. return _context.abrupt("return", true);
  1631. case 9:
  1632. _context.prev = 9;
  1633. _context.t0 = _context["catch"](2);
  1634. if (!(_context.t0.code === _ParseError.default.OBJECT_NOT_FOUND)) {
  1635. _context.next = 13;
  1636. break;
  1637. }
  1638. return _context.abrupt("return", false);
  1639. case 13:
  1640. throw _context.t0;
  1641. case 14:
  1642. case "end":
  1643. return _context.stop();
  1644. }
  1645. }
  1646. }, _callee, this, [[2, 9]]);
  1647. }));
  1648. function exists(_x) {
  1649. return _exists.apply(this, arguments);
  1650. }
  1651. return exists;
  1652. }()
  1653. /**
  1654. * Checks if the model is currently in a valid state.
  1655. *
  1656. * @returns {boolean}
  1657. */
  1658. }, {
  1659. key: "isValid",
  1660. value: function isValid()
  1661. /*: boolean*/
  1662. {
  1663. return !this.validate(this.attributes);
  1664. }
  1665. /**
  1666. * You should not call this function directly unless you subclass
  1667. * <code>Parse.Object</code>, in which case you can override this method
  1668. * to provide additional validation on <code>set</code> and
  1669. * <code>save</code>. Your implementation should return
  1670. *
  1671. * @param {object} attrs The current data to validate.
  1672. * @returns {Parse.Error|boolean} False if the data is valid. An error object otherwise.
  1673. * @see Parse.Object#set
  1674. */
  1675. }, {
  1676. key: "validate",
  1677. value: function validate(attrs
  1678. /*: AttributeMap*/
  1679. )
  1680. /*: ParseError | boolean*/
  1681. {
  1682. if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
  1683. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
  1684. }
  1685. for (var _key in attrs) {
  1686. if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(_key)) {
  1687. return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
  1688. }
  1689. }
  1690. return false;
  1691. }
  1692. /**
  1693. * Returns the ACL for this object.
  1694. *
  1695. * @returns {Parse.ACL} An instance of Parse.ACL.
  1696. * @see Parse.Object#get
  1697. */
  1698. }, {
  1699. key: "getACL",
  1700. value: function getACL()
  1701. /*: ?ParseACL*/
  1702. {
  1703. var acl = this.get('ACL');
  1704. if (acl instanceof _ParseACL.default) {
  1705. return acl;
  1706. }
  1707. return null;
  1708. }
  1709. /**
  1710. * Sets the ACL to be used for this object.
  1711. *
  1712. * @param {Parse.ACL} acl An instance of Parse.ACL.
  1713. * @param {object} options
  1714. * @returns {(ParseObject | boolean)} Whether the set passed validation.
  1715. * @see Parse.Object#set
  1716. */
  1717. }, {
  1718. key: "setACL",
  1719. value: function setACL(acl
  1720. /*: ParseACL*/
  1721. , options
  1722. /*:: ?: mixed*/
  1723. )
  1724. /*: ParseObject | boolean*/
  1725. {
  1726. return this.set('ACL', acl, options);
  1727. }
  1728. /**
  1729. * Clears any (or specific) changes to this object made since the last call to save()
  1730. *
  1731. * @param {string} [keys] - specify which fields to revert
  1732. */
  1733. }, {
  1734. key: "revert",
  1735. value: function revert()
  1736. /*: void*/
  1737. {
  1738. var keysToRevert;
  1739. for (var _len = arguments.length, keys = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
  1740. keys[_key2] = arguments[_key2];
  1741. }
  1742. if (keys.length) {
  1743. keysToRevert = [];
  1744. var _iterator = _createForOfIteratorHelper(keys),
  1745. _step;
  1746. try {
  1747. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1748. var _key3 = _step.value;
  1749. if (typeof _key3 === 'string') {
  1750. keysToRevert.push(_key3);
  1751. } else {
  1752. throw new Error('Parse.Object#revert expects either no, or a list of string, arguments.');
  1753. }
  1754. }
  1755. } catch (err) {
  1756. _iterator.e(err);
  1757. } finally {
  1758. _iterator.f();
  1759. }
  1760. }
  1761. this._clearPendingOps(keysToRevert);
  1762. }
  1763. /**
  1764. * Clears all attributes on a model
  1765. *
  1766. * @returns {(ParseObject | boolean)}
  1767. */
  1768. }, {
  1769. key: "clear",
  1770. value: function clear()
  1771. /*: ParseObject | boolean*/
  1772. {
  1773. var attributes = this.attributes;
  1774. var erasable = {};
  1775. var readonly = ['createdAt', 'updatedAt'];
  1776. if (typeof this.constructor.readOnlyAttributes === 'function') {
  1777. readonly = (0, _concat.default)(readonly).call(readonly, this.constructor.readOnlyAttributes());
  1778. }
  1779. for (var _attr11 in attributes) {
  1780. if ((0, _indexOf.default)(readonly).call(readonly, _attr11) < 0) {
  1781. erasable[_attr11] = true;
  1782. }
  1783. }
  1784. return this.set(erasable, {
  1785. unset: true
  1786. });
  1787. }
  1788. /**
  1789. * Fetch the model from the server. If the server's representation of the
  1790. * model differs from its current attributes, they will be overriden.
  1791. *
  1792. * @param {object} options
  1793. * Valid options are:<ul>
  1794. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1795. * be used for this request.
  1796. * <li>sessionToken: A valid session token, used for making a request on
  1797. * behalf of a specific user.
  1798. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  1799. * or an array of array of strings.
  1800. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  1801. * </ul>
  1802. * @returns {Promise} A promise that is fulfilled when the fetch
  1803. * completes.
  1804. */
  1805. }, {
  1806. key: "fetch",
  1807. value: function fetch(options
  1808. /*: RequestOptions*/
  1809. )
  1810. /*: Promise*/
  1811. {
  1812. options = options || {};
  1813. var fetchOptions = {};
  1814. if (options.hasOwnProperty('useMasterKey')) {
  1815. fetchOptions.useMasterKey = options.useMasterKey;
  1816. }
  1817. if (options.hasOwnProperty('sessionToken')) {
  1818. fetchOptions.sessionToken = options.sessionToken;
  1819. }
  1820. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  1821. fetchOptions.context = options.context;
  1822. }
  1823. if (options.hasOwnProperty('include')) {
  1824. fetchOptions.include = [];
  1825. if ((0, _isArray.default)(options.include)) {
  1826. var _context2;
  1827. (0, _forEach.default)(_context2 = options.include).call(_context2, function (key) {
  1828. if ((0, _isArray.default)(key)) {
  1829. var _context3;
  1830. fetchOptions.include = (0, _concat.default)(_context3 = fetchOptions.include).call(_context3, key);
  1831. } else {
  1832. fetchOptions.include.push(key);
  1833. }
  1834. });
  1835. } else {
  1836. fetchOptions.include.push(options.include);
  1837. }
  1838. }
  1839. var controller = _CoreManager.default.getObjectController();
  1840. return controller.fetch(this, true, fetchOptions);
  1841. }
  1842. /**
  1843. * Fetch the model from the server. If the server's representation of the
  1844. * model differs from its current attributes, they will be overriden.
  1845. *
  1846. * Includes nested Parse.Objects for the provided key. You can use dot
  1847. * notation to specify which fields in the included object are also fetched.
  1848. *
  1849. * @param {string | Array<string | Array<string>>} keys The name(s) of the key(s) to include.
  1850. * @param {object} options
  1851. * Valid options are:<ul>
  1852. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1853. * be used for this request.
  1854. * <li>sessionToken: A valid session token, used for making a request on
  1855. * behalf of a specific user.
  1856. * </ul>
  1857. * @returns {Promise} A promise that is fulfilled when the fetch
  1858. * completes.
  1859. */
  1860. }, {
  1861. key: "fetchWithInclude",
  1862. value: function fetchWithInclude(keys
  1863. /*: String | Array<string | Array<string>>*/
  1864. , options
  1865. /*: RequestOptions*/
  1866. )
  1867. /*: Promise*/
  1868. {
  1869. options = options || {};
  1870. options.include = keys;
  1871. return this.fetch(options);
  1872. }
  1873. /**
  1874. * Saves this object to the server at some unspecified time in the future,
  1875. * even if Parse is currently inaccessible.
  1876. *
  1877. * Use this when you may not have a solid network connection, and don't need to know when the save completes.
  1878. * If there is some problem with the object such that it can't be saved, it will be silently discarded.
  1879. *
  1880. * Objects saved with this method will be stored locally in an on-disk cache until they can be delivered to Parse.
  1881. * They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection is
  1882. * available. Objects saved this way will persist even after the app is closed, in which case they will be sent the
  1883. * next time the app is opened.
  1884. *
  1885. * @param {object} [options]
  1886. * Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
  1887. * Valid options are:
  1888. * <ul>
  1889. * <li>sessionToken: A valid session token, used for making a request on
  1890. * behalf of a specific user.
  1891. * <li>cascadeSave: If `false`, nested objects will not be saved (default is `true`).
  1892. * <li>context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
  1893. * </ul>
  1894. * @returns {Promise} A promise that is fulfilled when the save
  1895. * completes.
  1896. */
  1897. }, {
  1898. key: "saveEventually",
  1899. value: function () {
  1900. var _saveEventually = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(options
  1901. /*: SaveOptions*/
  1902. ) {
  1903. return _regeneratorRuntime().wrap(function _callee2$(_context4) {
  1904. while (1) {
  1905. switch (_context4.prev = _context4.next) {
  1906. case 0:
  1907. _context4.prev = 0;
  1908. _context4.next = 3;
  1909. return this.save(null, options);
  1910. case 3:
  1911. _context4.next = 11;
  1912. break;
  1913. case 5:
  1914. _context4.prev = 5;
  1915. _context4.t0 = _context4["catch"](0);
  1916. if (!(_context4.t0.message === 'XMLHttpRequest failed: "Unable to connect to the Parse API"')) {
  1917. _context4.next = 11;
  1918. break;
  1919. }
  1920. _context4.next = 10;
  1921. return _EventuallyQueue.default.save(this, options);
  1922. case 10:
  1923. _EventuallyQueue.default.poll();
  1924. case 11:
  1925. return _context4.abrupt("return", this);
  1926. case 12:
  1927. case "end":
  1928. return _context4.stop();
  1929. }
  1930. }
  1931. }, _callee2, this, [[0, 5]]);
  1932. }));
  1933. function saveEventually(_x2) {
  1934. return _saveEventually.apply(this, arguments);
  1935. }
  1936. return saveEventually;
  1937. }()
  1938. /**
  1939. * Set a hash of model attributes, and save the model to the server.
  1940. * updatedAt will be updated when the request returns.
  1941. * You can either call it as:<pre>
  1942. * object.save();</pre>
  1943. * or<pre>
  1944. * object.save(attrs);</pre>
  1945. * or<pre>
  1946. * object.save(null, options);</pre>
  1947. * or<pre>
  1948. * object.save(attrs, options);</pre>
  1949. * or<pre>
  1950. * object.save(key, value);</pre>
  1951. * or<pre>
  1952. * object.save(key, value, options);</pre>
  1953. *
  1954. * Example 1: <pre>
  1955. * gameTurn.save({
  1956. * player: "Jake Cutter",
  1957. * diceRoll: 2
  1958. * }).then(function(gameTurnAgain) {
  1959. * // The save was successful.
  1960. * }, function(error) {
  1961. * // The save failed. Error is an instance of Parse.Error.
  1962. * });</pre>
  1963. *
  1964. * Example 2: <pre>
  1965. * gameTurn.save("player", "Jake Cutter");</pre>
  1966. *
  1967. * @param {string | object | null} [arg1]
  1968. * Valid options are:<ul>
  1969. * <li>`Object` - Key/value pairs to update on the object.</li>
  1970. * <li>`String` Key - Key of attribute to update (requires arg2 to also be string)</li>
  1971. * <li>`null` - Passing null for arg1 allows you to save the object with options passed in arg2.</li>
  1972. * </ul>
  1973. * @param {string | object} [arg2]
  1974. * <ul>
  1975. * <li>`String` Value - If arg1 was passed as a key, arg2 is the value that should be set on that key.</li>
  1976. * <li>`Object` Options - Valid options are:
  1977. * <ul>
  1978. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1979. * be used for this request.
  1980. * <li>sessionToken: A valid session token, used for making a request on
  1981. * behalf of a specific user.
  1982. * <li>cascadeSave: If `false`, nested objects will not be saved (default is `true`).
  1983. * <li>context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
  1984. * </ul>
  1985. * </li>
  1986. * </ul>
  1987. * @param {object} [arg3]
  1988. * Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
  1989. * Valid options are:
  1990. * <ul>
  1991. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1992. * be used for this request.
  1993. * <li>sessionToken: A valid session token, used for making a request on
  1994. * behalf of a specific user.
  1995. * <li>cascadeSave: If `false`, nested objects will not be saved (default is `true`).
  1996. * <li>context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
  1997. * </ul>
  1998. * @returns {Promise} A promise that is fulfilled when the save
  1999. * completes.
  2000. */
  2001. }, {
  2002. key: "save",
  2003. value: function save(arg1
  2004. /*: ?string | { [attr: string]: mixed }*/
  2005. , arg2
  2006. /*: SaveOptions | mixed*/
  2007. , arg3
  2008. /*:: ?: SaveOptions*/
  2009. )
  2010. /*: Promise*/
  2011. {
  2012. var _this = this;
  2013. var attrs;
  2014. var options;
  2015. if ((0, _typeof2.default)(arg1) === 'object' || typeof arg1 === 'undefined') {
  2016. attrs = arg1;
  2017. if ((0, _typeof2.default)(arg2) === 'object') {
  2018. options = arg2;
  2019. }
  2020. } else {
  2021. attrs = {};
  2022. attrs[arg1] = arg2;
  2023. options = arg3;
  2024. }
  2025. if (attrs) {
  2026. var validation = this.validate(attrs);
  2027. if (validation) {
  2028. return _promise.default.reject(validation);
  2029. }
  2030. this.set(attrs, options);
  2031. }
  2032. options = options || {};
  2033. var saveOptions = {};
  2034. if (options.hasOwnProperty('useMasterKey')) {
  2035. saveOptions.useMasterKey = !!options.useMasterKey;
  2036. }
  2037. if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
  2038. saveOptions.sessionToken = options.sessionToken;
  2039. }
  2040. if (options.hasOwnProperty('installationId') && typeof options.installationId === 'string') {
  2041. saveOptions.installationId = options.installationId;
  2042. }
  2043. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  2044. saveOptions.context = options.context;
  2045. }
  2046. var controller = _CoreManager.default.getObjectController();
  2047. var unsaved = options.cascadeSave !== false ? (0, _unsavedChildren.default)(this) : null;
  2048. return controller.save(unsaved, saveOptions).then(function () {
  2049. return controller.save(_this, saveOptions);
  2050. });
  2051. }
  2052. /**
  2053. * Deletes this object from the server at some unspecified time in the future,
  2054. * even if Parse is currently inaccessible.
  2055. *
  2056. * Use this when you may not have a solid network connection,
  2057. * and don't need to know when the delete completes. If there is some problem with the object
  2058. * such that it can't be deleted, the request will be silently discarded.
  2059. *
  2060. * Delete instructions made with this method will be stored locally in an on-disk cache until they can be transmitted
  2061. * to Parse. They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection
  2062. * is available. Delete requests will persist even after the app is closed, in which case they will be sent the
  2063. * next time the app is opened.
  2064. *
  2065. * @param {object} [options]
  2066. * Valid options are:<ul>
  2067. * <li>sessionToken: A valid session token, used for making a request on
  2068. * behalf of a specific user.
  2069. * <li>context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers.
  2070. * </ul>
  2071. * @returns {Promise} A promise that is fulfilled when the destroy
  2072. * completes.
  2073. */
  2074. }, {
  2075. key: "destroyEventually",
  2076. value: function () {
  2077. var _destroyEventually = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(options
  2078. /*: RequestOptions*/
  2079. ) {
  2080. return _regeneratorRuntime().wrap(function _callee3$(_context5) {
  2081. while (1) {
  2082. switch (_context5.prev = _context5.next) {
  2083. case 0:
  2084. _context5.prev = 0;
  2085. _context5.next = 3;
  2086. return this.destroy(options);
  2087. case 3:
  2088. _context5.next = 11;
  2089. break;
  2090. case 5:
  2091. _context5.prev = 5;
  2092. _context5.t0 = _context5["catch"](0);
  2093. if (!(_context5.t0.message === 'XMLHttpRequest failed: "Unable to connect to the Parse API"')) {
  2094. _context5.next = 11;
  2095. break;
  2096. }
  2097. _context5.next = 10;
  2098. return _EventuallyQueue.default.destroy(this, options);
  2099. case 10:
  2100. _EventuallyQueue.default.poll();
  2101. case 11:
  2102. return _context5.abrupt("return", this);
  2103. case 12:
  2104. case "end":
  2105. return _context5.stop();
  2106. }
  2107. }
  2108. }, _callee3, this, [[0, 5]]);
  2109. }));
  2110. function destroyEventually(_x3) {
  2111. return _destroyEventually.apply(this, arguments);
  2112. }
  2113. return destroyEventually;
  2114. }()
  2115. /**
  2116. * Destroy this model on the server if it was already persisted.
  2117. *
  2118. * @param {object} options
  2119. * Valid options are:<ul>
  2120. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  2121. * be used for this request.
  2122. * <li>sessionToken: A valid session token, used for making a request on
  2123. * behalf of a specific user.
  2124. * <li>context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers.
  2125. * </ul>
  2126. * @returns {Promise} A promise that is fulfilled when the destroy
  2127. * completes.
  2128. */
  2129. }, {
  2130. key: "destroy",
  2131. value: function destroy(options
  2132. /*: RequestOptions*/
  2133. )
  2134. /*: Promise*/
  2135. {
  2136. options = options || {};
  2137. var destroyOptions = {};
  2138. if (options.hasOwnProperty('useMasterKey')) {
  2139. destroyOptions.useMasterKey = options.useMasterKey;
  2140. }
  2141. if (options.hasOwnProperty('sessionToken')) {
  2142. destroyOptions.sessionToken = options.sessionToken;
  2143. }
  2144. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  2145. destroyOptions.context = options.context;
  2146. }
  2147. if (!this.id) {
  2148. return _promise.default.resolve();
  2149. }
  2150. return _CoreManager.default.getObjectController().destroy(this, destroyOptions);
  2151. }
  2152. /**
  2153. * Asynchronously stores the object and every object it points to in the local datastore,
  2154. * recursively, using a default pin name: _default.
  2155. *
  2156. * If those other objects have not been fetched from Parse, they will not be stored.
  2157. * However, if they have changed data, all the changes will be retained.
  2158. *
  2159. * <pre>
  2160. * await object.pin();
  2161. * </pre>
  2162. *
  2163. * To retrieve object:
  2164. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  2165. *
  2166. * @returns {Promise} A promise that is fulfilled when the pin completes.
  2167. */
  2168. }, {
  2169. key: "pin",
  2170. value: function pin()
  2171. /*: Promise<void>*/
  2172. {
  2173. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  2174. }
  2175. /**
  2176. * Asynchronously removes the object and every object it points to in the local datastore,
  2177. * recursively, using a default pin name: _default.
  2178. *
  2179. * <pre>
  2180. * await object.unPin();
  2181. * </pre>
  2182. *
  2183. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  2184. */
  2185. }, {
  2186. key: "unPin",
  2187. value: function unPin()
  2188. /*: Promise<void>*/
  2189. {
  2190. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  2191. }
  2192. /**
  2193. * Asynchronously returns if the object is pinned
  2194. *
  2195. * <pre>
  2196. * const isPinned = await object.isPinned();
  2197. * </pre>
  2198. *
  2199. * @returns {Promise<boolean>} A boolean promise that is fulfilled if object is pinned.
  2200. */
  2201. }, {
  2202. key: "isPinned",
  2203. value: function () {
  2204. var _isPinned = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
  2205. var localDatastore, objectKey, pin;
  2206. return _regeneratorRuntime().wrap(function _callee4$(_context6) {
  2207. while (1) {
  2208. switch (_context6.prev = _context6.next) {
  2209. case 0:
  2210. localDatastore = _CoreManager.default.getLocalDatastore();
  2211. if (localDatastore.isEnabled) {
  2212. _context6.next = 3;
  2213. break;
  2214. }
  2215. return _context6.abrupt("return", _promise.default.reject('Parse.enableLocalDatastore() must be called first'));
  2216. case 3:
  2217. objectKey = localDatastore.getKeyForObject(this);
  2218. _context6.next = 6;
  2219. return localDatastore.fromPinWithName(objectKey);
  2220. case 6:
  2221. pin = _context6.sent;
  2222. return _context6.abrupt("return", pin.length > 0);
  2223. case 8:
  2224. case "end":
  2225. return _context6.stop();
  2226. }
  2227. }
  2228. }, _callee4, this);
  2229. }));
  2230. function isPinned() {
  2231. return _isPinned.apply(this, arguments);
  2232. }
  2233. return isPinned;
  2234. }()
  2235. /**
  2236. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  2237. *
  2238. * If those other objects have not been fetched from Parse, they will not be stored.
  2239. * However, if they have changed data, all the changes will be retained.
  2240. *
  2241. * <pre>
  2242. * await object.pinWithName(name);
  2243. * </pre>
  2244. *
  2245. * To retrieve object:
  2246. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  2247. *
  2248. * @param {string} name Name of Pin.
  2249. * @returns {Promise} A promise that is fulfilled when the pin completes.
  2250. */
  2251. }, {
  2252. key: "pinWithName",
  2253. value: function pinWithName(name
  2254. /*: string*/
  2255. )
  2256. /*: Promise<void>*/
  2257. {
  2258. return ParseObject.pinAllWithName(name, [this]);
  2259. }
  2260. /**
  2261. * Asynchronously removes the object and every object it points to in the local datastore, recursively.
  2262. *
  2263. * <pre>
  2264. * await object.unPinWithName(name);
  2265. * </pre>
  2266. *
  2267. * @param {string} name Name of Pin.
  2268. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  2269. */
  2270. }, {
  2271. key: "unPinWithName",
  2272. value: function unPinWithName(name
  2273. /*: string*/
  2274. )
  2275. /*: Promise<void>*/
  2276. {
  2277. return ParseObject.unPinAllWithName(name, [this]);
  2278. }
  2279. /**
  2280. * Asynchronously loads data from the local datastore into this object.
  2281. *
  2282. * <pre>
  2283. * await object.fetchFromLocalDatastore();
  2284. * </pre>
  2285. *
  2286. * You can create an unfetched pointer with <code>Parse.Object.createWithoutData()</code>
  2287. * and then call <code>fetchFromLocalDatastore()</code> on it.
  2288. *
  2289. * @returns {Promise} A promise that is fulfilled when the fetch completes.
  2290. */
  2291. }, {
  2292. key: "fetchFromLocalDatastore",
  2293. value: function () {
  2294. var _fetchFromLocalDatastore = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
  2295. var localDatastore, objectKey, pinned, result;
  2296. return _regeneratorRuntime().wrap(function _callee5$(_context7) {
  2297. while (1) {
  2298. switch (_context7.prev = _context7.next) {
  2299. case 0:
  2300. localDatastore = _CoreManager.default.getLocalDatastore();
  2301. if (localDatastore.isEnabled) {
  2302. _context7.next = 3;
  2303. break;
  2304. }
  2305. throw new Error('Parse.enableLocalDatastore() must be called first');
  2306. case 3:
  2307. objectKey = localDatastore.getKeyForObject(this);
  2308. _context7.next = 6;
  2309. return localDatastore._serializeObject(objectKey);
  2310. case 6:
  2311. pinned = _context7.sent;
  2312. if (pinned) {
  2313. _context7.next = 9;
  2314. break;
  2315. }
  2316. throw new Error('Cannot fetch an unsaved ParseObject');
  2317. case 9:
  2318. result = ParseObject.fromJSON(pinned);
  2319. this._finishFetch(result.toJSON());
  2320. return _context7.abrupt("return", this);
  2321. case 12:
  2322. case "end":
  2323. return _context7.stop();
  2324. }
  2325. }
  2326. }, _callee5, this);
  2327. }));
  2328. function fetchFromLocalDatastore() {
  2329. return _fetchFromLocalDatastore.apply(this, arguments);
  2330. }
  2331. return fetchFromLocalDatastore;
  2332. }()
  2333. /** Static methods **/
  2334. }], [{
  2335. key: "_getClassMap",
  2336. value: function _getClassMap() {
  2337. return classMap;
  2338. }
  2339. }, {
  2340. key: "_clearAllState",
  2341. value: function _clearAllState() {
  2342. var stateController = _CoreManager.default.getObjectStateController();
  2343. stateController.clearAllState();
  2344. }
  2345. /**
  2346. * Fetches the given list of Parse.Object.
  2347. * If any error is encountered, stops and calls the error handler.
  2348. *
  2349. * <pre>
  2350. * Parse.Object.fetchAll([object1, object2, ...])
  2351. * .then((list) => {
  2352. * // All the objects were fetched.
  2353. * }, (error) => {
  2354. * // An error occurred while fetching one of the objects.
  2355. * });
  2356. * </pre>
  2357. *
  2358. * @param {Array} list A list of <code>Parse.Object</code>.
  2359. * @param {object} options
  2360. * Valid options are:<ul>
  2361. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  2362. * be used for this request.
  2363. * <li>sessionToken: A valid session token, used for making a request on
  2364. * behalf of a specific user.
  2365. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  2366. * or an array of array of strings.
  2367. * </ul>
  2368. * @static
  2369. * @returns {Parse.Object[]}
  2370. */
  2371. }, {
  2372. key: "fetchAll",
  2373. value: function fetchAll(list
  2374. /*: Array<ParseObject>*/
  2375. ) {
  2376. var options
  2377. /*: RequestOptions*/
  2378. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2379. var queryOptions = {};
  2380. if (options.hasOwnProperty('useMasterKey')) {
  2381. queryOptions.useMasterKey = options.useMasterKey;
  2382. }
  2383. if (options.hasOwnProperty('sessionToken')) {
  2384. queryOptions.sessionToken = options.sessionToken;
  2385. }
  2386. if (options.hasOwnProperty('include')) {
  2387. queryOptions.include = ParseObject.handleIncludeOptions(options);
  2388. }
  2389. return _CoreManager.default.getObjectController().fetch(list, true, queryOptions);
  2390. }
  2391. /**
  2392. * Fetches the given list of Parse.Object.
  2393. *
  2394. * Includes nested Parse.Objects for the provided key. You can use dot
  2395. * notation to specify which fields in the included object are also fetched.
  2396. *
  2397. * If any error is encountered, stops and calls the error handler.
  2398. *
  2399. * <pre>
  2400. * Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
  2401. * .then((list) => {
  2402. * // All the objects were fetched.
  2403. * }, (error) => {
  2404. * // An error occurred while fetching one of the objects.
  2405. * });
  2406. * </pre>
  2407. *
  2408. * @param {Array} list A list of <code>Parse.Object</code>.
  2409. * @param {string | Array<string | Array<string>>} keys The name(s) of the key(s) to include.
  2410. * @param {object} options
  2411. * Valid options are:<ul>
  2412. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  2413. * be used for this request.
  2414. * <li>sessionToken: A valid session token, used for making a request on
  2415. * behalf of a specific user.
  2416. * </ul>
  2417. * @static
  2418. * @returns {Parse.Object[]}
  2419. */
  2420. }, {
  2421. key: "fetchAllWithInclude",
  2422. value: function fetchAllWithInclude(list
  2423. /*: Array<ParseObject>*/
  2424. , keys
  2425. /*: String | Array<string | Array<string>>*/
  2426. , options
  2427. /*: RequestOptions*/
  2428. ) {
  2429. options = options || {};
  2430. options.include = keys;
  2431. return ParseObject.fetchAll(list, options);
  2432. }
  2433. /**
  2434. * Fetches the given list of Parse.Object if needed.
  2435. * If any error is encountered, stops and calls the error handler.
  2436. *
  2437. * Includes nested Parse.Objects for the provided key. You can use dot
  2438. * notation to specify which fields in the included object are also fetched.
  2439. *
  2440. * If any error is encountered, stops and calls the error handler.
  2441. *
  2442. * <pre>
  2443. * Parse.Object.fetchAllIfNeededWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
  2444. * .then((list) => {
  2445. * // All the objects were fetched.
  2446. * }, (error) => {
  2447. * // An error occurred while fetching one of the objects.
  2448. * });
  2449. * </pre>
  2450. *
  2451. * @param {Array} list A list of <code>Parse.Object</code>.
  2452. * @param {string | Array<string | Array<string>>} keys The name(s) of the key(s) to include.
  2453. * @param {object} options
  2454. * Valid options are:<ul>
  2455. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  2456. * be used for this request.
  2457. * <li>sessionToken: A valid session token, used for making a request on
  2458. * behalf of a specific user.
  2459. * </ul>
  2460. * @static
  2461. * @returns {Parse.Object[]}
  2462. */
  2463. }, {
  2464. key: "fetchAllIfNeededWithInclude",
  2465. value: function fetchAllIfNeededWithInclude(list
  2466. /*: Array<ParseObject>*/
  2467. , keys
  2468. /*: String | Array<string | Array<string>>*/
  2469. , options
  2470. /*: RequestOptions*/
  2471. ) {
  2472. options = options || {};
  2473. options.include = keys;
  2474. return ParseObject.fetchAllIfNeeded(list, options);
  2475. }
  2476. /**
  2477. * Fetches the given list of Parse.Object if needed.
  2478. * If any error is encountered, stops and calls the error handler.
  2479. *
  2480. * <pre>
  2481. * Parse.Object.fetchAllIfNeeded([object1, ...])
  2482. * .then((list) => {
  2483. * // Objects were fetched and updated.
  2484. * }, (error) => {
  2485. * // An error occurred while fetching one of the objects.
  2486. * });
  2487. * </pre>
  2488. *
  2489. * @param {Array} list A list of <code>Parse.Object</code>.
  2490. * @param {object} options
  2491. * @static
  2492. * @returns {Parse.Object[]}
  2493. */
  2494. }, {
  2495. key: "fetchAllIfNeeded",
  2496. value: function fetchAllIfNeeded(list
  2497. /*: Array<ParseObject>*/
  2498. , options) {
  2499. options = options || {};
  2500. var queryOptions = {};
  2501. if (options.hasOwnProperty('useMasterKey')) {
  2502. queryOptions.useMasterKey = options.useMasterKey;
  2503. }
  2504. if (options.hasOwnProperty('sessionToken')) {
  2505. queryOptions.sessionToken = options.sessionToken;
  2506. }
  2507. if (options.hasOwnProperty('include')) {
  2508. queryOptions.include = ParseObject.handleIncludeOptions(options);
  2509. }
  2510. return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
  2511. }
  2512. }, {
  2513. key: "handleIncludeOptions",
  2514. value: function handleIncludeOptions(options) {
  2515. var include = [];
  2516. if ((0, _isArray.default)(options.include)) {
  2517. var _context8;
  2518. (0, _forEach.default)(_context8 = options.include).call(_context8, function (key) {
  2519. if ((0, _isArray.default)(key)) {
  2520. include = (0, _concat.default)(include).call(include, key);
  2521. } else {
  2522. include.push(key);
  2523. }
  2524. });
  2525. } else {
  2526. include.push(options.include);
  2527. }
  2528. return include;
  2529. }
  2530. /**
  2531. * Destroy the given list of models on the server if it was already persisted.
  2532. *
  2533. * <p>Unlike saveAll, if an error occurs while deleting an individual model,
  2534. * this method will continue trying to delete the rest of the models if
  2535. * possible, except in the case of a fatal error like a connection error.
  2536. *
  2537. * <p>In particular, the Parse.Error object returned in the case of error may
  2538. * be one of two types:
  2539. *
  2540. * <ul>
  2541. * <li>A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an
  2542. * array of other Parse.Error objects. Each error object in this array
  2543. * has an "object" property that references the object that could not be
  2544. * deleted (for instance, because that object could not be found).</li>
  2545. * <li>A non-aggregate Parse.Error. This indicates a serious error that
  2546. * caused the delete operation to be aborted partway through (for
  2547. * instance, a connection failure in the middle of the delete).</li>
  2548. * </ul>
  2549. *
  2550. * <pre>
  2551. * Parse.Object.destroyAll([object1, object2, ...])
  2552. * .then((list) => {
  2553. * // All the objects were deleted.
  2554. * }, (error) => {
  2555. * // An error occurred while deleting one or more of the objects.
  2556. * // If this is an aggregate error, then we can inspect each error
  2557. * // object individually to determine the reason why a particular
  2558. * // object was not deleted.
  2559. * if (error.code === Parse.Error.AGGREGATE_ERROR) {
  2560. * for (var i = 0; i < error.errors.length; i++) {
  2561. * console.log("Couldn't delete " + error.errors[i].object.id +
  2562. * "due to " + error.errors[i].message);
  2563. * }
  2564. * } else {
  2565. * console.log("Delete aborted because of " + error.message);
  2566. * }
  2567. * });
  2568. * </pre>
  2569. *
  2570. * @param {Array} list A list of <code>Parse.Object</code>.
  2571. * @param {object} options
  2572. * @static
  2573. * @returns {Promise} A promise that is fulfilled when the destroyAll
  2574. * completes.
  2575. */
  2576. }, {
  2577. key: "destroyAll",
  2578. value: function destroyAll(list
  2579. /*: Array<ParseObject>*/
  2580. ) {
  2581. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2582. var destroyOptions = {};
  2583. if (options.hasOwnProperty('useMasterKey')) {
  2584. destroyOptions.useMasterKey = options.useMasterKey;
  2585. }
  2586. if (options.hasOwnProperty('sessionToken')) {
  2587. destroyOptions.sessionToken = options.sessionToken;
  2588. }
  2589. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  2590. destroyOptions.batchSize = options.batchSize;
  2591. }
  2592. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  2593. destroyOptions.context = options.context;
  2594. }
  2595. return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
  2596. }
  2597. /**
  2598. * Saves the given list of Parse.Object.
  2599. * If any error is encountered, stops and calls the error handler.
  2600. *
  2601. * <pre>
  2602. * Parse.Object.saveAll([object1, object2, ...])
  2603. * .then((list) => {
  2604. * // All the objects were saved.
  2605. * }, (error) => {
  2606. * // An error occurred while saving one of the objects.
  2607. * });
  2608. * </pre>
  2609. *
  2610. * @param {Array} list A list of <code>Parse.Object</code>.
  2611. * @param {object} options
  2612. * @static
  2613. * @returns {Parse.Object[]}
  2614. */
  2615. }, {
  2616. key: "saveAll",
  2617. value: function saveAll(list
  2618. /*: Array<ParseObject>*/
  2619. ) {
  2620. var options
  2621. /*: RequestOptions*/
  2622. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2623. var saveOptions = {};
  2624. if (options.hasOwnProperty('useMasterKey')) {
  2625. saveOptions.useMasterKey = options.useMasterKey;
  2626. }
  2627. if (options.hasOwnProperty('sessionToken')) {
  2628. saveOptions.sessionToken = options.sessionToken;
  2629. }
  2630. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  2631. saveOptions.batchSize = options.batchSize;
  2632. }
  2633. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  2634. saveOptions.context = options.context;
  2635. }
  2636. return _CoreManager.default.getObjectController().save(list, saveOptions);
  2637. }
  2638. /**
  2639. * Creates a reference to a subclass of Parse.Object with the given id. This
  2640. * does not exist on Parse.Object, only on subclasses.
  2641. *
  2642. * <p>A shortcut for: <pre>
  2643. * var Foo = Parse.Object.extend("Foo");
  2644. * var pointerToFoo = new Foo();
  2645. * pointerToFoo.id = "myObjectId";
  2646. * </pre>
  2647. *
  2648. * @param {string} id The ID of the object to create a reference to.
  2649. * @static
  2650. * @returns {Parse.Object} A Parse.Object reference.
  2651. */
  2652. }, {
  2653. key: "createWithoutData",
  2654. value: function createWithoutData(id
  2655. /*: string*/
  2656. ) {
  2657. var obj = new this();
  2658. obj.id = id;
  2659. return obj;
  2660. }
  2661. /**
  2662. * Creates a new instance of a Parse Object from a JSON representation.
  2663. *
  2664. * @param {object} json The JSON map of the Object's data
  2665. * @param {boolean} override In single instance mode, all old server data
  2666. * is overwritten if this is set to true
  2667. * @param {boolean} dirty Whether the Parse.Object should set JSON keys to dirty
  2668. * @static
  2669. * @returns {Parse.Object} A Parse.Object reference
  2670. */
  2671. }, {
  2672. key: "fromJSON",
  2673. value: function fromJSON(json
  2674. /*: any*/
  2675. , override
  2676. /*:: ?: boolean*/
  2677. , dirty
  2678. /*:: ?: boolean*/
  2679. ) {
  2680. if (!json.className) {
  2681. throw new Error('Cannot create an object without a className');
  2682. }
  2683. var constructor = classMap[json.className];
  2684. var o = constructor ? new constructor(json.className) : new ParseObject(json.className);
  2685. var otherAttributes = {};
  2686. for (var _attr12 in json) {
  2687. if (_attr12 !== 'className' && _attr12 !== '__type') {
  2688. otherAttributes[_attr12] = json[_attr12];
  2689. if (dirty) {
  2690. o.set(_attr12, json[_attr12]);
  2691. }
  2692. }
  2693. }
  2694. if (override) {
  2695. // id needs to be set before clearServerData can work
  2696. if (otherAttributes.objectId) {
  2697. o.id = otherAttributes.objectId;
  2698. }
  2699. var preserved = null;
  2700. if (typeof o._preserveFieldsOnFetch === 'function') {
  2701. preserved = o._preserveFieldsOnFetch();
  2702. }
  2703. o._clearServerData();
  2704. if (preserved) {
  2705. o._finishFetch(preserved);
  2706. }
  2707. }
  2708. o._finishFetch(otherAttributes);
  2709. if (json.objectId) {
  2710. o._setExisted(true);
  2711. }
  2712. return o;
  2713. }
  2714. /**
  2715. * Registers a subclass of Parse.Object with a specific class name.
  2716. * When objects of that class are retrieved from a query, they will be
  2717. * instantiated with this subclass.
  2718. * This is only necessary when using ES6 subclassing.
  2719. *
  2720. * @param {string} className The class name of the subclass
  2721. * @param {Function} constructor The subclass
  2722. */
  2723. }, {
  2724. key: "registerSubclass",
  2725. value: function registerSubclass(className
  2726. /*: string*/
  2727. , constructor
  2728. /*: any*/
  2729. ) {
  2730. if (typeof className !== 'string') {
  2731. throw new TypeError('The first argument must be a valid class name.');
  2732. }
  2733. if (typeof constructor === 'undefined') {
  2734. throw new TypeError('You must supply a subclass constructor.');
  2735. }
  2736. if (typeof constructor !== 'function') {
  2737. throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
  2738. }
  2739. classMap[className] = constructor;
  2740. if (!constructor.className) {
  2741. constructor.className = className;
  2742. }
  2743. }
  2744. /**
  2745. * Unegisters a subclass of Parse.Object with a specific class name.
  2746. *
  2747. * @param {string} className The class name of the subclass
  2748. */
  2749. }, {
  2750. key: "unregisterSubclass",
  2751. value: function unregisterSubclass(className
  2752. /*: string*/
  2753. ) {
  2754. if (typeof className !== 'string') {
  2755. throw new TypeError('The first argument must be a valid class name.');
  2756. }
  2757. delete classMap[className];
  2758. }
  2759. /**
  2760. * Creates a new subclass of Parse.Object for the given Parse class name.
  2761. *
  2762. * <p>Every extension of a Parse class will inherit from the most recent
  2763. * previous extension of that class. When a Parse.Object is automatically
  2764. * created by parsing JSON, it will use the most recent extension of that
  2765. * class.</p>
  2766. *
  2767. * <p>You should call either:<pre>
  2768. * var MyClass = Parse.Object.extend("MyClass", {
  2769. * <i>Instance methods</i>,
  2770. * initialize: function(attrs, options) {
  2771. * this.someInstanceProperty = [],
  2772. * <i>Other instance properties</i>
  2773. * }
  2774. * }, {
  2775. * <i>Class properties</i>
  2776. * });</pre>
  2777. * or, for Backbone compatibility:<pre>
  2778. * var MyClass = Parse.Object.extend({
  2779. * className: "MyClass",
  2780. * <i>Instance methods</i>,
  2781. * initialize: function(attrs, options) {
  2782. * this.someInstanceProperty = [],
  2783. * <i>Other instance properties</i>
  2784. * }
  2785. * }, {
  2786. * <i>Class properties</i>
  2787. * });</pre></p>
  2788. *
  2789. * @param {string} className The name of the Parse class backing this model.
  2790. * @param {object} protoProps Instance properties to add to instances of the
  2791. * class returned from this method.
  2792. * @param {object} classProps Class properties to add the class returned from
  2793. * this method.
  2794. * @returns {Parse.Object} A new subclass of Parse.Object.
  2795. */
  2796. }, {
  2797. key: "extend",
  2798. value: function extend(className
  2799. /*: any*/
  2800. , protoProps
  2801. /*: any*/
  2802. , classProps
  2803. /*: any*/
  2804. ) {
  2805. if (typeof className !== 'string') {
  2806. if (className && typeof className.className === 'string') {
  2807. return ParseObject.extend(className.className, className, protoProps);
  2808. } else {
  2809. throw new Error("Parse.Object.extend's first argument should be the className.");
  2810. }
  2811. }
  2812. var adjustedClassName = className;
  2813. if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  2814. adjustedClassName = '_User';
  2815. }
  2816. var parentProto = ParseObject.prototype;
  2817. if (this.hasOwnProperty('__super__') && this.__super__) {
  2818. parentProto = this.prototype;
  2819. } else if (classMap[adjustedClassName]) {
  2820. parentProto = classMap[adjustedClassName].prototype;
  2821. }
  2822. var ParseObjectSubclass = function ParseObjectSubclass(attributes, options) {
  2823. this.className = adjustedClassName;
  2824. this._objCount = objectCount++; // Enable legacy initializers
  2825. if (typeof this.initialize === 'function') {
  2826. this.initialize.apply(this, arguments);
  2827. }
  2828. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  2829. if (!this.set(attributes || {}, options)) {
  2830. throw new Error("Can't create an invalid Parse Object");
  2831. }
  2832. }
  2833. };
  2834. ParseObjectSubclass.className = adjustedClassName;
  2835. ParseObjectSubclass.__super__ = parentProto;
  2836. ParseObjectSubclass.prototype = (0, _create.default)(parentProto, {
  2837. constructor: {
  2838. value: ParseObjectSubclass,
  2839. enumerable: false,
  2840. writable: true,
  2841. configurable: true
  2842. }
  2843. });
  2844. if (protoProps) {
  2845. for (var prop in protoProps) {
  2846. if (prop !== 'className') {
  2847. (0, _defineProperty2.default)(ParseObjectSubclass.prototype, prop, {
  2848. value: protoProps[prop],
  2849. enumerable: false,
  2850. writable: true,
  2851. configurable: true
  2852. });
  2853. }
  2854. }
  2855. }
  2856. if (classProps) {
  2857. for (var _prop in classProps) {
  2858. if (_prop !== 'className') {
  2859. (0, _defineProperty2.default)(ParseObjectSubclass, _prop, {
  2860. value: classProps[_prop],
  2861. enumerable: false,
  2862. writable: true,
  2863. configurable: true
  2864. });
  2865. }
  2866. }
  2867. }
  2868. ParseObjectSubclass.extend = function (name, protoProps, classProps) {
  2869. if (typeof name === 'string') {
  2870. return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
  2871. }
  2872. return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
  2873. };
  2874. ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
  2875. classMap[adjustedClassName] = ParseObjectSubclass;
  2876. return ParseObjectSubclass;
  2877. }
  2878. /**
  2879. * Enable single instance objects, where any local objects with the same Id
  2880. * share the same attributes, and stay synchronized with each other.
  2881. * This is disabled by default in server environments, since it can lead to
  2882. * security issues.
  2883. *
  2884. * @static
  2885. */
  2886. }, {
  2887. key: "enableSingleInstance",
  2888. value: function enableSingleInstance() {
  2889. singleInstance = true;
  2890. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  2891. }
  2892. /**
  2893. * Disable single instance objects, where any local objects with the same Id
  2894. * share the same attributes, and stay synchronized with each other.
  2895. * When disabled, you can have two instances of the same object in memory
  2896. * without them sharing attributes.
  2897. *
  2898. * @static
  2899. */
  2900. }, {
  2901. key: "disableSingleInstance",
  2902. value: function disableSingleInstance() {
  2903. singleInstance = false;
  2904. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  2905. }
  2906. /**
  2907. * Asynchronously stores the objects and every object they point to in the local datastore,
  2908. * recursively, using a default pin name: _default.
  2909. *
  2910. * If those other objects have not been fetched from Parse, they will not be stored.
  2911. * However, if they have changed data, all the changes will be retained.
  2912. *
  2913. * <pre>
  2914. * await Parse.Object.pinAll([...]);
  2915. * </pre>
  2916. *
  2917. * To retrieve object:
  2918. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  2919. *
  2920. * @param {Array} objects A list of <code>Parse.Object</code>.
  2921. * @returns {Promise} A promise that is fulfilled when the pin completes.
  2922. * @static
  2923. */
  2924. }, {
  2925. key: "pinAll",
  2926. value: function pinAll(objects
  2927. /*: Array<ParseObject>*/
  2928. )
  2929. /*: Promise<void>*/
  2930. {
  2931. var localDatastore = _CoreManager.default.getLocalDatastore();
  2932. if (!localDatastore.isEnabled) {
  2933. return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
  2934. }
  2935. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  2936. }
  2937. /**
  2938. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  2939. *
  2940. * If those other objects have not been fetched from Parse, they will not be stored.
  2941. * However, if they have changed data, all the changes will be retained.
  2942. *
  2943. * <pre>
  2944. * await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
  2945. * </pre>
  2946. *
  2947. * To retrieve object:
  2948. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  2949. *
  2950. * @param {string} name Name of Pin.
  2951. * @param {Array} objects A list of <code>Parse.Object</code>.
  2952. * @returns {Promise} A promise that is fulfilled when the pin completes.
  2953. * @static
  2954. */
  2955. }, {
  2956. key: "pinAllWithName",
  2957. value: function pinAllWithName(name
  2958. /*: string*/
  2959. , objects
  2960. /*: Array<ParseObject>*/
  2961. )
  2962. /*: Promise<void>*/
  2963. {
  2964. var localDatastore = _CoreManager.default.getLocalDatastore();
  2965. if (!localDatastore.isEnabled) {
  2966. return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
  2967. }
  2968. return localDatastore._handlePinAllWithName(name, objects);
  2969. }
  2970. /**
  2971. * Asynchronously removes the objects and every object they point to in the local datastore,
  2972. * recursively, using a default pin name: _default.
  2973. *
  2974. * <pre>
  2975. * await Parse.Object.unPinAll([...]);
  2976. * </pre>
  2977. *
  2978. * @param {Array} objects A list of <code>Parse.Object</code>.
  2979. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  2980. * @static
  2981. */
  2982. }, {
  2983. key: "unPinAll",
  2984. value: function unPinAll(objects
  2985. /*: Array<ParseObject>*/
  2986. )
  2987. /*: Promise<void>*/
  2988. {
  2989. var localDatastore = _CoreManager.default.getLocalDatastore();
  2990. if (!localDatastore.isEnabled) {
  2991. return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
  2992. }
  2993. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  2994. }
  2995. /**
  2996. * Asynchronously removes the objects and every object they point to in the local datastore, recursively.
  2997. *
  2998. * <pre>
  2999. * await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
  3000. * </pre>
  3001. *
  3002. * @param {string} name Name of Pin.
  3003. * @param {Array} objects A list of <code>Parse.Object</code>.
  3004. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  3005. * @static
  3006. */
  3007. }, {
  3008. key: "unPinAllWithName",
  3009. value: function unPinAllWithName(name
  3010. /*: string*/
  3011. , objects
  3012. /*: Array<ParseObject>*/
  3013. )
  3014. /*: Promise<void>*/
  3015. {
  3016. var localDatastore = _CoreManager.default.getLocalDatastore();
  3017. if (!localDatastore.isEnabled) {
  3018. return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
  3019. }
  3020. return localDatastore._handleUnPinAllWithName(name, objects);
  3021. }
  3022. /**
  3023. * Asynchronously removes all objects in the local datastore using a default pin name: _default.
  3024. *
  3025. * <pre>
  3026. * await Parse.Object.unPinAllObjects();
  3027. * </pre>
  3028. *
  3029. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  3030. * @static
  3031. */
  3032. }, {
  3033. key: "unPinAllObjects",
  3034. value: function unPinAllObjects()
  3035. /*: Promise<void>*/
  3036. {
  3037. var localDatastore = _CoreManager.default.getLocalDatastore();
  3038. if (!localDatastore.isEnabled) {
  3039. return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
  3040. }
  3041. return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  3042. }
  3043. /**
  3044. * Asynchronously removes all objects with the specified pin name.
  3045. * Deletes the pin name also.
  3046. *
  3047. * <pre>
  3048. * await Parse.Object.unPinAllObjectsWithName(name);
  3049. * </pre>
  3050. *
  3051. * @param {string} name Name of Pin.
  3052. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  3053. * @static
  3054. */
  3055. }, {
  3056. key: "unPinAllObjectsWithName",
  3057. value: function unPinAllObjectsWithName(name
  3058. /*: string*/
  3059. )
  3060. /*: Promise<void>*/
  3061. {
  3062. var localDatastore = _CoreManager.default.getLocalDatastore();
  3063. if (!localDatastore.isEnabled) {
  3064. return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
  3065. }
  3066. return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
  3067. }
  3068. }]);
  3069. return ParseObject;
  3070. }();
  3071. var DefaultController = {
  3072. fetch: function fetch(target
  3073. /*: ParseObject | Array<ParseObject>*/
  3074. , forceFetch
  3075. /*: boolean*/
  3076. , options
  3077. /*: RequestOptions*/
  3078. )
  3079. /*: Promise<Array<void> | ParseObject>*/
  3080. {
  3081. var localDatastore = _CoreManager.default.getLocalDatastore();
  3082. if ((0, _isArray.default)(target)) {
  3083. if (target.length < 1) {
  3084. return _promise.default.resolve([]);
  3085. }
  3086. var objs = [];
  3087. var ids = [];
  3088. var className = null;
  3089. var results = [];
  3090. var error = null;
  3091. (0, _forEach.default)(target).call(target, function (el) {
  3092. if (error) {
  3093. return;
  3094. }
  3095. if (!className) {
  3096. className = el.className;
  3097. }
  3098. if (className !== el.className) {
  3099. error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
  3100. }
  3101. if (!el.id) {
  3102. error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID');
  3103. }
  3104. if (forceFetch || !el.isDataAvailable()) {
  3105. ids.push(el.id);
  3106. objs.push(el);
  3107. }
  3108. results.push(el);
  3109. });
  3110. if (error) {
  3111. return _promise.default.reject(error);
  3112. }
  3113. var query = new _ParseQuery.default(className);
  3114. query.containedIn('objectId', ids);
  3115. if (options && options.include) {
  3116. query.include(options.include);
  3117. }
  3118. query._limit = ids.length;
  3119. return (0, _find.default)(query).call(query, options).then( /*#__PURE__*/function () {
  3120. var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(objects) {
  3121. var idMap, i, obj, _i, _obj, id, _iterator2, _step2, object;
  3122. return _regeneratorRuntime().wrap(function _callee6$(_context9) {
  3123. while (1) {
  3124. switch (_context9.prev = _context9.next) {
  3125. case 0:
  3126. idMap = {};
  3127. (0, _forEach.default)(objects).call(objects, function (o) {
  3128. idMap[o.id] = o;
  3129. });
  3130. i = 0;
  3131. case 3:
  3132. if (!(i < objs.length)) {
  3133. _context9.next = 11;
  3134. break;
  3135. }
  3136. obj = objs[i];
  3137. if (!(!obj || !obj.id || !idMap[obj.id])) {
  3138. _context9.next = 8;
  3139. break;
  3140. }
  3141. if (!forceFetch) {
  3142. _context9.next = 8;
  3143. break;
  3144. }
  3145. return _context9.abrupt("return", _promise.default.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.')));
  3146. case 8:
  3147. i++;
  3148. _context9.next = 3;
  3149. break;
  3150. case 11:
  3151. if (!singleInstance) {
  3152. // If single instance objects are disabled, we need to replace the
  3153. for (_i = 0; _i < results.length; _i++) {
  3154. _obj = results[_i];
  3155. if (_obj && _obj.id && idMap[_obj.id]) {
  3156. id = _obj.id;
  3157. _obj._finishFetch(idMap[id].toJSON());
  3158. results[_i] = idMap[id];
  3159. }
  3160. }
  3161. }
  3162. _iterator2 = _createForOfIteratorHelper(results);
  3163. _context9.prev = 13;
  3164. _iterator2.s();
  3165. case 15:
  3166. if ((_step2 = _iterator2.n()).done) {
  3167. _context9.next = 21;
  3168. break;
  3169. }
  3170. object = _step2.value;
  3171. _context9.next = 19;
  3172. return localDatastore._updateObjectIfPinned(object);
  3173. case 19:
  3174. _context9.next = 15;
  3175. break;
  3176. case 21:
  3177. _context9.next = 26;
  3178. break;
  3179. case 23:
  3180. _context9.prev = 23;
  3181. _context9.t0 = _context9["catch"](13);
  3182. _iterator2.e(_context9.t0);
  3183. case 26:
  3184. _context9.prev = 26;
  3185. _iterator2.f();
  3186. return _context9.finish(26);
  3187. case 29:
  3188. return _context9.abrupt("return", _promise.default.resolve(results));
  3189. case 30:
  3190. case "end":
  3191. return _context9.stop();
  3192. }
  3193. }
  3194. }, _callee6, null, [[13, 23, 26, 29]]);
  3195. }));
  3196. return function (_x4) {
  3197. return _ref.apply(this, arguments);
  3198. };
  3199. }());
  3200. } else if (target instanceof ParseObject) {
  3201. if (!target.id) {
  3202. return _promise.default.reject(new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'Object does not have an ID'));
  3203. }
  3204. var RESTController = _CoreManager.default.getRESTController();
  3205. var params = {};
  3206. if (options && options.include) {
  3207. params.include = options.include.join();
  3208. }
  3209. return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then( /*#__PURE__*/function () {
  3210. var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(response) {
  3211. return _regeneratorRuntime().wrap(function _callee7$(_context10) {
  3212. while (1) {
  3213. switch (_context10.prev = _context10.next) {
  3214. case 0:
  3215. target._clearPendingOps();
  3216. target._clearServerData();
  3217. target._finishFetch(response);
  3218. _context10.next = 5;
  3219. return localDatastore._updateObjectIfPinned(target);
  3220. case 5:
  3221. return _context10.abrupt("return", target);
  3222. case 6:
  3223. case "end":
  3224. return _context10.stop();
  3225. }
  3226. }
  3227. }, _callee7);
  3228. }));
  3229. return function (_x5) {
  3230. return _ref2.apply(this, arguments);
  3231. };
  3232. }());
  3233. }
  3234. return _promise.default.resolve();
  3235. },
  3236. destroy: function destroy(target
  3237. /*: ParseObject | Array<ParseObject>*/
  3238. , options
  3239. /*: RequestOptions*/
  3240. )
  3241. /*: Promise<Array<void> | ParseObject>*/
  3242. {
  3243. return (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
  3244. var batchSize, localDatastore, RESTController, batches, deleteCompleted, errors;
  3245. return _regeneratorRuntime().wrap(function _callee10$(_context13) {
  3246. while (1) {
  3247. switch (_context13.prev = _context13.next) {
  3248. case 0:
  3249. batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
  3250. localDatastore = _CoreManager.default.getLocalDatastore();
  3251. RESTController = _CoreManager.default.getRESTController();
  3252. if (!(0, _isArray.default)(target)) {
  3253. _context13.next = 15;
  3254. break;
  3255. }
  3256. if (!(target.length < 1)) {
  3257. _context13.next = 6;
  3258. break;
  3259. }
  3260. return _context13.abrupt("return", _promise.default.resolve([]));
  3261. case 6:
  3262. batches = [[]];
  3263. (0, _forEach.default)(target).call(target, function (obj) {
  3264. if (!obj.id) {
  3265. return;
  3266. }
  3267. batches[batches.length - 1].push(obj);
  3268. if (batches[batches.length - 1].length >= batchSize) {
  3269. batches.push([]);
  3270. }
  3271. });
  3272. if (batches[batches.length - 1].length === 0) {
  3273. // If the last batch is empty, remove it
  3274. batches.pop();
  3275. }
  3276. deleteCompleted = _promise.default.resolve();
  3277. errors = [];
  3278. (0, _forEach.default)(batches).call(batches, function (batch) {
  3279. deleteCompleted = deleteCompleted.then(function () {
  3280. return RESTController.request('POST', 'batch', {
  3281. requests: (0, _map.default)(batch).call(batch, function (obj) {
  3282. return {
  3283. method: 'DELETE',
  3284. path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
  3285. body: {}
  3286. };
  3287. })
  3288. }, options).then(function (results) {
  3289. for (var i = 0; i < results.length; i++) {
  3290. if (results[i] && results[i].hasOwnProperty('error')) {
  3291. var err = new _ParseError.default(results[i].error.code, results[i].error.error);
  3292. err.object = batch[i];
  3293. errors.push(err);
  3294. }
  3295. }
  3296. });
  3297. });
  3298. });
  3299. return _context13.abrupt("return", deleteCompleted.then( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
  3300. var aggregate, _iterator3, _step3, object;
  3301. return _regeneratorRuntime().wrap(function _callee8$(_context11) {
  3302. while (1) {
  3303. switch (_context11.prev = _context11.next) {
  3304. case 0:
  3305. if (!errors.length) {
  3306. _context11.next = 4;
  3307. break;
  3308. }
  3309. aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
  3310. aggregate.errors = errors;
  3311. return _context11.abrupt("return", _promise.default.reject(aggregate));
  3312. case 4:
  3313. _iterator3 = _createForOfIteratorHelper(target);
  3314. _context11.prev = 5;
  3315. _iterator3.s();
  3316. case 7:
  3317. if ((_step3 = _iterator3.n()).done) {
  3318. _context11.next = 13;
  3319. break;
  3320. }
  3321. object = _step3.value;
  3322. _context11.next = 11;
  3323. return localDatastore._destroyObjectIfPinned(object);
  3324. case 11:
  3325. _context11.next = 7;
  3326. break;
  3327. case 13:
  3328. _context11.next = 18;
  3329. break;
  3330. case 15:
  3331. _context11.prev = 15;
  3332. _context11.t0 = _context11["catch"](5);
  3333. _iterator3.e(_context11.t0);
  3334. case 18:
  3335. _context11.prev = 18;
  3336. _iterator3.f();
  3337. return _context11.finish(18);
  3338. case 21:
  3339. return _context11.abrupt("return", _promise.default.resolve(target));
  3340. case 22:
  3341. case "end":
  3342. return _context11.stop();
  3343. }
  3344. }
  3345. }, _callee8, null, [[5, 15, 18, 21]]);
  3346. }))));
  3347. case 15:
  3348. if (!(target instanceof ParseObject)) {
  3349. _context13.next = 17;
  3350. break;
  3351. }
  3352. return _context13.abrupt("return", RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
  3353. return _regeneratorRuntime().wrap(function _callee9$(_context12) {
  3354. while (1) {
  3355. switch (_context12.prev = _context12.next) {
  3356. case 0:
  3357. _context12.next = 2;
  3358. return localDatastore._destroyObjectIfPinned(target);
  3359. case 2:
  3360. return _context12.abrupt("return", _promise.default.resolve(target));
  3361. case 3:
  3362. case "end":
  3363. return _context12.stop();
  3364. }
  3365. }
  3366. }, _callee9);
  3367. }))));
  3368. case 17:
  3369. return _context13.abrupt("return", _promise.default.resolve(target));
  3370. case 18:
  3371. case "end":
  3372. return _context13.stop();
  3373. }
  3374. }
  3375. }, _callee10);
  3376. }))();
  3377. },
  3378. save: function save(target
  3379. /*: ParseObject | Array<ParseObject | ParseFile>*/
  3380. , options
  3381. /*: RequestOptions*/
  3382. ) {
  3383. var batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
  3384. var localDatastore = _CoreManager.default.getLocalDatastore();
  3385. var mapIdForPin = {};
  3386. var RESTController = _CoreManager.default.getRESTController();
  3387. var stateController = _CoreManager.default.getObjectStateController();
  3388. var allowCustomObjectId = _CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID');
  3389. options = options || {};
  3390. options.returnStatus = options.returnStatus || true;
  3391. if ((0, _isArray.default)(target)) {
  3392. if (target.length < 1) {
  3393. return _promise.default.resolve([]);
  3394. }
  3395. var unsaved = (0, _concat.default)(target).call(target);
  3396. for (var i = 0; i < target.length; i++) {
  3397. if (target[i] instanceof ParseObject) {
  3398. unsaved = (0, _concat.default)(unsaved).call(unsaved, (0, _unsavedChildren.default)(target[i], true));
  3399. }
  3400. }
  3401. unsaved = (0, _unique.default)(unsaved);
  3402. var filesSaved
  3403. /*: Array<ParseFile>*/
  3404. = [];
  3405. var pending
  3406. /*: Array<ParseObject>*/
  3407. = [];
  3408. (0, _forEach.default)(unsaved).call(unsaved, function (el) {
  3409. if (el instanceof _ParseFile.default) {
  3410. filesSaved.push(el.save(options));
  3411. } else if (el instanceof ParseObject) {
  3412. pending.push(el);
  3413. }
  3414. });
  3415. return _promise.default.all(filesSaved).then(function () {
  3416. var objectError = null;
  3417. return (0, _promiseUtils.continueWhile)(function () {
  3418. return pending.length > 0;
  3419. }, function () {
  3420. var batch = [];
  3421. var nextPending = [];
  3422. (0, _forEach.default)(pending).call(pending, function (el) {
  3423. if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(el, 'id') && !el.id) {
  3424. throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
  3425. }
  3426. if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) {
  3427. batch.push(el);
  3428. } else {
  3429. nextPending.push(el);
  3430. }
  3431. });
  3432. pending = nextPending;
  3433. if (batch.length < 1) {
  3434. return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
  3435. } // Queue up tasks for each object in the batch.
  3436. // When every task is ready, the API request will execute
  3437. var batchReturned = new _promiseUtils.resolvingPromise();
  3438. var batchReady = [];
  3439. var batchTasks = [];
  3440. (0, _forEach.default)(batch).call(batch, function (obj, index) {
  3441. var ready = new _promiseUtils.resolvingPromise();
  3442. batchReady.push(ready);
  3443. var task = function task() {
  3444. ready.resolve();
  3445. return batchReturned.then(function (responses) {
  3446. if (responses[index].hasOwnProperty('success')) {
  3447. var objectId = responses[index].success.objectId;
  3448. var status = responses[index]._status;
  3449. delete responses[index]._status;
  3450. mapIdForPin[objectId] = obj._localId;
  3451. obj._handleSaveResponse(responses[index].success, status);
  3452. } else {
  3453. if (!objectError && responses[index].hasOwnProperty('error')) {
  3454. var serverError = responses[index].error;
  3455. objectError = new _ParseError.default(serverError.code, serverError.error); // Cancel the rest of the save
  3456. pending = [];
  3457. }
  3458. obj._handleSaveError();
  3459. }
  3460. });
  3461. };
  3462. stateController.pushPendingState(obj._getStateIdentifier());
  3463. batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), task));
  3464. });
  3465. (0, _promiseUtils.when)(batchReady).then(function () {
  3466. // Kick off the batch request
  3467. return RESTController.request('POST', 'batch', {
  3468. requests: (0, _map.default)(batch).call(batch, function (obj) {
  3469. var params = obj._getSaveParams();
  3470. params.path = getServerUrlPath() + params.path;
  3471. return params;
  3472. })
  3473. }, options);
  3474. }).then(batchReturned.resolve, function (error) {
  3475. batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
  3476. });
  3477. return (0, _promiseUtils.when)(batchTasks);
  3478. }).then( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
  3479. var _iterator4, _step4, object;
  3480. return _regeneratorRuntime().wrap(function _callee11$(_context14) {
  3481. while (1) {
  3482. switch (_context14.prev = _context14.next) {
  3483. case 0:
  3484. if (!objectError) {
  3485. _context14.next = 2;
  3486. break;
  3487. }
  3488. return _context14.abrupt("return", _promise.default.reject(objectError));
  3489. case 2:
  3490. _iterator4 = _createForOfIteratorHelper(target);
  3491. _context14.prev = 3;
  3492. _iterator4.s();
  3493. case 5:
  3494. if ((_step4 = _iterator4.n()).done) {
  3495. _context14.next = 13;
  3496. break;
  3497. }
  3498. object = _step4.value;
  3499. _context14.next = 9;
  3500. return localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
  3501. case 9:
  3502. _context14.next = 11;
  3503. return localDatastore._updateObjectIfPinned(object);
  3504. case 11:
  3505. _context14.next = 5;
  3506. break;
  3507. case 13:
  3508. _context14.next = 18;
  3509. break;
  3510. case 15:
  3511. _context14.prev = 15;
  3512. _context14.t0 = _context14["catch"](3);
  3513. _iterator4.e(_context14.t0);
  3514. case 18:
  3515. _context14.prev = 18;
  3516. _iterator4.f();
  3517. return _context14.finish(18);
  3518. case 21:
  3519. return _context14.abrupt("return", _promise.default.resolve(target));
  3520. case 22:
  3521. case "end":
  3522. return _context14.stop();
  3523. }
  3524. }
  3525. }, _callee11, null, [[3, 15, 18, 21]]);
  3526. })));
  3527. });
  3528. } else if (target instanceof ParseObject) {
  3529. if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(target, 'id') && !target.id) {
  3530. throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
  3531. } // generate _localId in case if cascadeSave=false
  3532. target._getId();
  3533. var localId = target._localId; // copying target lets Flow guarantee the pointer isn't modified elsewhere
  3534. var targetCopy = target;
  3535. var task = function task() {
  3536. var params = targetCopy._getSaveParams();
  3537. return RESTController.request(params.method, params.path, params.body, options).then(function (response) {
  3538. var status = response._status;
  3539. delete response._status;
  3540. targetCopy._handleSaveResponse(response, status);
  3541. }, function (error) {
  3542. targetCopy._handleSaveError();
  3543. return _promise.default.reject(error);
  3544. });
  3545. };
  3546. stateController.pushPendingState(target._getStateIdentifier());
  3547. return stateController.enqueueTask(target._getStateIdentifier(), task).then( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
  3548. return _regeneratorRuntime().wrap(function _callee12$(_context15) {
  3549. while (1) {
  3550. switch (_context15.prev = _context15.next) {
  3551. case 0:
  3552. _context15.next = 2;
  3553. return localDatastore._updateLocalIdForObject(localId, target);
  3554. case 2:
  3555. _context15.next = 4;
  3556. return localDatastore._updateObjectIfPinned(target);
  3557. case 4:
  3558. return _context15.abrupt("return", target);
  3559. case 5:
  3560. case "end":
  3561. return _context15.stop();
  3562. }
  3563. }
  3564. }, _callee12);
  3565. })), function (error) {
  3566. return _promise.default.reject(error);
  3567. });
  3568. }
  3569. return _promise.default.resolve();
  3570. }
  3571. };
  3572. _CoreManager.default.setObjectController(DefaultController);
  3573. var _default = ParseObject;
  3574. exports.default = _default;