ParseFile.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  3. var _Object$defineProperties = require("@babel/runtime-corejs3/core-js-stable/object/define-properties");
  4. var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors");
  5. var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
  6. var _filterInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/filter");
  7. var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols");
  8. var _Object$keys2 = require("@babel/runtime-corejs3/core-js-stable/object/keys");
  9. var _sliceInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/slice");
  10. var _reverseInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/reverse");
  11. var _Promise2 = require("@babel/runtime-corejs3/core-js-stable/promise");
  12. var _Object$setPrototypeOf = require("@babel/runtime-corejs3/core-js-stable/object/set-prototype-of");
  13. var _typeof3 = require("@babel/runtime-corejs3/helpers/typeof");
  14. var _forEachInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/for-each");
  15. var _Object$getPrototypeOf = require("@babel/runtime-corejs3/core-js-stable/object/get-prototype-of");
  16. var _Object$create = require("@babel/runtime-corejs3/core-js-stable/object/create");
  17. var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
  18. var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");
  19. _Object$defineProperty(exports, "__esModule", {
  20. value: true
  21. });
  22. exports.default = void 0;
  23. var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
  24. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));
  25. var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
  26. var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
  27. var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
  28. var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));
  29. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));
  30. var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
  31. var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
  32. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/classCallCheck"));
  33. var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/createClass"));
  34. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
  35. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  36. function ownKeys(object, enumerableOnly) {
  37. var keys = _Object$keys2(object);
  38. if (_Object$getOwnPropertySymbols) {
  39. var symbols = _Object$getOwnPropertySymbols(object);
  40. enumerableOnly && (symbols = _filterInstanceProperty(symbols).call(symbols, function (sym) {
  41. return _Object$getOwnPropertyDescriptor(object, sym).enumerable;
  42. })), keys.push.apply(keys, symbols);
  43. }
  44. return keys;
  45. }
  46. function _objectSpread(target) {
  47. for (var i = 1; i < arguments.length; i++) {
  48. var _context10, _context11;
  49. var source = null != arguments[i] ? arguments[i] : {};
  50. i % 2 ? _forEachInstanceProperty2(_context10 = ownKeys(Object(source), !0)).call(_context10, function (key) {
  51. (0, _defineProperty2.default)(target, key, source[key]);
  52. }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(target, _Object$getOwnPropertyDescriptors(source)) : _forEachInstanceProperty2(_context11 = ownKeys(Object(source))).call(_context11, function (key) {
  53. _Object$defineProperty(target, key, _Object$getOwnPropertyDescriptor(source, key));
  54. });
  55. }
  56. return target;
  57. }
  58. function _regeneratorRuntime() {
  59. "use strict";
  60. /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  61. _regeneratorRuntime = function () {
  62. return exports;
  63. };
  64. var exports = {},
  65. Op = Object.prototype,
  66. hasOwn = Op.hasOwnProperty,
  67. $Symbol = "function" == typeof _Symbol ? _Symbol : {},
  68. iteratorSymbol = $Symbol.iterator || "@@iterator",
  69. asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
  70. toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  71. function define(obj, key, value) {
  72. return _Object$defineProperty(obj, key, {
  73. value: value,
  74. enumerable: !0,
  75. configurable: !0,
  76. writable: !0
  77. }), obj[key];
  78. }
  79. try {
  80. define({}, "");
  81. } catch (err) {
  82. define = function (obj, key, value) {
  83. return obj[key] = value;
  84. };
  85. }
  86. function wrap(innerFn, outerFn, self, tryLocsList) {
  87. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
  88. generator = _Object$create(protoGenerator.prototype),
  89. context = new Context(tryLocsList || []);
  90. return generator._invoke = function (innerFn, self, context) {
  91. var state = "suspendedStart";
  92. return function (method, arg) {
  93. if ("executing" === state) throw new Error("Generator is already running");
  94. if ("completed" === state) {
  95. if ("throw" === method) throw arg;
  96. return doneResult();
  97. }
  98. for (context.method = method, context.arg = arg;;) {
  99. var delegate = context.delegate;
  100. if (delegate) {
  101. var delegateResult = maybeInvokeDelegate(delegate, context);
  102. if (delegateResult) {
  103. if (delegateResult === ContinueSentinel) continue;
  104. return delegateResult;
  105. }
  106. }
  107. if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
  108. if ("suspendedStart" === state) throw state = "completed", context.arg;
  109. context.dispatchException(context.arg);
  110. } else "return" === context.method && context.abrupt("return", context.arg);
  111. state = "executing";
  112. var record = tryCatch(innerFn, self, context);
  113. if ("normal" === record.type) {
  114. if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
  115. return {
  116. value: record.arg,
  117. done: context.done
  118. };
  119. }
  120. "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
  121. }
  122. };
  123. }(innerFn, self, context), generator;
  124. }
  125. function tryCatch(fn, obj, arg) {
  126. try {
  127. return {
  128. type: "normal",
  129. arg: fn.call(obj, arg)
  130. };
  131. } catch (err) {
  132. return {
  133. type: "throw",
  134. arg: err
  135. };
  136. }
  137. }
  138. exports.wrap = wrap;
  139. var ContinueSentinel = {};
  140. function Generator() {}
  141. function GeneratorFunction() {}
  142. function GeneratorFunctionPrototype() {}
  143. var IteratorPrototype = {};
  144. define(IteratorPrototype, iteratorSymbol, function () {
  145. return this;
  146. });
  147. var getProto = _Object$getPrototypeOf,
  148. NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  149. NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
  150. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = _Object$create(IteratorPrototype);
  151. function defineIteratorMethods(prototype) {
  152. var _context8;
  153. _forEachInstanceProperty2(_context8 = ["next", "throw", "return"]).call(_context8, function (method) {
  154. define(prototype, method, function (arg) {
  155. return this._invoke(method, arg);
  156. });
  157. });
  158. }
  159. function AsyncIterator(generator, PromiseImpl) {
  160. function invoke(method, arg, resolve, reject) {
  161. var record = tryCatch(generator[method], generator, arg);
  162. if ("throw" !== record.type) {
  163. var result = record.arg,
  164. value = result.value;
  165. return value && "object" == _typeof3(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
  166. invoke("next", value, resolve, reject);
  167. }, function (err) {
  168. invoke("throw", err, resolve, reject);
  169. }) : PromiseImpl.resolve(value).then(function (unwrapped) {
  170. result.value = unwrapped, resolve(result);
  171. }, function (error) {
  172. return invoke("throw", error, resolve, reject);
  173. });
  174. }
  175. reject(record.arg);
  176. }
  177. var previousPromise;
  178. this._invoke = function (method, arg) {
  179. function callInvokeWithMethodAndArg() {
  180. return new PromiseImpl(function (resolve, reject) {
  181. invoke(method, arg, resolve, reject);
  182. });
  183. }
  184. return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  185. };
  186. }
  187. function maybeInvokeDelegate(delegate, context) {
  188. var method = delegate.iterator[context.method];
  189. if (undefined === method) {
  190. if (context.delegate = null, "throw" === context.method) {
  191. if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
  192. context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
  193. }
  194. return ContinueSentinel;
  195. }
  196. var record = tryCatch(method, delegate.iterator, context.arg);
  197. if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
  198. var info = record.arg;
  199. 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);
  200. }
  201. function pushTryEntry(locs) {
  202. var entry = {
  203. tryLoc: locs[0]
  204. };
  205. 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
  206. }
  207. function resetTryEntry(entry) {
  208. var record = entry.completion || {};
  209. record.type = "normal", delete record.arg, entry.completion = record;
  210. }
  211. function Context(tryLocsList) {
  212. this.tryEntries = [{
  213. tryLoc: "root"
  214. }], _forEachInstanceProperty2(tryLocsList).call(tryLocsList, pushTryEntry, this), this.reset(!0);
  215. }
  216. function values(iterable) {
  217. if (iterable) {
  218. var iteratorMethod = iterable[iteratorSymbol];
  219. if (iteratorMethod) return iteratorMethod.call(iterable);
  220. if ("function" == typeof iterable.next) return iterable;
  221. if (!isNaN(iterable.length)) {
  222. var i = -1,
  223. next = function next() {
  224. for (; ++i < iterable.length;) {
  225. if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
  226. }
  227. return next.value = undefined, next.done = !0, next;
  228. };
  229. return next.next = next;
  230. }
  231. }
  232. return {
  233. next: doneResult
  234. };
  235. }
  236. function doneResult() {
  237. return {
  238. value: undefined,
  239. done: !0
  240. };
  241. }
  242. return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
  243. var ctor = "function" == typeof genFun && genFun.constructor;
  244. return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
  245. }, exports.mark = function (genFun) {
  246. return _Object$setPrototypeOf ? _Object$setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = _Object$create(Gp), genFun;
  247. }, exports.awrap = function (arg) {
  248. return {
  249. __await: arg
  250. };
  251. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
  252. return this;
  253. }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  254. void 0 === PromiseImpl && (PromiseImpl = _Promise2);
  255. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  256. return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
  257. return result.done ? result.value : iter.next();
  258. });
  259. }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
  260. return this;
  261. }), define(Gp, "toString", function () {
  262. return "[object Generator]";
  263. }), exports.keys = function (object) {
  264. var keys = [];
  265. for (var key in object) {
  266. keys.push(key);
  267. }
  268. return _reverseInstanceProperty(keys).call(keys), function next() {
  269. for (; keys.length;) {
  270. var key = keys.pop();
  271. if (key in object) return next.value = key, next.done = !1, next;
  272. }
  273. return next.done = !0, next;
  274. };
  275. }, exports.values = values, Context.prototype = {
  276. constructor: Context,
  277. reset: function (skipTempReset) {
  278. var _context9;
  279. 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(_context9 = this.tryEntries).call(_context9, resetTryEntry), !skipTempReset) for (var name in this) {
  280. "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+_sliceInstanceProperty2(name).call(name, 1)) && (this[name] = undefined);
  281. }
  282. },
  283. stop: function () {
  284. this.done = !0;
  285. var rootRecord = this.tryEntries[0].completion;
  286. if ("throw" === rootRecord.type) throw rootRecord.arg;
  287. return this.rval;
  288. },
  289. dispatchException: function (exception) {
  290. if (this.done) throw exception;
  291. var context = this;
  292. function handle(loc, caught) {
  293. return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
  294. }
  295. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  296. var entry = this.tryEntries[i],
  297. record = entry.completion;
  298. if ("root" === entry.tryLoc) return handle("end");
  299. if (entry.tryLoc <= this.prev) {
  300. var hasCatch = hasOwn.call(entry, "catchLoc"),
  301. hasFinally = hasOwn.call(entry, "finallyLoc");
  302. if (hasCatch && hasFinally) {
  303. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  304. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  305. } else if (hasCatch) {
  306. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  307. } else {
  308. if (!hasFinally) throw new Error("try statement without catch or finally");
  309. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  310. }
  311. }
  312. }
  313. },
  314. abrupt: function (type, arg) {
  315. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  316. var entry = this.tryEntries[i];
  317. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  318. var finallyEntry = entry;
  319. break;
  320. }
  321. }
  322. finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
  323. var record = finallyEntry ? finallyEntry.completion : {};
  324. return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
  325. },
  326. complete: function (record, afterLoc) {
  327. if ("throw" === record.type) throw record.arg;
  328. 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;
  329. },
  330. finish: function (finallyLoc) {
  331. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  332. var entry = this.tryEntries[i];
  333. if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
  334. }
  335. },
  336. catch: function (tryLoc) {
  337. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  338. var entry = this.tryEntries[i];
  339. if (entry.tryLoc === tryLoc) {
  340. var record = entry.completion;
  341. if ("throw" === record.type) {
  342. var thrown = record.arg;
  343. resetTryEntry(entry);
  344. }
  345. return thrown;
  346. }
  347. }
  348. throw new Error("illegal catch attempt");
  349. },
  350. delegateYield: function (iterable, resultName, nextLoc) {
  351. return this.delegate = {
  352. iterator: values(iterable),
  353. resultName: resultName,
  354. nextLoc: nextLoc
  355. }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
  356. }
  357. }, exports;
  358. }
  359. var ParseError = require('./ParseError').default;
  360. var XHR = null;
  361. if (typeof XMLHttpRequest !== 'undefined') {
  362. XHR = XMLHttpRequest;
  363. }
  364. XHR = require('./Xhr.weapp');
  365. /*:: type Base64 = { base64: string };*/
  366. /*:: type Uri = { uri: string };*/
  367. /*:: type FileData = Array<number> | Base64 | Blob | Uri;*/
  368. /*:: export type FileSource =
  369. | {
  370. format: 'file',
  371. file: Blob,
  372. type: string,
  373. }
  374. | {
  375. format: 'base64',
  376. base64: string,
  377. type: string,
  378. }
  379. | {
  380. format: 'uri',
  381. uri: string,
  382. type: string,
  383. };*/
  384. function b64Digit(number
  385. /*: number*/
  386. )
  387. /*: string*/
  388. {
  389. if (number < 26) {
  390. return String.fromCharCode(65 + number);
  391. }
  392. if (number < 52) {
  393. return String.fromCharCode(97 + (number - 26));
  394. }
  395. if (number < 62) {
  396. return String.fromCharCode(48 + (number - 52));
  397. }
  398. if (number === 62) {
  399. return '+';
  400. }
  401. if (number === 63) {
  402. return '/';
  403. }
  404. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  405. }
  406. /**
  407. * A Parse.File is a local representation of a file that is saved to the Parse
  408. * cloud.
  409. *
  410. * @alias Parse.File
  411. */
  412. var ParseFile = /*#__PURE__*/function () {
  413. /**
  414. * @param name {String} The file's name. This will be prefixed by a unique
  415. * value once the file has finished saving. The file name must begin with
  416. * an alphanumeric character, and consist of alphanumeric characters,
  417. * periods, spaces, underscores, or dashes.
  418. * @param data {Array} The data for the file, as either:
  419. * 1. an Array of byte value Numbers, or
  420. * 2. an Object like { base64: "..." } with a base64-encoded String.
  421. * 3. an Object like { uri: "..." } with a uri String.
  422. * 4. a File object selected with a file upload control. (3) only works
  423. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  424. * For example:
  425. * <pre>
  426. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  427. * if (fileUploadControl.files.length > 0) {
  428. * var file = fileUploadControl.files[0];
  429. * var name = "photo.jpg";
  430. * var parseFile = new Parse.File(name, file);
  431. * parseFile.save().then(function() {
  432. * // The file has been saved to Parse.
  433. * }, function(error) {
  434. * // The file either could not be read, or could not be saved to Parse.
  435. * });
  436. * }</pre>
  437. * @param type {String} Optional Content-Type header to use for the file. If
  438. * this is omitted, the content type will be inferred from the name's
  439. * extension.
  440. * @param metadata {Object} Optional key value pairs to be stored with file object
  441. * @param tags {Object} Optional key value pairs to be stored with file object
  442. */
  443. function ParseFile(name
  444. /*: string*/
  445. , data
  446. /*:: ?: FileData*/
  447. , type
  448. /*:: ?: string*/
  449. , metadata
  450. /*:: ?: Object*/
  451. , tags
  452. /*:: ?: Object*/
  453. ) {
  454. (0, _classCallCheck2.default)(this, ParseFile);
  455. (0, _defineProperty2.default)(this, "_name", void 0);
  456. (0, _defineProperty2.default)(this, "_url", void 0);
  457. (0, _defineProperty2.default)(this, "_source", void 0);
  458. (0, _defineProperty2.default)(this, "_previousSave", void 0);
  459. (0, _defineProperty2.default)(this, "_data", void 0);
  460. (0, _defineProperty2.default)(this, "_requestTask", void 0);
  461. (0, _defineProperty2.default)(this, "_metadata", void 0);
  462. (0, _defineProperty2.default)(this, "_tags", void 0);
  463. var specifiedType = type || '';
  464. this._name = name;
  465. this._metadata = metadata || {};
  466. this._tags = tags || {};
  467. if (data !== undefined) {
  468. if ((0, _isArray.default)(data)) {
  469. this._data = ParseFile.encodeBase64(data);
  470. this._source = {
  471. format: 'base64',
  472. base64: this._data,
  473. type: specifiedType
  474. };
  475. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  476. this._source = {
  477. format: 'file',
  478. file: data,
  479. type: specifiedType
  480. };
  481. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  482. this._source = {
  483. format: 'uri',
  484. uri: data.uri,
  485. type: specifiedType
  486. };
  487. } else if (data && typeof data.base64 === 'string') {
  488. var _context, _context2, _context3;
  489. var base64 = (0, _slice.default)(_context = data.base64.split(',')).call(_context, -1)[0];
  490. var dataType = specifiedType || (0, _slice.default)(_context2 = (0, _slice.default)(_context3 = data.base64.split(';')).call(_context3, 0, 1)[0].split(':')).call(_context2, 1, 2)[0] || 'text/plain';
  491. this._data = base64;
  492. this._source = {
  493. format: 'base64',
  494. base64: base64,
  495. type: dataType
  496. };
  497. } else {
  498. throw new TypeError('Cannot create a Parse.File with that data.');
  499. }
  500. }
  501. }
  502. /**
  503. * Return the data for the file, downloading it if not already present.
  504. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  505. * Data is cleared if saved with File object selected with a file upload control
  506. *
  507. * @returns {Promise} Promise that is resolve with base64 data
  508. */
  509. (0, _createClass2.default)(ParseFile, [{
  510. key: "getData",
  511. value: function () {
  512. var _getData = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
  513. var _this = this;
  514. var options, controller, result;
  515. return _regeneratorRuntime().wrap(function (_context4) {
  516. while (1) {
  517. switch (_context4.prev = _context4.next) {
  518. case 0:
  519. if (!this._data) {
  520. _context4.next = 2;
  521. break;
  522. }
  523. return _context4.abrupt("return", this._data);
  524. case 2:
  525. if (this._url) {
  526. _context4.next = 4;
  527. break;
  528. }
  529. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  530. case 4:
  531. options = {
  532. requestTask: function (task) {
  533. return _this._requestTask = task;
  534. }
  535. };
  536. controller = _CoreManager.default.getFileController();
  537. _context4.next = 8;
  538. return controller.download(this._url, options);
  539. case 8:
  540. result = _context4.sent;
  541. this._data = result.base64;
  542. return _context4.abrupt("return", this._data);
  543. case 11:
  544. case "end":
  545. return _context4.stop();
  546. }
  547. }
  548. }, _callee, this);
  549. }));
  550. function getData() {
  551. return _getData.apply(this, arguments);
  552. }
  553. return getData;
  554. }()
  555. /**
  556. * Gets the name of the file. Before save is called, this is the filename
  557. * given by the user. After save is called, that name gets prefixed with a
  558. * unique identifier.
  559. *
  560. * @returns {string}
  561. */
  562. }, {
  563. key: "name",
  564. value: function ()
  565. /*: string*/
  566. {
  567. return this._name;
  568. }
  569. /**
  570. * Gets the url of the file. It is only available after you save the file or
  571. * after you get the file from a Parse.Object.
  572. *
  573. * @param {object} options An object to specify url options
  574. * @returns {string}
  575. */
  576. }, {
  577. key: "url",
  578. value: function (options
  579. /*:: ?: { forceSecure?: boolean }*/
  580. )
  581. /*: ?string*/
  582. {
  583. options = options || {};
  584. if (!this._url) {
  585. return;
  586. }
  587. if (options.forceSecure) {
  588. return this._url.replace(/^http:\/\//i, 'https://');
  589. } else {
  590. return this._url;
  591. }
  592. }
  593. /**
  594. * Gets the metadata of the file.
  595. *
  596. * @returns {object}
  597. */
  598. }, {
  599. key: "metadata",
  600. value: function ()
  601. /*: Object*/
  602. {
  603. return this._metadata;
  604. }
  605. /**
  606. * Gets the tags of the file.
  607. *
  608. * @returns {object}
  609. */
  610. }, {
  611. key: "tags",
  612. value: function ()
  613. /*: Object*/
  614. {
  615. return this._tags;
  616. }
  617. /**
  618. * Saves the file to the Parse cloud.
  619. *
  620. * @param {object} options
  621. * * Valid options are:<ul>
  622. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  623. * be used for this request.
  624. * <li>sessionToken: A valid session token, used for making a request on
  625. * behalf of a specific user.
  626. * <li>progress: In Browser only, callback for upload progress. For example:
  627. * <pre>
  628. * let parseFile = new Parse.File(name, file);
  629. * parseFile.save({
  630. * progress: (progressValue, loaded, total, { type }) => {
  631. * if (type === "upload" && progressValue !== null) {
  632. * // Update the UI using progressValue
  633. * }
  634. * }
  635. * });
  636. * </pre>
  637. * </ul>
  638. * @returns {Promise} Promise that is resolved when the save finishes.
  639. */
  640. }, {
  641. key: "save",
  642. value: function (options
  643. /*:: ?: FullOptions*/
  644. ) {
  645. var _this2 = this;
  646. options = options || {};
  647. options.requestTask = function (task) {
  648. return _this2._requestTask = task;
  649. };
  650. options.metadata = this._metadata;
  651. options.tags = this._tags;
  652. var controller = _CoreManager.default.getFileController();
  653. if (!this._previousSave) {
  654. if (this._source.format === 'file') {
  655. this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
  656. _this2._name = res.name;
  657. _this2._url = res.url;
  658. _this2._data = null;
  659. _this2._requestTask = null;
  660. return _this2;
  661. });
  662. } else if (this._source.format === 'uri') {
  663. this._previousSave = controller.download(this._source.uri, options).then(function (result) {
  664. if (!(result && result.base64)) {
  665. return {};
  666. }
  667. var newSource = {
  668. format: 'base64',
  669. base64: result.base64,
  670. type: result.contentType
  671. };
  672. _this2._data = result.base64;
  673. _this2._requestTask = null;
  674. return controller.saveBase64(_this2._name, newSource, options);
  675. }).then(function (res) {
  676. _this2._name = res.name;
  677. _this2._url = res.url;
  678. _this2._requestTask = null;
  679. return _this2;
  680. });
  681. } else {
  682. this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
  683. _this2._name = res.name;
  684. _this2._url = res.url;
  685. _this2._requestTask = null;
  686. return _this2;
  687. });
  688. }
  689. }
  690. if (this._previousSave) {
  691. return this._previousSave;
  692. }
  693. }
  694. /**
  695. * Aborts the request if it has already been sent.
  696. */
  697. }, {
  698. key: "cancel",
  699. value: function () {
  700. if (this._requestTask && typeof this._requestTask.abort === 'function') {
  701. this._requestTask.abort();
  702. }
  703. this._requestTask = null;
  704. }
  705. /**
  706. * Deletes the file from the Parse cloud.
  707. * In Cloud Code and Node only with Master Key.
  708. *
  709. * @param {object} options
  710. * * Valid options are:<ul>
  711. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  712. * be used for this request.
  713. * <pre>
  714. * @returns {Promise} Promise that is resolved when the delete finishes.
  715. */
  716. }, {
  717. key: "destroy",
  718. value: function () {
  719. var _this3 = this;
  720. var options
  721. /*:: ?: FullOptions*/
  722. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  723. if (!this._name) {
  724. throw new ParseError(ParseError.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
  725. }
  726. var destroyOptions = {
  727. useMasterKey: true
  728. };
  729. if (options.hasOwnProperty('useMasterKey')) {
  730. destroyOptions.useMasterKey = options.useMasterKey;
  731. }
  732. var controller = _CoreManager.default.getFileController();
  733. return controller.deleteFile(this._name, destroyOptions).then(function () {
  734. _this3._data = null;
  735. _this3._requestTask = null;
  736. return _this3;
  737. });
  738. }
  739. }, {
  740. key: "toJSON",
  741. value: function ()
  742. /*: { name: ?string, url: ?string }*/
  743. {
  744. return {
  745. __type: 'File',
  746. name: this._name,
  747. url: this._url
  748. };
  749. }
  750. }, {
  751. key: "equals",
  752. value: function (other
  753. /*: mixed*/
  754. )
  755. /*: boolean*/
  756. {
  757. if (this === other) {
  758. return true;
  759. } // Unsaved Files are never equal, since they will be saved to different URLs
  760. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  761. }
  762. /**
  763. * Sets metadata to be saved with file object. Overwrites existing metadata
  764. *
  765. * @param {object} metadata Key value pairs to be stored with file object
  766. */
  767. }, {
  768. key: "setMetadata",
  769. value: function (metadata
  770. /*: any*/
  771. ) {
  772. var _this4 = this;
  773. if (metadata && (0, _typeof2.default)(metadata) === 'object') {
  774. var _context5;
  775. (0, _forEach.default)(_context5 = (0, _keys.default)(metadata)).call(_context5, function (key) {
  776. _this4.addMetadata(key, metadata[key]);
  777. });
  778. }
  779. }
  780. /**
  781. * Sets metadata to be saved with file object. Adds to existing metadata.
  782. *
  783. * @param {string} key key to store the metadata
  784. * @param {*} value metadata
  785. */
  786. }, {
  787. key: "addMetadata",
  788. value: function (key
  789. /*: string*/
  790. , value
  791. /*: any*/
  792. ) {
  793. if (typeof key === 'string') {
  794. this._metadata[key] = value;
  795. }
  796. }
  797. /**
  798. * Sets tags to be saved with file object. Overwrites existing tags
  799. *
  800. * @param {object} tags Key value pairs to be stored with file object
  801. */
  802. }, {
  803. key: "setTags",
  804. value: function (tags
  805. /*: any*/
  806. ) {
  807. var _this5 = this;
  808. if (tags && (0, _typeof2.default)(tags) === 'object') {
  809. var _context6;
  810. (0, _forEach.default)(_context6 = (0, _keys.default)(tags)).call(_context6, function (key) {
  811. _this5.addTag(key, tags[key]);
  812. });
  813. }
  814. }
  815. /**
  816. * Sets tags to be saved with file object. Adds to existing tags.
  817. *
  818. * @param {string} key key to store tags
  819. * @param {*} value tag
  820. */
  821. }, {
  822. key: "addTag",
  823. value: function (key
  824. /*: string*/
  825. , value
  826. /*: string*/
  827. ) {
  828. if (typeof key === 'string') {
  829. this._tags[key] = value;
  830. }
  831. }
  832. }], [{
  833. key: "fromJSON",
  834. value: function (obj)
  835. /*: ParseFile*/
  836. {
  837. if (obj.__type !== 'File') {
  838. throw new TypeError('JSON object does not represent a ParseFile');
  839. }
  840. var file = new ParseFile(obj.name);
  841. file._url = obj.url;
  842. return file;
  843. }
  844. }, {
  845. key: "encodeBase64",
  846. value: function (bytes
  847. /*: Array<number>*/
  848. )
  849. /*: string*/
  850. {
  851. var chunks = [];
  852. chunks.length = Math.ceil(bytes.length / 3);
  853. for (var i = 0; i < chunks.length; i++) {
  854. var b1 = bytes[i * 3];
  855. var b2 = bytes[i * 3 + 1] || 0;
  856. var b3 = bytes[i * 3 + 2] || 0;
  857. var has2 = i * 3 + 1 < bytes.length;
  858. var has3 = i * 3 + 2 < bytes.length;
  859. chunks[i] = [b64Digit(b1 >> 2 & 0x3f), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0f), has2 ? b64Digit(b2 << 2 & 0x3c | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3f) : '='].join('');
  860. }
  861. return chunks.join('');
  862. }
  863. }]);
  864. return ParseFile;
  865. }();
  866. var DefaultController = {
  867. saveFile: function () {
  868. var _saveFile = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(name
  869. /*: string*/
  870. , source
  871. /*: FileSource*/
  872. , options
  873. /*:: ?: FullOptions*/
  874. ) {
  875. var base64Data, _base64Data$split, _base64Data$split2, first, second, data, newSource;
  876. return _regeneratorRuntime().wrap(function _callee2$(_context7) {
  877. while (1) {
  878. switch (_context7.prev = _context7.next) {
  879. case 0:
  880. if (!(source.format !== 'file')) {
  881. _context7.next = 2;
  882. break;
  883. }
  884. throw new Error('saveFile can only be used with File-type sources.');
  885. case 2:
  886. _context7.next = 4;
  887. return new _promise.default(function (res, rej) {
  888. // eslint-disable-next-line no-undef
  889. var reader = new FileReader();
  890. reader.onload = function () {
  891. return res(reader.result);
  892. };
  893. reader.onerror = function (error) {
  894. return rej(error);
  895. };
  896. reader.readAsDataURL(source.file);
  897. });
  898. case 4:
  899. base64Data = _context7.sent; // we only want the data after the comma
  900. // For example: "data:application/pdf;base64,JVBERi0xLjQKJ..." we would only want "JVBERi0xLjQKJ..."
  901. _base64Data$split = base64Data.split(','), _base64Data$split2 = (0, _slicedToArray2.default)(_base64Data$split, 2), first = _base64Data$split2[0], second = _base64Data$split2[1]; // in the event there is no 'data:application/pdf;base64,' at the beginning of the base64 string
  902. // use the entire string instead
  903. data = second ? second : first;
  904. newSource = {
  905. format: 'base64',
  906. base64: data,
  907. type: source.type || (source.file ? source.file.type : null)
  908. };
  909. _context7.next = 10;
  910. return DefaultController.saveBase64(name, newSource, options);
  911. case 10:
  912. return _context7.abrupt("return", _context7.sent);
  913. case 11:
  914. case "end":
  915. return _context7.stop();
  916. }
  917. }
  918. }, _callee2);
  919. }));
  920. function saveFile(_x, _x2, _x3) {
  921. return _saveFile.apply(this, arguments);
  922. }
  923. return saveFile;
  924. }(),
  925. saveBase64: function saveBase64(name
  926. /*: string*/
  927. , source
  928. /*: FileSource*/
  929. , options
  930. /*:: ?: FullOptions*/
  931. ) {
  932. if (source.format !== 'base64') {
  933. throw new Error('saveBase64 can only be used with Base64-type sources.');
  934. }
  935. var data
  936. /*: { base64: any, _ContentType?: any, fileData: Object }*/
  937. = {
  938. base64: source.base64,
  939. fileData: {
  940. metadata: _objectSpread({}, options.metadata),
  941. tags: _objectSpread({}, options.tags)
  942. }
  943. };
  944. delete options.metadata;
  945. delete options.tags;
  946. if (source.type) {
  947. data._ContentType = source.type;
  948. }
  949. var path = 'files/' + name;
  950. return _CoreManager.default.getRESTController().request('POST', path, data, options);
  951. },
  952. download: function download(uri, options) {
  953. if (XHR) {
  954. return this.downloadAjax(uri, options);
  955. } else {
  956. return _promise.default.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  957. }
  958. },
  959. downloadAjax: function downloadAjax(uri, options) {
  960. return new _promise.default(function (resolve, reject) {
  961. var xhr = new XHR();
  962. xhr.open('GET', uri, true);
  963. xhr.responseType = 'arraybuffer';
  964. xhr.onerror = function (e) {
  965. reject(e);
  966. };
  967. xhr.onreadystatechange = function () {
  968. if (xhr.readyState !== xhr.DONE) {
  969. return;
  970. }
  971. if (!this.response) {
  972. return resolve({});
  973. }
  974. var bytes = new Uint8Array(this.response);
  975. resolve({
  976. base64: ParseFile.encodeBase64(bytes),
  977. contentType: xhr.getResponseHeader('content-type')
  978. });
  979. };
  980. options.requestTask(xhr);
  981. xhr.send();
  982. });
  983. },
  984. deleteFile: function deleteFile(name
  985. /*: string*/
  986. , options
  987. /*:: ?: FullOptions*/
  988. ) {
  989. var headers = {
  990. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID')
  991. };
  992. if (options.useMasterKey) {
  993. headers['X-Parse-Master-Key'] = _CoreManager.default.get('MASTER_KEY');
  994. }
  995. var url = _CoreManager.default.get('SERVER_URL');
  996. if (url[url.length - 1] !== '/') {
  997. url += '/';
  998. }
  999. url += 'files/' + name;
  1000. return _CoreManager.default.getRESTController().ajax('DELETE', url, '', headers).catch(function (response) {
  1001. // TODO: return JSON object in server
  1002. if (!response || response === 'SyntaxError: Unexpected end of JSON input') {
  1003. return _promise.default.resolve();
  1004. } else {
  1005. return _CoreManager.default.getRESTController().handleError(response);
  1006. }
  1007. });
  1008. },
  1009. _setXHR: function _setXHR(xhr
  1010. /*: any*/
  1011. ) {
  1012. XHR = xhr;
  1013. },
  1014. _getXHR: function _getXHR() {
  1015. return XHR;
  1016. }
  1017. };
  1018. _CoreManager.default.setFileController(DefaultController);
  1019. var _default = ParseFile;
  1020. exports.default = _default;
  1021. exports.b64Digit = b64Digit;