function init(){ var options = { presets: [ require('babel-preset-es2015') ], plugins: [ require('babel-plugin-syntax-object-rest-spread'), require('babel-plugin-transform-object-rest-spread'), [require('../src/index.js'), { prefix: 'sql:', mode :'lodash', debug:true }] ], babelrc : false }; //gen loadsh code var lodashResult = babel.transformFileSync('./test/gen/test_main.js', options); fs.writeFileSync('./test/gen/test_main.lodash.gen.js', lodashResult.code); lodashTestCase = require(path.join(__dirname, '/gen/test_main.lodash.gen')); //gen underscore code options.plugins[2][1].mode = 'underscore'; var underscoreResult = babel.transformFileSync('./test/gen/test_main.js', options); fs.writeFileSync('./test/gen/test_main.underscore.gen.js', underscoreResult.code.replace(/require\('lodash'\)/gi, "require('underscore')")); underscoreTestCase = require(path.join(__dirname, '/gen/test_main.underscore.gen')); }
it(name, function () { var actualPath = path.join(dir, 'actual.js'); var expectedPath = path.join(dir, 'expected.js'); var opts = mergeOpts(options, getOpts(dir)); var throwsOpt = opts.throws; deleteTestingOptions(opts); opts = finalizeOpts(opts); var actual; try { actual = babel.transformFileSync(actualPath, opts).code; } catch(e) { if (throwsOpt) { var regex = new RegExp(throwsOpt); var expectedPattern = "Pattern /" + throwsOpt + "/"; if (!regex.test(e.message)) { assert.equal(expectedPattern, e.message, "Should throw an error matching the pattern"); } else { return assert.ok(expectedPattern); } } throw e; } var expected = fs.readFileSync(expectedPath, textEncoding); assert.equal(normalizeEndings(actual), normalizeEndings(expected)); });
return new Promise((resolve, reject) => { var babelExceptions = ['core/lib/lively-libs-debug.js'], cacheFile = path.join(cacheDir, file.replace(/\//g, "_")), mtimeFile = cacheFile + ".mtime", mtime = String(fs.statSync(file).mtime), needsUpdate = !fs.existsSync(cacheFile) || !fs.existsSync(mtimeFile) || mtime !== String(fs.readFileSync(mtimeFile)), source; if (needsUpdate) { console.log(file + " needs update"); source = babelExceptions.indexOf(file) > -1 ? fs.readFileSync(file) : babel.transformFileSync(file, {"presets": ["es2015"]}).code; fs.writeFileSync(cacheFile, source); fs.writeFileSync(mtimeFile, mtime); } resolve({ source: file, code: source && String(source), sourcesRelativeTo: rootDir.replace(/\/$/, "/"), cacheFile: cacheFile, wasChanged: !!source }); });
function transform(fixture) { const file = path.join(fixturesDir, fixture); return transformFileSync(file, { babelrc: false, plugins: [ plugin ] }).code; }
function transformFile(path, configuration = { config: './runtime.webpack.config.js' }) { return babel.transformFileSync(resolve(__dirname, path), { plugins: [ ['../../src/index.js', configuration] ] }); }
var babel = function(src, dist){ //http://babeljs.io/docs/usage/api/#options //https://github.com/babel/babel/tree/master/packages/babel-preset-es2015 var options = { presets: [ require('babel-preset-es2015') // require('babel-preset-es2015-without-strict') ,require('babel-preset-stage-1') ] } try { var dist = path.normalize(dist +'/'+ src); var src = path.normalize(jdf.currentDir +'/'+ src); if(jdf.config.build.hasCmdLog) console.log('buildES6js---'+ src); var result = babelCore.transformFileSync(src, options); f.write(dist, result.code); } catch (e) { console.log('jdf error [jdf.buildJS.ES6] - ' + src); console.log(e); } }
.map((caseName) => { var lib = caseName.split('-')[0] const options = { babelrc: false, plugins: [ [plugin, { moduleIdName: /module-id-name/.test(caseName), modulePath: /module-id-name/.test(caseName), testExportName: /test-export-name/.test(caseName) ? '^[A-Z]/m' : false, import: /import/.test(caseName), accept: /accept/.test(caseName), include: '**/fixtures/**', exclude: '**/exclude*/**', proxy: /proxy-options/.test(caseName) ? {debug: 'info'} : undefined, lib: lib }] ] } const fixtureDir = path.join(fixturesDir, caseName) const actualPath = path.join(fixtureDir, 'source.js') const expectedPath = path.join(fixtureDir, 'transformed.js') let actual try { actual = trim(transformFileSync(actualPath, options).code) } catch (e) { console.error(e.message, e.stack) } const expected = fs.existsSync(expectedPath) && trim(fs.readFileSync(expectedPath, 'utf-8')) handler && handler({caseName, actual, expected, expectedPath}) })
function transpileFile (filename, pluginOptions) { return Babel.transformFileSync(require.resolve(filename), { presets: [ 'es2015' ], plugins: [ [ __coverage__Plugin, pluginOptions ] ], babelrc: false }).code }
export default async (filename) => { console.info(`Executing: ${filename}\n`) const tmpDir = '/tmp/' const workdir = fs.mkdtempSync(tmpDir) const libname = filename.match(/[\w]+.js$/g)[0].replace('.js', '').toLowerCase() const file = fs.readFileSync(filename, { encoding: 'UTF-8' }) const deps = showdeps(file) const dependencies = deps.map(getFileName) const code = transformFileSync(filename, { plugins: ['transform-remove-import', 'add-module-exports', 'transform-remove-strict-mode'], }).code const library = {} library.code = makeCode(code, deps) library.package = makePackage(libname, packageJson.version, dependencies) library.readme = makeReadme(libname, packageJson.version) const options = { encoding: 'utf-8' } fs.writeFileSync(`${workdir}/index.js`, library.code, options) fs.writeFileSync(`${workdir}/package.json`, library.package, options) fs.writeFileSync(`${workdir}/readme.md`, library.readme, options) await exec(`cd ${workdir} && npm publish`, (error, stdout, stderr) => { console.info(filename) if (error) { console.error(`exec error: ${error}`) return } console.info(`stdout: ${stdout}`) console.info(`stderr: ${stderr}`) }) }
return __awaiter(this, void 0, void 0, function* () { let ast; if (FSHARP_EXT.test(path)) { // return Babel AST from F# file const fableMsg = JSON.stringify(Object.assign({}, options.fable, { path })); const response = yield fableUtils.client.send(options.port, fableMsg); const babelAst = JSON.parse(response); if (babelAst.error) { throw new Error(babelAst.error); } addLogs(babelAst.logs, info); ast = Babel.transformFromAst(babelAst, undefined, { code: false }); } else { // return Babel AST from JS file path = JAVASCRIPT_EXT.test(path) ? path : path + ".js"; if (fs.existsSync(path)) { try { ast = Babel.transformFileSync(path, { code: false }); } catch (err) { const log = `${path}(1,1): error BABEL: ${err.message}`; addLogs({ error: [log] }, info); } } else { console.log(`fable: Skipping missing JS file: ${path}`); } } return ast; });
function transformFile(path, configuration) { return babel.transformFileSync(resolve(__dirname, path), { plugins: [ configuration ? ['../../src/index.js', configuration] : '../../src/index.js', ], }); }
it(`should ${caseName.split('-').join(' ')}`, () => { const fixtureDir = path.join(fixturesDir, caseName); const actualPath = path.join(fixtureDir, 'actual.js'); const optionsPath = path.join(fixtureDir, 'options.js'); const exceptionPath = path.join(fixtureDir, 'exception.txt'); const options = { babelrc: false, plugins: [plugin] }; if (fileExists(optionsPath)) { const opts = require(optionsPath); options.plugins = [[plugin, opts]]; options.moduleId = opts.moduleName; } if (fileExists(exceptionPath)) { const exception = fs.readFileSync(exceptionPath).toString(); assert.throws(() => { transformFileSync(actualPath, options); }, new RegExp(exception)); } else { const actual = transformFileSync(actualPath, options).code; const expected = fs.readFileSync( path.join(fixtureDir, 'expected.js') ).toString(); assert.equal(trim(actual), trim(expected)); } });
it(`should work with ${caseName.split('-').join(' ')}`, () => { const actual = transformFileSync(actualFile, { 'plugins': [plugin] }).code; const expected = fs.readFileSync(expectedFile, 'utf8'); assert.equal(actual.trim(), expected.trim()); });
function buildFile(file, silent) { const destPath = getBuildPath(file, BUILD_DIR); if (micromatch.isMatch(file, IGNORE_PATTERN)) { silent || process.stdout.write( chalk.dim(' \u2022 ') + path.relative(PACKAGES_DIR, file) + ' (ignore)\n' ); return; } mkdirp.sync(path.dirname(destPath)); if (!micromatch.isMatch(file, JS_FILES_PATTERN)) { fs.createReadStream(file).pipe(fs.createWriteStream(destPath)); silent || process.stdout.write( chalk.red(' \u2022 ') + path.relative(PACKAGES_DIR, file) + chalk.red(' \u21D2 ') + path.relative(PACKAGES_DIR, destPath) + ' (copy)' + '\n' ); } else { const options = Object.assign({}, transformOptions); options.plugins = options.plugins.slice(); if (!INLINE_REQUIRE_BLACKLIST.test(file)) { // Remove normal plugin. options.plugins = options.plugins.filter( plugin => !( Array.isArray(plugin) && plugin[0] === 'transform-es2015-modules-commonjs' ) ); options.plugins.push([ 'transform-inline-imports-commonjs', { allowTopLevelThis: true, }, ]); } const transformed = babel.transformFileSync(file, options).code; const prettyCode = prettier.format(transformed, prettierConfig); fs.writeFileSync(destPath, prettyCode); silent || process.stdout.write( chalk.green(' \u2022 ') + path.relative(PACKAGES_DIR, file) + chalk.green(' \u21D2 ') + path.relative(PACKAGES_DIR, destPath) + '\n' ); } }
tranform(sourcePath) { const destPath = path.resolve(__dirname, this.outputPath + sourcePath.replace(/^src\//, '')) const dirPath = path.dirname(destPath) mkdirp.sync(dirPath, this.errHandle.bind(this)) return fs.writeFile(destPath, babel.transformFileSync(sourcePath, this.babelConfig).code, this.errHandle.bind(this)) }
it(`should work with ${ testName }`, () => { const expected = fs.readFileSync(expectedPath, 'utf8'); const actual = transformFileSync(actualPath, { 'plugins': [[plugin, options]] }).code; assert.strictEqual(_.trim(actual), _.trim(expected)); });
const test = (name, options) => { const expectedCode = getExpectedCode(name) const transformedCode = transformFileSync(getInputCode(name), { babelrc: false, plugins: [[plugin, options]] }).code expect(transformedCode).to.equal(expectedCode) }
it(`should ${caseName.split("-").join(" ")}`, () => { const fixtureDir = path.join(fixturesDir, caseName); const actual = babel.transformFileSync( path.join(fixtureDir, "actual.js") ).code; const expected = fs.readFileSync(path.join(fixtureDir, "expected.js")).toString(); assert.equal(trim(actual), trim(expected)); });
it(`Absolute path ${test.file}`, function(done) { var transform = transformFileSync(path.join(__dirname, `src/${test.file}.js`), { plugins: [[plugin, test.options]], babelrc: false // So we don't get babelrc from whole project }).code var expected = fs.readFileSync(path.join(__dirname, `expected/${test.file}.js`)).toString() assert.equal(transform, expected) done() })
it(`case: ${test.file}`, function() { var transform = normalize(transformFileSync(path.join(__dirname, `src/${test.file}.js`), { plugins: [[plugin, test.options]], babelrc: false // So we don't get babelrc from whole project }).code); var expected = normalize(fs.readFileSync(path.join(__dirname, `expected/${test.file}.js`), {encoding: 'utf-8'})); assert.equal(transform, expected); })
const compile = function (module, filename) { try { module._compile(transform(transformFileSync(filename, { plugins: ['transform-es2015-modules-commonjs'] }).code, bubleOpts).code, filename) } catch (err) { console.trace(err) } }
it(name, function () { var fixturePath = path.resolve(__dirname, 'fixtures', name, 'fixture.js'); var expectedPath = path.resolve(__dirname, 'fixtures', name, 'expected.js'); var expected = fs.readFileSync(expectedPath).toString(); var result = babel.transformFileSync(fixturePath, { plugins: plugins }); assert.strictEqual(result.code + '\n', expected); });
test(`should ${caseName.split('-').join(' ')}`, (t) => { const fixtureDir = join(fixturesDir, caseName); const actualPath = join(fixtureDir, 'actual.js'); const expectedPath = join(fixtureDir, 'expected.js'); const actual = transformFileSync(actualPath).code; const expected = readFileSync(expectedPath).toString(); t.is(sanitize(actual), sanitize(expected)); });
draw(filename) { const result = babel.transformFileSync(filename, { ast: false }) const g = Object.create(null) g.routeMapper = this vm.runInNewContext(result.code, g) }
test('Tests that required imports were overridden by hijack', () => { const parsed = babel.transformFileSync(path.resolve(__dirname, './fixture1.js'), babelOpts); const code = parsed.code; expect(code).toContain('./fixture2overrides'); const evaledCode = eval(code); // eslint-disable-line no-eval expect(evaledCode.fixture2Imported()).toBe('fixture2overrides'); expect(evaledCode.fixture2Required()).toBe('fixture2overrides'); expect(evaledCode.fixture3()).toBe('fixture3overrides'); expect(evaledCode.fs()).toBe('fsOverrides'); });
it(`should ${caseName.split('-').join(' ')}`, () => { const fixtureDir = path.join(fixturesDir, caseName); const actualPath = path.join(fixtureDir, 'actual.js'); const actual = transformFileSync(actualPath).code; const expected = fs.readFileSync( path.join(fixtureDir, 'expected.js') ).toString(); assert.equal(trim(actual), trim(expected)); });
it('should work with cherry-pick modular builds', () => { const actualPath = path.join(__dirname, 'feature/actual.js'); const expectedPath = path.join(__dirname, 'feature/expect.js'); const actual = transformFileSync(actualPath, { 'plugins': [plugin], }).code; const expected = fs.readFileSync(expectedPath, 'utf8'); assert.strictEqual(actual.trim(), expected.trim()); });
it(caseName, () => { const fixtureDir = path.join(fixturesDir, caseName) const actualPath = path.join(fixtureDir, "actual.js") const actual = transformFileSync(actualPath, { babelrc: false, plugins: [path.resolve("./src/index.js")] }).code const expected = fs.readFileSync(path.join(fixtureDir, "expected.js")).toString() expect(actual.trim()).to.eq(expected.trim()) })
const outputExpected = name => plugins => { const output = babel.transformFileSync(`${__dirname}/fixtures/${name}.source`, { plugins: [[pluginPath, { plugins: plugins }]] }).code.trim(); const expected = fs.readFileSync(`${__dirname}/fixtures/${name}.expected`, 'utf-8').trim(); return { output, expected } }
it(fixtureName.split('-').join(' '), () => { const actualPath = path.join(fixtureDir, 'actual.js'); const actual = transformFileSync(actualPath).code; const templatePath = path.sep === '\\' ? actualPath.replace(/\\/g, '/') : actualPath; const expected = fs.readFileSync( path.join(fixtureDir, 'expected.js') ).toString().replace(/__FILENAME__/g, JSON.stringify(templatePath)); expect(trim(actual)).toEqual(trim(expected)); });