UI for Zipcoin Blue

promise.ts 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. interface Promise<T> {
  9. finally<U>(onFinally?: () => U | PromiseLike<U>): Promise<T>;
  10. }
  11. Zone.__load_patch('ZoneAwarePromise', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
  12. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  13. const ObjectDefineProperty = Object.defineProperty;
  14. function readableObjectToString(obj: any) {
  15. if (obj && obj.toString === Object.prototype.toString) {
  16. const className = obj.constructor && obj.constructor.name;
  17. return (className ? className : '') + ': ' + JSON.stringify(obj);
  18. }
  19. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  20. }
  21. const __symbol__ = api.symbol;
  22. const _uncaughtPromiseErrors: UncaughtPromiseError[] = [];
  23. const symbolPromise = __symbol__('Promise');
  24. const symbolThen = __symbol__('then');
  25. const creationTrace = '__creationTrace__';
  26. api.onUnhandledError = (e: any) => {
  27. if (api.showUncaughtError()) {
  28. const rejection = e && e.rejection;
  29. if (rejection) {
  30. console.error(
  31. 'Unhandled Promise rejection:',
  32. rejection instanceof Error ? rejection.message : rejection, '; Zone:',
  33. (<Zone>e.zone).name, '; Task:', e.task && (<Task>e.task).source, '; Value:', rejection,
  34. rejection instanceof Error ? rejection.stack : undefined);
  35. } else {
  36. console.error(e);
  37. }
  38. }
  39. };
  40. api.microtaskDrainDone = () => {
  41. while (_uncaughtPromiseErrors.length) {
  42. while (_uncaughtPromiseErrors.length) {
  43. const uncaughtPromiseError: UncaughtPromiseError = _uncaughtPromiseErrors.shift();
  44. try {
  45. uncaughtPromiseError.zone.runGuarded(() => {
  46. throw uncaughtPromiseError;
  47. });
  48. } catch (error) {
  49. handleUnhandledRejection(error);
  50. }
  51. }
  52. }
  53. };
  54. const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  55. function handleUnhandledRejection(e: any) {
  56. api.onUnhandledError(e);
  57. try {
  58. const handler = (Zone as any)[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  59. if (handler && typeof handler === 'function') {
  60. handler.call(this, e);
  61. }
  62. } catch (err) {
  63. }
  64. }
  65. function isThenable(value: any): boolean {
  66. return value && value.then;
  67. }
  68. function forwardResolution(value: any): any {
  69. return value;
  70. }
  71. function forwardRejection(rejection: any): any {
  72. return ZoneAwarePromise.reject(rejection);
  73. }
  74. const symbolState: string = __symbol__('state');
  75. const symbolValue: string = __symbol__('value');
  76. const symbolFinally: string = __symbol__('finally');
  77. const symbolParentPromiseValue: string = __symbol__('parentPromiseValue');
  78. const symbolParentPromiseState: string = __symbol__('parentPromiseState');
  79. const source: string = 'Promise.then';
  80. const UNRESOLVED: null = null;
  81. const RESOLVED = true;
  82. const REJECTED = false;
  83. const REJECTED_NO_CATCH = 0;
  84. function makeResolver(promise: ZoneAwarePromise<any>, state: boolean): (value: any) => void {
  85. return (v) => {
  86. try {
  87. resolvePromise(promise, state, v);
  88. } catch (err) {
  89. resolvePromise(promise, false, err);
  90. }
  91. // Do not return value or you will break the Promise spec.
  92. };
  93. }
  94. const once = function() {
  95. let wasCalled = false;
  96. return function wrapper(wrappedFunction: Function) {
  97. return function() {
  98. if (wasCalled) {
  99. return;
  100. }
  101. wasCalled = true;
  102. wrappedFunction.apply(null, arguments);
  103. };
  104. };
  105. };
  106. const TYPE_ERROR = 'Promise resolved with itself';
  107. const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  108. // Promise Resolution
  109. function resolvePromise(
  110. promise: ZoneAwarePromise<any>, state: boolean, value: any): ZoneAwarePromise<any> {
  111. const onceWrapper = once();
  112. if (promise === value) {
  113. throw new TypeError(TYPE_ERROR);
  114. }
  115. if ((promise as any)[symbolState] === UNRESOLVED) {
  116. // should only get value.then once based on promise spec.
  117. let then: any = null;
  118. try {
  119. if (typeof value === 'object' || typeof value === 'function') {
  120. then = value && value.then;
  121. }
  122. } catch (err) {
  123. onceWrapper(() => {
  124. resolvePromise(promise, false, err);
  125. })();
  126. return promise;
  127. }
  128. // if (value instanceof ZoneAwarePromise) {
  129. if (state !== REJECTED && value instanceof ZoneAwarePromise &&
  130. value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
  131. (value as any)[symbolState] !== UNRESOLVED) {
  132. clearRejectedNoCatch(<Promise<any>>value);
  133. resolvePromise(promise, (value as any)[symbolState], (value as any)[symbolValue]);
  134. } else if (state !== REJECTED && typeof then === 'function') {
  135. try {
  136. then.call(
  137. value, onceWrapper(makeResolver(promise, state)),
  138. onceWrapper(makeResolver(promise, false)));
  139. } catch (err) {
  140. onceWrapper(() => {
  141. resolvePromise(promise, false, err);
  142. })();
  143. }
  144. } else {
  145. (promise as any)[symbolState] = state;
  146. const queue = (promise as any)[symbolValue];
  147. (promise as any)[symbolValue] = value;
  148. if ((promise as any)[symbolFinally] === symbolFinally) {
  149. // the promise is generated by Promise.prototype.finally
  150. if (state === RESOLVED) {
  151. // the state is resolved, should ignore the value
  152. // and use parent promise value
  153. (promise as any)[symbolState] = (promise as any)[symbolParentPromiseState];
  154. (promise as any)[symbolValue] = (promise as any)[symbolParentPromiseValue];
  155. }
  156. }
  157. // record task information in value when error occurs, so we can
  158. // do some additional work such as render longStackTrace
  159. if (state === REJECTED && value instanceof Error) {
  160. // check if longStackTraceZone is here
  161. const trace = Zone.currentTask && Zone.currentTask.data &&
  162. (Zone.currentTask.data as any)[creationTrace];
  163. if (trace) {
  164. // only keep the long stack trace into error when in longStackTraceZone
  165. ObjectDefineProperty(
  166. value, CURRENT_TASK_TRACE_SYMBOL,
  167. {configurable: true, enumerable: false, writable: true, value: trace});
  168. }
  169. }
  170. for (let i = 0; i < queue.length;) {
  171. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  172. }
  173. if (queue.length == 0 && state == REJECTED) {
  174. (promise as any)[symbolState] = REJECTED_NO_CATCH;
  175. try {
  176. // try to print more readable error log
  177. throw new Error(
  178. 'Uncaught (in promise): ' + readableObjectToString(value) +
  179. (value && value.stack ? '\n' + value.stack : ''));
  180. } catch (err) {
  181. const error: UncaughtPromiseError = err;
  182. error.rejection = value;
  183. error.promise = promise;
  184. error.zone = Zone.current;
  185. error.task = Zone.currentTask;
  186. _uncaughtPromiseErrors.push(error);
  187. api.scheduleMicroTask(); // to make sure that it is running
  188. }
  189. }
  190. }
  191. }
  192. // Resolving an already resolved promise is a noop.
  193. return promise;
  194. }
  195. const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  196. function clearRejectedNoCatch(promise: ZoneAwarePromise<any>): void {
  197. if ((promise as any)[symbolState] === REJECTED_NO_CATCH) {
  198. // if the promise is rejected no catch status
  199. // and queue.length > 0, means there is a error handler
  200. // here to handle the rejected promise, we should trigger
  201. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  202. // eventHandler
  203. try {
  204. const handler = (Zone as any)[REJECTION_HANDLED_HANDLER];
  205. if (handler && typeof handler === 'function') {
  206. handler.call(this, {rejection: (promise as any)[symbolValue], promise: promise});
  207. }
  208. } catch (err) {
  209. }
  210. (promise as any)[symbolState] = REJECTED;
  211. for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
  212. if (promise === _uncaughtPromiseErrors[i].promise) {
  213. _uncaughtPromiseErrors.splice(i, 1);
  214. }
  215. }
  216. }
  217. }
  218. function scheduleResolveOrReject<R, U1, U2>(
  219. promise: ZoneAwarePromise<any>, zone: AmbientZone, chainPromise: ZoneAwarePromise<any>,
  220. onFulfilled?: (value: R) => U1, onRejected?: (error: any) => U2): void {
  221. clearRejectedNoCatch(promise);
  222. const promiseState = (promise as any)[symbolState];
  223. const delegate = promiseState ?
  224. (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
  225. (typeof onRejected === 'function') ? onRejected : forwardRejection;
  226. zone.scheduleMicroTask(source, () => {
  227. try {
  228. const parentPromiseValue = (promise as any)[symbolValue];
  229. const isFinallyPromise = chainPromise && symbolFinally === (chainPromise as any)[symbolFinally];
  230. if (isFinallyPromise) {
  231. // if the promise is generated from finally call, keep parent promise's state and value
  232. (chainPromise as any)[symbolParentPromiseValue] = parentPromiseValue;
  233. (chainPromise as any)[symbolParentPromiseState] = promiseState;
  234. }
  235. // should not pass value to finally callback
  236. const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
  237. resolvePromise(chainPromise, true, value);
  238. } catch (error) {
  239. // if error occurs, should always return this error
  240. resolvePromise(chainPromise, false, error);
  241. }
  242. }, chainPromise as TaskData);
  243. }
  244. const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  245. class ZoneAwarePromise<R> implements Promise<R> {
  246. static toString() {
  247. return ZONE_AWARE_PROMISE_TO_STRING;
  248. }
  249. static resolve<R>(value: R): Promise<R> {
  250. return resolvePromise(<ZoneAwarePromise<R>>new this(null), RESOLVED, value);
  251. }
  252. static reject<U>(error: U): Promise<U> {
  253. return resolvePromise(<ZoneAwarePromise<U>>new this(null), REJECTED, error);
  254. }
  255. static race<R>(values: PromiseLike<any>[]): Promise<R> {
  256. let resolve: (v: any) => void;
  257. let reject: (v: any) => void;
  258. let promise: any = new this((res, rej) => {
  259. resolve = res;
  260. reject = rej;
  261. });
  262. function onResolve(value: any) {
  263. promise && (promise = null || resolve(value));
  264. }
  265. function onReject(error: any) {
  266. promise && (promise = null || reject(error));
  267. }
  268. for (let value of values) {
  269. if (!isThenable(value)) {
  270. value = this.resolve(value);
  271. }
  272. value.then(onResolve, onReject);
  273. }
  274. return promise;
  275. }
  276. static all<R>(values: any): Promise<R> {
  277. let resolve: (v: any) => void;
  278. let reject: (v: any) => void;
  279. let promise = new this<R>((res, rej) => {
  280. resolve = res;
  281. reject = rej;
  282. });
  283. let count = 0;
  284. const resolvedValues: any[] = [];
  285. for (let value of values) {
  286. if (!isThenable(value)) {
  287. value = this.resolve(value);
  288. }
  289. value.then(
  290. ((index) => (value: any) => {
  291. resolvedValues[index] = value;
  292. count--;
  293. if (!count) {
  294. resolve(resolvedValues);
  295. }
  296. })(count),
  297. reject);
  298. count++;
  299. }
  300. if (!count) resolve(resolvedValues);
  301. return promise;
  302. }
  303. constructor(
  304. executor:
  305. (resolve: (value?: R|PromiseLike<R>) => void, reject: (error?: any) => void) => void) {
  306. const promise: ZoneAwarePromise<R> = this;
  307. if (!(promise instanceof ZoneAwarePromise)) {
  308. throw new Error('Must be an instanceof Promise.');
  309. }
  310. (promise as any)[symbolState] = UNRESOLVED;
  311. (promise as any)[symbolValue] = []; // queue;
  312. try {
  313. executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
  314. } catch (error) {
  315. resolvePromise(promise, false, error);
  316. }
  317. }
  318. then<TResult1 = R, TResult2 = never>(
  319. onFulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>)|undefined|null,
  320. onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>)|undefined|
  321. null): Promise<TResult1|TResult2> {
  322. const chainPromise: Promise<TResult1|TResult2> =
  323. new (this.constructor as typeof ZoneAwarePromise)(null);
  324. const zone = Zone.current;
  325. if ((this as any)[symbolState] == UNRESOLVED) {
  326. (<any[]>(this as any)[symbolValue]).push(zone, chainPromise, onFulfilled, onRejected);
  327. } else {
  328. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  329. }
  330. return chainPromise;
  331. }
  332. catch<TResult = never>(onRejected?: ((reason: any) => TResult | PromiseLike<TResult>)|undefined|
  333. null): Promise<R|TResult> {
  334. return this.then(null, onRejected);
  335. }
  336. finally<U>(onFinally?: () => U | PromiseLike<U>): Promise<R> {
  337. const chainPromise: Promise<R|never> =
  338. new (this.constructor as typeof ZoneAwarePromise)(null);
  339. (chainPromise as any)[symbolFinally] = symbolFinally;
  340. const zone = Zone.current;
  341. if ((this as any)[symbolState] == UNRESOLVED) {
  342. (<any[]>(this as any)[symbolValue]).push(zone, chainPromise, onFinally, onFinally);
  343. } else {
  344. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  345. }
  346. return chainPromise;
  347. }
  348. }
  349. // Protect against aggressive optimizers dropping seemingly unused properties.
  350. // E.g. Closure Compiler in advanced mode.
  351. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  352. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  353. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  354. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  355. const NativePromise = global[symbolPromise] = global['Promise'];
  356. const ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
  357. let desc = ObjectGetOwnPropertyDescriptor(global, 'Promise');
  358. if (!desc || desc.configurable) {
  359. desc && delete desc.writable;
  360. desc && delete desc.value;
  361. if (!desc) {
  362. desc = {configurable: true, enumerable: true};
  363. }
  364. desc.get = function() {
  365. // if we already set ZoneAwarePromise, use patched one
  366. // otherwise return native one.
  367. return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
  368. };
  369. desc.set = function(NewNativePromise) {
  370. if (NewNativePromise === ZoneAwarePromise) {
  371. // if the NewNativePromise is ZoneAwarePromise
  372. // save to global
  373. global[ZONE_AWARE_PROMISE] = NewNativePromise;
  374. } else {
  375. // if the NewNativePromise is not ZoneAwarePromise
  376. // for example: after load zone.js, some library just
  377. // set es6-promise to global, if we set it to global
  378. // directly, assertZonePatched will fail and angular
  379. // will not loaded, so we just set the NewNativePromise
  380. // to global[symbolPromise], so the result is just like
  381. // we load ES6 Promise before zone.js
  382. global[symbolPromise] = NewNativePromise;
  383. if (!NewNativePromise.prototype[symbolThen]) {
  384. patchThen(NewNativePromise);
  385. }
  386. api.setNativePromise(NewNativePromise);
  387. }
  388. };
  389. ObjectDefineProperty(global, 'Promise', desc);
  390. }
  391. global['Promise'] = ZoneAwarePromise;
  392. const symbolThenPatched = __symbol__('thenPatched');
  393. function patchThen(Ctor: Function) {
  394. const proto = Ctor.prototype;
  395. const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  396. if (prop && (prop.writable === false || !prop.configurable)) {
  397. // check Ctor.prototype.then propertyDescriptor is writable or not
  398. // in meteor env, writable is false, we should ignore such case
  399. return;
  400. }
  401. const originalThen = proto.then;
  402. // Keep a reference to the original method.
  403. proto[symbolThen] = originalThen;
  404. Ctor.prototype.then = function(onResolve: any, onReject: any) {
  405. const wrapped = new ZoneAwarePromise((resolve, reject) => {
  406. originalThen.call(this, resolve, reject);
  407. });
  408. return wrapped.then(onResolve, onReject);
  409. };
  410. (Ctor as any)[symbolThenPatched] = true;
  411. }
  412. function zoneify(fn: Function) {
  413. return function() {
  414. let resultPromise = fn.apply(this, arguments);
  415. if (resultPromise instanceof ZoneAwarePromise) {
  416. return resultPromise;
  417. }
  418. let ctor = resultPromise.constructor;
  419. if (!ctor[symbolThenPatched]) {
  420. patchThen(ctor);
  421. }
  422. return resultPromise;
  423. };
  424. }
  425. if (NativePromise) {
  426. patchThen(NativePromise);
  427. let fetch = global['fetch'];
  428. if (typeof fetch == 'function') {
  429. global['fetch'] = zoneify(fetch);
  430. }
  431. }
  432. // This is not part of public API, but it is useful for tests, so we expose it.
  433. (Promise as any)[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  434. return ZoneAwarePromise;
  435. });