a zip code crypto-currency system good for red ONLY

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  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. /**
  9. * Suppress closure compiler errors about unknown 'global' variable
  10. * @fileoverview
  11. * @suppress {undefinedVars}
  12. */
  13. /**
  14. * Zone is a mechanism for intercepting and keeping track of asynchronous work.
  15. *
  16. * A Zone is a global object which is configured with rules about how to intercept and keep track
  17. * of the asynchronous callbacks. Zone has these responsibilities:
  18. *
  19. * 1. Intercept asynchronous task scheduling
  20. * 2. Wrap callbacks for error-handling and zone tracking across async operations.
  21. * 3. Provide a way to attach data to zones
  22. * 4. Provide a context specific last frame error handling
  23. * 5. (Intercept blocking methods)
  24. *
  25. * A zone by itself does not do anything, instead it relies on some other code to route existing
  26. * platform API through it. (The zone library ships with code which monkey patches all of the
  27. * browsers's asynchronous API and redirects them through the zone for interception.)
  28. *
  29. * In its simplest form a zone allows one to intercept the scheduling and calling of asynchronous
  30. * operations, and execute additional code before as well as after the asynchronous task. The rules
  31. * of interception are configured using [ZoneConfig]. There can be many different zone instances in
  32. * a system, but only one zone is active at any given time which can be retrieved using
  33. * [Zone#current].
  34. *
  35. *
  36. *
  37. * ## Callback Wrapping
  38. *
  39. * An important aspect of the zones is that they should persist across asynchronous operations. To
  40. * achieve this, when a future work is scheduled through async API, it is necessary to capture, and
  41. * subsequently restore the current zone. For example if a code is running in zone `b` and it
  42. * invokes `setTimeout` to scheduleTask work later, the `setTimeout` method needs to 1) capture the
  43. * current zone and 2) wrap the `wrapCallback` in code which will restore the current zone `b` once
  44. * the wrapCallback executes. In this way the rules which govern the current code are preserved in
  45. * all future asynchronous tasks. There could be a different zone `c` which has different rules and
  46. * is associated with different asynchronous tasks. As these tasks are processed, each asynchronous
  47. * wrapCallback correctly restores the correct zone, as well as preserves the zone for future
  48. * asynchronous callbacks.
  49. *
  50. * Example: Suppose a browser page consist of application code as well as third-party
  51. * advertisement code. (These two code bases are independent, developed by different mutually
  52. * unaware developers.) The application code may be interested in doing global error handling and
  53. * so it configures the `app` zone to send all of the errors to the server for analysis, and then
  54. * executes the application in the `app` zone. The advertising code is interested in the same
  55. * error processing but it needs to send the errors to a different third-party. So it creates the
  56. * `ads` zone with a different error handler. Now both advertising as well as application code
  57. * create many asynchronous operations, but the [Zone] will ensure that all of the asynchronous
  58. * operations created from the application code will execute in `app` zone with its error
  59. * handler and all of the advertisement code will execute in the `ads` zone with its error handler.
  60. * This will not only work for the async operations created directly, but also for all subsequent
  61. * asynchronous operations.
  62. *
  63. * If you think of chain of asynchronous operations as a thread of execution (bit of a stretch)
  64. * then [Zone#current] will act as a thread local variable.
  65. *
  66. *
  67. *
  68. * ## Asynchronous operation scheduling
  69. *
  70. * In addition to wrapping the callbacks to restore the zone, all operations which cause a
  71. * scheduling of work for later are routed through the current zone which is allowed to intercept
  72. * them by adding work before or after the wrapCallback as well as using different means of
  73. * achieving the request. (Useful for unit testing, or tracking of requests). In some instances
  74. * such as `setTimeout` the wrapping of the wrapCallback and scheduling is done in the same
  75. * wrapCallback, but there are other examples such as `Promises` where the `then` wrapCallback is
  76. * wrapped, but the execution of `then` is triggered by `Promise` scheduling `resolve` work.
  77. *
  78. * Fundamentally there are three kinds of tasks which can be scheduled:
  79. *
  80. * 1. [MicroTask] used for doing work right after the current task. This is non-cancelable which is
  81. * guaranteed to run exactly once and immediately.
  82. * 2. [MacroTask] used for doing work later. Such as `setTimeout`. This is typically cancelable
  83. * which is guaranteed to execute at least once after some well understood delay.
  84. * 3. [EventTask] used for listening on some future event. This may execute zero or more times, with
  85. * an unknown delay.
  86. *
  87. * Each asynchronous API is modeled and routed through one of these APIs.
  88. *
  89. *
  90. * ### [MicroTask]
  91. *
  92. * [MicroTask]s represent work which will be done in current VM turn as soon as possible, before VM
  93. * yielding.
  94. *
  95. *
  96. * ### [TimerTask]
  97. *
  98. * [TimerTask]s represent work which will be done after some delay. (Sometimes the delay is
  99. * approximate such as on next available animation frame). Typically these methods include:
  100. * `setTimeout`, `setImmediate`, `setInterval`, `requestAnimationFrame`, and all browser specific
  101. * variants.
  102. *
  103. *
  104. * ### [EventTask]
  105. *
  106. * [EventTask]s represent a request to create a listener on an event. Unlike the other task
  107. * events they may never be executed, but typically execute more than once. There is no queue of
  108. * events, rather their callbacks are unpredictable both in order and time.
  109. *
  110. *
  111. * ## Global Error Handling
  112. *
  113. *
  114. * ## Composability
  115. *
  116. * Zones can be composed together through [Zone.fork()]. A child zone may create its own set of
  117. * rules. A child zone is expected to either:
  118. *
  119. * 1. Delegate the interception to a parent zone, and optionally add before and after wrapCallback
  120. * hooks.
  121. * 2. Process the request itself without delegation.
  122. *
  123. * Composability allows zones to keep their concerns clean. For example a top most zone may choose
  124. * to handle error handling, while child zones may choose to do user action tracking.
  125. *
  126. *
  127. * ## Root Zone
  128. *
  129. * At the start the browser will run in a special root zone, which is configured to behave exactly
  130. * like the platform, making any existing code which is not zone-aware behave as expected. All
  131. * zones are children of the root zone.
  132. *
  133. */
  134. interface Zone {
  135. /**
  136. *
  137. * @returns {Zone} The parent Zone.
  138. */
  139. parent: Zone;
  140. /**
  141. * @returns {string} The Zone name (useful for debugging)
  142. */
  143. name: string;
  144. /**
  145. * Returns a value associated with the `key`.
  146. *
  147. * If the current zone does not have a key, the request is delegated to the parent zone. Use
  148. * [ZoneSpec.properties] to configure the set of properties associated with the current zone.
  149. *
  150. * @param key The key to retrieve.
  151. * @returns {any} The value for the key, or `undefined` if not found.
  152. */
  153. get(key: string): any;
  154. /**
  155. * Returns a Zone which defines a `key`.
  156. *
  157. * Recursively search the parent Zone until a Zone which has a property `key` is found.
  158. *
  159. * @param key The key to use for identification of the returned zone.
  160. * @returns {Zone} The Zone which defines the `key`, `null` if not found.
  161. */
  162. getZoneWith(key: string): Zone;
  163. /**
  164. * Used to create a child zone.
  165. *
  166. * @param zoneSpec A set of rules which the child zone should follow.
  167. * @returns {Zone} A new child zone.
  168. */
  169. fork(zoneSpec: ZoneSpec): Zone;
  170. /**
  171. * Wraps a callback function in a new function which will properly restore the current zone upon
  172. * invocation.
  173. *
  174. * The wrapped function will properly forward `this` as well as `arguments` to the `callback`.
  175. *
  176. * Before the function is wrapped the zone can intercept the `callback` by declaring
  177. * [ZoneSpec.onIntercept].
  178. *
  179. * @param callback the function which will be wrapped in the zone.
  180. * @param source A unique debug location of the API being wrapped.
  181. * @returns {function(): *} A function which will invoke the `callback` through [Zone.runGuarded].
  182. */
  183. wrap<F extends Function>(callback: F, source: string): F;
  184. /**
  185. * Invokes a function in a given zone.
  186. *
  187. * The invocation of `callback` can be intercepted by declaring [ZoneSpec.onInvoke].
  188. *
  189. * @param callback The function to invoke.
  190. * @param applyThis
  191. * @param applyArgs
  192. * @param source A unique debug location of the API being invoked.
  193. * @returns {any} Value from the `callback` function.
  194. */
  195. run<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
  196. /**
  197. * Invokes a function in a given zone and catches any exceptions.
  198. *
  199. * Any exceptions thrown will be forwarded to [Zone.HandleError].
  200. *
  201. * The invocation of `callback` can be intercepted by declaring [ZoneSpec.onInvoke]. The
  202. * handling of exceptions can be intercepted by declaring [ZoneSpec.handleError].
  203. *
  204. * @param callback The function to invoke.
  205. * @param applyThis
  206. * @param applyArgs
  207. * @param source A unique debug location of the API being invoked.
  208. * @returns {any} Value from the `callback` function.
  209. */
  210. runGuarded<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
  211. /**
  212. * Execute the Task by restoring the [Zone.currentTask] in the Task's zone.
  213. *
  214. * @param task to run
  215. * @param applyThis
  216. * @param applyArgs
  217. * @returns {*}
  218. */
  219. runTask(task: Task, applyThis?: any, applyArgs?: any): any;
  220. /**
  221. * Schedule a MicroTask.
  222. *
  223. * @param source
  224. * @param callback
  225. * @param data
  226. * @param customSchedule
  227. */
  228. scheduleMicroTask(
  229. source: string, callback: Function, data?: TaskData,
  230. customSchedule?: (task: Task) => void): MicroTask;
  231. /**
  232. * Schedule a MacroTask.
  233. *
  234. * @param source
  235. * @param callback
  236. * @param data
  237. * @param customSchedule
  238. * @param customCancel
  239. */
  240. scheduleMacroTask(
  241. source: string, callback: Function, data: TaskData, customSchedule: (task: Task) => void,
  242. customCancel: (task: Task) => void): MacroTask;
  243. /**
  244. * Schedule an EventTask.
  245. *
  246. * @param source
  247. * @param callback
  248. * @param data
  249. * @param customSchedule
  250. * @param customCancel
  251. */
  252. scheduleEventTask(
  253. source: string, callback: Function, data: TaskData, customSchedule: (task: Task) => void,
  254. customCancel: (task: Task) => void): EventTask;
  255. /**
  256. * Schedule an existing Task.
  257. *
  258. * Useful for rescheduling a task which was already canceled.
  259. *
  260. * @param task
  261. */
  262. scheduleTask<T extends Task>(task: T): T;
  263. /**
  264. * Allows the zone to intercept canceling of scheduled Task.
  265. *
  266. * The interception is configured using [ZoneSpec.onCancelTask]. The default canceler invokes
  267. * the [Task.cancelFn].
  268. *
  269. * @param task
  270. * @returns {any}
  271. */
  272. cancelTask(task: Task): any;
  273. }
  274. interface ZoneType {
  275. /**
  276. * @returns {Zone} Returns the current [Zone]. The only way to change
  277. * the current zone is by invoking a run() method, which will update the current zone for the
  278. * duration of the run method callback.
  279. */
  280. current: Zone;
  281. /**
  282. * @returns {Task} The task associated with the current execution.
  283. */
  284. currentTask: Task;
  285. /**
  286. * Verify that Zone has been correctly patched. Specifically that Promise is zone aware.
  287. */
  288. assertZonePatched(): void;
  289. /**
  290. * Return the root zone.
  291. */
  292. root: Zone;
  293. /** @internal */
  294. __load_patch(name: string, fn: _PatchFn): void;
  295. /** @internal */
  296. __symbol__(name: string): string;
  297. }
  298. /** @internal */
  299. type _PatchFn = (global: Window, Zone: ZoneType, api: _ZonePrivate) => void;
  300. /** @internal */
  301. interface _ZonePrivate {
  302. currentZoneFrame: () => _ZoneFrame;
  303. symbol: (name: string) => string;
  304. scheduleMicroTask: (task?: MicroTask) => void;
  305. onUnhandledError: (error: Error) => void;
  306. microtaskDrainDone: () => void;
  307. showUncaughtError: () => boolean;
  308. patchEventTarget: (global: any, apis: any[], options?: any) => boolean[];
  309. patchOnProperties: (obj: any, properties: string[]) => void;
  310. setNativePromise: (nativePromise: any) => void;
  311. patchMethod:
  312. (target: any, name: string,
  313. patchFn: (delegate: Function, delegateName: string, name: string) =>
  314. (self: any, args: any[]) => any) => Function;
  315. bindArguments: (args: any[], source: string) => any[];
  316. }
  317. /** @internal */
  318. interface _ZoneFrame {
  319. parent: _ZoneFrame;
  320. zone: Zone;
  321. }
  322. interface UncaughtPromiseError extends Error {
  323. zone: Zone;
  324. task: Task;
  325. promise: Promise<any>;
  326. rejection: any;
  327. }
  328. /**
  329. * Provides a way to configure the interception of zone events.
  330. *
  331. * Only the `name` property is required (all other are optional).
  332. */
  333. interface ZoneSpec {
  334. /**
  335. * The name of the zone. Useful when debugging Zones.
  336. */
  337. name: string;
  338. /**
  339. * A set of properties to be associated with Zone. Use [Zone.get] to retrieve them.
  340. */
  341. properties?: {[key: string]: any};
  342. /**
  343. * Allows the interception of zone forking.
  344. *
  345. * When the zone is being forked, the request is forwarded to this method for interception.
  346. *
  347. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  348. * @param currentZone The current [Zone] where the current interceptor has been declared.
  349. * @param targetZone The [Zone] which originally received the request.
  350. * @param zoneSpec The argument passed into the `fork` method.
  351. */
  352. onFork?:
  353. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
  354. zoneSpec: ZoneSpec) => Zone;
  355. /**
  356. * Allows interception of the wrapping of the callback.
  357. *
  358. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  359. * @param currentZone The current [Zone] where the current interceptor has been declared.
  360. * @param targetZone The [Zone] which originally received the request.
  361. * @param delegate The argument passed into the `wrap` method.
  362. * @param source The argument passed into the `wrap` method.
  363. */
  364. onIntercept?:
  365. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
  366. source: string) => Function;
  367. /**
  368. * Allows interception of the callback invocation.
  369. *
  370. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  371. * @param currentZone The current [Zone] where the current interceptor has been declared.
  372. * @param targetZone The [Zone] which originally received the request.
  373. * @param delegate The argument passed into the `run` method.
  374. * @param applyThis The argument passed into the `run` method.
  375. * @param applyArgs The argument passed into the `run` method.
  376. * @param source The argument passed into the `run` method.
  377. */
  378. onInvoke?:
  379. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
  380. applyThis: any, applyArgs: any[], source: string) => any;
  381. /**
  382. * Allows interception of the error handling.
  383. *
  384. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  385. * @param currentZone The current [Zone] where the current interceptor has been declared.
  386. * @param targetZone The [Zone] which originally received the request.
  387. * @param error The argument passed into the `handleError` method.
  388. */
  389. onHandleError?:
  390. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
  391. error: any) => boolean;
  392. /**
  393. * Allows interception of task scheduling.
  394. *
  395. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  396. * @param currentZone The current [Zone] where the current interceptor has been declared.
  397. * @param targetZone The [Zone] which originally received the request.
  398. * @param task The argument passed into the `scheduleTask` method.
  399. */
  400. onScheduleTask?:
  401. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => Task;
  402. onInvokeTask?:
  403. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
  404. applyThis: any, applyArgs: any) => any;
  405. /**
  406. * Allows interception of task cancellation.
  407. *
  408. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  409. * @param currentZone The current [Zone] where the current interceptor has been declared.
  410. * @param targetZone The [Zone] which originally received the request.
  411. * @param task The argument passed into the `cancelTask` method.
  412. */
  413. onCancelTask?:
  414. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => any;
  415. /**
  416. * Notifies of changes to the task queue empty status.
  417. *
  418. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  419. * @param currentZone The current [Zone] where the current interceptor has been declared.
  420. * @param targetZone The [Zone] which originally received the request.
  421. * @param hasTaskState
  422. */
  423. onHasTask?:
  424. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
  425. hasTaskState: HasTaskState) => void;
  426. }
  427. /**
  428. * A delegate when intercepting zone operations.
  429. *
  430. * A ZoneDelegate is needed because a child zone can't simply invoke a method on a parent zone. For
  431. * example a child zone wrap can't just call parent zone wrap. Doing so would create a callback
  432. * which is bound to the parent zone. What we are interested in is intercepting the callback before
  433. * it is bound to any zone. Furthermore, we also need to pass the targetZone (zone which received
  434. * the original request) to the delegate.
  435. *
  436. * The ZoneDelegate methods mirror those of Zone with an addition of extra targetZone argument in
  437. * the method signature. (The original Zone which received the request.) Some methods are renamed
  438. * to prevent confusion, because they have slightly different semantics and arguments.
  439. *
  440. * - `wrap` => `intercept`: The `wrap` method delegates to `intercept`. The `wrap` method returns
  441. * a callback which will run in a given zone, where as intercept allows wrapping the callback
  442. * so that additional code can be run before and after, but does not associate the callback
  443. * with the zone.
  444. * - `run` => `invoke`: The `run` method delegates to `invoke` to perform the actual execution of
  445. * the callback. The `run` method switches to new zone; saves and restores the `Zone.current`;
  446. * and optionally performs error handling. The invoke is not responsible for error handling,
  447. * or zone management.
  448. *
  449. * Not every method is usually overwritten in the child zone, for this reason the ZoneDelegate
  450. * stores the closest zone which overwrites this behavior along with the closest ZoneSpec.
  451. *
  452. * NOTE: We have tried to make this API analogous to Event bubbling with target and current
  453. * properties.
  454. *
  455. * Note: The ZoneDelegate treats ZoneSpec as class. This allows the ZoneSpec to use its `this` to
  456. * store internal state.
  457. */
  458. interface ZoneDelegate {
  459. zone: Zone;
  460. fork(targetZone: Zone, zoneSpec: ZoneSpec): Zone;
  461. intercept(targetZone: Zone, callback: Function, source: string): Function;
  462. invoke(targetZone: Zone, callback: Function, applyThis: any, applyArgs: any[], source: string):
  463. any;
  464. handleError(targetZone: Zone, error: any): boolean;
  465. scheduleTask(targetZone: Zone, task: Task): Task;
  466. invokeTask(targetZone: Zone, task: Task, applyThis: any, applyArgs: any): any;
  467. cancelTask(targetZone: Zone, task: Task): any;
  468. hasTask(targetZone: Zone, isEmpty: HasTaskState): void;
  469. }
  470. type HasTaskState = {
  471. microTask: boolean; macroTask: boolean; eventTask: boolean; change: TaskType;
  472. };
  473. /**
  474. * Task type: `microTask`, `macroTask`, `eventTask`.
  475. */
  476. type TaskType = 'microTask'|'macroTask'|'eventTask';
  477. /**
  478. * Task type: `notScheduled`, `scheduling`, `scheduled`, `running`, `canceling`, 'unknown'.
  479. */
  480. type TaskState = 'notScheduled'|'scheduling'|'scheduled'|'running'|'canceling'|'unknown';
  481. /**
  482. */
  483. interface TaskData {
  484. /**
  485. * A periodic [MacroTask] is such which get automatically rescheduled after it is executed.
  486. */
  487. isPeriodic?: boolean;
  488. /**
  489. * Delay in milliseconds when the Task will run.
  490. */
  491. delay?: number;
  492. /**
  493. * identifier returned by the native setTimeout.
  494. */
  495. handleId?: number;
  496. }
  497. /**
  498. * Represents work which is executed with a clean stack.
  499. *
  500. * Tasks are used in Zones to mark work which is performed on clean stack frame. There are three
  501. * kinds of task. [MicroTask], [MacroTask], and [EventTask].
  502. *
  503. * A JS VM can be modeled as a [MicroTask] queue, [MacroTask] queue, and [EventTask] set.
  504. *
  505. * - [MicroTask] queue represents a set of tasks which are executing right after the current stack
  506. * frame becomes clean and before a VM yield. All [MicroTask]s execute in order of insertion
  507. * before VM yield and the next [MacroTask] is executed.
  508. * - [MacroTask] queue represents a set of tasks which are executed one at a time after each VM
  509. * yield. The queue is ordered by time, and insertions can happen in any location.
  510. * - [EventTask] is a set of tasks which can at any time be inserted to the end of the [MacroTask]
  511. * queue. This happens when the event fires.
  512. *
  513. */
  514. interface Task {
  515. /**
  516. * Task type: `microTask`, `macroTask`, `eventTask`.
  517. */
  518. type: TaskType;
  519. /**
  520. * Task state: `notScheduled`, `scheduling`, `scheduled`, `running`, `canceling`, `unknown`.
  521. */
  522. state: TaskState;
  523. /**
  524. * Debug string representing the API which requested the scheduling of the task.
  525. */
  526. source: string;
  527. /**
  528. * The Function to be used by the VM upon entering the [Task]. This function will delegate to
  529. * [Zone.runTask] and delegate to `callback`.
  530. */
  531. invoke: Function;
  532. /**
  533. * Function which needs to be executed by the Task after the [Zone.currentTask] has been set to
  534. * the current task.
  535. */
  536. callback: Function;
  537. /**
  538. * Task specific options associated with the current task. This is passed to the `scheduleFn`.
  539. */
  540. data: TaskData;
  541. /**
  542. * Represents the default work which needs to be done to schedule the Task by the VM.
  543. *
  544. * A zone may choose to intercept this function and perform its own scheduling.
  545. */
  546. scheduleFn: (task: Task) => void;
  547. /**
  548. * Represents the default work which needs to be done to un-schedule the Task from the VM. Not all
  549. * Tasks are cancelable, and therefore this method is optional.
  550. *
  551. * A zone may chose to intercept this function and perform its own un-scheduling.
  552. */
  553. cancelFn: (task: Task) => void;
  554. /**
  555. * @type {Zone} The zone which will be used to invoke the `callback`. The Zone is captured
  556. * at the time of Task creation.
  557. */
  558. readonly zone: Zone;
  559. /**
  560. * Number of times the task has been executed, or -1 if canceled.
  561. */
  562. runCount: number;
  563. /**
  564. * Cancel the scheduling request. This method can be called from `ZoneSpec.onScheduleTask` to
  565. * cancel the current scheduling interception. Once canceled the task can be discarded or
  566. * rescheduled using `Zone.scheduleTask` on a different zone.
  567. */
  568. cancelScheduleRequest(): void;
  569. }
  570. interface MicroTask extends Task {
  571. type: 'microTask';
  572. }
  573. interface MacroTask extends Task {
  574. type: 'macroTask';
  575. }
  576. interface EventTask extends Task {
  577. type: 'eventTask';
  578. }
  579. /** @internal */
  580. type AmbientZone = Zone;
  581. /** @internal */
  582. type AmbientZoneDelegate = ZoneDelegate;
  583. const Zone: ZoneType = (function(global: any) {
  584. const FUNCTION = 'function';
  585. const performance: {mark(name: string): void; measure(name: string, label: string): void;} =
  586. global['performance'];
  587. function mark(name: string) {
  588. performance && performance['mark'] && performance['mark'](name);
  589. }
  590. function performanceMeasure(name: string, label: string) {
  591. performance && performance['measure'] && performance['measure'](name, label);
  592. }
  593. mark('Zone');
  594. if (global['Zone']) {
  595. throw new Error('Zone already loaded.');
  596. }
  597. class Zone implements AmbientZone {
  598. static __symbol__: (name: string) => string = __symbol__;
  599. static assertZonePatched() {
  600. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  601. throw new Error(
  602. 'Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  603. 'has been overwritten.\n' +
  604. 'Most likely cause is that a Promise polyfill has been loaded ' +
  605. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  606. 'If you must load one, do so before loading zone.js.)');
  607. }
  608. }
  609. static get root(): AmbientZone {
  610. let zone = Zone.current;
  611. while (zone.parent) {
  612. zone = zone.parent;
  613. }
  614. return zone;
  615. }
  616. static get current(): AmbientZone {
  617. return _currentZoneFrame.zone;
  618. }
  619. static get currentTask(): Task {
  620. return _currentTask;
  621. }
  622. static __load_patch(name: string, fn: _PatchFn): void {
  623. if (patches.hasOwnProperty(name)) {
  624. throw Error('Already loaded patch: ' + name);
  625. } else if (!global['__Zone_disable_' + name]) {
  626. const perfName = 'Zone:' + name;
  627. mark(perfName);
  628. patches[name] = fn(global, Zone, _api);
  629. performanceMeasure(perfName, perfName);
  630. }
  631. }
  632. public get parent(): AmbientZone {
  633. return this._parent;
  634. }
  635. public get name(): string {
  636. return this._name;
  637. }
  638. private _parent: Zone;
  639. private _name: string;
  640. private _properties: {[key: string]: any} = null;
  641. private _zoneDelegate: ZoneDelegate;
  642. constructor(parent: Zone, zoneSpec: ZoneSpec) {
  643. this._parent = parent;
  644. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  645. this._properties = zoneSpec && zoneSpec.properties || {};
  646. this._zoneDelegate =
  647. new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  648. }
  649. public get(key: string): any {
  650. const zone: Zone = this.getZoneWith(key) as Zone;
  651. if (zone) return zone._properties[key];
  652. }
  653. public getZoneWith(key: string): AmbientZone {
  654. let current: Zone = this;
  655. while (current) {
  656. if (current._properties.hasOwnProperty(key)) {
  657. return current;
  658. }
  659. current = current._parent;
  660. }
  661. return null;
  662. }
  663. public fork(zoneSpec: ZoneSpec): AmbientZone {
  664. if (!zoneSpec) throw new Error('ZoneSpec required!');
  665. return this._zoneDelegate.fork(this, zoneSpec);
  666. }
  667. public wrap<T extends Function>(callback: T, source: string): T {
  668. if (typeof callback !== FUNCTION) {
  669. throw new Error('Expecting function got: ' + callback);
  670. }
  671. const _callback = this._zoneDelegate.intercept(this, callback, source);
  672. const zone: Zone = this;
  673. return function() {
  674. return zone.runGuarded(_callback, this, <any>arguments, source);
  675. } as any as T;
  676. }
  677. public run(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
  678. public run<T>(
  679. callback: (...args: any[]) => T, applyThis: any = undefined, applyArgs: any[] = null,
  680. source: string = null): T {
  681. _currentZoneFrame = {parent: _currentZoneFrame, zone: this};
  682. try {
  683. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  684. } finally {
  685. _currentZoneFrame = _currentZoneFrame.parent;
  686. }
  687. }
  688. public runGuarded(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
  689. public runGuarded<T>(
  690. callback: (...args: any[]) => T, applyThis: any = null, applyArgs: any[] = null,
  691. source: string = null) {
  692. _currentZoneFrame = {parent: _currentZoneFrame, zone: this};
  693. try {
  694. try {
  695. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  696. } catch (error) {
  697. if (this._zoneDelegate.handleError(this, error)) {
  698. throw error;
  699. }
  700. }
  701. } finally {
  702. _currentZoneFrame = _currentZoneFrame.parent;
  703. }
  704. }
  705. runTask(task: Task, applyThis?: any, applyArgs?: any): any {
  706. if (task.zone != this) {
  707. throw new Error(
  708. 'A task can only be run in the zone of creation! (Creation: ' +
  709. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  710. }
  711. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  712. // will run in notScheduled(canceled) state, we should not try to
  713. // run such kind of task but just return
  714. // we have to define an variable here, if not
  715. // typescript compiler will complain below
  716. const isNotScheduled = task.state === notScheduled;
  717. if (isNotScheduled && task.type === eventTask) {
  718. return;
  719. }
  720. const reEntryGuard = task.state != running;
  721. reEntryGuard && (task as ZoneTask<any>)._transitionTo(running, scheduled);
  722. task.runCount++;
  723. const previousTask = _currentTask;
  724. _currentTask = task;
  725. _currentZoneFrame = {parent: _currentZoneFrame, zone: this};
  726. try {
  727. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  728. task.cancelFn = null;
  729. }
  730. try {
  731. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  732. } catch (error) {
  733. if (this._zoneDelegate.handleError(this, error)) {
  734. throw error;
  735. }
  736. }
  737. } finally {
  738. // if the task's state is notScheduled or unknown, then it has already been cancelled
  739. // we should not reset the state to scheduled
  740. if (task.state !== notScheduled && task.state !== unknown) {
  741. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  742. reEntryGuard && (task as ZoneTask<any>)._transitionTo(scheduled, running);
  743. } else {
  744. task.runCount = 0;
  745. this._updateTaskCount(task as ZoneTask<any>, -1);
  746. reEntryGuard &&
  747. (task as ZoneTask<any>)._transitionTo(notScheduled, running, notScheduled);
  748. }
  749. }
  750. _currentZoneFrame = _currentZoneFrame.parent;
  751. _currentTask = previousTask;
  752. }
  753. }
  754. scheduleTask<T extends Task>(task: T): T {
  755. if (task.zone && task.zone !== this) {
  756. // check if the task was rescheduled, the newZone
  757. // should not be the children of the original zone
  758. let newZone: any = this;
  759. while (newZone) {
  760. if (newZone === task.zone) {
  761. throw Error(`can not reschedule task to ${this
  762. .name} which is descendants of the original zone ${task.zone.name}`);
  763. }
  764. newZone = newZone.parent;
  765. }
  766. }
  767. (task as any as ZoneTask<any>)._transitionTo(scheduling, notScheduled);
  768. const zoneDelegates: ZoneDelegate[] = [];
  769. (task as any as ZoneTask<any>)._zoneDelegates = zoneDelegates;
  770. (task as any as ZoneTask<any>)._zone = this;
  771. try {
  772. task = this._zoneDelegate.scheduleTask(this, task) as T;
  773. } catch (err) {
  774. // should set task's state to unknown when scheduleTask throw error
  775. // because the err may from reschedule, so the fromState maybe notScheduled
  776. (task as any as ZoneTask<any>)._transitionTo(unknown, scheduling, notScheduled);
  777. // TODO: @JiaLiPassion, should we check the result from handleError?
  778. this._zoneDelegate.handleError(this, err);
  779. throw err;
  780. }
  781. if ((task as any as ZoneTask<any>)._zoneDelegates === zoneDelegates) {
  782. // we have to check because internally the delegate can reschedule the task.
  783. this._updateTaskCount(task as any as ZoneTask<any>, 1);
  784. }
  785. if ((task as any as ZoneTask<any>).state == scheduling) {
  786. (task as any as ZoneTask<any>)._transitionTo(scheduled, scheduling);
  787. }
  788. return task;
  789. }
  790. scheduleMicroTask(
  791. source: string, callback: Function, data?: TaskData,
  792. customSchedule?: (task: Task) => void): MicroTask {
  793. return this.scheduleTask(
  794. new ZoneTask(microTask, source, callback, data, customSchedule, null));
  795. }
  796. scheduleMacroTask(
  797. source: string, callback: Function, data: TaskData, customSchedule: (task: Task) => void,
  798. customCancel: (task: Task) => void): MacroTask {
  799. return this.scheduleTask(
  800. new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  801. }
  802. scheduleEventTask(
  803. source: string, callback: Function, data: TaskData, customSchedule: (task: Task) => void,
  804. customCancel: (task: Task) => void): EventTask {
  805. return this.scheduleTask(
  806. new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  807. }
  808. cancelTask(task: Task): any {
  809. if (task.zone != this)
  810. throw new Error(
  811. 'A task can only be cancelled in the zone of creation! (Creation: ' +
  812. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  813. (task as ZoneTask<any>)._transitionTo(canceling, scheduled, running);
  814. try {
  815. this._zoneDelegate.cancelTask(this, task);
  816. } catch (err) {
  817. // if error occurs when cancelTask, transit the state to unknown
  818. (task as ZoneTask<any>)._transitionTo(unknown, canceling);
  819. this._zoneDelegate.handleError(this, err);
  820. throw err;
  821. }
  822. this._updateTaskCount(task as ZoneTask<any>, -1);
  823. (task as ZoneTask<any>)._transitionTo(notScheduled, canceling);
  824. task.runCount = 0;
  825. return task;
  826. }
  827. private _updateTaskCount(task: ZoneTask<any>, count: number) {
  828. const zoneDelegates = task._zoneDelegates;
  829. if (count == -1) {
  830. task._zoneDelegates = null;
  831. }
  832. for (let i = 0; i < zoneDelegates.length; i++) {
  833. zoneDelegates[i]._updateTaskCount(task.type, count);
  834. }
  835. }
  836. }
  837. const DELEGATE_ZS: ZoneSpec = {
  838. name: '',
  839. onHasTask: (delegate: ZoneDelegate, _: Zone, target: Zone, hasTaskState: HasTaskState): void =>
  840. delegate.hasTask(target, hasTaskState),
  841. onScheduleTask: (delegate: ZoneDelegate, _: Zone, target: Zone, task: Task): Task =>
  842. delegate.scheduleTask(target, task),
  843. onInvokeTask: (delegate: ZoneDelegate, _: Zone, target: Zone, task: Task, applyThis: any,
  844. applyArgs: any): any => delegate.invokeTask(target, task, applyThis, applyArgs),
  845. onCancelTask: (delegate: ZoneDelegate, _: Zone, target: Zone, task: Task): any =>
  846. delegate.cancelTask(target, task)
  847. };
  848. class ZoneDelegate implements AmbientZoneDelegate {
  849. public zone: Zone;
  850. private _taskCounts: {microTask: number,
  851. macroTask: number,
  852. eventTask: number} = {'microTask': 0, 'macroTask': 0, 'eventTask': 0};
  853. private _parentDelegate: ZoneDelegate;
  854. private _forkDlgt: ZoneDelegate;
  855. private _forkZS: ZoneSpec;
  856. private _forkCurrZone: Zone;
  857. private _interceptDlgt: ZoneDelegate;
  858. private _interceptZS: ZoneSpec;
  859. private _interceptCurrZone: Zone;
  860. private _invokeDlgt: ZoneDelegate;
  861. private _invokeZS: ZoneSpec;
  862. private _invokeCurrZone: Zone;
  863. private _handleErrorDlgt: ZoneDelegate;
  864. private _handleErrorZS: ZoneSpec;
  865. private _handleErrorCurrZone: Zone;
  866. private _scheduleTaskDlgt: ZoneDelegate;
  867. private _scheduleTaskZS: ZoneSpec;
  868. private _scheduleTaskCurrZone: Zone;
  869. private _invokeTaskDlgt: ZoneDelegate;
  870. private _invokeTaskZS: ZoneSpec;
  871. private _invokeTaskCurrZone: Zone;
  872. private _cancelTaskDlgt: ZoneDelegate;
  873. private _cancelTaskZS: ZoneSpec;
  874. private _cancelTaskCurrZone: Zone;
  875. private _hasTaskDlgt: ZoneDelegate;
  876. private _hasTaskDlgtOwner: ZoneDelegate;
  877. private _hasTaskZS: ZoneSpec;
  878. private _hasTaskCurrZone: Zone;
  879. constructor(zone: Zone, parentDelegate: ZoneDelegate, zoneSpec: ZoneSpec) {
  880. this.zone = zone;
  881. this._parentDelegate = parentDelegate;
  882. this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
  883. this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
  884. this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone);
  885. this._interceptZS =
  886. zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
  887. this._interceptDlgt =
  888. zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
  889. this._interceptCurrZone =
  890. zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone);
  891. this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
  892. this._invokeDlgt =
  893. zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
  894. this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone);
  895. this._handleErrorZS =
  896. zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
  897. this._handleErrorDlgt =
  898. zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
  899. this._handleErrorCurrZone =
  900. zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
  901. this._scheduleTaskZS =
  902. zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
  903. this._scheduleTaskDlgt =
  904. zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
  905. this._scheduleTaskCurrZone =
  906. zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
  907. this._invokeTaskZS =
  908. zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
  909. this._invokeTaskDlgt =
  910. zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
  911. this._invokeTaskCurrZone =
  912. zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone);
  913. this._cancelTaskZS =
  914. zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
  915. this._cancelTaskDlgt =
  916. zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
  917. this._cancelTaskCurrZone =
  918. zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone);
  919. this._hasTaskZS = null;
  920. this._hasTaskDlgt = null;
  921. this._hasTaskDlgtOwner = null;
  922. this._hasTaskCurrZone = null;
  923. const zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
  924. const parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
  925. if (zoneSpecHasTask || parentHasTask) {
  926. // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
  927. // a case all task related interceptors must go through this ZD. We can't short circuit it.
  928. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
  929. this._hasTaskDlgt = parentDelegate;
  930. this._hasTaskDlgtOwner = this;
  931. this._hasTaskCurrZone = zone;
  932. if (!zoneSpec.onScheduleTask) {
  933. this._scheduleTaskZS = DELEGATE_ZS;
  934. this._scheduleTaskDlgt = parentDelegate;
  935. this._scheduleTaskCurrZone = this.zone;
  936. }
  937. if (!zoneSpec.onInvokeTask) {
  938. this._invokeTaskZS = DELEGATE_ZS;
  939. this._invokeTaskDlgt = parentDelegate;
  940. this._invokeTaskCurrZone = this.zone;
  941. }
  942. if (!zoneSpec.onCancelTask) {
  943. this._cancelTaskZS = DELEGATE_ZS;
  944. this._cancelTaskDlgt = parentDelegate;
  945. this._cancelTaskCurrZone = this.zone;
  946. }
  947. }
  948. }
  949. fork(targetZone: Zone, zoneSpec: ZoneSpec): AmbientZone {
  950. return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
  951. new Zone(targetZone, zoneSpec);
  952. }
  953. intercept(targetZone: Zone, callback: Function, source: string): Function {
  954. return this._interceptZS ?
  955. this._interceptZS.onIntercept(
  956. this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
  957. callback;
  958. }
  959. invoke(targetZone: Zone, callback: Function, applyThis: any, applyArgs: any[], source: string):
  960. any {
  961. return this._invokeZS ?
  962. this._invokeZS.onInvoke(
  963. this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs,
  964. source) :
  965. callback.apply(applyThis, applyArgs);
  966. }
  967. handleError(targetZone: Zone, error: any): boolean {
  968. return this._handleErrorZS ?
  969. this._handleErrorZS.onHandleError(
  970. this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
  971. true;
  972. }
  973. scheduleTask(targetZone: Zone, task: Task): Task {
  974. let returnTask: ZoneTask<any> = task as ZoneTask<any>;
  975. if (this._scheduleTaskZS) {
  976. if (this._hasTaskZS) {
  977. returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
  978. }
  979. returnTask = this._scheduleTaskZS.onScheduleTask(
  980. this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task) as ZoneTask<any>;
  981. if (!returnTask) returnTask = task as ZoneTask<any>;
  982. } else {
  983. if (task.scheduleFn) {
  984. task.scheduleFn(task);
  985. } else if (task.type == microTask) {
  986. scheduleMicroTask(<MicroTask>task);
  987. } else {
  988. throw new Error('Task is missing scheduleFn.');
  989. }
  990. }
  991. return returnTask;
  992. }
  993. invokeTask(targetZone: Zone, task: Task, applyThis: any, applyArgs: any): any {
  994. return this._invokeTaskZS ?
  995. this._invokeTaskZS.onInvokeTask(
  996. this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis,
  997. applyArgs) :
  998. task.callback.apply(applyThis, applyArgs);
  999. }
  1000. cancelTask(targetZone: Zone, task: Task): any {
  1001. let value: any;
  1002. if (this._cancelTaskZS) {
  1003. value = this._cancelTaskZS.onCancelTask(
  1004. this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
  1005. } else {
  1006. if (!task.cancelFn) {
  1007. throw Error('Task is not cancelable');
  1008. }
  1009. value = task.cancelFn(task);
  1010. }
  1011. return value;
  1012. }
  1013. hasTask(targetZone: Zone, isEmpty: HasTaskState) {
  1014. // hasTask should not throw error so other ZoneDelegate
  1015. // can still trigger hasTask callback
  1016. try {
  1017. return this._hasTaskZS &&
  1018. this._hasTaskZS.onHasTask(
  1019. this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
  1020. } catch (err) {
  1021. this.handleError(targetZone, err);
  1022. }
  1023. }
  1024. _updateTaskCount(type: TaskType, count: number) {
  1025. const counts = this._taskCounts;
  1026. const prev = counts[type];
  1027. const next = counts[type] = prev + count;
  1028. if (next < 0) {
  1029. throw new Error('More tasks executed then were scheduled.');
  1030. }
  1031. if (prev == 0 || next == 0) {
  1032. const isEmpty: HasTaskState = {
  1033. microTask: counts['microTask'] > 0,
  1034. macroTask: counts['macroTask'] > 0,
  1035. eventTask: counts['eventTask'] > 0,
  1036. change: type
  1037. };
  1038. this.hasTask(this.zone, isEmpty);
  1039. }
  1040. }
  1041. }
  1042. class ZoneTask<T extends TaskType> implements Task {
  1043. public type: T;
  1044. public source: string;
  1045. public invoke: Function;
  1046. public callback: Function;
  1047. public data: TaskData;
  1048. public scheduleFn: (task: Task) => void;
  1049. public cancelFn: (task: Task) => void;
  1050. _zone: Zone = null;
  1051. public runCount: number = 0;
  1052. _zoneDelegates: ZoneDelegate[] = null;
  1053. _state: TaskState = 'notScheduled';
  1054. constructor(
  1055. type: T, source: string, callback: Function, options: TaskData,
  1056. scheduleFn: (task: Task) => void, cancelFn: (task: Task) => void) {
  1057. this.type = type;
  1058. this.source = source;
  1059. this.data = options;
  1060. this.scheduleFn = scheduleFn;
  1061. this.cancelFn = cancelFn;
  1062. this.callback = callback;
  1063. const self = this;
  1064. // TODO: @JiaLiPassion options should have interface
  1065. if (type === eventTask && options && (options as any).useG) {
  1066. this.invoke = ZoneTask.invokeTask;
  1067. } else {
  1068. this.invoke = function() {
  1069. return ZoneTask.invokeTask.call(global, self, this, <any>arguments);
  1070. };
  1071. }
  1072. }
  1073. static invokeTask(task: any, target: any, args: any): any {
  1074. if (!task) {
  1075. task = this;
  1076. }
  1077. _numberOfNestedTaskFrames++;
  1078. try {
  1079. task.runCount++;
  1080. return task.zone.runTask(task, target, args);
  1081. } finally {
  1082. if (_numberOfNestedTaskFrames == 1) {
  1083. drainMicroTaskQueue();
  1084. }
  1085. _numberOfNestedTaskFrames--;
  1086. }
  1087. }
  1088. get zone(): Zone {
  1089. return this._zone;
  1090. }
  1091. get state(): TaskState {
  1092. return this._state;
  1093. }
  1094. public cancelScheduleRequest() {
  1095. this._transitionTo(notScheduled, scheduling);
  1096. }
  1097. _transitionTo(toState: TaskState, fromState1: TaskState, fromState2?: TaskState) {
  1098. if (this._state === fromState1 || this._state === fromState2) {
  1099. this._state = toState;
  1100. if (toState == notScheduled) {
  1101. this._zoneDelegates = null;
  1102. }
  1103. } else {
  1104. throw new Error(
  1105. `${this.type} '${this.source}': can not transition to '${toState
  1106. }', expecting state '${fromState1}'${fromState2 ?
  1107. ' or \'' + fromState2 + '\'' :
  1108. ''
  1109. }, was '${this._state}'.`);
  1110. }
  1111. }
  1112. public toString() {
  1113. if (this.data && typeof this.data.handleId !== 'undefined') {
  1114. return this.data.handleId;
  1115. } else {
  1116. return Object.prototype.toString.call(this);
  1117. }
  1118. }
  1119. // add toJSON method to prevent cyclic error when
  1120. // call JSON.stringify(zoneTask)
  1121. public toJSON() {
  1122. return {
  1123. type: this.type,
  1124. state: this.state,
  1125. source: this.source,
  1126. zone: this.zone.name,
  1127. runCount: this.runCount
  1128. };
  1129. }
  1130. }
  1131. //////////////////////////////////////////////////////
  1132. //////////////////////////////////////////////////////
  1133. /// MICROTASK QUEUE
  1134. //////////////////////////////////////////////////////
  1135. //////////////////////////////////////////////////////
  1136. const symbolSetTimeout = __symbol__('setTimeout');
  1137. const symbolPromise = __symbol__('Promise');
  1138. const symbolThen = __symbol__('then');
  1139. let _microTaskQueue: Task[] = [];
  1140. let _isDrainingMicrotaskQueue: boolean = false;
  1141. let nativeMicroTaskQueuePromise: any;
  1142. function scheduleMicroTask(task?: MicroTask) {
  1143. // if we are not running in any task, and there has not been anything scheduled
  1144. // we must bootstrap the initial task creation by manually scheduling the drain
  1145. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  1146. // We are not running in Task, so we need to kickstart the microtask queue.
  1147. if (!nativeMicroTaskQueuePromise) {
  1148. if (global[symbolPromise]) {
  1149. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  1150. }
  1151. }
  1152. if (nativeMicroTaskQueuePromise) {
  1153. nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue);
  1154. } else {
  1155. global[symbolSetTimeout](drainMicroTaskQueue, 0);
  1156. }
  1157. }
  1158. task && _microTaskQueue.push(task);
  1159. }
  1160. function drainMicroTaskQueue() {
  1161. if (!_isDrainingMicrotaskQueue) {
  1162. _isDrainingMicrotaskQueue = true;
  1163. while (_microTaskQueue.length) {
  1164. const queue = _microTaskQueue;
  1165. _microTaskQueue = [];
  1166. for (let i = 0; i < queue.length; i++) {
  1167. const task = queue[i];
  1168. try {
  1169. task.zone.runTask(task, null, null);
  1170. } catch (error) {
  1171. _api.onUnhandledError(error);
  1172. }
  1173. }
  1174. }
  1175. _api.microtaskDrainDone();
  1176. _isDrainingMicrotaskQueue = false;
  1177. }
  1178. }
  1179. //////////////////////////////////////////////////////
  1180. //////////////////////////////////////////////////////
  1181. /// BOOTSTRAP
  1182. //////////////////////////////////////////////////////
  1183. //////////////////////////////////////////////////////
  1184. const NO_ZONE = {name: 'NO ZONE'};
  1185. const notScheduled: 'notScheduled' = 'notScheduled', scheduling: 'scheduling' = 'scheduling',
  1186. scheduled: 'scheduled' = 'scheduled', running: 'running' = 'running',
  1187. canceling: 'canceling' = 'canceling', unknown: 'unknown' = 'unknown';
  1188. const microTask: 'microTask' = 'microTask', macroTask: 'macroTask' = 'macroTask',
  1189. eventTask: 'eventTask' = 'eventTask';
  1190. const patches: {[key: string]: any} = {};
  1191. const _api: _ZonePrivate = {
  1192. symbol: __symbol__,
  1193. currentZoneFrame: () => _currentZoneFrame,
  1194. onUnhandledError: noop,
  1195. microtaskDrainDone: noop,
  1196. scheduleMicroTask: scheduleMicroTask,
  1197. showUncaughtError: () => !(Zone as any)[__symbol__('ignoreConsoleErrorUncaughtError')],
  1198. patchEventTarget: () => [],
  1199. patchOnProperties: noop,
  1200. patchMethod: () => noop,
  1201. bindArguments: () => null,
  1202. setNativePromise: (NativePromise: any) => {
  1203. // sometimes NativePromise.resolve static function
  1204. // is not ready yet, (such as core-js/es6.promise)
  1205. // so we need to check here.
  1206. if (NativePromise && typeof NativePromise.resolve === FUNCTION) {
  1207. nativeMicroTaskQueuePromise = NativePromise.resolve(0);
  1208. }
  1209. },
  1210. };
  1211. let _currentZoneFrame: _ZoneFrame = {parent: null, zone: new Zone(null, null)};
  1212. let _currentTask: Task = null;
  1213. let _numberOfNestedTaskFrames = 0;
  1214. function noop() {}
  1215. function __symbol__(name: string) {
  1216. return '__zone_symbol__' + name;
  1217. }
  1218. performanceMeasure('Zone', 'Zone');
  1219. return global['Zone'] = Zone;
  1220. })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);