UNPKG

sucrase

Version:

Super-fast alternative to Babel for when you can target modern JS runtimes

67 lines (66 loc) 2.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const sucrase_babylon_1 = require("../sucrase-babylon"); const identifyShadowedGlobals_1 = require("./identifyShadowedGlobals"); const ImportProcessor_1 = require("./ImportProcessor"); const NameManager_1 = require("./NameManager"); const TokenProcessor_1 = require("./TokenProcessor"); const RootTransformer_1 = require("./transformers/RootTransformer"); const formatTokens_1 = require("./util/formatTokens"); function getVersion() { // eslint-disable-next-line return require("../../package.json").version; } exports.getVersion = getVersion; function transform(code, options) { const sucraseContext = getSucraseContext(code, options); return new RootTransformer_1.default(sucraseContext, options.transforms).transform(); } exports.transform = transform; /** * Return a string representation of the sucrase tokens, mostly useful for * diagnostic purposes. */ function getFormattedTokens(code, options) { const tokens = getSucraseContext(code, options).tokenProcessor.tokens; return formatTokens_1.default(code, tokens); } exports.getFormattedTokens = getFormattedTokens; /** * Call into the parser/tokenizer and do some further preprocessing: * - Come up with a set of used names so that we can assign new names. * - Preprocess all import/export statements so we know which globals we are interested in. * - Compute situations where any of those globals are shadowed. * * In the future, some of these preprocessing steps can be skipped based on what actual work is * being done. */ function getSucraseContext(code, options) { const babylonPlugins = []; if (options.transforms.includes("jsx")) { babylonPlugins.push("jsx"); } if (options.transforms.includes("flow")) { babylonPlugins.push("flow"); } if (options.transforms.includes("typescript")) { babylonPlugins.push("typescript"); } const file = sucrase_babylon_1.parse(code, { tokens: true, plugins: babylonPlugins, }); const tokens = file.tokens; const scopes = file.scopes; const tokenProcessor = new TokenProcessor_1.default(code, tokens); const nameManager = new NameManager_1.default(tokenProcessor); nameManager.preprocessNames(); const isTypeScript = options.transforms.includes("typescript"); const importProcessor = new ImportProcessor_1.default(nameManager, tokenProcessor, isTypeScript); importProcessor.preprocessTokens(); if (isTypeScript) { importProcessor.pruneTypeOnlyImports(); } identifyShadowedGlobals_1.default(tokens, scopes, importProcessor.getGlobalNames()); return { tokenProcessor, scopes, nameManager, importProcessor }; }