Bug 1614879 [wpt PR 21750] - Set request mode for beacon request with non-cors-safeli...
[gecko.git] / remote / Sync.jsm
blobabc532c372c3f74c17c0eb6243cdd82cb469809e
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 "use strict";
7 var EXPORTED_SYMBOLS = [
8   "DOMContentLoadedPromise",
9   "EventPromise",
10   "MessagePromise",
11   "PollPromise",
14 const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
16 const { TYPE_REPEATING_SLACK } = Ci.nsITimer;
18 /**
19  * Wait for a single event to be fired on a specific EventListener.
20  *
21  * The returned promise is guaranteed to not be called before the
22  * next event tick after the event listener is called, so that all
23  * other event listeners for the element are executed before the
24  * handler is executed.  For example:
25  *
26  *     const promise = new EventPromise(element, "myEvent");
27  *     // same event tick here
28  *     await promise;
29  *     // next event tick here
30  *
31  * @param {EventListener} listener
32  *     Object which receives a notification (an object that implements
33  *     the Event interface) when an event of the specificed type occurs.
34  * @param {string} type
35  *     Case-sensitive string representing the event type to listen for.
36  * @param {boolean?} [false] options.capture
37  *     Indicates the event will be despatched to this subject,
38  *     before it bubbles down to any EventTarget beneath it in the
39  *     DOM tree.
40  * @param {boolean?} [false] options.wantsUntrusted
41  *     Receive synthetic events despatched by web content.
42  * @param {boolean?} [false] options.mozSystemGroup
43  *     Determines whether to add listener to the system group.
44  *
45  * @return {Promise.<Event>}
46  *
47  * @throws {TypeError}
48  */
49 function EventPromise(
50   listener,
51   type,
52   options = {
53     capture: false,
54     wantsUntrusted: false,
55     mozSystemGroup: false,
56   }
57 ) {
58   if (!listener || !("addEventListener" in listener)) {
59     throw new TypeError();
60   }
61   if (typeof type != "string") {
62     throw new TypeError();
63   }
64   if (
65     ("capture" in options && typeof options.capture != "boolean") ||
66     ("wantsUntrusted" in options &&
67       typeof options.wantsUntrusted != "boolean") ||
68     ("mozSystemGroup" in options && typeof options.mozSystemGroup != "boolean")
69   ) {
70     throw new TypeError();
71   }
73   options.once = true;
75   return new Promise(resolve => {
76     listener.addEventListener(
77       type,
78       event => {
79         Services.tm.dispatchToMainThread(() => resolve(event));
80       },
81       options
82     );
83   });
86 function DOMContentLoadedPromise(window, options = { mozSystemGroup: true }) {
87   if (
88     window.document.readyState == "complete" ||
89     window.document.readyState == "interactive"
90   ) {
91     return Promise.resolve();
92   }
93   return new EventPromise(window, "DOMContentLoaded", options);
96 /**
97  * Awaits a single IPC message.
98  *
99  * @param {nsIMessageSender} target
100  * @param {string} name
102  * @return {Promise}
104  * @throws {TypeError}
105  *     If target is not an nsIMessageSender.
106  */
107 function MessagePromise(target, name) {
108   if (!(target instanceof Ci.nsIMessageSender)) {
109     throw new TypeError();
110   }
112   return new Promise(resolve => {
113     const onMessage = (...args) => {
114       target.removeMessageListener(name, onMessage);
115       resolve(...args);
116     };
117     target.addMessageListener(name, onMessage);
118   });
122  * Runs a Promise-like function off the main thread until it is resolved
123  * through ``resolve`` or ``rejected`` callbacks.  The function is
124  * guaranteed to be run at least once, irregardless of the timeout.
126  * The ``func`` is evaluated every ``interval`` for as long as its
127  * runtime duration does not exceed ``interval``.  Evaluations occur
128  * sequentially, meaning that evaluations of ``func`` are queued if
129  * the runtime evaluation duration of ``func`` is greater than ``interval``.
131  * ``func`` is given two arguments, ``resolve`` and ``reject``,
132  * of which one must be called for the evaluation to complete.
133  * Calling ``resolve`` with an argument indicates that the expected
134  * wait condition was met and will return the passed value to the
135  * caller.  Conversely, calling ``reject`` will evaluate ``func``
136  * again until the ``timeout`` duration has elapsed or ``func`` throws.
137  * The passed value to ``reject`` will also be returned to the caller
138  * once the wait has expired.
140  * Usage::
142  *     let els = new PollPromise((resolve, reject) => {
143  *       let res = document.querySelectorAll("p");
144  *       if (res.length > 0) {
145  *         resolve(Array.from(res));
146  *       } else {
147  *         reject([]);
148  *       }
149  *     }, {timeout: 1000});
151  * @param {Condition} func
152  *     Function to run off the main thread.
153  * @param {number=} [timeout] timeout
154  *     Desired timeout if wanted.  If 0 or less than the runtime evaluation
155  *     time of ``func``, ``func`` is guaranteed to run at least once.
156  *     Defaults to using no timeout.
157  * @param {number=} [interval=10] interval
158  *     Duration between each poll of ``func`` in milliseconds.
159  *     Defaults to 10 milliseconds.
161  * @return {Promise.<*>}
162  *     Yields the value passed to ``func``'s
163  *     ``resolve`` or ``reject`` callbacks.
165  * @throws {*}
166  *     If ``func`` throws, its error is propagated.
167  * @throws {TypeError}
168  *     If `timeout` or `interval`` are not numbers.
169  * @throws {RangeError}
170  *     If `timeout` or `interval` are not unsigned integers.
171  */
172 function PollPromise(func, { timeout = null, interval = 10 } = {}) {
173   const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
175   if (typeof func != "function") {
176     throw new TypeError();
177   }
178   if (timeout != null && typeof timeout != "number") {
179     throw new TypeError();
180   }
181   if (typeof interval != "number") {
182     throw new TypeError();
183   }
184   if (
185     (timeout && (!Number.isInteger(timeout) || timeout < 0)) ||
186     (!Number.isInteger(interval) || interval < 0)
187   ) {
188     throw new RangeError();
189   }
191   return new Promise((resolve, reject) => {
192     let start, end;
194     if (Number.isInteger(timeout)) {
195       start = new Date().getTime();
196       end = start + timeout;
197     }
199     let evalFn = () => {
200       new Promise(func)
201         .then(resolve, rejected => {
202           if (typeof rejected != "undefined") {
203             throw rejected;
204           }
206           // return if there is a timeout and set to 0,
207           // allowing |func| to be evaluated at least once
208           if (
209             typeof end != "undefined" &&
210             (start == end || new Date().getTime() >= end)
211           ) {
212             resolve(rejected);
213           }
214         })
215         .catch(reject);
216     };
218     // the repeating slack timer waits |interval|
219     // before invoking |evalFn|
220     evalFn();
222     timer.init(evalFn, interval, TYPE_REPEATING_SLACK);
223   }).then(
224     res => {
225       timer.cancel();
226       return res;
227     },
228     err => {
229       timer.cancel();
230       throw err;
231     }
232   );