selenium-webdriver 2.47.0 → 2.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (529) hide show
  1. package/CHANGES.md +96 -0
  2. package/NOTICE +1 -1
  3. package/README.md +57 -6
  4. package/builder.js +375 -358
  5. package/chrome.js +549 -586
  6. package/edge.js +378 -0
  7. package/error.js +597 -5
  8. package/example/google_search_generator.js +2 -4
  9. package/example/logging.js +6 -2
  10. package/executors.js +11 -27
  11. package/firefox/binary.js +80 -114
  12. package/firefox/extension.js +10 -19
  13. package/firefox/index.js +175 -171
  14. package/firefox/profile.js +221 -239
  15. package/http/index.js +396 -77
  16. package/http/util.js +35 -35
  17. package/ie.js +288 -309
  18. package/index.js +34 -125
  19. package/io/exec.js +58 -39
  20. package/io/index.js +54 -48
  21. package/lib/actions.js +594 -0
  22. package/lib/by.js +276 -0
  23. package/lib/capabilities.js +404 -0
  24. package/lib/{webdriver/command.js → command.js} +89 -72
  25. package/lib/{webdriver/button.js → devmode.js} +13 -8
  26. package/lib/events.js +210 -0
  27. package/lib/firefox/amd64/libnoblur64.so +0 -0
  28. package/lib/firefox/i386/libnoblur.so +0 -0
  29. package/lib/firefox/webdriver.json +6 -1
  30. package/lib/firefox/webdriver.xpi +0 -0
  31. package/lib/{webdriver/key.js → input.js} +82 -2
  32. package/lib/logging.js +668 -0
  33. package/lib/promise.js +3093 -0
  34. package/lib/safari/client.js +697 -659
  35. package/lib/session.js +79 -0
  36. package/{test/promise_aplus_test.js → lib/symbols.js} +15 -25
  37. package/lib/test/build.js +4 -4
  38. package/lib/test/data/click_tests/disappearing_element.html +62 -0
  39. package/lib/test/data/click_tests/html5_submit_buttons.html +2 -1
  40. package/lib/test/data/click_tests/overlapping_elements.html +70 -0
  41. package/lib/test/data/click_tests/partially_overlapping_elements.html +124 -0
  42. package/lib/test/data/click_tests/wrapped_overlapping_elements.html +13 -0
  43. package/lib/test/data/readOnlyPage.html +3 -1
  44. package/lib/test/data/selectPage.html +18 -2
  45. package/lib/test/data/simpleTest.html +1 -0
  46. package/lib/test/fileserver.js +3 -4
  47. package/lib/test/index.js +13 -4
  48. package/lib/test/resources.js +1 -1
  49. package/lib/until.js +428 -0
  50. package/lib/webdriver.js +2351 -0
  51. package/net/portprober.js +15 -11
  52. package/opera.js +295 -314
  53. package/package.json +6 -5
  54. package/phantomjs.js +135 -140
  55. package/proxy.js +6 -4
  56. package/remote/index.js +234 -219
  57. package/safari.js +319 -310
  58. package/test/chrome/options_test.js +11 -9
  59. package/test/element_finding_test.js +51 -13
  60. package/test/error_test.js +163 -0
  61. package/test/execute_script_test.js +1 -1
  62. package/test/firefox/firefox_test.js +24 -0
  63. package/test/http/http_test.js +354 -43
  64. package/test/http/util_test.js +25 -23
  65. package/test/io_test.js +6 -1
  66. package/test/lib/by_test.js +127 -0
  67. package/test/lib/capabilities_test.js +84 -0
  68. package/test/lib/events_test.js +177 -0
  69. package/test/lib/logging_test.js +272 -0
  70. package/test/lib/promise_aplus_test.js +74 -0
  71. package/test/lib/promise_error_test.js +808 -0
  72. package/test/lib/promise_flow_test.js +2282 -0
  73. package/test/lib/promise_generator_test.js +308 -0
  74. package/test/lib/promise_test.js +996 -0
  75. package/test/lib/testutil.js +90 -0
  76. package/test/lib/until_test.js +436 -0
  77. package/test/lib/webdriver_test.js +2207 -0
  78. package/test/page_loading_test.js +7 -9
  79. package/test/stale_element_test.js +2 -2
  80. package/test/testing/assert_test.js +374 -0
  81. package/test/testing/index_test.js +9 -11
  82. package/testing/assert.js +334 -17
  83. package/testing/index.js +10 -0
  84. package/_base.js +0 -200
  85. package/docs/Changes.html +0 -317
  86. package/docs/class_bot_Error.html +0 -15
  87. package/docs/class_webdriver_ActionSequence.html +0 -115
  88. package/docs/class_webdriver_Alert.html +0 -24
  89. package/docs/class_webdriver_AlertPromise.html +0 -91
  90. package/docs/class_webdriver_Capabilities.html +0 -60
  91. package/docs/class_webdriver_Command.html +0 -15
  92. package/docs/class_webdriver_EventEmitter.html +0 -35
  93. package/docs/class_webdriver_FileDetector.html +0 -21
  94. package/docs/class_webdriver_Locator.html +0 -12
  95. package/docs/class_webdriver_Serializable.html +0 -9
  96. package/docs/class_webdriver_Session.html +0 -13
  97. package/docs/class_webdriver_TouchSequence.html +0 -49
  98. package/docs/class_webdriver_UnhandledAlertError.html +0 -18
  99. package/docs/class_webdriver_WebDriver.html +0 -313
  100. package/docs/class_webdriver_WebDriver_Logs.html +0 -15
  101. package/docs/class_webdriver_WebDriver_Navigation.html +0 -16
  102. package/docs/class_webdriver_WebDriver_Options.html +0 -41
  103. package/docs/class_webdriver_WebDriver_TargetLocator.html +0 -38
  104. package/docs/class_webdriver_WebDriver_Timeouts.html +0 -29
  105. package/docs/class_webdriver_WebDriver_Window.html +0 -27
  106. package/docs/class_webdriver_WebElement.html +0 -216
  107. package/docs/class_webdriver_WebElementPromise.html +0 -266
  108. package/docs/class_webdriver_http_Executor.html +0 -22
  109. package/docs/class_webdriver_http_Request.html +0 -12
  110. package/docs/class_webdriver_http_Response.html +0 -13
  111. package/docs/class_webdriver_logging_Entry.html +0 -15
  112. package/docs/class_webdriver_logging_Level.html +0 -55
  113. package/docs/class_webdriver_logging_LogRecord.html +0 -45
  114. package/docs/class_webdriver_logging_Logger.html +0 -119
  115. package/docs/class_webdriver_logging_Preferences.html +0 -8
  116. package/docs/class_webdriver_promise_CancellationError.html +0 -18
  117. package/docs/class_webdriver_promise_ControlFlow.html +0 -109
  118. package/docs/class_webdriver_promise_Deferred.html +0 -84
  119. package/docs/class_webdriver_promise_Promise.html +0 -74
  120. package/docs/class_webdriver_stacktrace_Frame.html +0 -20
  121. package/docs/class_webdriver_stacktrace_Snapshot.html +0 -6
  122. package/docs/class_webdriver_testing_Assertion.html +0 -99
  123. package/docs/class_webdriver_testing_Assertion_DelegatingMatcher_.html +0 -13
  124. package/docs/class_webdriver_testing_ContainsMatcher.html +0 -11
  125. package/docs/class_webdriver_testing_NegatedAssertion.html +0 -97
  126. package/docs/class_webdriver_until_Condition.html +0 -7
  127. package/docs/dossier.css +0 -1
  128. package/docs/dossier.js +0 -86
  129. package/docs/enum_bot_ErrorCode.html +0 -3
  130. package/docs/enum_bot_Error_State.html +0 -2
  131. package/docs/enum_webdriver_Browser.html +0 -2
  132. package/docs/enum_webdriver_Button.html +0 -2
  133. package/docs/enum_webdriver_Capability.html +0 -33
  134. package/docs/enum_webdriver_CommandName.html +0 -3
  135. package/docs/enum_webdriver_Key.html +0 -12
  136. package/docs/enum_webdriver_logging_Type.html +0 -6
  137. package/docs/enum_webdriver_promise_ControlFlow_EventType.html +0 -9
  138. package/docs/index.html +0 -123
  139. package/docs/interface_webdriver_CommandExecutor.html +0 -9
  140. package/docs/interface_webdriver_http_Client.html +0 -10
  141. package/docs/interface_webdriver_promise_Thenable.html +0 -77
  142. package/docs/module_selenium-webdriver.html +0 -23
  143. package/docs/module_selenium-webdriver__base.html +0 -23
  144. package/docs/module_selenium-webdriver__base_class_Context.html +0 -5
  145. package/docs/module_selenium-webdriver_builder.html +0 -2
  146. package/docs/module_selenium-webdriver_builder_class_Builder.html +0 -138
  147. package/docs/module_selenium-webdriver_chrome.html +0 -90
  148. package/docs/module_selenium-webdriver_chrome_class_Driver.html +0 -280
  149. package/docs/module_selenium-webdriver_chrome_class_Options.html +0 -127
  150. package/docs/module_selenium-webdriver_chrome_class_ServiceBuilder.html +0 -46
  151. package/docs/module_selenium-webdriver_class_ActionSequence.html +0 -115
  152. package/docs/module_selenium-webdriver_class_Builder.html +0 -138
  153. package/docs/module_selenium-webdriver_class_Capabilities.html +0 -60
  154. package/docs/module_selenium-webdriver_class_Command.html +0 -15
  155. package/docs/module_selenium-webdriver_class_EventEmitter.html +0 -35
  156. package/docs/module_selenium-webdriver_class_FileDetector.html +0 -21
  157. package/docs/module_selenium-webdriver_class_Serializable.html +0 -9
  158. package/docs/module_selenium-webdriver_class_Session.html +0 -13
  159. package/docs/module_selenium-webdriver_class_WebDriver.html +0 -313
  160. package/docs/module_selenium-webdriver_class_WebElement.html +0 -216
  161. package/docs/module_selenium-webdriver_class_WebElementPromise.html +0 -266
  162. package/docs/module_selenium-webdriver_enum_Browser.html +0 -2
  163. package/docs/module_selenium-webdriver_enum_Button.html +0 -2
  164. package/docs/module_selenium-webdriver_enum_Capability.html +0 -33
  165. package/docs/module_selenium-webdriver_enum_CommandName.html +0 -3
  166. package/docs/module_selenium-webdriver_enum_Key.html +0 -12
  167. package/docs/module_selenium-webdriver_error.html +0 -4
  168. package/docs/module_selenium-webdriver_error_class_Error.html +0 -15
  169. package/docs/module_selenium-webdriver_error_enum_ErrorCode.html +0 -3
  170. package/docs/module_selenium-webdriver_executors.html +0 -10
  171. package/docs/module_selenium-webdriver_executors_class_DeferredExecutor.html +0 -12
  172. package/docs/module_selenium-webdriver_firefox.html +0 -67
  173. package/docs/module_selenium-webdriver_firefox_binary.html +0 -4
  174. package/docs/module_selenium-webdriver_firefox_binary_class_Binary.html +0 -21
  175. package/docs/module_selenium-webdriver_firefox_class_Binary.html +0 -21
  176. package/docs/module_selenium-webdriver_firefox_class_Driver.html +0 -276
  177. package/docs/module_selenium-webdriver_firefox_class_Options.html +0 -19
  178. package/docs/module_selenium-webdriver_firefox_class_Profile.html +0 -50
  179. package/docs/module_selenium-webdriver_firefox_extension.html +0 -8
  180. package/docs/module_selenium-webdriver_firefox_profile.html +0 -13
  181. package/docs/module_selenium-webdriver_firefox_profile_class_Profile.html +0 -50
  182. package/docs/module_selenium-webdriver_http.html +0 -9
  183. package/docs/module_selenium-webdriver_http_class_Executor.html +0 -22
  184. package/docs/module_selenium-webdriver_http_class_HttpClient.html +0 -16
  185. package/docs/module_selenium-webdriver_http_class_Request.html +0 -12
  186. package/docs/module_selenium-webdriver_http_class_Response.html +0 -13
  187. package/docs/module_selenium-webdriver_http_util.html +0 -17
  188. package/docs/module_selenium-webdriver_ie.html +0 -11
  189. package/docs/module_selenium-webdriver_ie_class_Driver.html +0 -274
  190. package/docs/module_selenium-webdriver_ie_class_Options.html +0 -89
  191. package/docs/module_selenium-webdriver_ie_enum_Level.html +0 -1
  192. package/docs/module_selenium-webdriver_io.html +0 -37
  193. package/docs/module_selenium-webdriver_io_exec.html +0 -6
  194. package/docs/module_selenium-webdriver_namespace_By.html +0 -56
  195. package/docs/module_selenium-webdriver_namespace_error.html +0 -4
  196. package/docs/module_selenium-webdriver_namespace_logging.html +0 -18
  197. package/docs/module_selenium-webdriver_namespace_promise.html +0 -162
  198. package/docs/module_selenium-webdriver_namespace_stacktrace.html +0 -17
  199. package/docs/module_selenium-webdriver_namespace_until.html +0 -82
  200. package/docs/module_selenium-webdriver_net.html +0 -7
  201. package/docs/module_selenium-webdriver_net_portprober.html +0 -12
  202. package/docs/module_selenium-webdriver_opera.html +0 -62
  203. package/docs/module_selenium-webdriver_opera_class_Driver.html +0 -276
  204. package/docs/module_selenium-webdriver_opera_class_Options.html +0 -44
  205. package/docs/module_selenium-webdriver_opera_class_ServiceBuilder.html +0 -35
  206. package/docs/module_selenium-webdriver_phantomjs.html +0 -2
  207. package/docs/module_selenium-webdriver_phantomjs_class_Driver.html +0 -299
  208. package/docs/module_selenium-webdriver_proxy.html +0 -28
  209. package/docs/module_selenium-webdriver_remote.html +0 -8
  210. package/docs/module_selenium-webdriver_remote_class_DriverService.html +0 -32
  211. package/docs/module_selenium-webdriver_remote_class_FileDetector.html +0 -22
  212. package/docs/module_selenium-webdriver_remote_class_SeleniumServer.html +0 -40
  213. package/docs/module_selenium-webdriver_safari.html +0 -9
  214. package/docs/module_selenium-webdriver_safari_class_Driver.html +0 -279
  215. package/docs/module_selenium-webdriver_safari_class_Options.html +0 -23
  216. package/docs/module_selenium-webdriver_testing.html +0 -74
  217. package/docs/module_selenium-webdriver_testing_assert.html +0 -9
  218. package/docs/namespace_bot.html +0 -4
  219. package/docs/namespace_bot_json.html +0 -20
  220. package/docs/namespace_bot_response.html +0 -18
  221. package/docs/namespace_bot_userAgent.html +0 -33
  222. package/docs/namespace_webdriver.html +0 -30
  223. package/docs/namespace_webdriver_By.html +0 -56
  224. package/docs/namespace_webdriver_http.html +0 -6
  225. package/docs/namespace_webdriver_logging.html +0 -70
  226. package/docs/namespace_webdriver_promise.html +0 -165
  227. package/docs/namespace_webdriver_stacktrace.html +0 -17
  228. package/docs/namespace_webdriver_testing.html +0 -7
  229. package/docs/namespace_webdriver_testing_assert.html +0 -9
  230. package/docs/namespace_webdriver_testing_asserts.html +0 -18
  231. package/docs/namespace_webdriver_until.html +0 -82
  232. package/docs/source/_base.js.src.html +0 -1
  233. package/docs/source/builder.js.src.html +0 -1
  234. package/docs/source/chrome.js.src.html +0 -1
  235. package/docs/source/error.js.src.html +0 -1
  236. package/docs/source/executors.js.src.html +0 -1
  237. package/docs/source/firefox/binary.js.src.html +0 -1
  238. package/docs/source/firefox/extension.js.src.html +0 -1
  239. package/docs/source/firefox/index.js.src.html +0 -1
  240. package/docs/source/firefox/profile.js.src.html +0 -1
  241. package/docs/source/http/index.js.src.html +0 -1
  242. package/docs/source/http/util.js.src.html +0 -1
  243. package/docs/source/ie.js.src.html +0 -1
  244. package/docs/source/index.js.src.html +0 -1
  245. package/docs/source/io/exec.js.src.html +0 -1
  246. package/docs/source/io/index.js.src.html +0 -1
  247. package/docs/source/lib/atoms/error.js.src.html +0 -1
  248. package/docs/source/lib/atoms/json.js.src.html +0 -1
  249. package/docs/source/lib/atoms/response.js.src.html +0 -1
  250. package/docs/source/lib/atoms/userAgent.js.src.html +0 -1
  251. package/docs/source/lib/goog/array/array.js.src.html +0 -1
  252. package/docs/source/lib/goog/asserts/asserts.js.src.html +0 -1
  253. package/docs/source/lib/goog/async/freelist.js.src.html +0 -1
  254. package/docs/source/lib/goog/async/nexttick.js.src.html +0 -1
  255. package/docs/source/lib/goog/async/run.js.src.html +0 -1
  256. package/docs/source/lib/goog/async/workqueue.js.src.html +0 -1
  257. package/docs/source/lib/goog/base.js.src.html +0 -1
  258. package/docs/source/lib/goog/debug/debug.js.src.html +0 -1
  259. package/docs/source/lib/goog/debug/entrypointregistry.js.src.html +0 -1
  260. package/docs/source/lib/goog/debug/error.js.src.html +0 -1
  261. package/docs/source/lib/goog/debug/logbuffer.js.src.html +0 -1
  262. package/docs/source/lib/goog/debug/logger.js.src.html +0 -1
  263. package/docs/source/lib/goog/debug/logrecord.js.src.html +0 -1
  264. package/docs/source/lib/goog/deps.js.src.html +0 -1
  265. package/docs/source/lib/goog/disposable/disposable.js.src.html +0 -1
  266. package/docs/source/lib/goog/disposable/idisposable.js.src.html +0 -1
  267. package/docs/source/lib/goog/dom/browserfeature.js.src.html +0 -1
  268. package/docs/source/lib/goog/dom/dom.js.src.html +0 -1
  269. package/docs/source/lib/goog/dom/nodetype.js.src.html +0 -1
  270. package/docs/source/lib/goog/dom/safe.js.src.html +0 -1
  271. package/docs/source/lib/goog/dom/tagname.js.src.html +0 -1
  272. package/docs/source/lib/goog/dom/tags.js.src.html +0 -1
  273. package/docs/source/lib/goog/dom/vendor.js.src.html +0 -1
  274. package/docs/source/lib/goog/events/browserevent.js.src.html +0 -1
  275. package/docs/source/lib/goog/events/browserfeature.js.src.html +0 -1
  276. package/docs/source/lib/goog/events/event.js.src.html +0 -1
  277. package/docs/source/lib/goog/events/eventid.js.src.html +0 -1
  278. package/docs/source/lib/goog/events/events.js.src.html +0 -1
  279. package/docs/source/lib/goog/events/eventtarget.js.src.html +0 -1
  280. package/docs/source/lib/goog/events/eventtype.js.src.html +0 -1
  281. package/docs/source/lib/goog/events/keycodes.js.src.html +0 -1
  282. package/docs/source/lib/goog/events/listenable.js.src.html +0 -1
  283. package/docs/source/lib/goog/events/listener.js.src.html +0 -1
  284. package/docs/source/lib/goog/events/listenermap.js.src.html +0 -1
  285. package/docs/source/lib/goog/fs/url.js.src.html +0 -1
  286. package/docs/source/lib/goog/functions/functions.js.src.html +0 -1
  287. package/docs/source/lib/goog/html/safehtml.js.src.html +0 -1
  288. package/docs/source/lib/goog/html/safescript.js.src.html +0 -1
  289. package/docs/source/lib/goog/html/safestyle.js.src.html +0 -1
  290. package/docs/source/lib/goog/html/safestylesheet.js.src.html +0 -1
  291. package/docs/source/lib/goog/html/safeurl.js.src.html +0 -1
  292. package/docs/source/lib/goog/html/trustedresourceurl.js.src.html +0 -1
  293. package/docs/source/lib/goog/html/uncheckedconversions.js.src.html +0 -1
  294. package/docs/source/lib/goog/i18n/bidi.js.src.html +0 -1
  295. package/docs/source/lib/goog/iter/iter.js.src.html +0 -1
  296. package/docs/source/lib/goog/json/json.js.src.html +0 -1
  297. package/docs/source/lib/goog/labs/testing/assertthat.js.src.html +0 -1
  298. package/docs/source/lib/goog/labs/testing/logicmatcher.js.src.html +0 -1
  299. package/docs/source/lib/goog/labs/testing/matcher.js.src.html +0 -1
  300. package/docs/source/lib/goog/labs/testing/numbermatcher.js.src.html +0 -1
  301. package/docs/source/lib/goog/labs/testing/objectmatcher.js.src.html +0 -1
  302. package/docs/source/lib/goog/labs/testing/stringmatcher.js.src.html +0 -1
  303. package/docs/source/lib/goog/labs/useragent/browser.js.src.html +0 -1
  304. package/docs/source/lib/goog/labs/useragent/engine.js.src.html +0 -1
  305. package/docs/source/lib/goog/labs/useragent/platform.js.src.html +0 -1
  306. package/docs/source/lib/goog/labs/useragent/util.js.src.html +0 -1
  307. package/docs/source/lib/goog/math/box.js.src.html +0 -1
  308. package/docs/source/lib/goog/math/coordinate.js.src.html +0 -1
  309. package/docs/source/lib/goog/math/math.js.src.html +0 -1
  310. package/docs/source/lib/goog/math/rect.js.src.html +0 -1
  311. package/docs/source/lib/goog/math/size.js.src.html +0 -1
  312. package/docs/source/lib/goog/net/wrapperxmlhttpfactory.js.src.html +0 -1
  313. package/docs/source/lib/goog/net/xhrlike.js.src.html +0 -1
  314. package/docs/source/lib/goog/net/xmlhttp.js.src.html +0 -1
  315. package/docs/source/lib/goog/net/xmlhttpfactory.js.src.html +0 -1
  316. package/docs/source/lib/goog/object/object.js.src.html +0 -1
  317. package/docs/source/lib/goog/promise/promise.js.src.html +0 -1
  318. package/docs/source/lib/goog/promise/resolver.js.src.html +0 -1
  319. package/docs/source/lib/goog/promise/thenable.js.src.html +0 -1
  320. package/docs/source/lib/goog/reflect/reflect.js.src.html +0 -1
  321. package/docs/source/lib/goog/string/const.js.src.html +0 -1
  322. package/docs/source/lib/goog/string/string.js.src.html +0 -1
  323. package/docs/source/lib/goog/string/typedstring.js.src.html +0 -1
  324. package/docs/source/lib/goog/structs/collection.js.src.html +0 -1
  325. package/docs/source/lib/goog/structs/map.js.src.html +0 -1
  326. package/docs/source/lib/goog/structs/set.js.src.html +0 -1
  327. package/docs/source/lib/goog/structs/structs.js.src.html +0 -1
  328. package/docs/source/lib/goog/style/style.js.src.html +0 -1
  329. package/docs/source/lib/goog/testing/asserts.js.src.html +0 -1
  330. package/docs/source/lib/goog/testing/events/events.js.src.html +0 -1
  331. package/docs/source/lib/goog/testing/functionmock.js.src.html +0 -1
  332. package/docs/source/lib/goog/testing/jsunit.js.src.html +0 -1
  333. package/docs/source/lib/goog/testing/loosemock.js.src.html +0 -1
  334. package/docs/source/lib/goog/testing/mock.js.src.html +0 -1
  335. package/docs/source/lib/goog/testing/mockclock.js.src.html +0 -1
  336. package/docs/source/lib/goog/testing/mockcontrol.js.src.html +0 -1
  337. package/docs/source/lib/goog/testing/mockinterface.js.src.html +0 -1
  338. package/docs/source/lib/goog/testing/mockmatchers.js.src.html +0 -1
  339. package/docs/source/lib/goog/testing/objectpropertystring.js.src.html +0 -1
  340. package/docs/source/lib/goog/testing/propertyreplacer.js.src.html +0 -1
  341. package/docs/source/lib/goog/testing/recordfunction.js.src.html +0 -1
  342. package/docs/source/lib/goog/testing/stacktrace.js.src.html +0 -1
  343. package/docs/source/lib/goog/testing/strictmock.js.src.html +0 -1
  344. package/docs/source/lib/goog/testing/testcase.js.src.html +0 -1
  345. package/docs/source/lib/goog/testing/testrunner.js.src.html +0 -1
  346. package/docs/source/lib/goog/testing/watchers.js.src.html +0 -1
  347. package/docs/source/lib/goog/uri/uri.js.src.html +0 -1
  348. package/docs/source/lib/goog/uri/utils.js.src.html +0 -1
  349. package/docs/source/lib/goog/useragent/product.js.src.html +0 -1
  350. package/docs/source/lib/goog/useragent/product_isversion.js.src.html +0 -1
  351. package/docs/source/lib/goog/useragent/useragent.js.src.html +0 -1
  352. package/docs/source/lib/webdriver/actionsequence.js.src.html +0 -1
  353. package/docs/source/lib/webdriver/button.js.src.html +0 -1
  354. package/docs/source/lib/webdriver/capabilities.js.src.html +0 -1
  355. package/docs/source/lib/webdriver/command.js.src.html +0 -1
  356. package/docs/source/lib/webdriver/events.js.src.html +0 -1
  357. package/docs/source/lib/webdriver/http/http.js.src.html +0 -1
  358. package/docs/source/lib/webdriver/key.js.src.html +0 -1
  359. package/docs/source/lib/webdriver/locators.js.src.html +0 -1
  360. package/docs/source/lib/webdriver/logging.js.src.html +0 -1
  361. package/docs/source/lib/webdriver/promise.js.src.html +0 -1
  362. package/docs/source/lib/webdriver/serializable.js.src.html +0 -1
  363. package/docs/source/lib/webdriver/session.js.src.html +0 -1
  364. package/docs/source/lib/webdriver/stacktrace.js.src.html +0 -1
  365. package/docs/source/lib/webdriver/testing/asserts.js.src.html +0 -1
  366. package/docs/source/lib/webdriver/touchsequence.js.src.html +0 -1
  367. package/docs/source/lib/webdriver/until.js.src.html +0 -1
  368. package/docs/source/lib/webdriver/webdriver.js.src.html +0 -1
  369. package/docs/source/net/index.js.src.html +0 -1
  370. package/docs/source/net/portprober.js.src.html +0 -1
  371. package/docs/source/opera.js.src.html +0 -1
  372. package/docs/source/phantomjs.js.src.html +0 -1
  373. package/docs/source/proxy.js.src.html +0 -1
  374. package/docs/source/remote/index.js.src.html +0 -1
  375. package/docs/source/safari.js.src.html +0 -1
  376. package/docs/source/testing/assert.js.src.html +0 -1
  377. package/docs/source/testing/index.js.src.html +0 -1
  378. package/docs/types.js +0 -1
  379. package/lib/atoms/error.js +0 -202
  380. package/lib/atoms/json.js +0 -80
  381. package/lib/atoms/response.js +0 -110
  382. package/lib/atoms/userAgent.js +0 -257
  383. package/lib/goog/LICENSE +0 -176
  384. package/lib/goog/array/array.js +0 -1655
  385. package/lib/goog/asserts/asserts.js +0 -365
  386. package/lib/goog/async/freelist.js +0 -88
  387. package/lib/goog/async/nexttick.js +0 -241
  388. package/lib/goog/async/run.js +0 -139
  389. package/lib/goog/async/workqueue.js +0 -139
  390. package/lib/goog/base.js +0 -2547
  391. package/lib/goog/debug/debug.js +0 -653
  392. package/lib/goog/debug/entrypointregistry.js +0 -158
  393. package/lib/goog/debug/error.js +0 -63
  394. package/lib/goog/debug/logbuffer.js +0 -148
  395. package/lib/goog/debug/logger.js +0 -873
  396. package/lib/goog/debug/logrecord.js +0 -242
  397. package/lib/goog/deps.js +0 -151
  398. package/lib/goog/disposable/disposable.js +0 -307
  399. package/lib/goog/disposable/idisposable.js +0 -45
  400. package/lib/goog/dom/browserfeature.js +0 -72
  401. package/lib/goog/dom/dom.js +0 -2995
  402. package/lib/goog/dom/nodetype.js +0 -48
  403. package/lib/goog/dom/safe.js +0 -347
  404. package/lib/goog/dom/tagname.js +0 -160
  405. package/lib/goog/dom/tags.js +0 -42
  406. package/lib/goog/dom/vendor.js +0 -96
  407. package/lib/goog/events/browserevent.js +0 -386
  408. package/lib/goog/events/browserfeature.js +0 -85
  409. package/lib/goog/events/event.js +0 -143
  410. package/lib/goog/events/eventid.js +0 -47
  411. package/lib/goog/events/events.js +0 -984
  412. package/lib/goog/events/eventtarget.js +0 -394
  413. package/lib/goog/events/eventtype.js +0 -233
  414. package/lib/goog/events/keycodes.js +0 -420
  415. package/lib/goog/events/listenable.js +0 -335
  416. package/lib/goog/events/listener.js +0 -131
  417. package/lib/goog/events/listenermap.js +0 -308
  418. package/lib/goog/fs/url.js +0 -105
  419. package/lib/goog/functions/functions.js +0 -332
  420. package/lib/goog/html/safehtml.js +0 -756
  421. package/lib/goog/html/safescript.js +0 -234
  422. package/lib/goog/html/safestyle.js +0 -442
  423. package/lib/goog/html/safestylesheet.js +0 -276
  424. package/lib/goog/html/safeurl.js +0 -431
  425. package/lib/goog/html/trustedresourceurl.js +0 -224
  426. package/lib/goog/html/uncheckedconversions.js +0 -231
  427. package/lib/goog/i18n/bidi.js +0 -908
  428. package/lib/goog/iter/iter.js +0 -1305
  429. package/lib/goog/json/json.js +0 -365
  430. package/lib/goog/labs/testing/assertthat.js +0 -58
  431. package/lib/goog/labs/testing/logicmatcher.js +0 -212
  432. package/lib/goog/labs/testing/matcher.js +0 -80
  433. package/lib/goog/labs/testing/numbermatcher.js +0 -346
  434. package/lib/goog/labs/testing/objectmatcher.js +0 -317
  435. package/lib/goog/labs/testing/stringmatcher.js +0 -415
  436. package/lib/goog/labs/useragent/browser.js +0 -327
  437. package/lib/goog/labs/useragent/engine.js +0 -160
  438. package/lib/goog/labs/useragent/platform.js +0 -160
  439. package/lib/goog/labs/useragent/util.js +0 -148
  440. package/lib/goog/math/box.js +0 -389
  441. package/lib/goog/math/coordinate.js +0 -268
  442. package/lib/goog/math/math.js +0 -451
  443. package/lib/goog/math/rect.js +0 -476
  444. package/lib/goog/math/size.js +0 -227
  445. package/lib/goog/net/wrapperxmlhttpfactory.js +0 -71
  446. package/lib/goog/net/xhrlike.js +0 -124
  447. package/lib/goog/net/xmlhttp.js +0 -246
  448. package/lib/goog/net/xmlhttpfactory.js +0 -67
  449. package/lib/goog/object/object.js +0 -686
  450. package/lib/goog/promise/promise.js +0 -1310
  451. package/lib/goog/promise/resolver.js +0 -48
  452. package/lib/goog/promise/thenable.js +0 -126
  453. package/lib/goog/reflect/reflect.js +0 -78
  454. package/lib/goog/string/const.js +0 -182
  455. package/lib/goog/string/string.js +0 -1565
  456. package/lib/goog/string/typedstring.js +0 -48
  457. package/lib/goog/structs/collection.js +0 -56
  458. package/lib/goog/structs/map.js +0 -456
  459. package/lib/goog/structs/set.js +0 -279
  460. package/lib/goog/structs/structs.js +0 -354
  461. package/lib/goog/style/style.js +0 -2054
  462. package/lib/goog/testing/asserts.js +0 -1265
  463. package/lib/goog/testing/events/events.js +0 -727
  464. package/lib/goog/testing/functionmock.js +0 -176
  465. package/lib/goog/testing/jsunit.js +0 -162
  466. package/lib/goog/testing/loosemock.js +0 -242
  467. package/lib/goog/testing/mock.js +0 -645
  468. package/lib/goog/testing/mockclock.js +0 -617
  469. package/lib/goog/testing/mockcontrol.js +0 -220
  470. package/lib/goog/testing/mockinterface.js +0 -45
  471. package/lib/goog/testing/mockmatchers.js +0 -400
  472. package/lib/goog/testing/objectpropertystring.js +0 -68
  473. package/lib/goog/testing/propertyreplacer.js +0 -245
  474. package/lib/goog/testing/recordfunction.js +0 -215
  475. package/lib/goog/testing/stacktrace.js +0 -594
  476. package/lib/goog/testing/strictmock.js +0 -130
  477. package/lib/goog/testing/testcase.js +0 -1569
  478. package/lib/goog/testing/testrunner.js +0 -440
  479. package/lib/goog/testing/watchers.js +0 -46
  480. package/lib/goog/uri/uri.js +0 -1507
  481. package/lib/goog/uri/utils.js +0 -1116
  482. package/lib/goog/useragent/product.js +0 -175
  483. package/lib/goog/useragent/product_isversion.js +0 -143
  484. package/lib/goog/useragent/useragent.js +0 -538
  485. package/lib/webdriver/actionsequence.js +0 -356
  486. package/lib/webdriver/builder.js +0 -208
  487. package/lib/webdriver/capabilities.js +0 -411
  488. package/lib/webdriver/events.js +0 -179
  489. package/lib/webdriver/firefoxdomexecutor.js +0 -175
  490. package/lib/webdriver/http/corsclient.js +0 -133
  491. package/lib/webdriver/http/http.js +0 -523
  492. package/lib/webdriver/http/xhrclient.js +0 -67
  493. package/lib/webdriver/locators.js +0 -257
  494. package/lib/webdriver/logging.js +0 -347
  495. package/lib/webdriver/promise.js +0 -2609
  496. package/lib/webdriver/serializable.js +0 -41
  497. package/lib/webdriver/session.js +0 -74
  498. package/lib/webdriver/stacktrace.js +0 -619
  499. package/lib/webdriver/test/builder_test.js +0 -53
  500. package/lib/webdriver/test/capabilities_test.js +0 -72
  501. package/lib/webdriver/test/events_test.js +0 -203
  502. package/lib/webdriver/test/http/corsclient_test.js +0 -151
  503. package/lib/webdriver/test/http/http_test.js +0 -428
  504. package/lib/webdriver/test/http/xhrclient_test.js +0 -196
  505. package/lib/webdriver/test/locators_test.js +0 -59
  506. package/lib/webdriver/test/logging_test.js +0 -85
  507. package/lib/webdriver/test/promise_error_test.js +0 -719
  508. package/lib/webdriver/test/promise_flow_test.js +0 -1957
  509. package/lib/webdriver/test/promise_generator_test.js +0 -251
  510. package/lib/webdriver/test/promise_test.js +0 -1981
  511. package/lib/webdriver/test/stacktrace_test.js +0 -480
  512. package/lib/webdriver/test/test_bootstrap.js +0 -67
  513. package/lib/webdriver/test/testing/asserts_test.js +0 -117
  514. package/lib/webdriver/test/testing/client_test.js +0 -88
  515. package/lib/webdriver/test/testing/testcase_test.js +0 -229
  516. package/lib/webdriver/test/testutil.js +0 -209
  517. package/lib/webdriver/test/testutil_test.js +0 -104
  518. package/lib/webdriver/test/until_test.js +0 -411
  519. package/lib/webdriver/test/webdriver_generator_test.js +0 -92
  520. package/lib/webdriver/test/webdriver_test.js +0 -2369
  521. package/lib/webdriver/testing/asserts.js +0 -487
  522. package/lib/webdriver/testing/client.js +0 -179
  523. package/lib/webdriver/testing/jsunit.js +0 -363
  524. package/lib/webdriver/testing/testcase.js +0 -168
  525. package/lib/webdriver/testing/window.js +0 -244
  526. package/lib/webdriver/touchsequence.js +0 -248
  527. package/lib/webdriver/until.js +0 -412
  528. package/lib/webdriver/webdriver.js +0 -2492
  529. package/test/_base_test.js +0 -129
package/lib/promise.js ADDED
@@ -0,0 +1,3093 @@
1
+ // Licensed to the Software Freedom Conservancy (SFC) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The SFC licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ /**
19
+ * @fileoverview
20
+ * The promise module is centered around the {@linkplain ControlFlow}, a class
21
+ * that coordinates the execution of asynchronous tasks. The ControlFlow allows
22
+ * users to focus on the imperative commands for their script without worrying
23
+ * about chaining together every single asynchronous action, which can be
24
+ * tedious and verbose. APIs may be layered on top of the control flow to read
25
+ * as if they were synchronous. For instance, the core
26
+ * {@linkplain ./webdriver.WebDriver WebDriver} API is built on top of the
27
+ * control flow, allowing users to write
28
+ *
29
+ * driver.get('http://www.google.com/ncr');
30
+ * driver.findElement({name: 'q'}).sendKeys('webdriver');
31
+ * driver.findElement({name: 'btnGn'}).click();
32
+ *
33
+ * instead of
34
+ *
35
+ * driver.get('http://www.google.com/ncr')
36
+ * .then(function() {
37
+ * return driver.findElement({name: 'q'});
38
+ * })
39
+ * .then(function(q) {
40
+ * return q.sendKeys('webdriver');
41
+ * })
42
+ * .then(function() {
43
+ * return driver.findElement({name: 'btnG'});
44
+ * })
45
+ * .then(function(btnG) {
46
+ * return btnG.click();
47
+ * });
48
+ *
49
+ * ## Tasks and Task Queues
50
+ *
51
+ * The control flow is based on the concept of tasks and task queues. Tasks are
52
+ * functions that define the basic unit of work for the control flow to execute.
53
+ * Each task is scheduled via {@link ControlFlow#execute()}, which will return
54
+ * a {@link ManagedPromise ManagedPromise} that will be resolved with the task's
55
+ * result.
56
+ *
57
+ * A task queue contains all of the tasks scheduled within a single turn of the
58
+ * [JavaScript event loop][JSEL]. The control flow will create a new task queue
59
+ * the first time a task is scheduled within an event loop.
60
+ *
61
+ * var flow = promise.controlFlow();
62
+ * flow.execute(foo); // Creates a new task queue and inserts foo.
63
+ * flow.execute(bar); // Inserts bar into the same queue as foo.
64
+ * setTimeout(function() {
65
+ * flow.execute(baz); // Creates a new task queue and inserts baz.
66
+ * }, 0);
67
+ *
68
+ * Whenever the control flow creates a new task queue, it will automatically
69
+ * begin executing tasks in the next available turn of the event loop. This
70
+ * execution is scheduled using a "micro-task" timer, such as a (native)
71
+ * `ManagedPromise.then()` callback.
72
+ *
73
+ * setTimeout(() => console.log('a'));
74
+ * ManagedPromise.resolve().then(() => console.log('b')); // A native promise.
75
+ * flow.execute(() => console.log('c'));
76
+ * ManagedPromise.resolve().then(() => console.log('d'));
77
+ * setTimeout(() => console.log('fin'));
78
+ * // b
79
+ * // c
80
+ * // d
81
+ * // a
82
+ * // fin
83
+ *
84
+ * In the example above, b/c/d is logged before a/fin because native promises
85
+ * and this module use "micro-task" timers, which have a higher priority than
86
+ * "macro-tasks" like `setTimeout`.
87
+ *
88
+ * ## Task Execution
89
+ *
90
+ * Upon creating a task queue, and whenever an exisiting queue completes a task,
91
+ * the control flow will schedule a micro-task timer to process any scheduled
92
+ * tasks. This ensures no task is ever started within the same turn of the
93
+ * JavaScript event loop in which it was scheduled, nor is a task ever started
94
+ * within the same turn that another finishes.
95
+ *
96
+ * When the execution timer fires, a single task will be dequeued and executed.
97
+ * There are several important events that may occur while executing a task
98
+ * function:
99
+ *
100
+ * 1. A new task queue is created by a call to {@link ControlFlow#execute()}.
101
+ * Any tasks scheduled within this task queue are considered subtasks of the
102
+ * current task.
103
+ * 2. The task function throws an error. Any scheduled tasks are immediately
104
+ * discarded and the task's promised result (previously returned by
105
+ * {@link ControlFlow#execute()}) is immediately rejected with the thrown
106
+ * error.
107
+ * 3. The task function returns sucessfully.
108
+ *
109
+ * If a task function created a new task queue, the control flow will wait for
110
+ * that queue to complete before processing the task result. If the queue
111
+ * completes without error, the flow will settle the task's promise with the
112
+ * value originaly returned by the task function. On the other hand, if the task
113
+ * queue termintes with an error, the task's promise will be rejected with that
114
+ * error.
115
+ *
116
+ * flow.execute(function() {
117
+ * flow.execute(() => console.log('a'));
118
+ * flow.execute(() => console.log('b'));
119
+ * });
120
+ * flow.execute(() => console.log('c'));
121
+ * // a
122
+ * // b
123
+ * // c
124
+ *
125
+ * ## ManagedPromise Integration
126
+ *
127
+ * In addition to the {@link ControlFlow} class, the promise module also exports
128
+ * a [ManagedPromise/A+] {@linkplain ManagedPromise implementation} that is deeply
129
+ * integrated with the ControlFlow. First and foremost, each promise
130
+ * {@linkplain ManagedPromise#then() callback} is scheduled with the
131
+ * control flow as a task. As a result, each callback is invoked in its own turn
132
+ * of the JavaScript event loop with its own task queue. If any tasks are
133
+ * scheduled within a callback, the callback's promised result will not be
134
+ * settled until the task queue has completed.
135
+ *
136
+ * promise.fulfilled().then(function() {
137
+ * flow.execute(function() {
138
+ * console.log('b');
139
+ * });
140
+ * }).then(() => console.log('a'));
141
+ * // b
142
+ * // a
143
+ *
144
+ * ### Scheduling ManagedPromise Callbacks <a id="scheduling_callbacks"></a>
145
+ *
146
+ * How callbacks are scheduled in the control flow depends on when they are
147
+ * attached to the promise. Callbacks attached to a _previously_ resolved
148
+ * promise are immediately enqueued as subtasks of the currently running task.
149
+ *
150
+ * var p = promise.fulfilled();
151
+ * flow.execute(function() {
152
+ * flow.execute(() => console.log('A'));
153
+ * p.then( () => console.log('B'));
154
+ * flow.execute(() => console.log('C'));
155
+ * p.then( () => console.log('D'));
156
+ * }).then(function() {
157
+ * console.log('fin');
158
+ * });
159
+ * // A
160
+ * // B
161
+ * // C
162
+ * // D
163
+ * // fin
164
+ *
165
+ * When a promise is resolved while a task function is on the call stack, any
166
+ * callbacks also registered in that stack frame are scheduled as if the promise
167
+ * were already resolved:
168
+ *
169
+ * var d = promise.defer();
170
+ * flow.execute(function() {
171
+ * flow.execute( () => console.log('A'));
172
+ * d.promise.then(() => console.log('B'));
173
+ * flow.execute( () => console.log('C'));
174
+ * d.promise.then(() => console.log('D'));
175
+ *
176
+ * d.fulfill();
177
+ * }).then(function() {
178
+ * console.log('fin');
179
+ * });
180
+ * // A
181
+ * // B
182
+ * // C
183
+ * // D
184
+ * // fin
185
+ *
186
+ * Callbacks attached to an _unresolved_ promise within a task function are
187
+ * only weakly scheduled as subtasks and will be dropped if they reach the
188
+ * front of the queue before the promise is resolved. In the example below, the
189
+ * callbacks for `B` & `D` are dropped as sub-tasks since they are attached to
190
+ * an unresolved promise when they reach the front of the task queue.
191
+ *
192
+ * var d = promise.defer();
193
+ * flow.execute(function() {
194
+ * flow.execute( () => console.log('A'));
195
+ * d.promise.then(() => console.log('B'));
196
+ * flow.execute( () => console.log('C'));
197
+ * d.promise.then(() => console.log('D'));
198
+ *
199
+ * setTimeout(d.fulfill, 20);
200
+ * }).then(function() {
201
+ * console.log('fin')
202
+ * });
203
+ * // A
204
+ * // C
205
+ * // fin
206
+ * // B
207
+ * // D
208
+ *
209
+ * If a promise is resolved while a task function is on the call stack, any
210
+ * previously registered and unqueued callbacks (i.e. either attached while no
211
+ * task was on the call stack, or previously dropped as described above) act as
212
+ * _interrupts_ and are inserted at the front of the task queue. If multiple
213
+ * promises are fulfilled, their interrupts are enqueued in the order the
214
+ * promises are resolved.
215
+ *
216
+ * var d1 = promise.defer();
217
+ * d1.promise.then(() => console.log('A'));
218
+ *
219
+ * var d2 = promise.defer();
220
+ * d2.promise.then(() => console.log('B'));
221
+ *
222
+ * flow.execute(function() {
223
+ * d1.promise.then(() => console.log('C'));
224
+ * flow.execute(() => console.log('D'));
225
+ * });
226
+ * flow.execute(function() {
227
+ * flow.execute(() => console.log('E'));
228
+ * flow.execute(() => console.log('F'));
229
+ * d1.fulfill();
230
+ * d2.fulfill();
231
+ * }).then(function() {
232
+ * console.log('fin');
233
+ * });
234
+ * // D
235
+ * // A
236
+ * // C
237
+ * // B
238
+ * // E
239
+ * // F
240
+ * // fin
241
+ *
242
+ * Within a task function (or callback), each step of a promise chain acts as
243
+ * an interrupt on the task queue:
244
+ *
245
+ * var d = promise.defer();
246
+ * flow.execute(function() {
247
+ * d.promise.
248
+ * then(() => console.log('A')).
249
+ * then(() => console.log('B')).
250
+ * then(() => console.log('C')).
251
+ * then(() => console.log('D'));
252
+ *
253
+ * flow.execute(() => console.log('E'));
254
+ * d.fulfill();
255
+ * }).then(function() {
256
+ * console.log('fin');
257
+ * });
258
+ * // A
259
+ * // B
260
+ * // C
261
+ * // D
262
+ * // E
263
+ * // fin
264
+ *
265
+ * If there are multiple promise chains derived from a single promise, they are
266
+ * processed in the order created:
267
+ *
268
+ * var d = promise.defer();
269
+ * flow.execute(function() {
270
+ * var chain = d.promise.then(() => console.log('A'));
271
+ *
272
+ * chain.then(() => console.log('B')).
273
+ * then(() => console.log('C'));
274
+ *
275
+ * chain.then(() => console.log('D')).
276
+ * then(() => console.log('E'));
277
+ *
278
+ * flow.execute(() => console.log('F'));
279
+ *
280
+ * d.fulfill();
281
+ * }).then(function() {
282
+ * console.log('fin');
283
+ * });
284
+ * // A
285
+ * // B
286
+ * // C
287
+ * // D
288
+ * // E
289
+ * // F
290
+ * // fin
291
+ *
292
+ * Even though a subtask's promised result will never resolve while the task
293
+ * function is on the stack, it will be treated as a promise resolved within the
294
+ * task. In all other scenarios, a task's promise behaves just like a normal
295
+ * promise. In the sample below, `C/D` is loggged before `B` because the
296
+ * resolution of `subtask1` interrupts the flow of the enclosing task. Within
297
+ * the final subtask, `E/F` is logged in order because `subtask1` is a resolved
298
+ * promise when that task runs.
299
+ *
300
+ * flow.execute(function() {
301
+ * var subtask1 = flow.execute(() => console.log('A'));
302
+ * var subtask2 = flow.execute(() => console.log('B'));
303
+ *
304
+ * subtask1.then(() => console.log('C'));
305
+ * subtask1.then(() => console.log('D'));
306
+ *
307
+ * flow.execute(function() {
308
+ * flow.execute(() => console.log('E'));
309
+ * subtask1.then(() => console.log('F'));
310
+ * });
311
+ * }).then(function() {
312
+ * console.log('fin');
313
+ * });
314
+ * // A
315
+ * // C
316
+ * // D
317
+ * // B
318
+ * // E
319
+ * // F
320
+ * // fin
321
+ *
322
+ * Finally, consider the following:
323
+ *
324
+ * var d = promise.defer();
325
+ * d.promise.then(() => console.log('A'));
326
+ * d.promise.then(() => console.log('B'));
327
+ *
328
+ * flow.execute(function() {
329
+ * flow.execute( () => console.log('C'));
330
+ * d.promise.then(() => console.log('D'));
331
+ *
332
+ * flow.execute( () => console.log('E'));
333
+ * d.promise.then(() => console.log('F'));
334
+ *
335
+ * d.fulfill();
336
+ *
337
+ * flow.execute( () => console.log('G'));
338
+ * d.promise.then(() => console.log('H'));
339
+ * }).then(function() {
340
+ * console.log('fin');
341
+ * });
342
+ * // A
343
+ * // B
344
+ * // C
345
+ * // D
346
+ * // E
347
+ * // F
348
+ * // G
349
+ * // H
350
+ * // fin
351
+ *
352
+ * In this example, callbacks are registered on `d.promise` both before and
353
+ * during the invocation of the task function. When `d.fulfill()` is called,
354
+ * the callbacks registered before the task (`A` & `B`) are registered as
355
+ * interrupts. The remaining callbacks were all attached within the task and
356
+ * are scheduled in the flow as standard tasks.
357
+ *
358
+ * ## Generator Support
359
+ *
360
+ * [Generators][GF] may be scheduled as tasks within a control flow or attached
361
+ * as callbacks to a promise. Each time the generator yields a promise, the
362
+ * control flow will wait for that promise to settle before executing the next
363
+ * iteration of the generator. The yielded promise's fulfilled value will be
364
+ * passed back into the generator:
365
+ *
366
+ * flow.execute(function* () {
367
+ * var d = promise.defer();
368
+ *
369
+ * setTimeout(() => console.log('...waiting...'), 25);
370
+ * setTimeout(() => d.fulfill(123), 50);
371
+ *
372
+ * console.log('start: ' + Date.now());
373
+ *
374
+ * var value = yield d.promise;
375
+ * console.log('mid: %d; value = %d', Date.now(), value);
376
+ *
377
+ * yield promise.delayed(10);
378
+ * console.log('end: ' + Date.now());
379
+ * }).then(function() {
380
+ * console.log('fin');
381
+ * });
382
+ * // start: 0
383
+ * // ...waiting...
384
+ * // mid: 50; value = 123
385
+ * // end: 60
386
+ * // fin
387
+ *
388
+ * Yielding the result of a promise chain will wait for the entire chain to
389
+ * complete:
390
+ *
391
+ * promise.fulfilled().then(function* () {
392
+ * console.log('start: ' + Date.now());
393
+ *
394
+ * var value = yield flow.
395
+ * execute(() => console.log('A')).
396
+ * then( () => console.log('B')).
397
+ * then( () => 123);
398
+ *
399
+ * console.log('mid: %s; value = %d', Date.now(), value);
400
+ *
401
+ * yield flow.execute(() => console.log('C'));
402
+ * }).then(function() {
403
+ * console.log('fin');
404
+ * });
405
+ * // start: 0
406
+ * // A
407
+ * // B
408
+ * // mid: 2; value = 123
409
+ * // C
410
+ * // fin
411
+ *
412
+ * Yielding a _rejected_ promise will cause the rejected value to be thrown
413
+ * within the generator function:
414
+ *
415
+ * flow.execute(function* () {
416
+ * console.log('start: ' + Date.now());
417
+ * try {
418
+ * yield promise.delayed(10).then(function() {
419
+ * throw Error('boom');
420
+ * });
421
+ * } catch (ex) {
422
+ * console.log('caught time: ' + Date.now());
423
+ * console.log(ex.message);
424
+ * }
425
+ * });
426
+ * // start: 0
427
+ * // caught time: 10
428
+ * // boom
429
+ *
430
+ * # Error Handling
431
+ *
432
+ * ES6 promises do not require users to handle a promise rejections. This can
433
+ * result in subtle bugs as the rejections are silently "swallowed" by the
434
+ * ManagedPromise class.
435
+ *
436
+ * ManagedPromise.reject(Error('boom'));
437
+ * // ... *crickets* ...
438
+ *
439
+ * Selenium's promise module, on the other hand, requires that every rejection
440
+ * be explicitly handled. When a {@linkplain ManagedPromise ManagedPromise} is
441
+ * rejected and no callbacks are defined on that promise, it is considered an
442
+ * _unhandled rejection_ and reproted to the active task queue. If the rejection
443
+ * remains unhandled after a single turn of the [event loop][JSEL] (scheduled
444
+ * with a micro-task), it will propagate up the stack.
445
+ *
446
+ * ## Error Propagation
447
+ *
448
+ * If an unhandled rejection occurs within a task function, that task's promised
449
+ * result is rejected and all remaining subtasks are discarded:
450
+ *
451
+ * flow.execute(function() {
452
+ * // No callbacks registered on promise -> unhandled rejection
453
+ * promise.rejected(Error('boom'));
454
+ * flow.execute(function() { console.log('this will never run'); });
455
+ * }).catch(function(e) {
456
+ * console.log(e.message);
457
+ * });
458
+ * // boom
459
+ *
460
+ * The promised results for discarded tasks are silently rejected with a
461
+ * cancellation error and existing callback chains will never fire.
462
+ *
463
+ * flow.execute(function() {
464
+ * promise.rejected(Error('boom'));
465
+ * flow.execute(function() { console.log('a'); }).
466
+ * then(function() { console.log('b'); });
467
+ * }).catch(function(e) {
468
+ * console.log(e.message);
469
+ * });
470
+ * // boom
471
+ *
472
+ * An unhandled rejection takes precedence over a task function's returned
473
+ * result, even if that value is another promise:
474
+ *
475
+ * flow.execute(function() {
476
+ * promise.rejected(Error('boom'));
477
+ * return flow.execute(someOtherTask);
478
+ * }).catch(function(e) {
479
+ * console.log(e.message);
480
+ * });
481
+ * // boom
482
+ *
483
+ * If there are multiple unhandled rejections within a task, they are packaged
484
+ * in a {@link MultipleUnhandledRejectionError}, which has an `errors` property
485
+ * that is a `Set` of the recorded unhandled rejections:
486
+ *
487
+ * flow.execute(function() {
488
+ * promise.rejected(Error('boom1'));
489
+ * promise.rejected(Error('boom2'));
490
+ * }).catch(function(ex) {
491
+ * console.log(ex instanceof MultipleUnhandledRejectionError);
492
+ * for (var e of ex.errors) {
493
+ * console.log(e.message);
494
+ * }
495
+ * });
496
+ * // boom1
497
+ * // boom2
498
+ *
499
+ * When a subtask is discarded due to an unreported rejection in its parent
500
+ * frame, the existing callbacks on that task will never settle and the
501
+ * callbacks will not be invoked. If a new callback is attached ot the subtask
502
+ * _after_ it has been discarded, it is handled the same as adding a callback
503
+ * to a cancelled promise: the error-callback path is invoked. This behavior is
504
+ * intended to handle cases where the user saves a reference to a task promise,
505
+ * as illustrated below.
506
+ *
507
+ * var subTask;
508
+ * flow.execute(function() {
509
+ * promise.rejected(Error('boom'));
510
+ * subTask = flow.execute(function() {});
511
+ * }).catch(function(e) {
512
+ * console.log(e.message);
513
+ * }).then(function() {
514
+ * return subTask.then(
515
+ * () => console.log('subtask success!'),
516
+ * (e) => console.log('subtask failed:\n' + e));
517
+ * });
518
+ * // boom
519
+ * // subtask failed:
520
+ * // DiscardedTaskError: Task was discarded due to a previous failure: boom
521
+ *
522
+ * When a subtask fails, its promised result is treated the same as any other
523
+ * promise: it must be handled within one turn of the rejection or the unhandled
524
+ * rejection is propagated to the parent task. This means users can catch errors
525
+ * from complex flows from the top level task:
526
+ *
527
+ * flow.execute(function() {
528
+ * flow.execute(function() {
529
+ * flow.execute(function() {
530
+ * throw Error('fail!');
531
+ * });
532
+ * });
533
+ * }).catch(function(e) {
534
+ * console.log(e.message);
535
+ * });
536
+ * // fail!
537
+ *
538
+ * ## Unhandled Rejection Events
539
+ *
540
+ * When an unhandled rejection propagates to the root of the control flow, the
541
+ * flow will emit an __uncaughtException__ event. If no listeners are registered
542
+ * on the flow, the error will be rethrown to the global error handler: an
543
+ * __uncaughtException__ event from the
544
+ * [`process`](https://nodejs.org/api/process.html) object in node, or
545
+ * `window.onerror` when running in a browser.
546
+ *
547
+ * Bottom line: you __*must*__ handle rejected promises.
548
+ *
549
+ * # ManagedPromise/A+ Compatibility
550
+ *
551
+ * This `promise` module is compliant with the [ManagedPromise/A+][] specification
552
+ * except for sections `2.2.6.1` and `2.2.6.2`:
553
+ *
554
+ * >
555
+ * > - `then` may be called multiple times on the same promise.
556
+ * > - If/when `promise` is fulfilled, all respective `onFulfilled` callbacks
557
+ * > must execute in the order of their originating calls to `then`.
558
+ * > - If/when `promise` is rejected, all respective `onRejected` callbacks
559
+ * > must execute in the order of their originating calls to `then`.
560
+ * >
561
+ *
562
+ * Specifically, the conformance tests contains the following scenario (for
563
+ * brevity, only the fulfillment version is shown):
564
+ *
565
+ * var p1 = ManagedPromise.resolve();
566
+ * p1.then(function() {
567
+ * console.log('A');
568
+ * p1.then(() => console.log('B'));
569
+ * });
570
+ * p1.then(() => console.log('C'));
571
+ * // A
572
+ * // C
573
+ * // B
574
+ *
575
+ * Since the [ControlFlow](#scheduling_callbacks) executes promise callbacks as
576
+ * tasks, with this module, the result would be
577
+ *
578
+ * var p2 = promise.fulfilled();
579
+ * p2.then(function() {
580
+ * console.log('A');
581
+ * p2.then(() => console.log('B');
582
+ * });
583
+ * p2.then(() => console.log('C'));
584
+ * // A
585
+ * // B
586
+ * // C
587
+ *
588
+ * [JSEL]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
589
+ * [GF]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
590
+ * [ManagedPromise/A+]: https://promisesaplus.com/
591
+ */
592
+
593
+ 'use strict';
594
+
595
+ const events = require('./events');
596
+ const logging = require('./logging');
597
+
598
+
599
+ /**
600
+ * Alias to help with readability and differentiate types.
601
+ * @const
602
+ */
603
+ const NativePromise = Promise;
604
+
605
+
606
+ /**
607
+ * Whether to append traces of `then` to rejection errors.
608
+ * @type {boolean}
609
+ */
610
+ exports.LONG_STACK_TRACES = false; // TODO: this should not be CONSTANT_CASE
611
+
612
+
613
+ /** @const */
614
+ const LOG = logging.getLogger('promise');
615
+
616
+
617
+ const UNIQUE_IDS = new WeakMap;
618
+ let nextId = 1;
619
+
620
+
621
+ function getUid(obj) {
622
+ let id = UNIQUE_IDS.get(obj);
623
+ if (!id) {
624
+ id = nextId;
625
+ nextId += 1;
626
+ UNIQUE_IDS.set(obj, id);
627
+ }
628
+ return id;
629
+ }
630
+
631
+
632
+ /**
633
+ * Runs the given function after a micro-task yield.
634
+ * @param {function()} fn The function to run.
635
+ */
636
+ function asyncRun(fn) {
637
+ NativePromise.resolve().then(function() {
638
+ try {
639
+ fn();
640
+ } catch (ignored) {
641
+ // Do nothing.
642
+ }
643
+ });
644
+ }
645
+
646
+
647
+ /**
648
+ * Throws an error asynchronously so it is reported to the global error handler.
649
+ *
650
+ * @param {!Error} error The error to throw.
651
+ */
652
+ function asyncThrow(error) {
653
+ setTimeout(function() {
654
+ throw error;
655
+ }, 0);
656
+ }
657
+
658
+
659
+ /**
660
+ * @param {number} level What level of verbosity to log with.
661
+ * @param {(string|function(this: T): string)} loggable The message to log.
662
+ * @param {T=} opt_self The object in whose context to run the loggable
663
+ * function.
664
+ * @template T
665
+ */
666
+ function vlog(level, loggable, opt_self) {
667
+ var logLevel = logging.Level.FINE;
668
+ if (level > 1) {
669
+ logLevel = logging.Level.FINEST;
670
+ } else if (level > 0) {
671
+ logLevel = logging.Level.FINER;
672
+ }
673
+
674
+ if (typeof loggable === 'function') {
675
+ loggable = loggable.bind(opt_self);
676
+ }
677
+
678
+ LOG.log(logLevel, loggable);
679
+ }
680
+
681
+
682
+ /**
683
+ * Generates an error to capture the current stack trace.
684
+ * @param {string} name Error name for this stack trace.
685
+ * @param {string} msg Message to record.
686
+ * @param {Function=} opt_topFn The function that should appear at the top of
687
+ * the stack; only applicable in V8.
688
+ * @return {!Error} The generated error.
689
+ */
690
+ function captureStackTrace(name, msg, opt_topFn) {
691
+ var e = Error(msg);
692
+ e.name = name;
693
+ if (Error.captureStackTrace) {
694
+ Error.captureStackTrace(e, opt_topFn);
695
+ } else {
696
+ var stack = Error().stack;
697
+ if (stack) {
698
+ e.stack = e.toString();
699
+ e.stack += '\n' + stack;
700
+ }
701
+ }
702
+ return e;
703
+ }
704
+
705
+
706
+ /**
707
+ * Error used when the computation of a promise is cancelled.
708
+ */
709
+ class CancellationError extends Error {
710
+ /**
711
+ * @param {string=} opt_msg The cancellation message.
712
+ */
713
+ constructor(opt_msg) {
714
+ super(opt_msg);
715
+
716
+ /** @override */
717
+ this.name = this.constructor.name;
718
+
719
+ /** @private {boolean} */
720
+ this.silent_ = false;
721
+ }
722
+
723
+ /**
724
+ * Wraps the given error in a CancellationError.
725
+ *
726
+ * @param {*} error The error to wrap.
727
+ * @param {string=} opt_msg The prefix message to use.
728
+ * @return {!CancellationError} A cancellation error.
729
+ */
730
+ static wrap(error, opt_msg) {
731
+ var message;
732
+ if (error instanceof CancellationError) {
733
+ return new CancellationError(
734
+ opt_msg ? (opt_msg + ': ' + error.message) : error.message);
735
+ } else if (opt_msg) {
736
+ message = opt_msg;
737
+ if (error) {
738
+ message += ': ' + error;
739
+ }
740
+ return new CancellationError(message);
741
+ }
742
+ if (error) {
743
+ message = error + '';
744
+ }
745
+ return new CancellationError(message);
746
+ }
747
+ }
748
+
749
+
750
+ /**
751
+ * Error used to cancel tasks when a control flow is reset.
752
+ * @final
753
+ */
754
+ class FlowResetError extends CancellationError {
755
+ constructor() {
756
+ super('ControlFlow was reset');
757
+ this.silent_ = true;
758
+ }
759
+ }
760
+
761
+
762
+ /**
763
+ * Error used to cancel tasks that have been discarded due to an uncaught error
764
+ * reported earlier in the control flow.
765
+ * @final
766
+ */
767
+ class DiscardedTaskError extends CancellationError {
768
+ /** @param {*} error The original error. */
769
+ constructor(error) {
770
+ if (error instanceof DiscardedTaskError) {
771
+ return /** @type {!DiscardedTaskError} */(error);
772
+ }
773
+
774
+ var msg = '';
775
+ if (error) {
776
+ msg = ': ' + (
777
+ typeof error.message === 'string' ? error.message : error);
778
+ }
779
+
780
+ super('Task was discarded due to a previous failure' + msg);
781
+ this.silent_ = true;
782
+ }
783
+ }
784
+
785
+
786
+ /**
787
+ * Error used when there are multiple unhandled promise rejections detected
788
+ * within a task or callback.
789
+ *
790
+ * @final
791
+ */
792
+ class MultipleUnhandledRejectionError extends Error {
793
+ /**
794
+ * @param {!(Set<*>)} errors The errors to report.
795
+ */
796
+ constructor(errors) {
797
+ super('Multiple unhandled promise rejections reported');
798
+
799
+ /** @override */
800
+ this.name = this.constructor.name;
801
+
802
+ /** @type {!Set<*>} */
803
+ this.errors = errors;
804
+ }
805
+ }
806
+
807
+
808
+ /**
809
+ * Property used to flag constructor's as implementing the Thenable interface
810
+ * for runtime type checking.
811
+ * @const
812
+ */
813
+ const IMPLEMENTED_BY_SYMBOL = Symbol('promise.Thenable');
814
+
815
+
816
+ /**
817
+ * Thenable is a promise-like object with a {@code then} method which may be
818
+ * used to schedule callbacks on a promised value.
819
+ *
820
+ * @interface
821
+ * @extends {IThenable<T>}
822
+ * @template T
823
+ */
824
+ class Thenable {
825
+ /**
826
+ * Adds a property to a class prototype to allow runtime checks of whether
827
+ * instances of that class implement the Thenable interface. This function
828
+ * will also ensure the prototype's {@code then} function is exported from
829
+ * compiled code.
830
+ * @param {function(new: Thenable, ...?)} ctor The
831
+ * constructor whose prototype to modify.
832
+ */
833
+ static addImplementation(ctor) {
834
+ ctor.prototype['then'] = ctor.prototype.then;
835
+ try {
836
+ ctor.prototype[IMPLEMENTED_BY_SYMBOL] = true;
837
+ } catch (ignored) {
838
+ // Property access denied?
839
+ }
840
+ }
841
+
842
+ /**
843
+ * Checks if an object has been tagged for implementing the Thenable
844
+ * interface as defined by {@link Thenable.addImplementation}.
845
+ * @param {*} object The object to test.
846
+ * @return {boolean} Whether the object is an implementation of the Thenable
847
+ * interface.
848
+ */
849
+ static isImplementation(object) {
850
+ if (!object) {
851
+ return false;
852
+ }
853
+ try {
854
+ return !!object[IMPLEMENTED_BY_SYMBOL];
855
+ } catch (e) {
856
+ return false; // Property access seems to be forbidden.
857
+ }
858
+ }
859
+
860
+ /**
861
+ * Cancels the computation of this promise's value, rejecting the promise in
862
+ * the process. This method is a no-op if the promise has already been
863
+ * resolved.
864
+ *
865
+ * @param {(string|Error)=} opt_reason The reason this promise is being
866
+ * cancelled. This value will be wrapped in a {@link CancellationError}.
867
+ */
868
+ cancel(opt_reason) {}
869
+
870
+ /** @return {boolean} Whether this promise's value is still being computed. */
871
+ isPending() {}
872
+
873
+ /**
874
+ * Registers listeners for when this instance is resolved.
875
+ *
876
+ * @param {?(function(T): (R|IThenable<R>))=} opt_callback The
877
+ * function to call if this promise is successfully resolved. The function
878
+ * should expect a single argument: the promise's resolved value.
879
+ * @param {?(function(*): (R|IThenable<R>))=} opt_errback
880
+ * The function to call if this promise is rejected. The function should
881
+ * expect a single argument: the rejection reason.
882
+ * @return {!ManagedPromise<R>} A new promise which will be
883
+ * resolved with the result of the invoked callback.
884
+ * @template R
885
+ */
886
+ then(opt_callback, opt_errback) {}
887
+
888
+ /**
889
+ * Registers a listener for when this promise is rejected. This is synonymous
890
+ * with the {@code catch} clause in a synchronous API:
891
+ *
892
+ * // Synchronous API:
893
+ * try {
894
+ * doSynchronousWork();
895
+ * } catch (ex) {
896
+ * console.error(ex);
897
+ * }
898
+ *
899
+ * // Asynchronous promise API:
900
+ * doAsynchronousWork().catch(function(ex) {
901
+ * console.error(ex);
902
+ * });
903
+ *
904
+ * @param {function(*): (R|IThenable<R>)} errback The
905
+ * function to call if this promise is rejected. The function should
906
+ * expect a single argument: the rejection reason.
907
+ * @return {!ManagedPromise<R>} A new promise which will be
908
+ * resolved with the result of the invoked callback.
909
+ * @template R
910
+ */
911
+ catch(errback) {}
912
+
913
+ /**
914
+ * An alias for {@link #catch()}
915
+ *
916
+ * @param {function(*): (R|IThenable<R>)} errback The
917
+ * function to call if this promise is rejected. The function should
918
+ * expect a single argument: the rejection reason.
919
+ * @return {!ManagedPromise<R>} A new promise which will be
920
+ * resolved wdith the result of the invoked callback.
921
+ * @template R
922
+ */
923
+ thenCatch(errback) {}
924
+
925
+ /**
926
+ * Registers a listener to invoke when this promise is resolved, regardless
927
+ * of whether the promise's value was successfully computed. This function
928
+ * is synonymous with the {@code finally} clause in a synchronous API:
929
+ *
930
+ * // Synchronous API:
931
+ * try {
932
+ * doSynchronousWork();
933
+ * } finally {
934
+ * cleanUp();
935
+ * }
936
+ *
937
+ * // Asynchronous promise API:
938
+ * doAsynchronousWork().thenFinally(cleanUp);
939
+ *
940
+ * __Note:__ similar to the {@code finally} clause, if the registered
941
+ * callback returns a rejected promise or throws an error, it will silently
942
+ * replace the rejection error (if any) from this promise:
943
+ *
944
+ * try {
945
+ * throw Error('one');
946
+ * } finally {
947
+ * throw Error('two'); // Hides Error: one
948
+ * }
949
+ *
950
+ * promise.rejected(Error('one'))
951
+ * .thenFinally(function() {
952
+ * throw Error('two'); // Hides Error: one
953
+ * });
954
+ *
955
+ * @param {function(): (R|IThenable<R>)} callback The function
956
+ * to call when this promise is resolved.
957
+ * @return {!ManagedPromise<R>} A promise that will be fulfilled
958
+ * with the callback result.
959
+ * @template R
960
+ */
961
+ thenFinally(callback) {}
962
+ }
963
+
964
+
965
+ /**
966
+ * @enum {string}
967
+ */
968
+ const PromiseState = {
969
+ PENDING: 'pending',
970
+ BLOCKED: 'blocked',
971
+ REJECTED: 'rejected',
972
+ FULFILLED: 'fulfilled'
973
+ };
974
+
975
+
976
+ /**
977
+ * Internal symbol used to store a cancellation handler for
978
+ * {@link ManagedPromise} objects. This is an internal implementation detail
979
+ * used by the {@link TaskQueue} class to monitor for when a promise is
980
+ * cancelled without generating an extra promise via then().
981
+ */
982
+ const CANCEL_HANDLER_SYMBOL = Symbol('on cancel');
983
+
984
+
985
+ /**
986
+ * Represents the eventual value of a completed operation. Each promise may be
987
+ * in one of three states: pending, fulfilled, or rejected. Each promise starts
988
+ * in the pending state and may make a single transition to either a
989
+ * fulfilled or rejected state, at which point the promise is considered
990
+ * resolved.
991
+ *
992
+ * @implements {Thenable<T>}
993
+ * @unrestricted
994
+ * @template T
995
+ * @see http://promises-aplus.github.io/promises-spec/
996
+ */
997
+ const ManagedPromise = class Promise {
998
+ /**
999
+ * @param {function(
1000
+ * function((T|IThenable<T>|Thenable)=),
1001
+ * function(*=))} resolver
1002
+ * Function that is invoked immediately to begin computation of this
1003
+ * promise's value. The function should accept a pair of callback
1004
+ * functions, one for fulfilling the promise and another for rejecting it.
1005
+ * @param {ControlFlow=} opt_flow The control flow
1006
+ * this instance was created under. Defaults to the currently active flow.
1007
+ */
1008
+ constructor(resolver, opt_flow) {
1009
+ getUid(this);
1010
+
1011
+ /** @private {!ControlFlow} */
1012
+ this.flow_ = opt_flow || controlFlow();
1013
+
1014
+ /** @private {Error} */
1015
+ this.stack_ = null;
1016
+ if (exports.LONG_STACK_TRACES) {
1017
+ this.stack_ = captureStackTrace('Promise', 'new', this.constructor);
1018
+ }
1019
+
1020
+ /** @private {ManagedPromise<?>} */
1021
+ this.parent_ = null;
1022
+
1023
+ /** @private {Array<!Task>} */
1024
+ this.callbacks_ = null;
1025
+
1026
+ /** @private {PromiseState} */
1027
+ this.state_ = PromiseState.PENDING;
1028
+
1029
+ /** @private {boolean} */
1030
+ this.handled_ = false;
1031
+
1032
+ /** @private {*} */
1033
+ this.value_ = undefined;
1034
+
1035
+ /** @private {TaskQueue} */
1036
+ this.queue_ = null;
1037
+
1038
+ /** @private {(function(CancellationError)|null)} */
1039
+ this[CANCEL_HANDLER_SYMBOL] = null;
1040
+
1041
+ try {
1042
+ var self = this;
1043
+ resolver(function(value) {
1044
+ self.resolve_(PromiseState.FULFILLED, value);
1045
+ }, function(reason) {
1046
+ self.resolve_(PromiseState.REJECTED, reason);
1047
+ });
1048
+ } catch (ex) {
1049
+ this.resolve_(PromiseState.REJECTED, ex);
1050
+ }
1051
+ }
1052
+
1053
+ /** @override */
1054
+ toString() {
1055
+ return 'ManagedPromise::' + getUid(this) +
1056
+ ' {[[PromiseStatus]]: "' + this.state_ + '"}';
1057
+ }
1058
+
1059
+ /**
1060
+ * Resolves this promise. If the new value is itself a promise, this function
1061
+ * will wait for it to be resolved before notifying the registered listeners.
1062
+ * @param {PromiseState} newState The promise's new state.
1063
+ * @param {*} newValue The promise's new value.
1064
+ * @throws {TypeError} If {@code newValue === this}.
1065
+ * @private
1066
+ */
1067
+ resolve_(newState, newValue) {
1068
+ if (PromiseState.PENDING !== this.state_) {
1069
+ return;
1070
+ }
1071
+
1072
+ if (newValue === this) {
1073
+ // See promise a+, 2.3.1
1074
+ // http://promises-aplus.github.io/promises-spec/#point-48
1075
+ newValue = new TypeError('A promise may not resolve to itself');
1076
+ newState = PromiseState.REJECTED;
1077
+ }
1078
+
1079
+ this.parent_ = null;
1080
+ this.state_ = PromiseState.BLOCKED;
1081
+
1082
+ if (newState !== PromiseState.REJECTED) {
1083
+ if (Thenable.isImplementation(newValue)) {
1084
+ // 2.3.2
1085
+ newValue = /** @type {!Thenable} */(newValue);
1086
+ newValue.then(
1087
+ this.unblockAndResolve_.bind(this, PromiseState.FULFILLED),
1088
+ this.unblockAndResolve_.bind(this, PromiseState.REJECTED));
1089
+ return;
1090
+
1091
+ } else if (newValue
1092
+ && (typeof newValue === 'object' || typeof newValue === 'function')) {
1093
+ // 2.3.3
1094
+
1095
+ try {
1096
+ // 2.3.3.1
1097
+ var then = newValue['then'];
1098
+ } catch (e) {
1099
+ // 2.3.3.2
1100
+ this.state_ = PromiseState.REJECTED;
1101
+ this.value_ = e;
1102
+ this.scheduleNotifications_();
1103
+ return;
1104
+ }
1105
+
1106
+ if (typeof then === 'function') {
1107
+ // 2.3.3.3
1108
+ this.invokeThen_(/** @type {!Object} */(newValue), then);
1109
+ return;
1110
+ }
1111
+ }
1112
+ }
1113
+
1114
+ if (newState === PromiseState.REJECTED &&
1115
+ isError(newValue) && newValue.stack && this.stack_) {
1116
+ newValue.stack += '\nFrom: ' + (this.stack_.stack || this.stack_);
1117
+ }
1118
+
1119
+ // 2.3.3.4 and 2.3.4
1120
+ this.state_ = newState;
1121
+ this.value_ = newValue;
1122
+ this.scheduleNotifications_();
1123
+ }
1124
+
1125
+ /**
1126
+ * Invokes a thenable's "then" method according to 2.3.3.3 of the promise
1127
+ * A+ spec.
1128
+ * @param {!Object} x The thenable object.
1129
+ * @param {!Function} then The "then" function to invoke.
1130
+ * @private
1131
+ */
1132
+ invokeThen_(x, then) {
1133
+ var called = false;
1134
+ var self = this;
1135
+
1136
+ var resolvePromise = function(value) {
1137
+ if (!called) { // 2.3.3.3.3
1138
+ called = true;
1139
+ // 2.3.3.3.1
1140
+ self.unblockAndResolve_(PromiseState.FULFILLED, value);
1141
+ }
1142
+ };
1143
+
1144
+ var rejectPromise = function(reason) {
1145
+ if (!called) { // 2.3.3.3.3
1146
+ called = true;
1147
+ // 2.3.3.3.2
1148
+ self.unblockAndResolve_(PromiseState.REJECTED, reason);
1149
+ }
1150
+ };
1151
+
1152
+ try {
1153
+ // 2.3.3.3
1154
+ then.call(x, resolvePromise, rejectPromise);
1155
+ } catch (e) {
1156
+ // 2.3.3.3.4.2
1157
+ rejectPromise(e);
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * @param {PromiseState} newState The promise's new state.
1163
+ * @param {*} newValue The promise's new value.
1164
+ * @private
1165
+ */
1166
+ unblockAndResolve_(newState, newValue) {
1167
+ if (this.state_ === PromiseState.BLOCKED) {
1168
+ this.state_ = PromiseState.PENDING;
1169
+ this.resolve_(newState, newValue);
1170
+ }
1171
+ }
1172
+
1173
+ /**
1174
+ * @private
1175
+ */
1176
+ scheduleNotifications_() {
1177
+ vlog(2, () => this + ' scheduling notifications', this);
1178
+
1179
+ this[CANCEL_HANDLER_SYMBOL] = null;
1180
+ if (this.value_ instanceof CancellationError
1181
+ && this.value_.silent_) {
1182
+ this.callbacks_ = null;
1183
+ }
1184
+
1185
+ if (!this.queue_) {
1186
+ this.queue_ = this.flow_.getActiveQueue_();
1187
+ }
1188
+
1189
+ if (!this.handled_ &&
1190
+ this.state_ === PromiseState.REJECTED &&
1191
+ !(this.value_ instanceof CancellationError)) {
1192
+ this.queue_.addUnhandledRejection(this);
1193
+ }
1194
+ this.queue_.scheduleCallbacks(this);
1195
+ }
1196
+
1197
+ /** @override */
1198
+ cancel(opt_reason) {
1199
+ if (!canCancel(this)) {
1200
+ return;
1201
+ }
1202
+
1203
+ if (this.parent_ && canCancel(this.parent_)) {
1204
+ this.parent_.cancel(opt_reason);
1205
+ } else {
1206
+ var reason = CancellationError.wrap(opt_reason);
1207
+ if (this[CANCEL_HANDLER_SYMBOL]) {
1208
+ this[CANCEL_HANDLER_SYMBOL](reason);
1209
+ this[CANCEL_HANDLER_SYMBOL] = null;
1210
+ }
1211
+
1212
+ if (this.state_ === PromiseState.BLOCKED) {
1213
+ this.unblockAndResolve_(PromiseState.REJECTED, reason);
1214
+ } else {
1215
+ this.resolve_(PromiseState.REJECTED, reason);
1216
+ }
1217
+ }
1218
+
1219
+ function canCancel(promise) {
1220
+ return promise.state_ === PromiseState.PENDING
1221
+ || promise.state_ === PromiseState.BLOCKED;
1222
+ }
1223
+ }
1224
+
1225
+ /** @override */
1226
+ isPending() {
1227
+ return this.state_ === PromiseState.PENDING;
1228
+ }
1229
+
1230
+ /** @override */
1231
+ then(opt_callback, opt_errback) {
1232
+ return this.addCallback_(
1233
+ opt_callback, opt_errback, 'then', ManagedPromise.prototype.then);
1234
+ }
1235
+
1236
+ /** @override */
1237
+ catch(errback) {
1238
+ return this.addCallback_(
1239
+ null, errback, 'catch', ManagedPromise.prototype.catch);
1240
+ }
1241
+
1242
+ /** @override */
1243
+ thenCatch(errback) {
1244
+ return this.catch(errback);
1245
+ }
1246
+
1247
+ /** @override */
1248
+ thenFinally(callback) {
1249
+ var error;
1250
+ var mustThrow = false;
1251
+ return this.then(function() {
1252
+ return callback();
1253
+ }, function(err) {
1254
+ error = err;
1255
+ mustThrow = true;
1256
+ return callback();
1257
+ }).then(function() {
1258
+ if (mustThrow) {
1259
+ throw error;
1260
+ }
1261
+ });
1262
+ }
1263
+
1264
+ /**
1265
+ * Registers a new callback with this promise
1266
+ * @param {(function(T): (R|IThenable<R>)|null|undefined)} callback The
1267
+ * fulfillment callback.
1268
+ * @param {(function(*): (R|IThenable<R>)|null|undefined)} errback The
1269
+ * rejection callback.
1270
+ * @param {string} name The callback name.
1271
+ * @param {!Function} fn The function to use as the top of the stack when
1272
+ * recording the callback's creation point.
1273
+ * @return {!ManagedPromise<R>} A new promise which will be resolved with the
1274
+ * esult of the invoked callback.
1275
+ * @template R
1276
+ * @private
1277
+ */
1278
+ addCallback_(callback, errback, name, fn) {
1279
+ if (typeof callback !== 'function' && typeof errback !== 'function') {
1280
+ return this;
1281
+ }
1282
+
1283
+ this.handled_ = true;
1284
+ if (this.queue_) {
1285
+ this.queue_.clearUnhandledRejection(this);
1286
+ }
1287
+
1288
+ var cb = new Task(
1289
+ this.flow_,
1290
+ this.invokeCallback_.bind(this, callback, errback),
1291
+ name,
1292
+ exports.LONG_STACK_TRACES ? {name: 'Promise', top: fn} : undefined);
1293
+ cb.promise.parent_ = this;
1294
+
1295
+ if (this.state_ !== PromiseState.PENDING &&
1296
+ this.state_ !== PromiseState.BLOCKED) {
1297
+ this.flow_.getActiveQueue_().enqueue(cb);
1298
+ } else {
1299
+ if (!this.callbacks_) {
1300
+ this.callbacks_ = [];
1301
+ }
1302
+ this.callbacks_.push(cb);
1303
+ cb.blocked = true;
1304
+ this.flow_.getActiveQueue_().enqueue(cb);
1305
+ }
1306
+
1307
+ return cb.promise;
1308
+ }
1309
+
1310
+ /**
1311
+ * Invokes a callback function attached to this promise.
1312
+ * @param {(function(T): (R|IThenable<R>)|null|undefined)} callback The
1313
+ * fulfillment callback.
1314
+ * @param {(function(*): (R|IThenable<R>)|null|undefined)} errback The
1315
+ * rejection callback.
1316
+ * @template R
1317
+ * @private
1318
+ */
1319
+ invokeCallback_(callback, errback) {
1320
+ var callbackFn = callback;
1321
+ if (this.state_ === PromiseState.REJECTED) {
1322
+ callbackFn = errback;
1323
+ }
1324
+
1325
+ if (typeof callbackFn === 'function') {
1326
+ if (isGenerator(callbackFn)) {
1327
+ return consume(callbackFn, null, this.value_);
1328
+ }
1329
+ return callbackFn(this.value_);
1330
+ } else if (this.state_ === PromiseState.REJECTED) {
1331
+ throw this.value_;
1332
+ } else {
1333
+ return this.value_;
1334
+ }
1335
+ }
1336
+ }
1337
+ Thenable.addImplementation(ManagedPromise);
1338
+
1339
+
1340
+ /**
1341
+ * Represents a value that will be resolved at some point in the future. This
1342
+ * class represents the protected "producer" half of a ManagedPromise - each Deferred
1343
+ * has a {@code promise} property that may be returned to consumers for
1344
+ * registering callbacks, reserving the ability to resolve the deferred to the
1345
+ * producer.
1346
+ *
1347
+ * If this Deferred is rejected and there are no listeners registered before
1348
+ * the next turn of the event loop, the rejection will be passed to the
1349
+ * {@link ControlFlow} as an unhandled failure.
1350
+ *
1351
+ * @implements {Thenable<T>}
1352
+ * @template T
1353
+ */
1354
+ class Deferred {
1355
+ /**
1356
+ * @param {ControlFlow=} opt_flow The control flow this instance was
1357
+ * created under. This should only be provided during unit tests.
1358
+ */
1359
+ constructor(opt_flow) {
1360
+ var fulfill, reject;
1361
+
1362
+ /** @type {!ManagedPromise<T>} */
1363
+ this.promise = new ManagedPromise(function(f, r) {
1364
+ fulfill = f;
1365
+ reject = r;
1366
+ }, opt_flow);
1367
+
1368
+ var self = this;
1369
+ var checkNotSelf = function(value) {
1370
+ if (value === self) {
1371
+ throw new TypeError('May not resolve a Deferred with itself');
1372
+ }
1373
+ };
1374
+
1375
+ /**
1376
+ * Resolves this deferred with the given value. It is safe to call this as a
1377
+ * normal function (with no bound "this").
1378
+ * @param {(T|IThenable<T>|Thenable)=} opt_value The fulfilled value.
1379
+ */
1380
+ this.fulfill = function(opt_value) {
1381
+ checkNotSelf(opt_value);
1382
+ fulfill(opt_value);
1383
+ };
1384
+
1385
+ /**
1386
+ * Rejects this promise with the given reason. It is safe to call this as a
1387
+ * normal function (with no bound "this").
1388
+ * @param {*=} opt_reason The rejection reason.
1389
+ */
1390
+ this.reject = function(opt_reason) {
1391
+ checkNotSelf(opt_reason);
1392
+ reject(opt_reason);
1393
+ };
1394
+ }
1395
+
1396
+ /** @override */
1397
+ isPending() {
1398
+ return this.promise.isPending();
1399
+ }
1400
+
1401
+ /** @override */
1402
+ cancel(opt_reason) {
1403
+ this.promise.cancel(opt_reason);
1404
+ }
1405
+
1406
+ /**
1407
+ * @override
1408
+ * @deprecated Use {@code then} from the promise property directly.
1409
+ */
1410
+ then(opt_cb, opt_eb) {
1411
+ return this.promise.then(opt_cb, opt_eb);
1412
+ }
1413
+
1414
+ /**
1415
+ * @override
1416
+ * @deprecated Use {@lcode catch} from the promise property directly.
1417
+ */
1418
+ catch(opt_eb) {
1419
+ return this.promise.catch(opt_eb);
1420
+ }
1421
+
1422
+ /**
1423
+ * @override
1424
+ * @deprecated Use {@code thenCatch} from the promise property directly.
1425
+ */
1426
+ thenCatch(opt_eb) {
1427
+ return this.promise.thenCatch(opt_eb);
1428
+ }
1429
+
1430
+ /**
1431
+ * @override
1432
+ * @deprecated Use {@code thenFinally} from the promise property directly.
1433
+ */
1434
+ thenFinally(opt_cb) {
1435
+ return this.promise.thenFinally(opt_cb);
1436
+ }
1437
+ }
1438
+ Thenable.addImplementation(Deferred);
1439
+
1440
+
1441
+ /**
1442
+ * Tests if a value is an Error-like object. This is more than an straight
1443
+ * instanceof check since the value may originate from another context.
1444
+ * @param {*} value The value to test.
1445
+ * @return {boolean} Whether the value is an error.
1446
+ */
1447
+ function isError(value) {
1448
+ return value instanceof Error ||
1449
+ (!!value && typeof value === 'object'
1450
+ && typeof value.message === 'string');
1451
+ }
1452
+
1453
+
1454
+ /**
1455
+ * Determines whether a {@code value} should be treated as a promise.
1456
+ * Any object whose "then" property is a function will be considered a promise.
1457
+ *
1458
+ * @param {?} value The value to test.
1459
+ * @return {boolean} Whether the value is a promise.
1460
+ */
1461
+ function isPromise(value) {
1462
+ try {
1463
+ // Use array notation so the Closure compiler does not obfuscate away our
1464
+ // contract.
1465
+ return value
1466
+ && (typeof value === 'object' || typeof value === 'function')
1467
+ && typeof value['then'] === 'function';
1468
+ } catch (ex) {
1469
+ return false;
1470
+ }
1471
+ }
1472
+
1473
+
1474
+ /**
1475
+ * Creates a promise that will be resolved at a set time in the future.
1476
+ * @param {number} ms The amount of time, in milliseconds, to wait before
1477
+ * resolving the promise.
1478
+ * @return {!ManagedPromise} The promise.
1479
+ */
1480
+ function delayed(ms) {
1481
+ var key;
1482
+ return new ManagedPromise(function(fulfill) {
1483
+ key = setTimeout(function() {
1484
+ key = null;
1485
+ fulfill();
1486
+ }, ms);
1487
+ }).catch(function(e) {
1488
+ clearTimeout(key);
1489
+ key = null;
1490
+ throw e;
1491
+ });
1492
+ }
1493
+
1494
+
1495
+ /**
1496
+ * Creates a new deferred object.
1497
+ * @return {!Deferred<T>} The new deferred object.
1498
+ * @template T
1499
+ */
1500
+ function defer() {
1501
+ return new Deferred();
1502
+ }
1503
+
1504
+
1505
+ /**
1506
+ * Creates a promise that has been resolved with the given value.
1507
+ * @param {T=} opt_value The resolved value.
1508
+ * @return {!ManagedPromise<T>} The resolved promise.
1509
+ * @template T
1510
+ */
1511
+ function fulfilled(opt_value) {
1512
+ if (opt_value instanceof ManagedPromise) {
1513
+ return opt_value;
1514
+ }
1515
+ return new ManagedPromise(function(fulfill) {
1516
+ fulfill(opt_value);
1517
+ });
1518
+ }
1519
+
1520
+
1521
+ /**
1522
+ * Creates a promise that has been rejected with the given reason.
1523
+ * @param {*=} opt_reason The rejection reason; may be any value, but is
1524
+ * usually an Error or a string.
1525
+ * @return {!ManagedPromise<T>} The rejected promise.
1526
+ * @template T
1527
+ */
1528
+ function rejected(opt_reason) {
1529
+ if (opt_reason instanceof ManagedPromise) {
1530
+ return opt_reason;
1531
+ }
1532
+ return new ManagedPromise(function(_, reject) {
1533
+ reject(opt_reason);
1534
+ });
1535
+ }
1536
+
1537
+
1538
+ /**
1539
+ * Wraps a function that expects a node-style callback as its final
1540
+ * argument. This callback expects two arguments: an error value (which will be
1541
+ * null if the call succeeded), and the success value as the second argument.
1542
+ * The callback will the resolve or reject the returned promise, based on its
1543
+ * arguments.
1544
+ * @param {!Function} fn The function to wrap.
1545
+ * @param {...?} var_args The arguments to apply to the function, excluding the
1546
+ * final callback.
1547
+ * @return {!ManagedPromise} A promise that will be resolved with the
1548
+ * result of the provided function's callback.
1549
+ */
1550
+ function checkedNodeCall(fn, var_args) {
1551
+ let args = Array.prototype.slice.call(arguments, 1);
1552
+ return new ManagedPromise(function(fulfill, reject) {
1553
+ try {
1554
+ args.push(function(error, value) {
1555
+ error ? reject(error) : fulfill(value);
1556
+ });
1557
+ fn.apply(undefined, args);
1558
+ } catch (ex) {
1559
+ reject(ex);
1560
+ }
1561
+ });
1562
+ }
1563
+
1564
+
1565
+ /**
1566
+ * Registers an observer on a promised {@code value}, returning a new promise
1567
+ * that will be resolved when the value is. If {@code value} is not a promise,
1568
+ * then the return promise will be immediately resolved.
1569
+ * @param {*} value The value to observe.
1570
+ * @param {Function=} opt_callback The function to call when the value is
1571
+ * resolved successfully.
1572
+ * @param {Function=} opt_errback The function to call when the value is
1573
+ * rejected.
1574
+ * @return {!ManagedPromise} A new promise.
1575
+ */
1576
+ function when(value, opt_callback, opt_errback) {
1577
+ if (Thenable.isImplementation(value)) {
1578
+ return value.then(opt_callback, opt_errback);
1579
+ }
1580
+
1581
+ return new ManagedPromise(function(fulfill) {
1582
+ fulfill(value);
1583
+ }).then(opt_callback, opt_errback);
1584
+ }
1585
+
1586
+
1587
+ /**
1588
+ * Invokes the appropriate callback function as soon as a promised `value` is
1589
+ * resolved. This function is similar to `when()`, except it does not return
1590
+ * a new promise.
1591
+ * @param {*} value The value to observe.
1592
+ * @param {Function} callback The function to call when the value is
1593
+ * resolved successfully.
1594
+ * @param {Function=} opt_errback The function to call when the value is
1595
+ * rejected.
1596
+ */
1597
+ function asap(value, callback, opt_errback) {
1598
+ if (isPromise(value)) {
1599
+ value.then(callback, opt_errback);
1600
+
1601
+ } else if (callback) {
1602
+ callback(value);
1603
+ }
1604
+ }
1605
+
1606
+
1607
+ /**
1608
+ * Given an array of promises, will return a promise that will be fulfilled
1609
+ * with the fulfillment values of the input array's values. If any of the
1610
+ * input array's promises are rejected, the returned promise will be rejected
1611
+ * with the same reason.
1612
+ *
1613
+ * @param {!Array<(T|!ManagedPromise<T>)>} arr An array of
1614
+ * promises to wait on.
1615
+ * @return {!ManagedPromise<!Array<T>>} A promise that is
1616
+ * fulfilled with an array containing the fulfilled values of the
1617
+ * input array, or rejected with the same reason as the first
1618
+ * rejected value.
1619
+ * @template T
1620
+ */
1621
+ function all(arr) {
1622
+ return new ManagedPromise(function(fulfill, reject) {
1623
+ var n = arr.length;
1624
+ var values = [];
1625
+
1626
+ if (!n) {
1627
+ fulfill(values);
1628
+ return;
1629
+ }
1630
+
1631
+ var toFulfill = n;
1632
+ var onFulfilled = function(index, value) {
1633
+ values[index] = value;
1634
+ toFulfill--;
1635
+ if (toFulfill == 0) {
1636
+ fulfill(values);
1637
+ }
1638
+ };
1639
+
1640
+ function processPromise(index) {
1641
+ asap(arr[index], function(value) {
1642
+ onFulfilled(index, value);
1643
+ }, reject);
1644
+ }
1645
+
1646
+ for (var i = 0; i < n; ++i) {
1647
+ processPromise(i);
1648
+ }
1649
+ });
1650
+ }
1651
+
1652
+
1653
+ /**
1654
+ * Calls a function for each element in an array and inserts the result into a
1655
+ * new array, which is used as the fulfillment value of the promise returned
1656
+ * by this function.
1657
+ *
1658
+ * If the return value of the mapping function is a promise, this function
1659
+ * will wait for it to be fulfilled before inserting it into the new array.
1660
+ *
1661
+ * If the mapping function throws or returns a rejected promise, the
1662
+ * promise returned by this function will be rejected with the same reason.
1663
+ * Only the first failure will be reported; all subsequent errors will be
1664
+ * silently ignored.
1665
+ *
1666
+ * @param {!(Array<TYPE>|ManagedPromise<!Array<TYPE>>)} arr The
1667
+ * array to iterator over, or a promise that will resolve to said array.
1668
+ * @param {function(this: SELF, TYPE, number, !Array<TYPE>): ?} fn The
1669
+ * function to call for each element in the array. This function should
1670
+ * expect three arguments (the element, the index, and the array itself.
1671
+ * @param {SELF=} opt_self The object to be used as the value of 'this' within
1672
+ * {@code fn}.
1673
+ * @template TYPE, SELF
1674
+ */
1675
+ function map(arr, fn, opt_self) {
1676
+ return fulfilled(arr).then(function(v) {
1677
+ if (!Array.isArray(v)) {
1678
+ throw TypeError('not an array');
1679
+ }
1680
+ var arr = /** @type {!Array} */(v);
1681
+ return new ManagedPromise(function(fulfill, reject) {
1682
+ var n = arr.length;
1683
+ var values = new Array(n);
1684
+ (function processNext(i) {
1685
+ for (; i < n; i++) {
1686
+ if (i in arr) {
1687
+ break;
1688
+ }
1689
+ }
1690
+ if (i >= n) {
1691
+ fulfill(values);
1692
+ return;
1693
+ }
1694
+ try {
1695
+ asap(
1696
+ fn.call(opt_self, arr[i], i, /** @type {!Array} */(arr)),
1697
+ function(value) {
1698
+ values[i] = value;
1699
+ processNext(i + 1);
1700
+ },
1701
+ reject);
1702
+ } catch (ex) {
1703
+ reject(ex);
1704
+ }
1705
+ })(0);
1706
+ });
1707
+ });
1708
+ }
1709
+
1710
+
1711
+ /**
1712
+ * Calls a function for each element in an array, and if the function returns
1713
+ * true adds the element to a new array.
1714
+ *
1715
+ * If the return value of the filter function is a promise, this function
1716
+ * will wait for it to be fulfilled before determining whether to insert the
1717
+ * element into the new array.
1718
+ *
1719
+ * If the filter function throws or returns a rejected promise, the promise
1720
+ * returned by this function will be rejected with the same reason. Only the
1721
+ * first failure will be reported; all subsequent errors will be silently
1722
+ * ignored.
1723
+ *
1724
+ * @param {!(Array<TYPE>|ManagedPromise<!Array<TYPE>>)} arr The
1725
+ * array to iterator over, or a promise that will resolve to said array.
1726
+ * @param {function(this: SELF, TYPE, number, !Array<TYPE>): (
1727
+ * boolean|ManagedPromise<boolean>)} fn The function
1728
+ * to call for each element in the array.
1729
+ * @param {SELF=} opt_self The object to be used as the value of 'this' within
1730
+ * {@code fn}.
1731
+ * @template TYPE, SELF
1732
+ */
1733
+ function filter(arr, fn, opt_self) {
1734
+ return fulfilled(arr).then(function(v) {
1735
+ if (!Array.isArray(v)) {
1736
+ throw TypeError('not an array');
1737
+ }
1738
+ var arr = /** @type {!Array} */(v);
1739
+ return new ManagedPromise(function(fulfill, reject) {
1740
+ var n = arr.length;
1741
+ var values = [];
1742
+ var valuesLength = 0;
1743
+ (function processNext(i) {
1744
+ for (; i < n; i++) {
1745
+ if (i in arr) {
1746
+ break;
1747
+ }
1748
+ }
1749
+ if (i >= n) {
1750
+ fulfill(values);
1751
+ return;
1752
+ }
1753
+ try {
1754
+ var value = arr[i];
1755
+ var include = fn.call(opt_self, value, i, /** @type {!Array} */(arr));
1756
+ asap(include, function(include) {
1757
+ if (include) {
1758
+ values[valuesLength++] = value;
1759
+ }
1760
+ processNext(i + 1);
1761
+ }, reject);
1762
+ } catch (ex) {
1763
+ reject(ex);
1764
+ }
1765
+ })(0);
1766
+ });
1767
+ });
1768
+ }
1769
+
1770
+
1771
+ /**
1772
+ * Returns a promise that will be resolved with the input value in a
1773
+ * fully-resolved state. If the value is an array, each element will be fully
1774
+ * resolved. Likewise, if the value is an object, all keys will be fully
1775
+ * resolved. In both cases, all nested arrays and objects will also be
1776
+ * fully resolved. All fields are resolved in place; the returned promise will
1777
+ * resolve on {@code value} and not a copy.
1778
+ *
1779
+ * Warning: This function makes no checks against objects that contain
1780
+ * cyclical references:
1781
+ *
1782
+ * var value = {};
1783
+ * value['self'] = value;
1784
+ * promise.fullyResolved(value); // Stack overflow.
1785
+ *
1786
+ * @param {*} value The value to fully resolve.
1787
+ * @return {!ManagedPromise} A promise for a fully resolved version
1788
+ * of the input value.
1789
+ */
1790
+ function fullyResolved(value) {
1791
+ if (isPromise(value)) {
1792
+ return when(value, fullyResolveValue);
1793
+ }
1794
+ return fullyResolveValue(value);
1795
+ }
1796
+
1797
+
1798
+ /**
1799
+ * @param {*} value The value to fully resolve. If a promise, assumed to
1800
+ * already be resolved.
1801
+ * @return {!ManagedPromise} A promise for a fully resolved version
1802
+ * of the input value.
1803
+ */
1804
+ function fullyResolveValue(value) {
1805
+ if (Array.isArray(value)) {
1806
+ return fullyResolveKeys(/** @type {!Array} */ (value));
1807
+ }
1808
+
1809
+ if (isPromise(value)) {
1810
+ if (isPromise(value)) {
1811
+ // We get here when the original input value is a promise that
1812
+ // resolves to itself. When the user provides us with such a promise,
1813
+ // trust that it counts as a "fully resolved" value and return it.
1814
+ // Of course, since it's already a promise, we can just return it
1815
+ // to the user instead of wrapping it in another promise.
1816
+ return /** @type {!ManagedPromise} */ (value);
1817
+ }
1818
+ }
1819
+
1820
+ if (value && typeof value === 'object') {
1821
+ return fullyResolveKeys(/** @type {!Object} */ (value));
1822
+ }
1823
+
1824
+ if (typeof value === 'function') {
1825
+ return fullyResolveKeys(/** @type {!Object} */ (value));
1826
+ }
1827
+
1828
+ return fulfilled(value);
1829
+ }
1830
+
1831
+
1832
+ /**
1833
+ * @param {!(Array|Object)} obj the object to resolve.
1834
+ * @return {!ManagedPromise} A promise that will be resolved with the
1835
+ * input object once all of its values have been fully resolved.
1836
+ */
1837
+ function fullyResolveKeys(obj) {
1838
+ var isArray = Array.isArray(obj);
1839
+ var numKeys = isArray ? obj.length : (function() {
1840
+ let n = 0;
1841
+ for (let key in obj) {
1842
+ n += 1;
1843
+ }
1844
+ return n;
1845
+ })();
1846
+ if (!numKeys) {
1847
+ return fulfilled(obj);
1848
+ }
1849
+
1850
+ function forEachProperty(obj, fn) {
1851
+ for (let key in obj) {
1852
+ fn.call(null, obj[key], key, obj);
1853
+ }
1854
+ }
1855
+
1856
+ function forEachElement(arr, fn) {
1857
+ arr.forEach(fn);
1858
+ }
1859
+
1860
+ var numResolved = 0;
1861
+ return new ManagedPromise(function(fulfill, reject) {
1862
+ var forEachKey = isArray ? forEachElement: forEachProperty;
1863
+
1864
+ forEachKey(obj, function(partialValue, key) {
1865
+ if (!Array.isArray(partialValue)
1866
+ && (!partialValue || typeof partialValue !== 'object')) {
1867
+ maybeResolveValue();
1868
+ return;
1869
+ }
1870
+
1871
+ fullyResolved(partialValue).then(
1872
+ function(resolvedValue) {
1873
+ obj[key] = resolvedValue;
1874
+ maybeResolveValue();
1875
+ },
1876
+ reject);
1877
+ });
1878
+
1879
+ function maybeResolveValue() {
1880
+ if (++numResolved == numKeys) {
1881
+ fulfill(obj);
1882
+ }
1883
+ }
1884
+ });
1885
+ }
1886
+
1887
+
1888
+ //////////////////////////////////////////////////////////////////////////////
1889
+ //
1890
+ // ControlFlow
1891
+ //
1892
+ //////////////////////////////////////////////////////////////////////////////
1893
+
1894
+
1895
+
1896
+ /**
1897
+ * Handles the execution of scheduled tasks, each of which may be an
1898
+ * asynchronous operation. The control flow will ensure tasks are executed in
1899
+ * the ordered scheduled, starting each task only once those before it have
1900
+ * completed.
1901
+ *
1902
+ * Each task scheduled within this flow may return a {@link ManagedPromise} to
1903
+ * indicate it is an asynchronous operation. The ControlFlow will wait for such
1904
+ * promises to be resolved before marking the task as completed.
1905
+ *
1906
+ * Tasks and each callback registered on a {@link ManagedPromise} will be run
1907
+ * in their own ControlFlow frame. Any tasks scheduled within a frame will take
1908
+ * priority over previously scheduled tasks. Furthermore, if any of the tasks in
1909
+ * the frame fail, the remainder of the tasks in that frame will be discarded
1910
+ * and the failure will be propagated to the user through the callback/task's
1911
+ * promised result.
1912
+ *
1913
+ * Each time a ControlFlow empties its task queue, it will fire an
1914
+ * {@link ControlFlow.EventType.IDLE IDLE} event. Conversely,
1915
+ * whenever the flow terminates due to an unhandled error, it will remove all
1916
+ * remaining tasks in its queue and fire an
1917
+ * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION UNCAUGHT_EXCEPTION} event.
1918
+ * If there are no listeners registered with the flow, the error will be
1919
+ * rethrown to the global error handler.
1920
+ *
1921
+ * Refer to the {@link ./promise} module documentation fora detailed
1922
+ * explanation of how the ControlFlow coordinates task execution.
1923
+ *
1924
+ * @final
1925
+ */
1926
+ class ControlFlow extends events.EventEmitter {
1927
+ constructor() {
1928
+ super();
1929
+
1930
+ /** @private {boolean} */
1931
+ this.propagateUnhandledRejections_ = true;
1932
+
1933
+ /** @private {TaskQueue} */
1934
+ this.activeQueue_ = null;
1935
+
1936
+ /** @private {Set<TaskQueue>} */
1937
+ this.taskQueues_ = null;
1938
+
1939
+ /**
1940
+ * Micro task that controls shutting down the control flow. Upon shut down,
1941
+ * the flow will emit an
1942
+ * {@link ControlFlow.EventType.IDLE} event. Idle events
1943
+ * always follow a brief timeout in order to catch latent errors from the
1944
+ * last completed task. If this task had a callback registered, but no
1945
+ * errback, and the task fails, the unhandled failure would not be reported
1946
+ * by the promise system until the next turn of the event loop:
1947
+ *
1948
+ * // Schedule 1 task that fails.
1949
+ * var result = promise.controlFlow().schedule('example',
1950
+ * function() { return promise.rejected('failed'); });
1951
+ * // Set a callback on the result. This delays reporting the unhandled
1952
+ * // failure for 1 turn of the event loop.
1953
+ * result.then(function() {});
1954
+ *
1955
+ * @private {MicroTask}
1956
+ */
1957
+ this.shutdownTask_ = null;
1958
+
1959
+ /**
1960
+ * ID for a long running interval used to keep a Node.js process running
1961
+ * while a control flow's event loop is still working. This is a cheap hack
1962
+ * required since JS events are only scheduled to run when there is
1963
+ * _actually_ something to run. When a control flow is waiting on a task,
1964
+ * there will be nothing in the JS event loop and the process would
1965
+ * terminate without this.
1966
+ * @private
1967
+ */
1968
+ this.hold_ = null;
1969
+ }
1970
+
1971
+ /**
1972
+ * Returns a string representation of this control flow, which is its current
1973
+ * {@linkplain #getSchedule() schedule}, sans task stack traces.
1974
+ * @return {string} The string representation of this contorl flow.
1975
+ * @override
1976
+ */
1977
+ toString() {
1978
+ return this.getSchedule();
1979
+ }
1980
+
1981
+ /**
1982
+ * Sets whether any unhandled rejections should propagate up through the
1983
+ * control flow stack and cause rejections within parent tasks. If error
1984
+ * propagation is disabled, tasks will not be aborted when an unhandled
1985
+ * promise rejection is detected, but the rejection _will_ trigger an
1986
+ * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION}
1987
+ * event.
1988
+ *
1989
+ * The default behavior is to propagate all unhandled rejections. _The use
1990
+ * of this option is highly discouraged._
1991
+ *
1992
+ * @param {boolean} propagate whether to propagate errors.
1993
+ */
1994
+ setPropagateUnhandledRejections(propagate) {
1995
+ this.propagateUnhandledRejections_ = propagate;
1996
+ }
1997
+
1998
+ /**
1999
+ * @return {boolean} Whether this flow is currently idle.
2000
+ */
2001
+ isIdle() {
2002
+ return !this.shutdownTask_ && (!this.taskQueues_ || !this.taskQueues_.size);
2003
+ }
2004
+
2005
+ /**
2006
+ * Resets this instance, clearing its queue and removing all event listeners.
2007
+ */
2008
+ reset() {
2009
+ this.cancelQueues_(new FlowResetError);
2010
+ this.emit(ControlFlow.EventType.RESET);
2011
+ this.removeAllListeners();
2012
+ this.cancelShutdown_();
2013
+ }
2014
+
2015
+ /**
2016
+ * Generates an annotated string describing the internal state of this control
2017
+ * flow, including the currently executing as well as pending tasks. If
2018
+ * {@code opt_includeStackTraces === true}, the string will include the
2019
+ * stack trace from when each task was scheduled.
2020
+ * @param {string=} opt_includeStackTraces Whether to include the stack traces
2021
+ * from when each task was scheduled. Defaults to false.
2022
+ * @return {string} String representation of this flow's internal state.
2023
+ */
2024
+ getSchedule(opt_includeStackTraces) {
2025
+ var ret = 'ControlFlow::' + getUid(this);
2026
+ var activeQueue = this.activeQueue_;
2027
+ if (!this.taskQueues_ || !this.taskQueues_.size) {
2028
+ return ret;
2029
+ }
2030
+ var childIndent = '| ';
2031
+ for (var q of this.taskQueues_) {
2032
+ ret += '\n' + printQ(q, childIndent);
2033
+ }
2034
+ return ret;
2035
+
2036
+ function printQ(q, indent) {
2037
+ var ret = q.toString();
2038
+ if (q === activeQueue) {
2039
+ ret = '(active) ' + ret;
2040
+ }
2041
+ var prefix = indent + childIndent;
2042
+ if (q.pending_) {
2043
+ if (q.pending_.q.state_ !== TaskQueueState.FINISHED) {
2044
+ ret += '\n' + prefix + '(pending) ' + q.pending_.task;
2045
+ ret += '\n' + printQ(q.pending_.q, prefix + childIndent);
2046
+ } else {
2047
+ ret += '\n' + prefix + '(blocked) ' + q.pending_.task;
2048
+ }
2049
+ }
2050
+ if (q.interrupts_) {
2051
+ q.interrupts_.forEach((task) => {
2052
+ ret += '\n' + prefix + task;
2053
+ });
2054
+ }
2055
+ if (q.tasks_) {
2056
+ q.tasks_.forEach((task) => ret += printTask(task, '\n' + prefix));
2057
+ }
2058
+ return indent + ret;
2059
+ }
2060
+
2061
+ function printTask(task, prefix) {
2062
+ var ret = prefix + task;
2063
+ if (opt_includeStackTraces && task.promise.stack_) {
2064
+ ret += prefix + childIndent
2065
+ + (task.promise.stack_.stack || task.promise.stack_)
2066
+ .replace(/\n/g, prefix);
2067
+ }
2068
+ return ret;
2069
+ }
2070
+ }
2071
+
2072
+ /**
2073
+ * Returns the currently actively task queue for this flow. If there is no
2074
+ * active queue, one will be created.
2075
+ * @return {!TaskQueue} the currently active task queue for this flow.
2076
+ * @private
2077
+ */
2078
+ getActiveQueue_() {
2079
+ if (this.activeQueue_) {
2080
+ return this.activeQueue_;
2081
+ }
2082
+
2083
+ this.activeQueue_ = new TaskQueue(this);
2084
+ if (!this.taskQueues_) {
2085
+ this.taskQueues_ = new Set();
2086
+ }
2087
+ this.taskQueues_.add(this.activeQueue_);
2088
+ this.activeQueue_
2089
+ .once('end', this.onQueueEnd_, this)
2090
+ .once('error', this.onQueueError_, this);
2091
+
2092
+ asyncRun(() => this.activeQueue_ = null);
2093
+ this.activeQueue_.start();
2094
+ return this.activeQueue_;
2095
+ }
2096
+
2097
+ /**
2098
+ * Schedules a task for execution. If there is nothing currently in the
2099
+ * queue, the task will be executed in the next turn of the event loop. If
2100
+ * the task function is a generator, the task will be executed using
2101
+ * {@link ./promise.consume consume()}.
2102
+ *
2103
+ * @param {function(): (T|ManagedPromise<T>)} fn The function to
2104
+ * call to start the task. If the function returns a
2105
+ * {@link ManagedPromise}, this instance will wait for it to be
2106
+ * resolved before starting the next task.
2107
+ * @param {string=} opt_description A description of the task.
2108
+ * @return {!ManagedPromise<T>} A promise that will be resolved
2109
+ * with the result of the action.
2110
+ * @template T
2111
+ */
2112
+ execute(fn, opt_description) {
2113
+ if (isGenerator(fn)) {
2114
+ let original = fn;
2115
+ fn = () => consume(original);
2116
+ }
2117
+
2118
+ if (!this.hold_) {
2119
+ var holdIntervalMs = 2147483647; // 2^31-1; max timer length for Node.js
2120
+ this.hold_ = setInterval(function() {}, holdIntervalMs);
2121
+ }
2122
+
2123
+ var task = new Task(
2124
+ this, fn, opt_description || '<anonymous>',
2125
+ {name: 'Task', top: ControlFlow.prototype.execute});
2126
+
2127
+ var q = this.getActiveQueue_();
2128
+ q.enqueue(task);
2129
+ this.emit(ControlFlow.EventType.SCHEDULE_TASK, task.description);
2130
+ return task.promise;
2131
+ }
2132
+
2133
+ /**
2134
+ * Inserts a {@code setTimeout} into the command queue. This is equivalent to
2135
+ * a thread sleep in a synchronous programming language.
2136
+ *
2137
+ * @param {number} ms The timeout delay, in milliseconds.
2138
+ * @param {string=} opt_description A description to accompany the timeout.
2139
+ * @return {!ManagedPromise} A promise that will be resolved with
2140
+ * the result of the action.
2141
+ */
2142
+ timeout(ms, opt_description) {
2143
+ return this.execute(function() {
2144
+ return delayed(ms);
2145
+ }, opt_description);
2146
+ }
2147
+
2148
+ /**
2149
+ * Schedules a task that shall wait for a condition to hold. Each condition
2150
+ * function may return any value, but it will always be evaluated as a
2151
+ * boolean.
2152
+ *
2153
+ * Condition functions may schedule sub-tasks with this instance, however,
2154
+ * their execution time will be factored into whether a wait has timed out.
2155
+ *
2156
+ * In the event a condition returns a ManagedPromise, the polling loop will wait for
2157
+ * it to be resolved before evaluating whether the condition has been
2158
+ * satisfied. The resolution time for a promise is factored into whether a
2159
+ * wait has timed out.
2160
+ *
2161
+ * If the condition function throws, or returns a rejected promise, the
2162
+ * wait task will fail.
2163
+ *
2164
+ * If the condition is defined as a promise, the flow will wait for it to
2165
+ * settle. If the timeout expires before the promise settles, the promise
2166
+ * returned by this function will be rejected.
2167
+ *
2168
+ * If this function is invoked with `timeout === 0`, or the timeout is
2169
+ * omitted, the flow will wait indefinitely for the condition to be satisfied.
2170
+ *
2171
+ * @param {(!ManagedPromise<T>|function())} condition The condition to poll,
2172
+ * or a promise to wait on.
2173
+ * @param {number=} opt_timeout How long to wait, in milliseconds, for the
2174
+ * condition to hold before timing out. If omitted, the flow will wait
2175
+ * indefinitely.
2176
+ * @param {string=} opt_message An optional error message to include if the
2177
+ * wait times out; defaults to the empty string.
2178
+ * @return {!ManagedPromise<T>} A promise that will be fulfilled
2179
+ * when the condition has been satisified. The promise shall be rejected
2180
+ * if the wait times out waiting for the condition.
2181
+ * @throws {TypeError} If condition is not a function or promise or if timeout
2182
+ * is not a number >= 0.
2183
+ * @template T
2184
+ */
2185
+ wait(condition, opt_timeout, opt_message) {
2186
+ var timeout = opt_timeout || 0;
2187
+ if (typeof timeout !== 'number' || timeout < 0) {
2188
+ throw TypeError('timeout must be a number >= 0: ' + timeout);
2189
+ }
2190
+
2191
+ if (isPromise(condition)) {
2192
+ return this.execute(function() {
2193
+ if (!timeout) {
2194
+ return condition;
2195
+ }
2196
+ return new ManagedPromise(function(fulfill, reject) {
2197
+ var start = Date.now();
2198
+ var timer = setTimeout(function() {
2199
+ timer = null;
2200
+ reject(Error((opt_message ? opt_message + '\n' : '') +
2201
+ 'Timed out waiting for promise to resolve after ' +
2202
+ (Date.now() - start) + 'ms'));
2203
+ }, timeout);
2204
+
2205
+ /** @type {Thenable} */(condition).then(
2206
+ function(value) {
2207
+ timer && clearTimeout(timer);
2208
+ fulfill(value);
2209
+ },
2210
+ function(error) {
2211
+ timer && clearTimeout(timer);
2212
+ reject(error);
2213
+ });
2214
+ });
2215
+ }, opt_message || '<anonymous wait: promise resolution>');
2216
+ }
2217
+
2218
+ if (typeof condition !== 'function') {
2219
+ throw TypeError('Invalid condition; must be a function or promise: ' +
2220
+ typeof condition);
2221
+ }
2222
+
2223
+ if (isGenerator(condition)) {
2224
+ let original = condition;
2225
+ condition = () => consume(original);
2226
+ }
2227
+
2228
+ var self = this;
2229
+ return this.execute(function() {
2230
+ var startTime = Date.now();
2231
+ return new ManagedPromise(function(fulfill, reject) {
2232
+ pollCondition();
2233
+
2234
+ function pollCondition() {
2235
+ var conditionFn = /** @type {function()} */(condition);
2236
+ self.execute(conditionFn).then(function(value) {
2237
+ var elapsed = Date.now() - startTime;
2238
+ if (!!value) {
2239
+ fulfill(value);
2240
+ } else if (timeout && elapsed >= timeout) {
2241
+ reject(new Error((opt_message ? opt_message + '\n' : '') +
2242
+ 'Wait timed out after ' + elapsed + 'ms'));
2243
+ } else {
2244
+ // Do not use asyncRun here because we need a non-micro yield
2245
+ // here so the UI thread is given a chance when running in a
2246
+ // browser.
2247
+ setTimeout(pollCondition, 0);
2248
+ }
2249
+ }, reject);
2250
+ }
2251
+ });
2252
+ }, opt_message || '<anonymous wait>');
2253
+ }
2254
+
2255
+ /**
2256
+ * Executes a function in the next available turn of the JavaScript event
2257
+ * loop. This ensures the function runs with its own task queue and any
2258
+ * scheduled tasks will run in "parallel" to those scheduled in the current
2259
+ * function.
2260
+ *
2261
+ * flow.execute(() => console.log('a'));
2262
+ * flow.execute(() => console.log('b'));
2263
+ * flow.execute(() => console.log('c'));
2264
+ * flow.async(() => {
2265
+ * flow.execute(() => console.log('d'));
2266
+ * flow.execute(() => console.log('e'));
2267
+ * });
2268
+ * flow.async(() => {
2269
+ * flow.execute(() => console.log('f'));
2270
+ * flow.execute(() => console.log('g'));
2271
+ * });
2272
+ * flow.once('idle', () => console.log('fin'));
2273
+ * // a
2274
+ * // d
2275
+ * // f
2276
+ * // b
2277
+ * // e
2278
+ * // g
2279
+ * // c
2280
+ * // fin
2281
+ *
2282
+ * If the function itself throws, the error will be treated the same as an
2283
+ * unhandled rejection within the control flow.
2284
+ *
2285
+ * __NOTE__: This function is considered _unstable_.
2286
+ *
2287
+ * @param {!Function} fn The function to execute.
2288
+ * @param {Object=} opt_self The object in whose context to run the function.
2289
+ * @param {...*} var_args Any arguments to pass to the function.
2290
+ */
2291
+ async(fn, opt_self, var_args) {
2292
+ asyncRun(() => {
2293
+ // Clear any lingering queues, forces getActiveQueue_ to create a new one.
2294
+ this.activeQueue_ = null;
2295
+ var q = this.getActiveQueue_();
2296
+ try {
2297
+ q.execute_(fn.bind(opt_self, var_args));
2298
+ } catch (ex) {
2299
+ var cancellationError = CancellationError.wrap(ex,
2300
+ 'Function passed to ControlFlow.async() threw');
2301
+ cancellationError.silent_ = true;
2302
+ q.abort_(cancellationError);
2303
+ } finally {
2304
+ this.activeQueue_ = null;
2305
+ }
2306
+ });
2307
+ }
2308
+
2309
+ /**
2310
+ * Event handler for when a task queue is exhausted. This starts the shutdown
2311
+ * sequence for this instance if there are no remaining task queues: after
2312
+ * one turn of the event loop, this object will emit the
2313
+ * {@link ControlFlow.EventType.IDLE IDLE} event to signal
2314
+ * listeners that it has completed. During this wait, if another task is
2315
+ * scheduled, the shutdown will be aborted.
2316
+ *
2317
+ * @param {!TaskQueue} q the completed task queue.
2318
+ * @private
2319
+ */
2320
+ onQueueEnd_(q) {
2321
+ if (!this.taskQueues_) {
2322
+ return;
2323
+ }
2324
+ this.taskQueues_.delete(q);
2325
+
2326
+ vlog(1, () => q + ' has finished');
2327
+ vlog(1, () => this.taskQueues_.size + ' queues remain\n' + this, this);
2328
+
2329
+ if (!this.taskQueues_.size) {
2330
+ if (this.shutdownTask_) {
2331
+ throw Error('Already have a shutdown task??');
2332
+ }
2333
+ vlog(1, () => 'Scheduling shutdown\n' + this);
2334
+ this.shutdownTask_ = new MicroTask(() => this.shutdown_());
2335
+ }
2336
+ }
2337
+
2338
+ /**
2339
+ * Event handler for when a task queue terminates with an error. This triggers
2340
+ * the cancellation of all other task queues and a
2341
+ * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION} event.
2342
+ * If there are no error event listeners registered with this instance, the
2343
+ * error will be rethrown to the global error handler.
2344
+ *
2345
+ * @param {*} error the error that caused the task queue to terminate.
2346
+ * @param {!TaskQueue} q the task queue.
2347
+ * @private
2348
+ */
2349
+ onQueueError_(error, q) {
2350
+ if (this.taskQueues_) {
2351
+ this.taskQueues_.delete(q);
2352
+ }
2353
+ this.cancelQueues_(CancellationError.wrap(
2354
+ error, 'There was an uncaught error in the control flow'));
2355
+ this.cancelShutdown_();
2356
+ this.cancelHold_();
2357
+
2358
+ var listeners = this.listeners(
2359
+ ControlFlow.EventType.UNCAUGHT_EXCEPTION);
2360
+ if (!listeners.size) {
2361
+ asyncThrow(/** @type {!Error} */(error));
2362
+ } else {
2363
+ this.reportUncaughtException_(error);
2364
+ }
2365
+ }
2366
+
2367
+ /**
2368
+ * Cancels all remaining task queues.
2369
+ * @param {!CancellationError} reason The cancellation reason.
2370
+ * @private
2371
+ */
2372
+ cancelQueues_(reason) {
2373
+ reason.silent_ = true;
2374
+ if (this.taskQueues_) {
2375
+ for (var q of this.taskQueues_) {
2376
+ q.removeAllListeners();
2377
+ q.abort_(reason);
2378
+ }
2379
+ this.taskQueues_.clear();
2380
+ this.taskQueues_ = null;
2381
+ }
2382
+ }
2383
+
2384
+ /**
2385
+ * Reports an uncaught exception using a
2386
+ * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION} event.
2387
+ *
2388
+ * @param {*} e the error to report.
2389
+ * @private
2390
+ */
2391
+ reportUncaughtException_(e) {
2392
+ this.emit(ControlFlow.EventType.UNCAUGHT_EXCEPTION, e);
2393
+ }
2394
+
2395
+ /** @private */
2396
+ cancelHold_() {
2397
+ if (this.hold_) {
2398
+ clearInterval(this.hold_);
2399
+ this.hold_ = null;
2400
+ }
2401
+ }
2402
+
2403
+ /** @private */
2404
+ shutdown_() {
2405
+ vlog(1, () => 'Going idle: ' + this);
2406
+ this.cancelHold_();
2407
+ this.shutdownTask_ = null;
2408
+ this.emit(ControlFlow.EventType.IDLE);
2409
+ }
2410
+
2411
+ /**
2412
+ * Cancels the shutdown sequence if it is currently scheduled.
2413
+ * @private
2414
+ */
2415
+ cancelShutdown_() {
2416
+ if (this.shutdownTask_) {
2417
+ this.shutdownTask_.cancel();
2418
+ this.shutdownTask_ = null;
2419
+ }
2420
+ }
2421
+ }
2422
+
2423
+
2424
+ /**
2425
+ * Events that may be emitted by an {@link ControlFlow}.
2426
+ * @enum {string}
2427
+ */
2428
+ ControlFlow.EventType = {
2429
+
2430
+ /** Emitted when all tasks have been successfully executed. */
2431
+ IDLE: 'idle',
2432
+
2433
+ /** Emitted when a ControlFlow has been reset. */
2434
+ RESET: 'reset',
2435
+
2436
+ /** Emitted whenever a new task has been scheduled. */
2437
+ SCHEDULE_TASK: 'scheduleTask',
2438
+
2439
+ /**
2440
+ * Emitted whenever a control flow aborts due to an unhandled promise
2441
+ * rejection. This event will be emitted along with the offending rejection
2442
+ * reason. Upon emitting this event, the control flow will empty its task
2443
+ * queue and revert to its initial state.
2444
+ */
2445
+ UNCAUGHT_EXCEPTION: 'uncaughtException'
2446
+ };
2447
+
2448
+
2449
+ /**
2450
+ * Wraps a function to execute as a cancellable micro task.
2451
+ * @final
2452
+ */
2453
+ class MicroTask {
2454
+ /**
2455
+ * @param {function()} fn The function to run as a micro task.
2456
+ */
2457
+ constructor(fn) {
2458
+ /** @private {boolean} */
2459
+ this.cancelled_ = false;
2460
+ asyncRun(() => {
2461
+ if (!this.cancelled_) {
2462
+ fn();
2463
+ }
2464
+ });
2465
+ }
2466
+
2467
+ /**
2468
+ * Runs the given function after a micro-task yield.
2469
+ * @param {function()} fn The function to run.
2470
+ */
2471
+ static run(fn) {
2472
+ NativePromise.resolve().then(function() {
2473
+ try {
2474
+ fn();
2475
+ } catch (ignored) {
2476
+ // Do nothing.
2477
+ }
2478
+ });
2479
+ }
2480
+
2481
+ /**
2482
+ * Cancels the execution of this task. Note: this will not prevent the task
2483
+ * timer from firing, just the invocation of the wrapped function.
2484
+ */
2485
+ cancel() {
2486
+ this.cancelled_ = true;
2487
+ }
2488
+ }
2489
+
2490
+
2491
+ /**
2492
+ * A task to be executed by a {@link ControlFlow}.
2493
+ *
2494
+ * @template T
2495
+ * @final
2496
+ */
2497
+ class Task extends Deferred {
2498
+ /**
2499
+ * @param {!ControlFlow} flow The flow this instances belongs
2500
+ * to.
2501
+ * @param {function(): (T|!ManagedPromise<T>)} fn The function to
2502
+ * call when the task executes. If it returns a
2503
+ * {@link ManagedPromise}, the flow will wait for it to be
2504
+ * resolved before starting the next task.
2505
+ * @param {string} description A description of the task for debugging.
2506
+ * @param {{name: string, top: !Function}=} opt_stackOptions Options to use
2507
+ * when capturing the stacktrace for when this task was created.
2508
+ */
2509
+ constructor(flow, fn, description, opt_stackOptions) {
2510
+ super(flow);
2511
+ getUid(this);
2512
+
2513
+ /** @type {function(): (T|!ManagedPromise<T>)} */
2514
+ this.execute = fn;
2515
+
2516
+ /** @type {string} */
2517
+ this.description = description;
2518
+
2519
+ /** @type {TaskQueue} */
2520
+ this.queue = null;
2521
+
2522
+ /**
2523
+ * Whether this task is considered block. A blocked task may be registered
2524
+ * in a task queue, but will be dropped if it is still blocked when it
2525
+ * reaches the front of the queue. A dropped task may always be rescheduled.
2526
+ *
2527
+ * Blocked tasks are used when a callback is attached to an unsettled
2528
+ * promise to reserve a spot in line (in a manner of speaking). If the
2529
+ * promise is not settled before the callback reaches the front of the
2530
+ * of the queue, it will be dropped. Once the promise is settled, the
2531
+ * dropped task will be rescheduled as an interrupt on the currently task
2532
+ * queue.
2533
+ *
2534
+ * @type {boolean}
2535
+ */
2536
+ this.blocked = false;
2537
+
2538
+ if (opt_stackOptions) {
2539
+ this.promise.stack_ = captureStackTrace(
2540
+ opt_stackOptions.name, this.description, opt_stackOptions.top);
2541
+ }
2542
+ }
2543
+
2544
+ /** @override */
2545
+ toString() {
2546
+ return 'Task::' + getUid(this) + '<' + this.description + '>';
2547
+ }
2548
+ }
2549
+
2550
+
2551
+ /** @enum {string} */
2552
+ const TaskQueueState = {
2553
+ NEW: 'new',
2554
+ STARTED: 'started',
2555
+ FINISHED: 'finished'
2556
+ };
2557
+
2558
+
2559
+ /**
2560
+ * @final
2561
+ */
2562
+ class TaskQueue extends events.EventEmitter {
2563
+ /** @param {!ControlFlow} flow . */
2564
+ constructor(flow) {
2565
+ super();
2566
+
2567
+ /** @private {string} */
2568
+ this.name_ = 'TaskQueue::' + getUid(this);
2569
+
2570
+ /** @private {!ControlFlow} */
2571
+ this.flow_ = flow;
2572
+
2573
+ /** @private {!Array<!Task>} */
2574
+ this.tasks_ = [];
2575
+
2576
+ /** @private {Array<!Task>} */
2577
+ this.interrupts_ = null;
2578
+
2579
+ /** @private {({task: !Task, q: !TaskQueue}|null)} */
2580
+ this.pending_ = null;
2581
+
2582
+ /** @private {TaskQueueState} */
2583
+ this.state_ = TaskQueueState.NEW;
2584
+
2585
+ /** @private {!Set<!ManagedPromise>} */
2586
+ this.unhandledRejections_ = new Set();
2587
+ }
2588
+
2589
+ /** @override */
2590
+ toString() {
2591
+ return 'TaskQueue::' + getUid(this);
2592
+ }
2593
+
2594
+ /**
2595
+ * @param {!ManagedPromise} promise .
2596
+ */
2597
+ addUnhandledRejection(promise) {
2598
+ // TODO: node 4.0.0+
2599
+ vlog(2, () => this + ' registering unhandled rejection: ' + promise, this);
2600
+ this.unhandledRejections_.add(promise);
2601
+ }
2602
+
2603
+ /**
2604
+ * @param {!ManagedPromise} promise .
2605
+ */
2606
+ clearUnhandledRejection(promise) {
2607
+ var deleted = this.unhandledRejections_.delete(promise);
2608
+ if (deleted) {
2609
+ // TODO: node 4.0.0+
2610
+ vlog(2, () => this + ' clearing unhandled rejection: ' + promise, this);
2611
+ }
2612
+ }
2613
+
2614
+ /**
2615
+ * Enqueues a new task for execution.
2616
+ * @param {!Task} task The task to enqueue.
2617
+ * @throws {Error} If this instance has already started execution.
2618
+ */
2619
+ enqueue(task) {
2620
+ if (this.state_ !== TaskQueueState.NEW) {
2621
+ throw Error('TaskQueue has started: ' + this);
2622
+ }
2623
+
2624
+ if (task.queue) {
2625
+ throw Error('Task is already scheduled in another queue');
2626
+ }
2627
+
2628
+ this.tasks_.push(task);
2629
+ task.queue = this;
2630
+ task.promise[CANCEL_HANDLER_SYMBOL] =
2631
+ this.onTaskCancelled_.bind(this, task);
2632
+
2633
+ vlog(1, () => this + '.enqueue(' + task + ')', this);
2634
+ vlog(2, () => this.flow_.toString(), this);
2635
+ }
2636
+
2637
+ /**
2638
+ * Schedules the callbacks registered on the given promise in this queue.
2639
+ *
2640
+ * @param {!ManagedPromise} promise the promise whose callbacks should be
2641
+ * registered as interrupts in this task queue.
2642
+ * @throws {Error} if this queue has already finished.
2643
+ */
2644
+ scheduleCallbacks(promise) {
2645
+ if (this.state_ === TaskQueueState.FINISHED) {
2646
+ throw new Error('cannot interrupt a finished q(' + this + ')');
2647
+ }
2648
+
2649
+ if (this.pending_ && this.pending_.task.promise === promise) {
2650
+ this.pending_.task.promise.queue_ = null;
2651
+ this.pending_ = null;
2652
+ asyncRun(() => this.executeNext_());
2653
+ }
2654
+
2655
+ if (!promise.callbacks_) {
2656
+ return;
2657
+ }
2658
+ promise.callbacks_.forEach(function(cb) {
2659
+ cb.blocked = false;
2660
+ if (cb.queue) {
2661
+ return;
2662
+ }
2663
+
2664
+ cb.promise[CANCEL_HANDLER_SYMBOL] = this.onTaskCancelled_.bind(this, cb);
2665
+
2666
+ if (cb.queue === this && this.tasks_.indexOf(cb) !== -1) {
2667
+ return;
2668
+ }
2669
+
2670
+ if (cb.queue) {
2671
+ cb.queue.dropTask_(cb);
2672
+ }
2673
+
2674
+ cb.queue = this;
2675
+ if (!this.interrupts_) {
2676
+ this.interrupts_ = [];
2677
+ }
2678
+ this.interrupts_.push(cb);
2679
+ }, this);
2680
+ promise.callbacks_ = null;
2681
+ vlog(2, () => this + ' interrupted\n' + this.flow_, this);
2682
+ }
2683
+
2684
+ /**
2685
+ * Starts executing tasks in this queue. Once called, no further tasks may
2686
+ * be {@linkplain #enqueue() enqueued} with this instance.
2687
+ *
2688
+ * @throws {Error} if this queue has already been started.
2689
+ */
2690
+ start() {
2691
+ if (this.state_ !== TaskQueueState.NEW) {
2692
+ throw new Error('TaskQueue has already started');
2693
+ }
2694
+ // Always asynchronously execute next, even if there doesn't look like
2695
+ // there is anything in the queue. This will catch pending unhandled
2696
+ // rejections that were registered before start was called.
2697
+ asyncRun(() => this.executeNext_());
2698
+ }
2699
+
2700
+ /**
2701
+ * Aborts this task queue. If there are any scheduled tasks, they are silently
2702
+ * cancelled and discarded (their callbacks will never fire). If this queue
2703
+ * has a _pending_ task, the abortion error is used to cancel that task.
2704
+ * Otherwise, this queue will emit an error event.
2705
+ *
2706
+ * @param {*} error The abortion reason.
2707
+ * @private
2708
+ */
2709
+ abort_(error) {
2710
+ var cancellation;
2711
+
2712
+ if (error instanceof FlowResetError) {
2713
+ cancellation = error;
2714
+ } else {
2715
+ cancellation = new DiscardedTaskError(error);
2716
+ }
2717
+
2718
+ if (this.interrupts_ && this.interrupts_.length) {
2719
+ this.interrupts_.forEach((t) => t.reject(cancellation));
2720
+ this.interrupts_ = [];
2721
+ }
2722
+
2723
+ if (this.tasks_ && this.tasks_.length) {
2724
+ this.tasks_.forEach((t) => t.reject(cancellation));
2725
+ this.tasks_ = [];
2726
+ }
2727
+
2728
+ if (this.pending_) {
2729
+ vlog(2, () => this + '.abort(); cancelling pending task', this);
2730
+ this.pending_.task.cancel(/** @type {!CancellationError} */(error));
2731
+
2732
+ } else {
2733
+ vlog(2, () => this + '.abort(); emitting error event', this);
2734
+ this.emit('error', error, this);
2735
+ }
2736
+ }
2737
+
2738
+ /** @private */
2739
+ executeNext_() {
2740
+ if (this.state_ === TaskQueueState.FINISHED) {
2741
+ return;
2742
+ }
2743
+ this.state_ = TaskQueueState.STARTED;
2744
+
2745
+ if (this.pending_ != null || this.processUnhandledRejections_()) {
2746
+ return;
2747
+ }
2748
+
2749
+ var task;
2750
+ do {
2751
+ task = this.getNextTask_();
2752
+ } while (task && !task.promise.isPending());
2753
+
2754
+ if (!task) {
2755
+ this.state_ = TaskQueueState.FINISHED;
2756
+ this.tasks_ = [];
2757
+ this.interrupts_ = null;
2758
+ vlog(2, () => this + '.emit(end)', this);
2759
+ this.emit('end', this);
2760
+ return;
2761
+ }
2762
+
2763
+ var self = this;
2764
+ var subQ = new TaskQueue(this.flow_);
2765
+ subQ.once('end', () => self.onTaskComplete_(result))
2766
+ .once('error', (e) => self.onTaskFailure_(result, e));
2767
+ vlog(2, () => self + ' created ' + subQ + ' for ' + task);
2768
+
2769
+ var result = undefined;
2770
+ try {
2771
+ this.pending_ = {task: task, q: subQ};
2772
+ task.promise.queue_ = this;
2773
+ result = subQ.execute_(task.execute);
2774
+ subQ.start();
2775
+ } catch (ex) {
2776
+ subQ.abort_(ex);
2777
+ }
2778
+ }
2779
+
2780
+ /**
2781
+ * @param {!Function} fn .
2782
+ * @return {T} .
2783
+ * @template T
2784
+ * @private
2785
+ */
2786
+ execute_(fn) {
2787
+ try {
2788
+ activeFlows.push(this.flow_);
2789
+ this.flow_.activeQueue_ = this;
2790
+ return fn();
2791
+ } finally {
2792
+ this.flow_.activeQueue_ = null;
2793
+ activeFlows.pop();
2794
+ }
2795
+ }
2796
+
2797
+ /**
2798
+ * Process any unhandled rejections registered with this task queue. If there
2799
+ * is a rejection, this queue will be aborted with the rejection error. If
2800
+ * there are multiple rejections registered, this queue will be aborted with
2801
+ * a {@link MultipleUnhandledRejectionError}.
2802
+ * @return {boolean} whether there was an unhandled rejection.
2803
+ * @private
2804
+ */
2805
+ processUnhandledRejections_() {
2806
+ if (!this.unhandledRejections_.size) {
2807
+ return false;
2808
+ }
2809
+
2810
+ var errors = new Set();
2811
+ for (var rejection of this.unhandledRejections_) {
2812
+ errors.add(rejection.value_);
2813
+ }
2814
+ this.unhandledRejections_.clear();
2815
+
2816
+ var errorToReport = errors.size === 1
2817
+ ? errors.values().next().value
2818
+ : new MultipleUnhandledRejectionError(errors);
2819
+
2820
+ vlog(1, () => this + ' aborting due to unhandled rejections', this);
2821
+ if (this.flow_.propagateUnhandledRejections_) {
2822
+ this.abort_(errorToReport);
2823
+ return true;
2824
+ } else {
2825
+ vlog(1, 'error propagation disabled; reporting to control flow');
2826
+ this.flow_.reportUncaughtException_(errorToReport);
2827
+ return false;
2828
+ }
2829
+ }
2830
+
2831
+ /**
2832
+ * @param {!Task} task The task to drop.
2833
+ * @private
2834
+ */
2835
+ dropTask_(task) {
2836
+ var index;
2837
+ if (this.interrupts_) {
2838
+ index = this.interrupts_.indexOf(task);
2839
+ if (index != -1) {
2840
+ task.queue = null;
2841
+ this.interrupts_.splice(index, 1);
2842
+ return;
2843
+ }
2844
+ }
2845
+
2846
+ index = this.tasks_.indexOf(task);
2847
+ if (index != -1) {
2848
+ task.queue = null;
2849
+ this.tasks_.splice(index, 1);
2850
+ }
2851
+ }
2852
+
2853
+ /**
2854
+ * @param {!Task} task The task that was cancelled.
2855
+ * @param {!CancellationError} reason The cancellation reason.
2856
+ * @private
2857
+ */
2858
+ onTaskCancelled_(task, reason) {
2859
+ if (this.pending_ && this.pending_.task === task) {
2860
+ this.pending_.q.abort_(reason);
2861
+ } else {
2862
+ this.dropTask_(task);
2863
+ }
2864
+ }
2865
+
2866
+ /**
2867
+ * @param {*} value the value originally returned by the task function.
2868
+ * @private
2869
+ */
2870
+ onTaskComplete_(value) {
2871
+ if (this.pending_) {
2872
+ this.pending_.task.fulfill(value);
2873
+ }
2874
+ }
2875
+
2876
+ /**
2877
+ * @param {*} taskFnResult the value originally returned by the task function.
2878
+ * @param {*} error the error that caused the task function to terminate.
2879
+ * @private
2880
+ */
2881
+ onTaskFailure_(taskFnResult, error) {
2882
+ if (Thenable.isImplementation(taskFnResult)) {
2883
+ taskFnResult.cancel(CancellationError.wrap(error));
2884
+ }
2885
+ this.pending_.task.reject(error);
2886
+ }
2887
+
2888
+ /**
2889
+ * @return {(Task|undefined)} the next task scheduled within this queue,
2890
+ * if any.
2891
+ * @private
2892
+ */
2893
+ getNextTask_() {
2894
+ var task = undefined;
2895
+ while (true) {
2896
+ if (this.interrupts_) {
2897
+ task = this.interrupts_.shift();
2898
+ }
2899
+ if (!task && this.tasks_) {
2900
+ task = this.tasks_.shift();
2901
+ }
2902
+ if (task && task.blocked) {
2903
+ vlog(2, () => this + ' skipping blocked task ' + task, this);
2904
+ task.queue = null;
2905
+ task = null;
2906
+ // TODO: recurse when tail-call optimization is available in node.
2907
+ } else {
2908
+ break;
2909
+ }
2910
+ }
2911
+ return task;
2912
+ }
2913
+ };
2914
+
2915
+
2916
+
2917
+ /**
2918
+ * The default flow to use if no others are active.
2919
+ * @type {!ControlFlow}
2920
+ */
2921
+ var defaultFlow = new ControlFlow();
2922
+
2923
+
2924
+ /**
2925
+ * A stack of active control flows, with the top of the stack used to schedule
2926
+ * commands. When there are multiple flows on the stack, the flow at index N
2927
+ * represents a callback triggered within a task owned by the flow at index
2928
+ * N-1.
2929
+ * @type {!Array<!ControlFlow>}
2930
+ */
2931
+ var activeFlows = [];
2932
+
2933
+
2934
+ /**
2935
+ * Changes the default flow to use when no others are active.
2936
+ * @param {!ControlFlow} flow The new default flow.
2937
+ * @throws {Error} If the default flow is not currently active.
2938
+ */
2939
+ function setDefaultFlow(flow) {
2940
+ if (activeFlows.length) {
2941
+ throw Error('You may only change the default flow while it is active');
2942
+ }
2943
+ defaultFlow = flow;
2944
+ }
2945
+
2946
+
2947
+ /**
2948
+ * @return {!ControlFlow} The currently active control flow.
2949
+ */
2950
+ function controlFlow() {
2951
+ return /** @type {!ControlFlow} */ (
2952
+ activeFlows.length ? activeFlows[activeFlows.length - 1] : defaultFlow);
2953
+ }
2954
+
2955
+
2956
+ /**
2957
+ * Creates a new control flow. The provided callback will be invoked as the
2958
+ * first task within the new flow, with the flow as its sole argument. Returns
2959
+ * a promise that resolves to the callback result.
2960
+ * @param {function(!ControlFlow)} callback The entry point
2961
+ * to the newly created flow.
2962
+ * @return {!ManagedPromise} A promise that resolves to the callback
2963
+ * result.
2964
+ */
2965
+ function createFlow(callback) {
2966
+ var flow = new ControlFlow;
2967
+ return flow.execute(function() {
2968
+ return callback(flow);
2969
+ });
2970
+ }
2971
+
2972
+
2973
+ /**
2974
+ * Tests is a function is a generator.
2975
+ * @param {!Function} fn The function to test.
2976
+ * @return {boolean} Whether the function is a generator.
2977
+ */
2978
+ function isGenerator(fn) {
2979
+ return fn.constructor.name === 'GeneratorFunction';
2980
+ }
2981
+
2982
+
2983
+ /**
2984
+ * Consumes a {@code GeneratorFunction}. Each time the generator yields a
2985
+ * promise, this function will wait for it to be fulfilled before feeding the
2986
+ * fulfilled value back into {@code next}. Likewise, if a yielded promise is
2987
+ * rejected, the rejection error will be passed to {@code throw}.
2988
+ *
2989
+ * __Example 1:__ the Fibonacci Sequence.
2990
+ *
2991
+ * promise.consume(function* fibonacci() {
2992
+ * var n1 = 1, n2 = 1;
2993
+ * for (var i = 0; i < 4; ++i) {
2994
+ * var tmp = yield n1 + n2;
2995
+ * n1 = n2;
2996
+ * n2 = tmp;
2997
+ * }
2998
+ * return n1 + n2;
2999
+ * }).then(function(result) {
3000
+ * console.log(result); // 13
3001
+ * });
3002
+ *
3003
+ * __Example 2:__ a generator that throws.
3004
+ *
3005
+ * promise.consume(function* () {
3006
+ * yield promise.delayed(250).then(function() {
3007
+ * throw Error('boom');
3008
+ * });
3009
+ * }).catch(function(e) {
3010
+ * console.log(e.toString()); // Error: boom
3011
+ * });
3012
+ *
3013
+ * @param {!Function} generatorFn The generator function to execute.
3014
+ * @param {Object=} opt_self The object to use as "this" when invoking the
3015
+ * initial generator.
3016
+ * @param {...*} var_args Any arguments to pass to the initial generator.
3017
+ * @return {!ManagedPromise<?>} A promise that will resolve to the
3018
+ * generator's final result.
3019
+ * @throws {TypeError} If the given function is not a generator.
3020
+ */
3021
+ function consume(generatorFn, opt_self, var_args) {
3022
+ if (!isGenerator(generatorFn)) {
3023
+ throw new TypeError('Input is not a GeneratorFunction: ' +
3024
+ generatorFn.constructor.name);
3025
+ }
3026
+
3027
+ var deferred = defer();
3028
+ var generator = generatorFn.apply(
3029
+ opt_self, Array.prototype.slice.call(arguments, 2));
3030
+ callNext();
3031
+ return deferred.promise;
3032
+
3033
+ /** @param {*=} opt_value . */
3034
+ function callNext(opt_value) {
3035
+ pump(generator.next, opt_value);
3036
+ }
3037
+
3038
+ /** @param {*=} opt_error . */
3039
+ function callThrow(opt_error) {
3040
+ // Dictionary lookup required because Closure compiler's built-in
3041
+ // externs does not include GeneratorFunction.prototype.throw.
3042
+ pump(generator['throw'], opt_error);
3043
+ }
3044
+
3045
+ function pump(fn, opt_arg) {
3046
+ if (!deferred.isPending()) {
3047
+ return; // Defererd was cancelled; silently abort.
3048
+ }
3049
+
3050
+ try {
3051
+ var result = fn.call(generator, opt_arg);
3052
+ } catch (ex) {
3053
+ deferred.reject(ex);
3054
+ return;
3055
+ }
3056
+
3057
+ if (result.done) {
3058
+ deferred.fulfill(result.value);
3059
+ return;
3060
+ }
3061
+
3062
+ asap(result.value, callNext, callThrow);
3063
+ }
3064
+ }
3065
+
3066
+
3067
+ // PUBLIC API
3068
+
3069
+
3070
+ exports.CancellationError = CancellationError;
3071
+ exports.ControlFlow = ControlFlow;
3072
+ exports.Deferred = Deferred;
3073
+ exports.MultipleUnhandledRejectionError = MultipleUnhandledRejectionError;
3074
+ exports.Thenable = Thenable;
3075
+ exports.Promise = ManagedPromise;
3076
+ exports.all = all;
3077
+ exports.asap = asap;
3078
+ exports.captureStackTrace = captureStackTrace;
3079
+ exports.checkedNodeCall = checkedNodeCall;
3080
+ exports.consume = consume;
3081
+ exports.controlFlow = controlFlow;
3082
+ exports.createFlow = createFlow;
3083
+ exports.defer = defer;
3084
+ exports.delayed = delayed;
3085
+ exports.filter = filter;
3086
+ exports.fulfilled = fulfilled;
3087
+ exports.fullyResolved = fullyResolved;
3088
+ exports.isGenerator = isGenerator;
3089
+ exports.isPromise = isPromise;
3090
+ exports.map = map;
3091
+ exports.rejected = rejected;
3092
+ exports.setDefaultFlow = setDefaultFlow;
3093
+ exports.when = when;