UNPKG

2.17 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2014-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8var fs = require("fs");
9var through = require("through");
10var transform = require("./lib/visit").transform;
11var utils = require("./lib/util");
12
13function exports(file, options) {
14 var data = [];
15 return through(write, end);
16
17 function write(buf) {
18 data.push(buf);
19 }
20
21 function end() {
22 try {
23 this.queue(compile(data.join(""), options).code);
24 this.queue(null);
25 } catch (e) { this.emit('error', e); }
26 }
27}
28
29// To get a writable stream for use as a browserify transform, call
30// require("regenerator")().
31module.exports = exports;
32
33// To include the runtime globally in the current node process, call
34// require("regenerator").runtime().
35function runtime() {
36 regeneratorRuntime = require("regenerator-runtime");
37}
38exports.runtime = runtime;
39runtime.path = require("regenerator-runtime/path.js").path;
40
41var cachedRuntimeCode;
42function getRuntimeCode() {
43 return cachedRuntimeCode ||
44 (cachedRuntimeCode = fs.readFileSync(runtime.path, "utf8"));
45}
46
47var transformOptions = {
48 presets: [require("regenerator-preset")],
49 parserOpts: {
50 sourceType: "module",
51 allowImportExportEverywhere: true,
52 allowReturnOutsideFunction: true,
53 allowSuperOutsideMethod: true,
54 strictMode: false,
55 plugins: ["*", "jsx", "flow"]
56 }
57};
58
59function compile(source, options) {
60 var result;
61
62 options = utils.defaults(options || {}, {
63 includeRuntime: false
64 });
65
66 var result = require("@babel/core").transformSync(
67 source,
68 transformOptions
69 );
70
71 if (options.includeRuntime === true) {
72 result.code = getRuntimeCode() + "\n" + result.code;
73 }
74
75 return result;
76}
77
78// Allow packages that depend on Regenerator to use the same copy of
79// ast-types, in case multiple versions are installed by NPM.
80exports.types = require("recast").types;
81
82// Transforms a string of source code, returning a { code, map? } result.
83exports.compile = compile;
84
85// To modify an AST directly, call require("regenerator").transform(ast).
86exports.transform = transform;