2 * Copyright (c) 2014, Facebook, Inc.
5 * This source code is licensed under the BSD-style license found in the
6 * https://raw.github.com/facebook/regenerator/master/LICENSE file. An
7 * additional grant of patent rights can be found in the PATENTS file in
14 var Op = Object.prototype;
15 var hasOwn = Op.hasOwnProperty;
16 var undefined; // More compressible than void 0.
17 var $Symbol = typeof Symbol === "function" ? Symbol : {};
18 var iteratorSymbol = $Symbol.iterator || "@@iterator";
19 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
21 var inModule = typeof module === "object";
22 var runtime = global.regeneratorRuntime;
25 // If regeneratorRuntime is defined globally and we're in a module,
26 // make the exports object identical to regeneratorRuntime.
27 module.exports = runtime;
29 // Don't bother evaluating the rest of this file if the runtime was
30 // already defined globally.
34 // Define the runtime globally (as expected by generated code) as either
35 // module.exports (if we're in a module) or a new, empty object.
36 runtime = global.regeneratorRuntime = inModule ? module.exports : {};
38 function wrap(innerFn, outerFn, self, tryLocsList) {
39 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
40 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
41 var generator = Object.create(protoGenerator.prototype);
42 var context = new Context(tryLocsList || []);
44 // The ._invoke method unifies the implementations of the .next,
45 // .throw, and .return methods.
46 generator._invoke = makeInvokeMethod(innerFn, self, context);
52 // Try/catch helper to minimize deoptimizations. Returns a completion
53 // record like context.tryEntries[i].completion. This interface could
54 // have been (and was previously) designed to take a closure to be
55 // invoked without arguments, but in all the cases we care about we
56 // already have an existing method we want to call, so there's no need
57 // to create a new function object. We can even get away with assuming
58 // the method takes exactly one argument, since that happens to be true
59 // in every case, so we don't have to touch the arguments object. The
60 // only additional allocation required is the completion record, which
61 // has a stable shape and so hopefully should be cheap to allocate.
62 function tryCatch(fn, obj, arg) {
64 return { type: "normal", arg: fn.call(obj, arg) };
66 return { type: "throw", arg: err };
70 var GenStateSuspendedStart = "suspendedStart";
71 var GenStateSuspendedYield = "suspendedYield";
72 var GenStateExecuting = "executing";
73 var GenStateCompleted = "completed";
75 // Returning this object from the innerFn has the same effect as
76 // breaking out of the dispatch switch statement.
77 var ContinueSentinel = {};
79 // Dummy constructor functions that we use as the .constructor and
80 // .constructor.prototype properties for functions that return Generator
81 // objects. For full spec compliance, you may wish to configure your
82 // minifier not to mangle the names of these two functions.
83 function Generator() {}
84 function GeneratorFunction() {}
85 function GeneratorFunctionPrototype() {}
87 // This is a polyfill for %IteratorPrototype% for environments that
88 // don't natively support it.
89 var IteratorPrototype = {};
90 IteratorPrototype[iteratorSymbol] = function () {
94 var getProto = Object.getPrototypeOf;
95 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
96 if (NativeIteratorPrototype &&
97 NativeIteratorPrototype !== Op &&
98 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
99 // This environment has a native %IteratorPrototype%; use it instead
101 IteratorPrototype = NativeIteratorPrototype;
104 var Gp = GeneratorFunctionPrototype.prototype =
105 Generator.prototype = Object.create(IteratorPrototype);
106 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
107 GeneratorFunctionPrototype.constructor = GeneratorFunction;
108 GeneratorFunctionPrototype[toStringTagSymbol] =
109 GeneratorFunction.displayName = "GeneratorFunction";
111 // Helper for defining the .next, .throw, and .return methods of the
112 // Iterator interface in terms of a single ._invoke method.
113 function defineIteratorMethods(prototype) {
114 ["next", "throw", "return"].forEach(function(method) {
115 prototype[method] = function(arg) {
116 return this._invoke(method, arg);
121 runtime.isGeneratorFunction = function(genFun) {
122 var ctor = typeof genFun === "function" && genFun.constructor;
124 ? ctor === GeneratorFunction ||
125 // For the native GeneratorFunction constructor, the best we can
126 // do is to check its .name property.
127 (ctor.displayName || ctor.name) === "GeneratorFunction"
131 runtime.mark = function(genFun) {
132 if (Object.setPrototypeOf) {
133 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
135 genFun.__proto__ = GeneratorFunctionPrototype;
136 if (!(toStringTagSymbol in genFun)) {
137 genFun[toStringTagSymbol] = "GeneratorFunction";
140 genFun.prototype = Object.create(Gp);
144 // Within the body of any async function, `await x` is transformed to
145 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
146 // `hasOwn.call(value, "__await")` to determine if the yielded value is
147 // meant to be awaited.
148 runtime.awrap = function(arg) {
149 return { __await: arg };
152 function AsyncIterator(generator) {
153 function invoke(method, arg, resolve, reject) {
154 var record = tryCatch(generator[method], generator, arg);
155 if (record.type === "throw") {
158 var result = record.arg;
159 var value = result.value;
161 typeof value === "object" &&
162 hasOwn.call(value, "__await")) {
163 return Promise.resolve(value.__await).then(function(value) {
164 invoke("next", value, resolve, reject);
166 invoke("throw", err, resolve, reject);
170 return Promise.resolve(value).then(function(unwrapped) {
171 // When a yielded Promise is resolved, its final value becomes
172 // the .value of the Promise<{value,done}> result for the
173 // current iteration. If the Promise is rejected, however, the
174 // result for this iteration will be rejected with the same
175 // reason. Note that rejections of yielded Promises are not
176 // thrown back into the generator function, as is the case
177 // when an awaited Promise is rejected. This difference in
178 // behavior between yield and await is important, because it
179 // allows the consumer to decide what to do with the yielded
180 // rejection (swallow it and continue, manually .throw it back
181 // into the generator, abandon iteration, whatever). With
182 // await, by contrast, there is no opportunity to examine the
183 // rejection reason outside the generator function, so the
184 // only option is to throw it from the await expression, and
185 // let the generator function handle the exception.
186 result.value = unwrapped;
192 if (typeof process === "object" && process.domain) {
193 invoke = process.domain.bind(invoke);
198 function enqueue(method, arg) {
199 function callInvokeWithMethodAndArg() {
200 return new Promise(function(resolve, reject) {
201 invoke(method, arg, resolve, reject);
205 return previousPromise =
206 // If enqueue has been called before, then we want to wait until
207 // all previous Promises have been resolved before calling invoke,
208 // so that results are always delivered in the correct order. If
209 // enqueue has not been called before, then it is important to
210 // call invoke immediately, without waiting on a callback to fire,
211 // so that the async generator function has the opportunity to do
212 // any necessary setup in a predictable way. This predictability
213 // is why the Promise constructor synchronously invokes its
214 // executor callback, and why async functions synchronously
215 // execute code before the first await. Since we implement simple
216 // async functions in terms of async generators, it is especially
217 // important to get this right, even though it requires care.
218 previousPromise ? previousPromise.then(
219 callInvokeWithMethodAndArg,
220 // Avoid propagating failures to Promises returned by later
221 // invocations of the iterator.
222 callInvokeWithMethodAndArg
223 ) : callInvokeWithMethodAndArg();
226 // Define the unified helper method that is used to implement .next,
227 // .throw, and .return (see defineIteratorMethods).
228 this._invoke = enqueue;
231 defineIteratorMethods(AsyncIterator.prototype);
232 runtime.AsyncIterator = AsyncIterator;
234 // Note that simple async functions are implemented on top of
235 // AsyncIterator objects; they just return a Promise for the value of
236 // the final result produced by the iterator.
237 runtime.async = function(innerFn, outerFn, self, tryLocsList) {
238 var iter = new AsyncIterator(
239 wrap(innerFn, outerFn, self, tryLocsList)
242 return runtime.isGeneratorFunction(outerFn)
243 ? iter // If outerFn is a generator, return the full iterator.
244 : iter.next().then(function(result) {
245 return result.done ? result.value : iter.next();
249 function makeInvokeMethod(innerFn, self, context) {
250 var state = GenStateSuspendedStart;
252 return function invoke(method, arg) {
253 if (state === GenStateExecuting) {
254 throw new Error("Generator is already running");
257 if (state === GenStateCompleted) {
258 if (method === "throw") {
262 // Be forgiving, per 25.3.3.3.3 of the spec:
263 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
267 context.method = method;
271 var delegate = context.delegate;
273 var delegateResult = maybeInvokeDelegate(delegate, context);
274 if (delegateResult) {
275 if (delegateResult === ContinueSentinel) continue;
276 return delegateResult;
280 if (context.method === "next") {
281 // Setting context._sent for legacy support of Babel's
282 // function.sent implementation.
283 context.sent = context._sent = context.arg;
285 } else if (context.method === "throw") {
286 if (state === GenStateSuspendedStart) {
287 state = GenStateCompleted;
291 context.dispatchException(context.arg);
293 } else if (context.method === "return") {
294 context.abrupt("return", context.arg);
297 state = GenStateExecuting;
299 var record = tryCatch(innerFn, self, context);
300 if (record.type === "normal") {
301 // If an exception is thrown from innerFn, we leave state ===
302 // GenStateExecuting and loop back for another invocation.
305 : GenStateSuspendedYield;
307 if (record.arg === ContinueSentinel) {
316 } else if (record.type === "throw") {
317 state = GenStateCompleted;
318 // Dispatch the exception by looping back around to the
319 // context.dispatchException(context.arg) call above.
320 context.method = "throw";
321 context.arg = record.arg;
327 // Call delegate.iterator[context.method](context.arg) and handle the
328 // result, either by returning a { value, done } result from the
329 // delegate iterator, or by modifying context.method and context.arg,
330 // setting context.delegate to null, and returning the ContinueSentinel.
331 function maybeInvokeDelegate(delegate, context) {
332 var method = delegate.iterator[context.method];
333 if (method === undefined) {
334 // A .throw or .return when the delegate iterator has no .throw
335 // method always terminates the yield* loop.
336 context.delegate = null;
338 if (context.method === "throw") {
339 if (delegate.iterator.return) {
340 // If the delegate iterator has a return method, give it a
341 // chance to clean up.
342 context.method = "return";
343 context.arg = undefined;
344 maybeInvokeDelegate(delegate, context);
346 if (context.method === "throw") {
347 // If maybeInvokeDelegate(context) changed context.method from
348 // "return" to "throw", let that override the TypeError below.
349 return ContinueSentinel;
353 context.method = "throw";
354 context.arg = new TypeError(
355 "The iterator does not provide a 'throw' method");
358 return ContinueSentinel;
361 var record = tryCatch(method, delegate.iterator, context.arg);
363 if (record.type === "throw") {
364 context.method = "throw";
365 context.arg = record.arg;
366 context.delegate = null;
367 return ContinueSentinel;
370 var info = record.arg;
373 context.method = "throw";
374 context.arg = new TypeError("iterator result is not an object");
375 context.delegate = null;
376 return ContinueSentinel;
380 // Assign the result of the finished delegate to the temporary
381 // variable specified by delegate.resultName (see delegateYield).
382 context[delegate.resultName] = info.value;
384 // Resume execution at the desired location (see delegateYield).
385 context.next = delegate.nextLoc;
387 // If context.method was "throw" but the delegate handled the
388 // exception, let the outer generator proceed normally. If
389 // context.method was "next", forget context.arg since it has been
390 // "consumed" by the delegate iterator. If context.method was
391 // "return", allow the original .return call to continue in the
393 if (context.method !== "return") {
394 context.method = "next";
395 context.arg = undefined;
399 // Re-yield the result returned by the delegate method.
403 // The delegate iterator is finished, so forget it and continue with
404 // the outer generator.
405 context.delegate = null;
406 return ContinueSentinel;
409 // Define Generator.prototype.{next,throw,return} in terms of the
410 // unified ._invoke helper method.
411 defineIteratorMethods(Gp);
413 Gp[toStringTagSymbol] = "Generator";
415 Gp.toString = function() {
416 return "[object Generator]";
419 function pushTryEntry(locs) {
420 var entry = { tryLoc: locs[0] };
423 entry.catchLoc = locs[1];
427 entry.finallyLoc = locs[2];
428 entry.afterLoc = locs[3];
431 this.tryEntries.push(entry);
434 function resetTryEntry(entry) {
435 var record = entry.completion || {};
436 record.type = "normal";
438 entry.completion = record;
441 function Context(tryLocsList) {
442 // The root entry object (effectively a try statement without a catch
443 // or a finally block) gives us a place to store values thrown from
444 // locations where there is no enclosing try statement.
445 this.tryEntries = [{ tryLoc: "root" }];
446 tryLocsList.forEach(pushTryEntry, this);
450 runtime.keys = function(object) {
452 for (var key in object) {
457 // Rather than returning an object with a next method, we keep
458 // things simple and return the next function itself.
459 return function next() {
460 while (keys.length) {
461 var key = keys.pop();
469 // To avoid creating an additional object, we just hang the .value
470 // and .done properties off the next function object itself. This
471 // also ensures that the minifier will not anonymize the function.
477 function values(iterable) {
479 var iteratorMethod = iterable[iteratorSymbol];
480 if (iteratorMethod) {
481 return iteratorMethod.call(iterable);
484 if (typeof iterable.next === "function") {
488 if (!isNaN(iterable.length)) {
489 var i = -1, next = function next() {
490 while (++i < iterable.length) {
491 if (hasOwn.call(iterable, i)) {
492 next.value = iterable[i];
498 next.value = undefined;
504 return next.next = next;
508 // Return an iterator with no values.
509 return { next: doneResult };
511 runtime.values = values;
513 function doneResult() {
514 return { value: undefined, done: true };
517 Context.prototype = {
518 constructor: Context,
520 reset: function(skipTempReset) {
523 // Resetting context._sent for legacy support of Babel's
524 // function.sent implementation.
525 this.sent = this._sent = undefined;
527 this.delegate = null;
529 this.method = "next";
530 this.arg = undefined;
532 this.tryEntries.forEach(resetTryEntry);
534 if (!skipTempReset) {
535 for (var name in this) {
536 // Not sure about the optimal order of these conditions:
537 if (name.charAt(0) === "t" &&
538 hasOwn.call(this, name) &&
539 !isNaN(+name.slice(1))) {
540 this[name] = undefined;
549 var rootEntry = this.tryEntries[0];
550 var rootRecord = rootEntry.completion;
551 if (rootRecord.type === "throw") {
552 throw rootRecord.arg;
558 dispatchException: function(exception) {
564 function handle(loc, caught) {
565 record.type = "throw";
566 record.arg = exception;
570 // If the dispatched exception was caught by a catch block,
571 // then let that catch block handle the exception normally.
572 context.method = "next";
573 context.arg = undefined;
579 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
580 var entry = this.tryEntries[i];
581 var record = entry.completion;
583 if (entry.tryLoc === "root") {
584 // Exception thrown outside of any try block that could handle
585 // it, so set the completion value of the entire function to
586 // throw the exception.
587 return handle("end");
590 if (entry.tryLoc <= this.prev) {
591 var hasCatch = hasOwn.call(entry, "catchLoc");
592 var hasFinally = hasOwn.call(entry, "finallyLoc");
594 if (hasCatch && hasFinally) {
595 if (this.prev < entry.catchLoc) {
596 return handle(entry.catchLoc, true);
597 } else if (this.prev < entry.finallyLoc) {
598 return handle(entry.finallyLoc);
601 } else if (hasCatch) {
602 if (this.prev < entry.catchLoc) {
603 return handle(entry.catchLoc, true);
606 } else if (hasFinally) {
607 if (this.prev < entry.finallyLoc) {
608 return handle(entry.finallyLoc);
612 throw new Error("try statement without catch or finally");
618 abrupt: function(type, arg) {
619 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
620 var entry = this.tryEntries[i];
621 if (entry.tryLoc <= this.prev &&
622 hasOwn.call(entry, "finallyLoc") &&
623 this.prev < entry.finallyLoc) {
624 var finallyEntry = entry;
631 type === "continue") &&
632 finallyEntry.tryLoc <= arg &&
633 arg <= finallyEntry.finallyLoc) {
634 // Ignore the finally entry if control is not jumping to a
635 // location outside the try/catch block.
639 var record = finallyEntry ? finallyEntry.completion : {};
644 this.method = "next";
645 this.next = finallyEntry.finallyLoc;
646 return ContinueSentinel;
649 return this.complete(record);
652 complete: function(record, afterLoc) {
653 if (record.type === "throw") {
657 if (record.type === "break" ||
658 record.type === "continue") {
659 this.next = record.arg;
660 } else if (record.type === "return") {
661 this.rval = this.arg = record.arg;
662 this.method = "return";
664 } else if (record.type === "normal" && afterLoc) {
665 this.next = afterLoc;
668 return ContinueSentinel;
671 finish: function(finallyLoc) {
672 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
673 var entry = this.tryEntries[i];
674 if (entry.finallyLoc === finallyLoc) {
675 this.complete(entry.completion, entry.afterLoc);
676 resetTryEntry(entry);
677 return ContinueSentinel;
682 "catch": function(tryLoc) {
683 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
684 var entry = this.tryEntries[i];
685 if (entry.tryLoc === tryLoc) {
686 var record = entry.completion;
687 if (record.type === "throw") {
688 var thrown = record.arg;
689 resetTryEntry(entry);
695 // The context.catch method must only be called with a location
696 // argument that corresponds to a known catch block.
697 throw new Error("illegal catch attempt");
700 delegateYield: function(iterable, resultName, nextLoc) {
702 iterator: values(iterable),
703 resultName: resultName,
707 if (this.method === "next") {
708 // Deliberately forget the last sent value so that we don't
709 // accidentally pass it on to the delegate.
710 this.arg = undefined;
713 return ContinueSentinel;
717 // Among the various tricks for obtaining a reference to the global
718 // object, this seems to be the most reliable technique that does not
719 // use indirect eval (which violates Content Security Policy).
720 typeof global === "object" ? global :
721 typeof window === "object" ? window :
722 typeof self === "object" ? self : this