LocalDatastore.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  2. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  3. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
  4. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  5. var _ParseQuery = _interopRequireDefault(require("./ParseQuery"));
  6. var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
  7. function _regeneratorRuntime() {
  8. "use strict";
  9. _regeneratorRuntime = function () {
  10. return exports;
  11. };
  12. var exports = {},
  13. Op = Object.prototype,
  14. hasOwn = Op.hasOwnProperty,
  15. $Symbol = "function" == typeof Symbol ? Symbol : {},
  16. iteratorSymbol = $Symbol.iterator || "@@iterator",
  17. asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
  18. toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  19. function define(obj, key, value) {
  20. return Object.defineProperty(obj, key, {
  21. value: value,
  22. enumerable: !0,
  23. configurable: !0,
  24. writable: !0
  25. }), obj[key];
  26. }
  27. try {
  28. define({}, "");
  29. } catch (err) {
  30. define = function (obj, key, value) {
  31. return obj[key] = value;
  32. };
  33. }
  34. function wrap(innerFn, outerFn, self, tryLocsList) {
  35. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
  36. generator = Object.create(protoGenerator.prototype),
  37. context = new Context(tryLocsList || []);
  38. return generator._invoke = function (innerFn, self, context) {
  39. var state = "suspendedStart";
  40. return function (method, arg) {
  41. if ("executing" === state) throw new Error("Generator is already running");
  42. if ("completed" === state) {
  43. if ("throw" === method) throw arg;
  44. return doneResult();
  45. }
  46. for (context.method = method, context.arg = arg;;) {
  47. var delegate = context.delegate;
  48. if (delegate) {
  49. var delegateResult = maybeInvokeDelegate(delegate, context);
  50. if (delegateResult) {
  51. if (delegateResult === ContinueSentinel) continue;
  52. return delegateResult;
  53. }
  54. }
  55. if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
  56. if ("suspendedStart" === state) throw state = "completed", context.arg;
  57. context.dispatchException(context.arg);
  58. } else "return" === context.method && context.abrupt("return", context.arg);
  59. state = "executing";
  60. var record = tryCatch(innerFn, self, context);
  61. if ("normal" === record.type) {
  62. if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
  63. return {
  64. value: record.arg,
  65. done: context.done
  66. };
  67. }
  68. "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
  69. }
  70. };
  71. }(innerFn, self, context), generator;
  72. }
  73. function tryCatch(fn, obj, arg) {
  74. try {
  75. return {
  76. type: "normal",
  77. arg: fn.call(obj, arg)
  78. };
  79. } catch (err) {
  80. return {
  81. type: "throw",
  82. arg: err
  83. };
  84. }
  85. }
  86. exports.wrap = wrap;
  87. var ContinueSentinel = {};
  88. function Generator() {}
  89. function GeneratorFunction() {}
  90. function GeneratorFunctionPrototype() {}
  91. var IteratorPrototype = {};
  92. define(IteratorPrototype, iteratorSymbol, function () {
  93. return this;
  94. });
  95. var getProto = Object.getPrototypeOf,
  96. NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  97. NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
  98. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
  99. function defineIteratorMethods(prototype) {
  100. ["next", "throw", "return"].forEach(function (method) {
  101. define(prototype, method, function (arg) {
  102. return this._invoke(method, arg);
  103. });
  104. });
  105. }
  106. function AsyncIterator(generator, PromiseImpl) {
  107. function invoke(method, arg, resolve, reject) {
  108. var record = tryCatch(generator[method], generator, arg);
  109. if ("throw" !== record.type) {
  110. var result = record.arg,
  111. value = result.value;
  112. return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
  113. invoke("next", value, resolve, reject);
  114. }, function (err) {
  115. invoke("throw", err, resolve, reject);
  116. }) : PromiseImpl.resolve(value).then(function (unwrapped) {
  117. result.value = unwrapped, resolve(result);
  118. }, function (error) {
  119. return invoke("throw", error, resolve, reject);
  120. });
  121. }
  122. reject(record.arg);
  123. }
  124. var previousPromise;
  125. this._invoke = function (method, arg) {
  126. function callInvokeWithMethodAndArg() {
  127. return new PromiseImpl(function (resolve, reject) {
  128. invoke(method, arg, resolve, reject);
  129. });
  130. }
  131. return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  132. };
  133. }
  134. function maybeInvokeDelegate(delegate, context) {
  135. var method = delegate.iterator[context.method];
  136. if (undefined === method) {
  137. if (context.delegate = null, "throw" === context.method) {
  138. if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
  139. context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
  140. }
  141. return ContinueSentinel;
  142. }
  143. var record = tryCatch(method, delegate.iterator, context.arg);
  144. if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
  145. var info = record.arg;
  146. 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);
  147. }
  148. function pushTryEntry(locs) {
  149. var entry = {
  150. tryLoc: locs[0]
  151. };
  152. 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
  153. }
  154. function resetTryEntry(entry) {
  155. var record = entry.completion || {};
  156. record.type = "normal", delete record.arg, entry.completion = record;
  157. }
  158. function Context(tryLocsList) {
  159. this.tryEntries = [{
  160. tryLoc: "root"
  161. }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
  162. }
  163. function values(iterable) {
  164. if (iterable) {
  165. var iteratorMethod = iterable[iteratorSymbol];
  166. if (iteratorMethod) return iteratorMethod.call(iterable);
  167. if ("function" == typeof iterable.next) return iterable;
  168. if (!isNaN(iterable.length)) {
  169. var i = -1,
  170. next = function next() {
  171. for (; ++i < iterable.length;) {
  172. if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
  173. }
  174. return next.value = undefined, next.done = !0, next;
  175. };
  176. return next.next = next;
  177. }
  178. }
  179. return {
  180. next: doneResult
  181. };
  182. }
  183. function doneResult() {
  184. return {
  185. value: undefined,
  186. done: !0
  187. };
  188. }
  189. return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
  190. var ctor = "function" == typeof genFun && genFun.constructor;
  191. return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
  192. }, exports.mark = function (genFun) {
  193. return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
  194. }, exports.awrap = function (arg) {
  195. return {
  196. __await: arg
  197. };
  198. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
  199. return this;
  200. }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  201. void 0 === PromiseImpl && (PromiseImpl = Promise);
  202. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  203. return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
  204. return result.done ? result.value : iter.next();
  205. });
  206. }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
  207. return this;
  208. }), define(Gp, "toString", function () {
  209. return "[object Generator]";
  210. }), exports.keys = function (object) {
  211. var keys = [];
  212. for (var key in object) {
  213. keys.push(key);
  214. }
  215. return keys.reverse(), function next() {
  216. for (; keys.length;) {
  217. var key = keys.pop();
  218. if (key in object) return next.value = key, next.done = !1, next;
  219. }
  220. return next.done = !0, next;
  221. };
  222. }, exports.values = values, Context.prototype = {
  223. constructor: Context,
  224. reset: function (skipTempReset) {
  225. if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) {
  226. "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
  227. }
  228. },
  229. stop: function () {
  230. this.done = !0;
  231. var rootRecord = this.tryEntries[0].completion;
  232. if ("throw" === rootRecord.type) throw rootRecord.arg;
  233. return this.rval;
  234. },
  235. dispatchException: function (exception) {
  236. if (this.done) throw exception;
  237. var context = this;
  238. function handle(loc, caught) {
  239. return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
  240. }
  241. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  242. var entry = this.tryEntries[i],
  243. record = entry.completion;
  244. if ("root" === entry.tryLoc) return handle("end");
  245. if (entry.tryLoc <= this.prev) {
  246. var hasCatch = hasOwn.call(entry, "catchLoc"),
  247. hasFinally = hasOwn.call(entry, "finallyLoc");
  248. if (hasCatch && hasFinally) {
  249. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  250. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  251. } else if (hasCatch) {
  252. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  253. } else {
  254. if (!hasFinally) throw new Error("try statement without catch or finally");
  255. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  256. }
  257. }
  258. }
  259. },
  260. abrupt: function (type, arg) {
  261. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  262. var entry = this.tryEntries[i];
  263. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  264. var finallyEntry = entry;
  265. break;
  266. }
  267. }
  268. finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
  269. var record = finallyEntry ? finallyEntry.completion : {};
  270. return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
  271. },
  272. complete: function (record, afterLoc) {
  273. if ("throw" === record.type) throw record.arg;
  274. 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;
  275. },
  276. finish: function (finallyLoc) {
  277. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  278. var entry = this.tryEntries[i];
  279. if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
  280. }
  281. },
  282. catch: function (tryLoc) {
  283. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  284. var entry = this.tryEntries[i];
  285. if (entry.tryLoc === tryLoc) {
  286. var record = entry.completion;
  287. if ("throw" === record.type) {
  288. var thrown = record.arg;
  289. resetTryEntry(entry);
  290. }
  291. return thrown;
  292. }
  293. }
  294. throw new Error("illegal catch attempt");
  295. },
  296. delegateYield: function (iterable, resultName, nextLoc) {
  297. return this.delegate = {
  298. iterator: values(iterable),
  299. resultName: resultName,
  300. nextLoc: nextLoc
  301. }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
  302. }
  303. }, exports;
  304. }
  305. function _createForOfIteratorHelperLoose(o, allowArrayLike) {
  306. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  307. if (it) return (it = it.call(o)).next.bind(it);
  308. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  309. if (it) o = it;
  310. var i = 0;
  311. return function () {
  312. if (i >= o.length) return {
  313. done: true
  314. };
  315. return {
  316. done: false,
  317. value: o[i++]
  318. };
  319. };
  320. }
  321. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  322. }
  323. function _unsupportedIterableToArray(o, minLen) {
  324. if (!o) return;
  325. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  326. var n = Object.prototype.toString.call(o).slice(8, -1);
  327. if (n === "Object" && o.constructor) n = o.constructor.name;
  328. if (n === "Map" || n === "Set") return Array.from(o);
  329. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  330. }
  331. function _arrayLikeToArray(arr, len) {
  332. if (len == null || len > arr.length) len = arr.length;
  333. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  334. arr2[i] = arr[i];
  335. }
  336. return arr2;
  337. }
  338. var LocalDatastore = {
  339. isEnabled: false,
  340. isSyncing: false,
  341. fromPinWithName: function (name) {
  342. var controller = _CoreManager.default.getLocalDatastoreController();
  343. return controller.fromPinWithName(name);
  344. },
  345. pinWithName: function (name, value) {
  346. var controller = _CoreManager.default.getLocalDatastoreController();
  347. return controller.pinWithName(name, value);
  348. },
  349. unPinWithName: function (name) {
  350. var controller = _CoreManager.default.getLocalDatastoreController();
  351. return controller.unPinWithName(name);
  352. },
  353. _getAllContents: function () {
  354. var controller = _CoreManager.default.getLocalDatastoreController();
  355. return controller.getAllContents();
  356. },
  357. _getRawStorage: function () {
  358. var controller = _CoreManager.default.getLocalDatastoreController();
  359. return controller.getRawStorage();
  360. },
  361. _clear: function () {
  362. var controller = _CoreManager.default.getLocalDatastoreController();
  363. return controller.clear();
  364. },
  365. _handlePinAllWithName: function (name, objects) {
  366. var pinName, toPinPromises, objectKeys, _iterator, _step, parent, children, parentKey, json, objectKey, fromPinPromise, _await$Promise$all, _await$Promise$all2, pinned, toPin;
  367. return _regeneratorRuntime().async(function (_context) {
  368. while (1) {
  369. switch (_context.prev = _context.next) {
  370. case 0:
  371. pinName = this.getPinName(name);
  372. toPinPromises = [];
  373. objectKeys = [];
  374. for (_iterator = _createForOfIteratorHelperLoose(objects); !(_step = _iterator()).done;) {
  375. parent = _step.value;
  376. children = this._getChildren(parent);
  377. parentKey = this.getKeyForObject(parent);
  378. json = parent._toFullJSON(undefined, true);
  379. if (parent._localId) {
  380. json._localId = parent._localId;
  381. }
  382. children[parentKey] = json;
  383. for (objectKey in children) {
  384. objectKeys.push(objectKey);
  385. toPinPromises.push(this.pinWithName(objectKey, [children[objectKey]]));
  386. }
  387. }
  388. fromPinPromise = this.fromPinWithName(pinName);
  389. _context.next = 7;
  390. return _regeneratorRuntime().awrap(Promise.all([fromPinPromise, toPinPromises]));
  391. case 7:
  392. _await$Promise$all = _context.sent;
  393. _await$Promise$all2 = (0, _slicedToArray2.default)(_await$Promise$all, 1);
  394. pinned = _await$Promise$all2[0];
  395. toPin = (0, _toConsumableArray2.default)(new Set([].concat((0, _toConsumableArray2.default)(pinned || []), objectKeys)));
  396. return _context.abrupt("return", this.pinWithName(pinName, toPin));
  397. case 12:
  398. case "end":
  399. return _context.stop();
  400. }
  401. }
  402. }, null, this, null, Promise);
  403. },
  404. _handleUnPinAllWithName: function (name, objects) {
  405. var localDatastore, pinName, promises, objectKeys, _iterator2, _step2, _objectKeys, parent, children, parentKey, pinned, _iterator3, _step3, objectKey, hasReference, key, pinnedObjects;
  406. return _regeneratorRuntime().async(function (_context2) {
  407. while (1) {
  408. switch (_context2.prev = _context2.next) {
  409. case 0:
  410. _context2.next = 2;
  411. return _regeneratorRuntime().awrap(this._getAllContents());
  412. case 2:
  413. localDatastore = _context2.sent;
  414. pinName = this.getPinName(name);
  415. promises = [];
  416. objectKeys = [];
  417. for (_iterator2 = _createForOfIteratorHelperLoose(objects); !(_step2 = _iterator2()).done;) {
  418. parent = _step2.value;
  419. children = this._getChildren(parent);
  420. parentKey = this.getKeyForObject(parent);
  421. (_objectKeys = objectKeys).push.apply(_objectKeys, [parentKey].concat((0, _toConsumableArray2.default)(Object.keys(children))));
  422. }
  423. objectKeys = (0, _toConsumableArray2.default)(new Set(objectKeys));
  424. pinned = localDatastore[pinName] || [];
  425. pinned = pinned.filter(function (item) {
  426. return !objectKeys.includes(item);
  427. });
  428. if (pinned.length == 0) {
  429. promises.push(this.unPinWithName(pinName));
  430. delete localDatastore[pinName];
  431. } else {
  432. promises.push(this.pinWithName(pinName, pinned));
  433. localDatastore[pinName] = pinned;
  434. }
  435. _iterator3 = _createForOfIteratorHelperLoose(objectKeys);
  436. case 12:
  437. if ((_step3 = _iterator3()).done) {
  438. _context2.next = 28;
  439. break;
  440. }
  441. objectKey = _step3.value;
  442. hasReference = false;
  443. _context2.t0 = _regeneratorRuntime().keys(localDatastore);
  444. case 16:
  445. if ((_context2.t1 = _context2.t0()).done) {
  446. _context2.next = 25;
  447. break;
  448. }
  449. key = _context2.t1.value;
  450. if (!(key === _LocalDatastoreUtils.DEFAULT_PIN || key.startsWith(_LocalDatastoreUtils.PIN_PREFIX))) {
  451. _context2.next = 23;
  452. break;
  453. }
  454. pinnedObjects = localDatastore[key] || [];
  455. if (!pinnedObjects.includes(objectKey)) {
  456. _context2.next = 23;
  457. break;
  458. }
  459. hasReference = true;
  460. return _context2.abrupt("break", 25);
  461. case 23:
  462. _context2.next = 16;
  463. break;
  464. case 25:
  465. if (!hasReference) {
  466. promises.push(this.unPinWithName(objectKey));
  467. }
  468. case 26:
  469. _context2.next = 12;
  470. break;
  471. case 28:
  472. return _context2.abrupt("return", Promise.all(promises));
  473. case 29:
  474. case "end":
  475. return _context2.stop();
  476. }
  477. }
  478. }, null, this, null, Promise);
  479. },
  480. _getChildren: function (object) {
  481. var encountered = {};
  482. var json = object._toFullJSON(undefined, true);
  483. for (var key in json) {
  484. if (json[key] && json[key].__type && json[key].__type === 'Object') {
  485. this._traverse(json[key], encountered);
  486. }
  487. }
  488. return encountered;
  489. },
  490. _traverse: function (object, encountered) {
  491. if (!object.objectId) {
  492. return;
  493. } else {
  494. var objectKey = this.getKeyForObject(object);
  495. if (encountered[objectKey]) {
  496. return;
  497. }
  498. encountered[objectKey] = object;
  499. }
  500. for (var key in object) {
  501. var json = object[key];
  502. if (!object[key]) {
  503. json = object;
  504. }
  505. if (json.__type && json.__type === 'Object') {
  506. this._traverse(json, encountered);
  507. }
  508. }
  509. },
  510. _serializeObjectsFromPinName: function (name) {
  511. var _this = this,
  512. _ref;
  513. var localDatastore, allObjects, key, pinName, pinned, promises, objects;
  514. return _regeneratorRuntime().async(function (_context3) {
  515. while (1) {
  516. switch (_context3.prev = _context3.next) {
  517. case 0:
  518. _context3.next = 2;
  519. return _regeneratorRuntime().awrap(this._getAllContents());
  520. case 2:
  521. localDatastore = _context3.sent;
  522. allObjects = [];
  523. for (key in localDatastore) {
  524. if (key.startsWith(_LocalDatastoreUtils.OBJECT_PREFIX)) {
  525. allObjects.push(localDatastore[key][0]);
  526. }
  527. }
  528. if (name) {
  529. _context3.next = 7;
  530. break;
  531. }
  532. return _context3.abrupt("return", allObjects);
  533. case 7:
  534. pinName = this.getPinName(name);
  535. pinned = localDatastore[pinName];
  536. if (Array.isArray(pinned)) {
  537. _context3.next = 11;
  538. break;
  539. }
  540. return _context3.abrupt("return", []);
  541. case 11:
  542. promises = pinned.map(function (objectKey) {
  543. return _this.fromPinWithName(objectKey);
  544. });
  545. _context3.next = 14;
  546. return _regeneratorRuntime().awrap(Promise.all(promises));
  547. case 14:
  548. objects = _context3.sent;
  549. objects = (_ref = []).concat.apply(_ref, (0, _toConsumableArray2.default)(objects));
  550. return _context3.abrupt("return", objects.filter(function (object) {
  551. return object != null;
  552. }));
  553. case 17:
  554. case "end":
  555. return _context3.stop();
  556. }
  557. }
  558. }, null, this, null, Promise);
  559. },
  560. _serializeObject: function (objectKey, localDatastore) {
  561. var LDS, root, queue, meta, uniqueId, nodeId, subTreeRoot, field, value, key, pointer;
  562. return _regeneratorRuntime().async(function (_context4) {
  563. while (1) {
  564. switch (_context4.prev = _context4.next) {
  565. case 0:
  566. LDS = localDatastore;
  567. if (LDS) {
  568. _context4.next = 5;
  569. break;
  570. }
  571. _context4.next = 4;
  572. return _regeneratorRuntime().awrap(this._getAllContents());
  573. case 4:
  574. LDS = _context4.sent;
  575. case 5:
  576. if (!(!LDS[objectKey] || LDS[objectKey].length === 0)) {
  577. _context4.next = 7;
  578. break;
  579. }
  580. return _context4.abrupt("return", null);
  581. case 7:
  582. root = LDS[objectKey][0];
  583. queue = [];
  584. meta = {};
  585. uniqueId = 0;
  586. meta[uniqueId] = root;
  587. queue.push(uniqueId);
  588. while (queue.length !== 0) {
  589. nodeId = queue.shift();
  590. subTreeRoot = meta[nodeId];
  591. for (field in subTreeRoot) {
  592. value = subTreeRoot[field];
  593. if (value.__type && value.__type === 'Object') {
  594. key = this.getKeyForObject(value);
  595. if (LDS[key] && LDS[key].length > 0) {
  596. pointer = LDS[key][0];
  597. uniqueId++;
  598. meta[uniqueId] = pointer;
  599. subTreeRoot[field] = pointer;
  600. queue.push(uniqueId);
  601. }
  602. }
  603. }
  604. }
  605. return _context4.abrupt("return", root);
  606. case 15:
  607. case "end":
  608. return _context4.stop();
  609. }
  610. }
  611. }, null, this, null, Promise);
  612. },
  613. _updateObjectIfPinned: function (object) {
  614. var objectKey, pinned;
  615. return _regeneratorRuntime().async(function (_context5) {
  616. while (1) {
  617. switch (_context5.prev = _context5.next) {
  618. case 0:
  619. if (this.isEnabled) {
  620. _context5.next = 2;
  621. break;
  622. }
  623. return _context5.abrupt("return");
  624. case 2:
  625. objectKey = this.getKeyForObject(object);
  626. _context5.next = 5;
  627. return _regeneratorRuntime().awrap(this.fromPinWithName(objectKey));
  628. case 5:
  629. pinned = _context5.sent;
  630. if (!(!pinned || pinned.length === 0)) {
  631. _context5.next = 8;
  632. break;
  633. }
  634. return _context5.abrupt("return");
  635. case 8:
  636. return _context5.abrupt("return", this.pinWithName(objectKey, [object._toFullJSON()]));
  637. case 9:
  638. case "end":
  639. return _context5.stop();
  640. }
  641. }
  642. }, null, this, null, Promise);
  643. },
  644. _destroyObjectIfPinned: function (object) {
  645. var localDatastore, objectKey, pin, promises, key, pinned;
  646. return _regeneratorRuntime().async(function (_context6) {
  647. while (1) {
  648. switch (_context6.prev = _context6.next) {
  649. case 0:
  650. if (this.isEnabled) {
  651. _context6.next = 2;
  652. break;
  653. }
  654. return _context6.abrupt("return");
  655. case 2:
  656. _context6.next = 4;
  657. return _regeneratorRuntime().awrap(this._getAllContents());
  658. case 4:
  659. localDatastore = _context6.sent;
  660. objectKey = this.getKeyForObject(object);
  661. pin = localDatastore[objectKey];
  662. if (pin) {
  663. _context6.next = 9;
  664. break;
  665. }
  666. return _context6.abrupt("return");
  667. case 9:
  668. promises = [this.unPinWithName(objectKey)];
  669. delete localDatastore[objectKey];
  670. for (key in localDatastore) {
  671. if (key === _LocalDatastoreUtils.DEFAULT_PIN || key.startsWith(_LocalDatastoreUtils.PIN_PREFIX)) {
  672. pinned = localDatastore[key] || [];
  673. if (pinned.includes(objectKey)) {
  674. pinned = pinned.filter(function (item) {
  675. return item !== objectKey;
  676. });
  677. if (pinned.length == 0) {
  678. promises.push(this.unPinWithName(key));
  679. delete localDatastore[key];
  680. } else {
  681. promises.push(this.pinWithName(key, pinned));
  682. localDatastore[key] = pinned;
  683. }
  684. }
  685. }
  686. }
  687. return _context6.abrupt("return", Promise.all(promises));
  688. case 13:
  689. case "end":
  690. return _context6.stop();
  691. }
  692. }
  693. }, null, this, null, Promise);
  694. },
  695. _updateLocalIdForObject: function (localId, object) {
  696. var localKey, objectKey, unsaved, promises, localDatastore, key, pinned;
  697. return _regeneratorRuntime().async(function (_context7) {
  698. while (1) {
  699. switch (_context7.prev = _context7.next) {
  700. case 0:
  701. if (this.isEnabled) {
  702. _context7.next = 2;
  703. break;
  704. }
  705. return _context7.abrupt("return");
  706. case 2:
  707. localKey = "" + _LocalDatastoreUtils.OBJECT_PREFIX + object.className + "_" + localId;
  708. objectKey = this.getKeyForObject(object);
  709. _context7.next = 6;
  710. return _regeneratorRuntime().awrap(this.fromPinWithName(localKey));
  711. case 6:
  712. unsaved = _context7.sent;
  713. if (!(!unsaved || unsaved.length === 0)) {
  714. _context7.next = 9;
  715. break;
  716. }
  717. return _context7.abrupt("return");
  718. case 9:
  719. promises = [this.unPinWithName(localKey), this.pinWithName(objectKey, unsaved)];
  720. _context7.next = 12;
  721. return _regeneratorRuntime().awrap(this._getAllContents());
  722. case 12:
  723. localDatastore = _context7.sent;
  724. for (key in localDatastore) {
  725. if (key === _LocalDatastoreUtils.DEFAULT_PIN || key.startsWith(_LocalDatastoreUtils.PIN_PREFIX)) {
  726. pinned = localDatastore[key] || [];
  727. if (pinned.includes(localKey)) {
  728. pinned = pinned.filter(function (item) {
  729. return item !== localKey;
  730. });
  731. pinned.push(objectKey);
  732. promises.push(this.pinWithName(key, pinned));
  733. localDatastore[key] = pinned;
  734. }
  735. }
  736. }
  737. return _context7.abrupt("return", Promise.all(promises));
  738. case 15:
  739. case "end":
  740. return _context7.stop();
  741. }
  742. }
  743. }, null, this, null, Promise);
  744. },
  745. updateFromServer: function () {
  746. var _this2 = this;
  747. var localDatastore, keys, key, pointersHash, _i, _keys, _key, _key$split, _key$split2, className, objectId, queryPromises, responses, objects, pinPromises;
  748. return _regeneratorRuntime().async(function (_context8) {
  749. while (1) {
  750. switch (_context8.prev = _context8.next) {
  751. case 0:
  752. if (!(!this.checkIfEnabled() || this.isSyncing)) {
  753. _context8.next = 2;
  754. break;
  755. }
  756. return _context8.abrupt("return");
  757. case 2:
  758. _context8.next = 4;
  759. return _regeneratorRuntime().awrap(this._getAllContents());
  760. case 4:
  761. localDatastore = _context8.sent;
  762. keys = [];
  763. for (key in localDatastore) {
  764. if (key.startsWith(_LocalDatastoreUtils.OBJECT_PREFIX)) {
  765. keys.push(key);
  766. }
  767. }
  768. if (!(keys.length === 0)) {
  769. _context8.next = 9;
  770. break;
  771. }
  772. return _context8.abrupt("return");
  773. case 9:
  774. this.isSyncing = true;
  775. pointersHash = {};
  776. _i = 0, _keys = keys;
  777. case 12:
  778. if (!(_i < _keys.length)) {
  779. _context8.next = 23;
  780. break;
  781. }
  782. _key = _keys[_i];
  783. _key$split = _key.split('_'), _key$split2 = (0, _slicedToArray2.default)(_key$split, 4), className = _key$split2[2], objectId = _key$split2[3];
  784. if (_key.split('_').length === 5 && _key.split('_')[3] === 'User') {
  785. className = '_User';
  786. objectId = _key.split('_')[4];
  787. }
  788. if (!objectId.startsWith('local')) {
  789. _context8.next = 18;
  790. break;
  791. }
  792. return _context8.abrupt("continue", 20);
  793. case 18:
  794. if (!(className in pointersHash)) {
  795. pointersHash[className] = new Set();
  796. }
  797. pointersHash[className].add(objectId);
  798. case 20:
  799. _i++;
  800. _context8.next = 12;
  801. break;
  802. case 23:
  803. queryPromises = Object.keys(pointersHash).map(function (className) {
  804. var objectIds = Array.from(pointersHash[className]);
  805. var query = new _ParseQuery.default(className);
  806. query.limit(objectIds.length);
  807. if (objectIds.length === 1) {
  808. query.equalTo('objectId', objectIds[0]);
  809. } else {
  810. query.containedIn('objectId', objectIds);
  811. }
  812. return query.find();
  813. });
  814. _context8.prev = 24;
  815. _context8.next = 27;
  816. return _regeneratorRuntime().awrap(Promise.all(queryPromises));
  817. case 27:
  818. responses = _context8.sent;
  819. objects = [].concat.apply([], responses);
  820. pinPromises = objects.map(function (object) {
  821. var objectKey = _this2.getKeyForObject(object);
  822. return _this2.pinWithName(objectKey, object._toFullJSON());
  823. });
  824. _context8.next = 32;
  825. return _regeneratorRuntime().awrap(Promise.all(pinPromises));
  826. case 32:
  827. this.isSyncing = false;
  828. _context8.next = 39;
  829. break;
  830. case 35:
  831. _context8.prev = 35;
  832. _context8.t0 = _context8["catch"](24);
  833. console.error('Error syncing LocalDatastore: ', _context8.t0);
  834. this.isSyncing = false;
  835. case 39:
  836. case "end":
  837. return _context8.stop();
  838. }
  839. }
  840. }, null, this, [[24, 35]], Promise);
  841. },
  842. getKeyForObject: function (object) {
  843. var objectId = object.objectId || object._getId();
  844. return "" + _LocalDatastoreUtils.OBJECT_PREFIX + object.className + "_" + objectId;
  845. },
  846. getPinName: function (pinName) {
  847. if (!pinName || pinName === _LocalDatastoreUtils.DEFAULT_PIN) {
  848. return _LocalDatastoreUtils.DEFAULT_PIN;
  849. }
  850. return _LocalDatastoreUtils.PIN_PREFIX + pinName;
  851. },
  852. checkIfEnabled: function () {
  853. if (!this.isEnabled) {
  854. console.error('Parse.enableLocalDatastore() must be called first');
  855. }
  856. return this.isEnabled;
  857. }
  858. };
  859. module.exports = LocalDatastore;
  860. _CoreManager.default.setLocalDatastoreController(require('./LocalDatastoreController.react-native'));
  861. _CoreManager.default.setLocalDatastore(LocalDatastore);