larry babby and threejs for glsl

This commit is contained in:
Sam
2024-06-24 21:24:00 +12:00
parent 87d5dc634d
commit 907ebae4c0
6474 changed files with 1279596 additions and 8 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017-present Devon Govett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,17 @@
# @parcel/transformer-babel
This Parcel transformer plugin is responsible for transforming assets with Babel. It uses `@babel/core` to resolve babel config the same way Babel does and uses that if found. If no filesystem config is found it uses a default config that supports the most common cases.
## Default config
- `@babel/preset-env` - Uses the targets defined in `package.json` or a default set of targets if none are defined to pass to `@babel/preset-env` as options. It runs over all source code as well as installed packages that have a browserslist with higher targets than the app being built by Parcel.
- `@babel/plugin-flow-strip-types` - Right now it configures the flow plugin which uses the ast to check if there is a flow directive and strips types if so [TODO: It should do a cheap check of the code and only apply the plugin if a flow directive is found as it may affect parsing when it shouldn't]
- `@babel/plugin-transform-typescript` - Configured for files with extenions `.ts` and `.tsx`
- `@babel/plugin-transform-react-jsx` - Configured if file has extension `.jsx` or if a React like dependency is found as a dependency in package.json.
## Custom config perf warnings
Parcel now supports all configuration formats that Babel supports, but some of them come with negative performance impacts.
- `babel.config.js`/`.babelrc.js` - Since Babel 7, config files as JS are now supported. While this provides flexibility it hurts cacheability. Parcel cannot cache using the contents of the these files because the config they return is non deterministic based on content alone. Imported dependencies may change or the results may be based on environment variables. For this reason Parcel has to resolve load these files on each build and make sure their output is still the same. Another downside to using JS config files is that they end up being `require()`ed by Babel so Parcel cannot rebuild when the file changes in watch mode. To avoid these performance penalties, it is suggested that you use a `babel.config.json` or `.babelrc` file instead.
- `require('@babel')` - With the advent of JS config files, it is now possible to directly require presets and plugins in configs instead of using names or paths that are resolved by Babel. Unfortunately this gives Parcel no information about which plugins/presets were used in a transformation so Parcel will be forced to run the Babel transformations on every build. It is suggested to avoid this type of configuration.

View File

@@ -0,0 +1,128 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _babelErrorUtils = require("./babelErrorUtils");
function _plugin() {
const data = require("@parcel/plugin");
_plugin = function () {
return data;
};
return data;
}
function _utils() {
const data = require("@parcel/utils");
_utils = function () {
return data;
};
return data;
}
function _sourceMap() {
const data = _interopRequireDefault(require("@parcel/source-map"));
_sourceMap = function () {
return data;
};
return data;
}
function _semver() {
const data = _interopRequireDefault(require("semver"));
_semver = function () {
return data;
};
return data;
}
var _babel = _interopRequireDefault(require("./babel7"));
var _config = require("./config");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = exports.default = new (_plugin().Transformer)({
loadConfig({
config,
options,
logger
}) {
return (0, _config.load)(config, options, logger);
},
canReuseAST({
ast
}) {
return ast.type === 'babel' && _semver().default.satisfies(ast.version, '^7.0.0');
},
async transform({
asset,
config,
logger,
options,
tracer
}) {
try {
if (config !== null && config !== void 0 && config.config) {
if (asset.meta.babelPlugins != null && Array.isArray(asset.meta.babelPlugins)) {
await (0, _babel.default)({
asset,
options,
logger,
babelOptions: config,
additionalPlugins: asset.meta.babelPlugins,
tracer
});
} else {
await (0, _babel.default)({
asset,
options,
logger,
babelOptions: config,
tracer
});
}
}
return [asset];
} catch (e) {
throw await (0, _babelErrorUtils.babelErrorEnhancer)(e, asset);
}
},
async generate({
asset,
ast,
options
}) {
let originalSourceMap = await asset.getMap();
let sourceFileName = (0, _utils().relativeUrl)(options.projectRoot, asset.filePath);
const babelCorePath = await options.packageManager.resolve('@babel/core', asset.filePath, {
range: '^7.12.0',
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall
});
const {
default: generate
} = await options.packageManager.require('@babel/generator', babelCorePath.resolved);
let {
code,
rawMappings
} = generate(ast.program, {
sourceFileName,
sourceMaps: !!asset.env.sourceMap,
comments: true
});
let map = new (_sourceMap().default)(options.projectRoot);
if (rawMappings) {
map.addIndexedMappings(rawMappings);
}
if (originalSourceMap) {
// The babel AST already contains the correct mappings, but not the source contents.
// We need to copy over the source contents from the original map.
let sourcesContent = originalSourceMap.getSourcesContentMap();
for (let filePath in sourcesContent) {
let content = sourcesContent[filePath];
if (content != null) {
map.setSourceContent(filePath, content);
}
}
}
return {
content: code,
map
};
}
});

View File

@@ -0,0 +1,133 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = babel7;
function _assert() {
const data = _interopRequireDefault(require("assert"));
_assert = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _diagnostic() {
const data = require("@parcel/diagnostic");
_diagnostic = function () {
return data;
};
return data;
}
function _utils() {
const data = require("@parcel/utils");
_utils = function () {
return data;
};
return data;
}
var _remapAstLocations = require("./remapAstLocations");
var _package = _interopRequireDefault(require("../package.json"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const transformerVersion = _package.default.version;
(0, _assert().default)(typeof transformerVersion === 'string');
async function babel7(opts) {
var _babelOptions$config$, _babelOptions$config$2, _babelOptions$syntaxP;
let {
asset,
options,
babelOptions,
additionalPlugins = [],
tracer
} = opts;
const babelCore = await options.packageManager.require('@babel/core', asset.filePath, {
range: '^7.12.0',
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall
});
let config = {
...babelOptions.config,
plugins: additionalPlugins.concat(babelOptions.config.plugins),
code: false,
ast: true,
filename: asset.filePath,
babelrc: false,
configFile: false,
parserOpts: {
...babelOptions.config.parserOpts,
sourceFilename: (0, _utils().relativeUrl)(options.projectRoot, asset.filePath),
allowReturnOutsideFunction: true,
strictMode: false,
sourceType: 'module',
plugins: [...((_babelOptions$config$ = (_babelOptions$config$2 = babelOptions.config.parserOpts) === null || _babelOptions$config$2 === void 0 ? void 0 : _babelOptions$config$2.plugins) !== null && _babelOptions$config$ !== void 0 ? _babelOptions$config$ : []), ...((_babelOptions$syntaxP = babelOptions.syntaxPlugins) !== null && _babelOptions$syntaxP !== void 0 ? _babelOptions$syntaxP : []),
// Applied by preset-env
'classProperties', 'classPrivateProperties', 'classPrivateMethods', 'exportDefaultFrom'
// 'topLevelAwait'
]
},
caller: {
name: 'parcel',
version: transformerVersion,
targets: JSON.stringify(babelOptions.targets),
outputFormat: asset.env.outputFormat
}
};
if (tracer.enabled) {
config.wrapPluginVisitorMethod = (key, nodeType, fn) => {
return function () {
let pluginKey = key;
if (pluginKey.startsWith(options.projectRoot)) {
pluginKey = _path().default.relative(options.projectRoot, pluginKey);
}
const measurement = tracer.createMeasurement(pluginKey, nodeType, _path().default.relative(options.projectRoot, asset.filePath));
fn.apply(this, arguments);
measurement && measurement.end();
};
};
}
let ast = await asset.getAST();
let res;
if (ast) {
res = await babelCore.transformFromAstAsync(ast.program, asset.isASTDirty() ? undefined : await asset.getCode(), config);
} else {
res = await babelCore.transformAsync(await asset.getCode(), config);
if (res.ast) {
let map = await asset.getMap();
if (map) {
(0, _remapAstLocations.remapAstLocations)(babelCore.types, res.ast, map);
}
}
if (res.externalDependencies) {
for (let f of res.externalDependencies) {
if (!_path().default.isAbsolute(f)) {
opts.logger.warn({
message: (0, _diagnostic().md)`Ignoring non-absolute Babel external dependency: ${f}`,
hints: ['Please report this to the corresponding Babel plugin and/or to Parcel.']
});
} else {
if (await options.inputFS.exists(f)) {
asset.invalidateOnFileChange(f);
} else {
asset.invalidateOnFileCreate({
filePath: f
});
}
}
}
}
}
if (res.ast) {
asset.setAST({
type: 'babel',
version: '7.0.0',
program: res.ast
});
}
}

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.babelErrorEnhancer = babelErrorEnhancer;
async function babelErrorEnhancer(error, asset) {
if (error.loc) {
let start = error.message.startsWith(asset.filePath) ? asset.filePath.length + 1 : 0;
error.message = error.message.slice(start).split('\n')[0].trim();
}
error.source = await asset.getCode();
error.filePath = asset.filePath;
return error;
}

View File

@@ -0,0 +1,314 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.load = load;
function _json() {
const data = _interopRequireDefault(require("json5"));
_json = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _utils() {
const data = require("@parcel/utils");
_utils = function () {
return data;
};
return data;
}
function _diagnostic() {
const data = require("@parcel/diagnostic");
_diagnostic = function () {
return data;
};
return data;
}
var _constants = require("./constants");
var _jsx = _interopRequireDefault(require("./jsx"));
var _flow = _interopRequireDefault(require("./flow"));
var _utils2 = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const TYPESCRIPT_EXTNAME_RE = /\.tsx?$/;
const JS_EXTNAME_RE = /^\.(js|cjs|mjs)$/;
const BABEL_CONFIG_FILENAMES = ['.babelrc', '.babelrc.js', '.babelrc.json', '.babelrc.cjs', '.babelrc.mjs', '.babelignore', 'babel.config.js', 'babel.config.json', 'babel.config.mjs', 'babel.config.cjs'];
async function load(config, options, logger) {
var _ref, _ref2, _options$env$BABEL_EN;
// Don't transpile inside node_modules
if (!config.isSource) {
return;
}
// Invalidate when any babel config file is added.
for (let fileName of BABEL_CONFIG_FILENAMES) {
config.invalidateOnFileCreate({
fileName,
aboveFilePath: config.searchPath
});
}
// Do nothing if we cannot resolve any babel config filenames. Checking using our own
// config resolution (which is cached) is much faster than relying on babel.
if (!(await (0, _utils().resolveConfig)(options.inputFS, config.searchPath, BABEL_CONFIG_FILENAMES, options.projectRoot))) {
return buildDefaultBabelConfig(options, config);
}
const babelCore = await options.packageManager.require('@babel/core', config.searchPath, {
range: _constants.BABEL_CORE_RANGE,
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall
});
config.addDevDependency({
specifier: '@babel/core',
resolveFrom: config.searchPath,
range: _constants.BABEL_CORE_RANGE
});
config.invalidateOnEnvChange('BABEL_ENV');
config.invalidateOnEnvChange('NODE_ENV');
let babelOptions = {
filename: config.searchPath,
cwd: options.projectRoot,
envName: (_ref = (_ref2 = (_options$env$BABEL_EN = options.env.BABEL_ENV) !== null && _options$env$BABEL_EN !== void 0 ? _options$env$BABEL_EN : options.env.NODE_ENV) !== null && _ref2 !== void 0 ? _ref2 : options.mode === 'production' || options.mode === 'development' ? options.mode : null) !== null && _ref !== void 0 ? _ref : 'development',
showIgnoredFiles: true
};
let partialConfig = await babelCore.loadPartialConfigAsync(babelOptions);
let addIncludedFile = file => {
if (JS_EXTNAME_RE.test(_path().default.extname(file))) {
// We need to invalidate on startup in case the config is non-static,
// e.g. uses unknown environment variables, reads from the filesystem, etc.
logger.warn({
message: `It looks like you're using a JavaScript Babel config file. This means the config cannot be watched for changes, and Babel transformations cannot be cached. You'll need to restart Parcel for changes to this config to take effect. Try using a ${_path().default.basename(file, _path().default.extname(file)) + '.json'} file instead.`
});
config.invalidateOnStartup();
// But also add the config as a dev dependency so we can at least attempt invalidation in watch mode.
config.addDevDependency({
specifier: (0, _utils().relativePath)(options.projectRoot, file),
resolveFrom: _path().default.join(options.projectRoot, 'index'),
// Also invalidate @babel/core when the config or a dependency updates.
// This ensures that the caches in @babel/core are also invalidated.
additionalInvalidations: [{
specifier: '@babel/core',
resolveFrom: config.searchPath,
range: _constants.BABEL_CORE_RANGE
}]
});
} else {
config.invalidateOnFileChange(file);
}
};
let warnOldVersion = () => {
logger.warn({
message: 'You are using an old version of @babel/core which does not support the necessary features for Parcel to cache and watch babel config files safely. You may need to restart Parcel for config changes to take effect. Please upgrade to @babel/core 7.12.0 or later to resolve this issue.'
});
config.invalidateOnStartup();
};
// Old versions of @babel/core return null from loadPartialConfig when the file should explicitly not be run through babel (ignore/exclude)
if (partialConfig == null) {
warnOldVersion();
return;
}
if (partialConfig.files == null) {
// If the files property is missing, we're on an old version of @babel/core.
// We need to invalidate on startup because we can't properly track dependencies.
if (partialConfig.hasFilesystemConfig()) {
warnOldVersion();
if (typeof partialConfig.babelrcPath === 'string') {
addIncludedFile(partialConfig.babelrcPath);
}
if (typeof partialConfig.configPath === 'string') {
addIncludedFile(partialConfig.configPath);
}
}
} else {
for (let file of partialConfig.files) {
addIncludedFile(file);
}
}
if (partialConfig.fileHandling != null && partialConfig.fileHandling !== 'transpile') {} else if (partialConfig.hasFilesystemConfig()) {
// Determine what syntax plugins we need to enable
let syntaxPlugins = [];
if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
syntaxPlugins.push('typescript');
if (config.searchPath.endsWith('.tsx')) {
syntaxPlugins.push('jsx');
}
} else if (await (0, _jsx.default)(options, config)) {
syntaxPlugins.push('jsx');
}
// If the config has plugins loaded with require(), or inline plugins in the config,
// we can't cache the result of the compilation because we don't know where they came from.
if (hasRequire(partialConfig.options)) {
logger.warn({
message: 'It looks like you are using `require` to configure Babel plugins or presets. This means Babel transformations cannot be cached and will run on each build. Please use strings to configure Babel instead.'
});
config.setCacheKey(JSON.stringify(Date.now()));
config.invalidateOnStartup();
} else {
await warnOnRedundantPlugins(options.inputFS, partialConfig, logger);
definePluginDependencies(config, partialConfig.options, options);
config.setCacheKey((0, _utils().hashObject)(partialConfig.options));
}
return {
internal: false,
config: partialConfig.options,
targets: (0, _utils2.enginesToBabelTargets)(config.env),
syntaxPlugins
};
} else {
return buildDefaultBabelConfig(options, config);
}
}
async function buildDefaultBabelConfig(options, config) {
// If this is a .ts or .tsx file, we don't need to enable flow.
if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
return;
}
// Detect flow. If not enabled, babel doesn't need to run at all.
let babelOptions = await (0, _flow.default)(config, options);
if (babelOptions == null) {
return;
}
// When flow is enabled, we may also need to enable JSX so it parses properly.
let syntaxPlugins = [];
if (await (0, _jsx.default)(options, config)) {
syntaxPlugins.push('jsx');
}
definePluginDependencies(config, babelOptions, options);
return {
internal: true,
config: babelOptions,
syntaxPlugins
};
}
function hasRequire(options) {
let configItems = [...options.presets, ...options.plugins];
return configItems.some(item => !item.file);
}
function definePluginDependencies(config, babelConfig, options) {
if (babelConfig == null) {
return;
}
let configItems = [...(babelConfig.presets || []), ...(babelConfig.plugins || [])];
for (let configItem of configItems) {
// FIXME: this uses a relative path from the project root rather than resolving
// from the config location because configItem.file.request can be a shorthand
// rather than a full package name.
config.addDevDependency({
specifier: (0, _utils().relativePath)(options.projectRoot, configItem.file.resolved),
resolveFrom: _path().default.join(options.projectRoot, 'index'),
// Also invalidate @babel/core when the plugin or a dependency updates.
// This ensures that the caches in @babel/core are also invalidated.
additionalInvalidations: [{
specifier: '@babel/core',
resolveFrom: config.searchPath,
range: _constants.BABEL_CORE_RANGE
}]
});
}
}
const redundantPresets = new Set(['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', '@parcel/babel-preset-env']);
async function warnOnRedundantPlugins(fs, babelConfig, logger) {
var _babelConfig$config;
if (babelConfig == null) {
return;
}
let configPath = (_babelConfig$config = babelConfig.config) !== null && _babelConfig$config !== void 0 ? _babelConfig$config : babelConfig.babelrc;
if (!configPath) {
return;
}
let presets = babelConfig.options.presets || [];
let plugins = babelConfig.options.plugins || [];
let foundRedundantPresets = new Set();
let filteredPresets = presets.filter(preset => {
if (redundantPresets.has(preset.file.request)) {
foundRedundantPresets.add(preset.file.request);
return false;
}
return true;
});
let filePath = _path().default.relative(process.cwd(), configPath);
let diagnostics = [];
if (filteredPresets.length === 0 && foundRedundantPresets.size > 0 && plugins.length === 0) {
diagnostics.push({
message: (0, _diagnostic().md)`Parcel includes transpilation by default. Babel config __${filePath}__ contains only redundant presets. Deleting it may significantly improve build performance.`,
codeFrames: [{
filePath: configPath,
codeHighlights: await getCodeHighlights(fs, configPath, foundRedundantPresets)
}],
hints: [(0, _diagnostic().md)`Delete __${filePath}__`],
documentationURL: 'https://parceljs.org/languages/javascript/#default-presets'
});
} else if (foundRedundantPresets.size > 0) {
diagnostics.push({
message: (0, _diagnostic().md)`Parcel includes transpilation by default. Babel config __${filePath}__ includes the following redundant presets: ${[...foundRedundantPresets].map(p => _diagnostic().md.underline(p))}. Removing these may improve build performance.`,
codeFrames: [{
filePath: configPath,
codeHighlights: await getCodeHighlights(fs, configPath, foundRedundantPresets)
}],
hints: [(0, _diagnostic().md)`Remove the above presets from __${filePath}__`],
documentationURL: 'https://parceljs.org/languages/javascript/#default-presets'
});
}
if (foundRedundantPresets.has('@babel/preset-env')) {
var _babelConfig$config2, _babelConfig$config3;
diagnostics.push({
message: "@babel/preset-env does not support Parcel's targets, which will likely result in unnecessary transpilation and larger bundle sizes.",
codeFrames: [{
filePath: (_babelConfig$config2 = babelConfig.config) !== null && _babelConfig$config2 !== void 0 ? _babelConfig$config2 : babelConfig.babelrc,
codeHighlights: await getCodeHighlights(fs, (_babelConfig$config3 = babelConfig.config) !== null && _babelConfig$config3 !== void 0 ? _babelConfig$config3 : babelConfig.babelrc, new Set(['@babel/preset-env']))
}],
hints: [`Either remove __@babel/preset-env__ to use Parcel's builtin transpilation, or replace with __@parcel/babel-preset-env__`],
documentationURL: 'https://parceljs.org/languages/javascript/#custom-plugins'
});
}
if (diagnostics.length > 0) {
logger.warn(diagnostics);
}
}
async function getCodeHighlights(fs, filePath, redundantPresets) {
let ext = _path().default.extname(filePath);
if (ext !== '.js' && ext !== '.cjs' && ext !== '.mjs') {
let contents = await fs.readFile(filePath, 'utf8');
let json = _json().default.parse(contents);
let presets = json.presets || [];
let pointers = [];
for (let i = 0; i < presets.length; i++) {
if (Array.isArray(presets[i]) && redundantPresets.has(presets[i][0])) {
pointers.push({
type: 'value',
key: `/presets/${i}/0`
});
} else if (redundantPresets.has(presets[i])) {
pointers.push({
type: 'value',
key: `/presets/${i}`
});
}
}
if (pointers.length > 0) {
return (0, _diagnostic().generateJSONCodeHighlights)(contents, pointers);
}
}
return [{
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 1
}
}];
}

View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BABEL_CORE_RANGE = void 0;
const BABEL_CORE_RANGE = exports.BABEL_CORE_RANGE = '^7.12.0';

View File

@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getFlowOptions;
var _constants = require("./constants");
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Generates a babel config for stripping away Flow types.
*/
async function getFlowOptions(config, options) {
if (!config.isSource) {
return null;
}
// Only add flow plugin if `flow-bin` is listed as a dependency in the root package.json
let conf = await config.getConfigFrom(options.projectRoot + '/index', ['package.json']);
let pkg = conf === null || conf === void 0 ? void 0 : conf.contents;
if (!pkg || !(pkg.dependencies && pkg.dependencies['flow-bin']) && !(pkg.devDependencies && pkg.devDependencies['flow-bin'])) {
return null;
}
const babelCore = await options.packageManager.require('@babel/core', config.searchPath, {
range: _constants.BABEL_CORE_RANGE,
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall
});
await options.packageManager.require('@babel/plugin-transform-flow-strip-types', config.searchPath, {
range: '^7.0.0',
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall
});
return {
plugins: [babelCore.createConfigItem(['@babel/plugin-transform-flow-strip-types', {
requireDirective: true
}], {
type: 'plugin',
dirname: _path().default.dirname(config.searchPath)
})]
};
}

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isJSX;
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']);
const JSX_LIBRARIES = ['react', 'preact', 'nervejs', 'hyperapp'];
/**
* Returns whether an asset is likely JSX. Attempts to detect react or react-like libraries
* along with
*/
async function isJSX(options, config) {
if (!config.isSource) {
return false;
}
if (JSX_EXTENSIONS.has(_path().default.extname(config.searchPath))) {
return true;
}
let pkg = await config.getPackage();
if (pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react']) {
// e.g.: `{ alias: { "react": "preact/compat" } }`
return true;
} else {
// Find a dependency that implies JSX syntax.
return JSX_LIBRARIES.some(libName => pkg && (pkg.dependencies && pkg.dependencies[libName] || pkg.devDependencies && pkg.devDependencies[libName] || pkg.peerDependencies && pkg.peerDependencies[libName]));
}
}

View File

@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.remapAstLocations = remapAstLocations;
function remapAstLocations(t, ast, map) {
// remap ast to original mappings
// This improves sourcemap accuracy and fixes sourcemaps when scope-hoisting
traverseAll(t, ast.program, node => {
if (node.loc) {
var _node$loc;
if ((_node$loc = node.loc) !== null && _node$loc !== void 0 && _node$loc.start) {
let mapping = map.findClosestMapping(node.loc.start.line, node.loc.start.column);
if (mapping !== null && mapping !== void 0 && mapping.original) {
// $FlowFixMe
node.loc.start.line = mapping.original.line;
// $FlowFixMe
node.loc.start.column = mapping.original.column;
// $FlowFixMe
let length = node.loc.end.column - node.loc.start.column;
// $FlowFixMe
node.loc.end.line = mapping.original.line;
// $FlowFixMe
node.loc.end.column = mapping.original.column + length;
// $FlowFixMe
node.loc.filename = mapping.source;
} else {
// Maintain null mappings?
node.loc = null;
}
}
}
});
}
function traverseAll(t, node, visitor) {
if (!node) {
return;
}
visitor(node);
for (let key of t.VISITOR_KEYS[node.type] || []) {
// $FlowFixMe
let subNode = node[key];
if (Array.isArray(subNode)) {
for (let i = 0; i < subNode.length; i++) {
traverseAll(t, subNode[i], visitor);
}
} else {
traverseAll(t, subNode, visitor);
}
}
}

View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1,75 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.enginesToBabelTargets = enginesToBabelTargets;
function _assert() {
const data = _interopRequireDefault(require("assert"));
_assert = function () {
return data;
};
return data;
}
function _semver() {
const data = _interopRequireDefault(require("semver"));
_semver = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copied from @babel/helper-compilation-targets/lib/options.js
const TargetNames = {
node: 'node',
chrome: 'chrome',
opera: 'opera',
edge: 'edge',
firefox: 'firefox',
safari: 'safari',
ie: 'ie',
ios: 'ios',
android: 'android',
electron: 'electron',
samsung: 'samsung',
rhino: 'rhino'
};
// List of browsers to exclude when the esmodule target is specified.
// Based on https://caniuse.com/#feat=es6-module
const ESMODULE_BROWSERS = ['not ie <= 11', 'not edge < 16', 'not firefox < 60', 'not chrome < 61', 'not safari < 11', 'not opera < 48', 'not ios_saf < 11', 'not op_mini all', 'not android < 76', 'not blackberry > 0', 'not op_mob > 0', 'not and_chr < 76', 'not and_ff < 68', 'not ie_mob > 0', 'not and_uc > 0', 'not samsung < 8.2', 'not and_qq > 0', 'not baidu > 0', 'not kaios > 0'];
function enginesToBabelTargets(env) {
// "Targets" is the name @babel/preset-env uses for what Parcel calls engines.
// This should not be confused with Parcel's own targets.
// Unlike Parcel's engines, @babel/preset-env expects to work with minimum
// versions, not semver ranges, of its targets.
let targets = {};
for (let engineName of Object.keys(env.engines)) {
let engineValue = env.engines[engineName];
// if the engineValue is a string, it might be a semver range. Use the minimum
// possible version instead.
if (engineName === 'browsers') {
targets[engineName] = engineValue;
} else {
var _semver$minVersion;
(0, _assert().default)(typeof engineValue === 'string');
if (!TargetNames.hasOwnProperty(engineName)) continue;
let minVersion = (_semver$minVersion = _semver().default.minVersion(engineValue)) === null || _semver$minVersion === void 0 ? void 0 : _semver$minVersion.toString();
targets[engineName] = minVersion !== null && minVersion !== void 0 ? minVersion : engineValue;
}
}
if (env.outputFormat === 'esmodule' && env.isBrowser()) {
// If there is already a browsers target, add a blacklist to exclude
// instead of using babel's esmodules target. This allows specifying
// a newer set of browsers than the baseline esmodule support list.
// See https://github.com/babel/babel/issues/8809.
if (targets.browsers) {
let browsers = Array.isArray(targets.browsers) ? targets.browsers : [targets.browsers];
targets.browsers = [...browsers, ...ESMODULE_BROWSERS];
} else {
targets.esmodules = true;
}
}
return targets;
}

View File

@@ -0,0 +1,39 @@
{
"name": "@parcel/transformer-babel",
"version": "2.12.0",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
},
"repository": {
"type": "git",
"url": "https://github.com/parcel-bundler/parcel.git"
},
"main": "lib/BabelTransformer.js",
"source": "src/BabelTransformer.js",
"engines": {
"node": ">= 12.0.0",
"parcel": "^2.12.0"
},
"dependencies": {
"@parcel/diagnostic": "2.12.0",
"@parcel/plugin": "2.12.0",
"@parcel/source-map": "^2.1.1",
"@parcel/utils": "2.12.0",
"browserslist": "^4.6.6",
"json5": "^2.2.0",
"nullthrows": "^1.1.1",
"semver": "^7.5.2"
},
"devDependencies": {
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.14",
"@babel/types": "^7.22.11",
"@parcel/types": "2.12.0"
},
"gitHead": "2059029ee91e5f03a273b0954d3e629d7375f986"
}

View File

@@ -0,0 +1,102 @@
// @flow strict-local
import {babelErrorEnhancer} from './babelErrorUtils';
import {Transformer} from '@parcel/plugin';
import {relativeUrl} from '@parcel/utils';
import SourceMap from '@parcel/source-map';
import semver from 'semver';
import babel7 from './babel7';
import {load} from './config';
export default (new Transformer({
loadConfig({config, options, logger}) {
return load(config, options, logger);
},
canReuseAST({ast}) {
return ast.type === 'babel' && semver.satisfies(ast.version, '^7.0.0');
},
async transform({asset, config, logger, options, tracer}) {
try {
if (config?.config) {
if (
asset.meta.babelPlugins != null &&
Array.isArray(asset.meta.babelPlugins)
) {
await babel7({
asset,
options,
logger,
babelOptions: config,
additionalPlugins: asset.meta.babelPlugins,
tracer,
});
} else {
await babel7({
asset,
options,
logger,
babelOptions: config,
tracer,
});
}
}
return [asset];
} catch (e) {
throw await babelErrorEnhancer(e, asset);
}
},
async generate({asset, ast, options}) {
let originalSourceMap = await asset.getMap();
let sourceFileName: string = relativeUrl(
options.projectRoot,
asset.filePath,
);
const babelCorePath = await options.packageManager.resolve(
'@babel/core',
asset.filePath,
{
range: '^7.12.0',
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall,
},
);
const {default: generate} = await options.packageManager.require(
'@babel/generator',
babelCorePath.resolved,
);
let {code, rawMappings} = generate(ast.program, {
sourceFileName,
sourceMaps: !!asset.env.sourceMap,
comments: true,
});
let map = new SourceMap(options.projectRoot);
if (rawMappings) {
map.addIndexedMappings(rawMappings);
}
if (originalSourceMap) {
// The babel AST already contains the correct mappings, but not the source contents.
// We need to copy over the source contents from the original map.
let sourcesContent = originalSourceMap.getSourcesContentMap();
for (let filePath in sourcesContent) {
let content = sourcesContent[filePath];
if (content != null) {
map.setSourceContent(filePath, content);
}
}
}
return {
content: code,
map,
};
},
}): Transformer);

View File

@@ -0,0 +1,144 @@
// @flow
import type {
MutableAsset,
AST,
PluginOptions,
PluginTracer,
PluginLogger,
} from '@parcel/types';
import typeof * as BabelCore from '@babel/core';
import invariant from 'assert';
import path from 'path';
import {md} from '@parcel/diagnostic';
import {relativeUrl} from '@parcel/utils';
import {remapAstLocations} from './remapAstLocations';
import packageJson from '../package.json';
const transformerVersion: mixed = packageJson.version;
invariant(typeof transformerVersion === 'string');
type Babel7TransformOptions = {|
asset: MutableAsset,
options: PluginOptions,
logger: PluginLogger,
babelOptions: any,
additionalPlugins?: Array<any>,
tracer: PluginTracer,
|};
export default async function babel7(
opts: Babel7TransformOptions,
): Promise<?AST> {
let {asset, options, babelOptions, additionalPlugins = [], tracer} = opts;
const babelCore: BabelCore = await options.packageManager.require(
'@babel/core',
asset.filePath,
{
range: '^7.12.0',
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall,
},
);
let config = {
...babelOptions.config,
plugins: additionalPlugins.concat(babelOptions.config.plugins),
code: false,
ast: true,
filename: asset.filePath,
babelrc: false,
configFile: false,
parserOpts: {
...babelOptions.config.parserOpts,
sourceFilename: relativeUrl(options.projectRoot, asset.filePath),
allowReturnOutsideFunction: true,
strictMode: false,
sourceType: 'module',
plugins: [
...(babelOptions.config.parserOpts?.plugins ?? []),
...(babelOptions.syntaxPlugins ?? []),
// Applied by preset-env
'classProperties',
'classPrivateProperties',
'classPrivateMethods',
'exportDefaultFrom',
// 'topLevelAwait'
],
},
caller: {
name: 'parcel',
version: transformerVersion,
targets: JSON.stringify(babelOptions.targets),
outputFormat: asset.env.outputFormat,
},
};
if (tracer.enabled) {
config.wrapPluginVisitorMethod = (
key: string,
nodeType: string,
fn: Function,
) => {
return function () {
let pluginKey = key;
if (pluginKey.startsWith(options.projectRoot)) {
pluginKey = path.relative(options.projectRoot, pluginKey);
}
const measurement = tracer.createMeasurement(
pluginKey,
nodeType,
path.relative(options.projectRoot, asset.filePath),
);
fn.apply(this, arguments);
measurement && measurement.end();
};
};
}
let ast = await asset.getAST();
let res;
if (ast) {
res = await babelCore.transformFromAstAsync(
ast.program,
asset.isASTDirty() ? undefined : await asset.getCode(),
config,
);
} else {
res = await babelCore.transformAsync(await asset.getCode(), config);
if (res.ast) {
let map = await asset.getMap();
if (map) {
remapAstLocations(babelCore.types, res.ast, map);
}
}
if (res.externalDependencies) {
for (let f of res.externalDependencies) {
if (!path.isAbsolute(f)) {
opts.logger.warn({
message: md`Ignoring non-absolute Babel external dependency: ${f}`,
hints: [
'Please report this to the corresponding Babel plugin and/or to Parcel.',
],
});
} else {
if (await options.inputFS.exists(f)) {
asset.invalidateOnFileChange(f);
} else {
asset.invalidateOnFileCreate({filePath: f});
}
}
}
}
}
if (res.ast) {
asset.setAST({
type: 'babel',
version: '7.0.0',
program: res.ast,
});
}
}

View File

@@ -0,0 +1,30 @@
// @flow
import type {BaseAsset} from '@parcel/types';
export type BabelError = Error & {
loc?: {
line: number,
column: number,
...
},
source?: string,
filePath?: string,
...
};
export async function babelErrorEnhancer(
error: BabelError,
asset: BaseAsset,
): Promise<BabelError> {
if (error.loc) {
let start = error.message.startsWith(asset.filePath)
? asset.filePath.length + 1
: 0;
error.message = error.message.slice(start).split('\n')[0].trim();
}
error.source = await asset.getCode();
error.filePath = asset.filePath;
return error;
}

View File

@@ -0,0 +1,413 @@
// @flow
import type {Config, PluginOptions, PluginLogger} from '@parcel/types';
import typeof * as BabelCore from '@babel/core';
import type {Diagnostic} from '@parcel/diagnostic';
import type {BabelConfig} from './types';
import json5 from 'json5';
import path from 'path';
import {hashObject, relativePath, resolveConfig} from '@parcel/utils';
import {md, generateJSONCodeHighlights} from '@parcel/diagnostic';
import {BABEL_CORE_RANGE} from './constants';
import isJSX from './jsx';
import getFlowOptions from './flow';
import {enginesToBabelTargets} from './utils';
const TYPESCRIPT_EXTNAME_RE = /\.tsx?$/;
const JS_EXTNAME_RE = /^\.(js|cjs|mjs)$/;
const BABEL_CONFIG_FILENAMES = [
'.babelrc',
'.babelrc.js',
'.babelrc.json',
'.babelrc.cjs',
'.babelrc.mjs',
'.babelignore',
'babel.config.js',
'babel.config.json',
'babel.config.mjs',
'babel.config.cjs',
];
type BabelConfigResult = {|
internal: boolean,
config: BabelConfig,
targets?: mixed,
syntaxPlugins?: mixed,
|};
export async function load(
config: Config,
options: PluginOptions,
logger: PluginLogger,
): Promise<?BabelConfigResult> {
// Don't transpile inside node_modules
if (!config.isSource) {
return;
}
// Invalidate when any babel config file is added.
for (let fileName of BABEL_CONFIG_FILENAMES) {
config.invalidateOnFileCreate({
fileName,
aboveFilePath: config.searchPath,
});
}
// Do nothing if we cannot resolve any babel config filenames. Checking using our own
// config resolution (which is cached) is much faster than relying on babel.
if (
!(await resolveConfig(
options.inputFS,
config.searchPath,
BABEL_CONFIG_FILENAMES,
options.projectRoot,
))
) {
return buildDefaultBabelConfig(options, config);
}
const babelCore: BabelCore = await options.packageManager.require(
'@babel/core',
config.searchPath,
{
range: BABEL_CORE_RANGE,
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall,
},
);
config.addDevDependency({
specifier: '@babel/core',
resolveFrom: config.searchPath,
range: BABEL_CORE_RANGE,
});
config.invalidateOnEnvChange('BABEL_ENV');
config.invalidateOnEnvChange('NODE_ENV');
let babelOptions = {
filename: config.searchPath,
cwd: options.projectRoot,
envName:
options.env.BABEL_ENV ??
options.env.NODE_ENV ??
(options.mode === 'production' || options.mode === 'development'
? options.mode
: null) ??
'development',
showIgnoredFiles: true,
};
let partialConfig: ?{|
[string]: any,
|} = await babelCore.loadPartialConfigAsync(babelOptions);
let addIncludedFile = file => {
if (JS_EXTNAME_RE.test(path.extname(file))) {
// We need to invalidate on startup in case the config is non-static,
// e.g. uses unknown environment variables, reads from the filesystem, etc.
logger.warn({
message: `It looks like you're using a JavaScript Babel config file. This means the config cannot be watched for changes, and Babel transformations cannot be cached. You'll need to restart Parcel for changes to this config to take effect. Try using a ${
path.basename(file, path.extname(file)) + '.json'
} file instead.`,
});
config.invalidateOnStartup();
// But also add the config as a dev dependency so we can at least attempt invalidation in watch mode.
config.addDevDependency({
specifier: relativePath(options.projectRoot, file),
resolveFrom: path.join(options.projectRoot, 'index'),
// Also invalidate @babel/core when the config or a dependency updates.
// This ensures that the caches in @babel/core are also invalidated.
additionalInvalidations: [
{
specifier: '@babel/core',
resolveFrom: config.searchPath,
range: BABEL_CORE_RANGE,
},
],
});
} else {
config.invalidateOnFileChange(file);
}
};
let warnOldVersion = () => {
logger.warn({
message:
'You are using an old version of @babel/core which does not support the necessary features for Parcel to cache and watch babel config files safely. You may need to restart Parcel for config changes to take effect. Please upgrade to @babel/core 7.12.0 or later to resolve this issue.',
});
config.invalidateOnStartup();
};
// Old versions of @babel/core return null from loadPartialConfig when the file should explicitly not be run through babel (ignore/exclude)
if (partialConfig == null) {
warnOldVersion();
return;
}
if (partialConfig.files == null) {
// If the files property is missing, we're on an old version of @babel/core.
// We need to invalidate on startup because we can't properly track dependencies.
if (partialConfig.hasFilesystemConfig()) {
warnOldVersion();
if (typeof partialConfig.babelrcPath === 'string') {
addIncludedFile(partialConfig.babelrcPath);
}
if (typeof partialConfig.configPath === 'string') {
addIncludedFile(partialConfig.configPath);
}
}
} else {
for (let file of partialConfig.files) {
addIncludedFile(file);
}
}
if (
partialConfig.fileHandling != null &&
partialConfig.fileHandling !== 'transpile'
) {
return;
} else if (partialConfig.hasFilesystemConfig()) {
// Determine what syntax plugins we need to enable
let syntaxPlugins = [];
if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
syntaxPlugins.push('typescript');
if (config.searchPath.endsWith('.tsx')) {
syntaxPlugins.push('jsx');
}
} else if (await isJSX(options, config)) {
syntaxPlugins.push('jsx');
}
// If the config has plugins loaded with require(), or inline plugins in the config,
// we can't cache the result of the compilation because we don't know where they came from.
if (hasRequire(partialConfig.options)) {
logger.warn({
message:
'It looks like you are using `require` to configure Babel plugins or presets. This means Babel transformations cannot be cached and will run on each build. Please use strings to configure Babel instead.',
});
config.setCacheKey(JSON.stringify(Date.now()));
config.invalidateOnStartup();
} else {
await warnOnRedundantPlugins(options.inputFS, partialConfig, logger);
definePluginDependencies(config, partialConfig.options, options);
config.setCacheKey(hashObject(partialConfig.options));
}
return {
internal: false,
config: partialConfig.options,
targets: enginesToBabelTargets(config.env),
syntaxPlugins,
};
} else {
return buildDefaultBabelConfig(options, config);
}
}
async function buildDefaultBabelConfig(
options: PluginOptions,
config: Config,
): Promise<?BabelConfigResult> {
// If this is a .ts or .tsx file, we don't need to enable flow.
if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
return;
}
// Detect flow. If not enabled, babel doesn't need to run at all.
let babelOptions = await getFlowOptions(config, options);
if (babelOptions == null) {
return;
}
// When flow is enabled, we may also need to enable JSX so it parses properly.
let syntaxPlugins = [];
if (await isJSX(options, config)) {
syntaxPlugins.push('jsx');
}
definePluginDependencies(config, babelOptions, options);
return {
internal: true,
config: babelOptions,
syntaxPlugins,
};
}
function hasRequire(options) {
let configItems = [...options.presets, ...options.plugins];
return configItems.some(item => !item.file);
}
function definePluginDependencies(config, babelConfig: ?BabelConfig, options) {
if (babelConfig == null) {
return;
}
let configItems = [
...(babelConfig.presets || []),
...(babelConfig.plugins || []),
];
for (let configItem of configItems) {
// FIXME: this uses a relative path from the project root rather than resolving
// from the config location because configItem.file.request can be a shorthand
// rather than a full package name.
config.addDevDependency({
specifier: relativePath(options.projectRoot, configItem.file.resolved),
resolveFrom: path.join(options.projectRoot, 'index'),
// Also invalidate @babel/core when the plugin or a dependency updates.
// This ensures that the caches in @babel/core are also invalidated.
additionalInvalidations: [
{
specifier: '@babel/core',
resolveFrom: config.searchPath,
range: BABEL_CORE_RANGE,
},
],
});
}
}
const redundantPresets = new Set([
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-typescript',
'@parcel/babel-preset-env',
]);
async function warnOnRedundantPlugins(fs, babelConfig, logger) {
if (babelConfig == null) {
return;
}
let configPath = babelConfig.config ?? babelConfig.babelrc;
if (!configPath) {
return;
}
let presets = babelConfig.options.presets || [];
let plugins = babelConfig.options.plugins || [];
let foundRedundantPresets = new Set();
let filteredPresets = presets.filter(preset => {
if (redundantPresets.has(preset.file.request)) {
foundRedundantPresets.add(preset.file.request);
return false;
}
return true;
});
let filePath = path.relative(process.cwd(), configPath);
let diagnostics: Array<Diagnostic> = [];
if (
filteredPresets.length === 0 &&
foundRedundantPresets.size > 0 &&
plugins.length === 0
) {
diagnostics.push({
message: md`Parcel includes transpilation by default. Babel config __${filePath}__ contains only redundant presets. Deleting it may significantly improve build performance.`,
codeFrames: [
{
filePath: configPath,
codeHighlights: await getCodeHighlights(
fs,
configPath,
foundRedundantPresets,
),
},
],
hints: [md`Delete __${filePath}__`],
documentationURL:
'https://parceljs.org/languages/javascript/#default-presets',
});
} else if (foundRedundantPresets.size > 0) {
diagnostics.push({
message: md`Parcel includes transpilation by default. Babel config __${filePath}__ includes the following redundant presets: ${[
...foundRedundantPresets,
].map(p =>
md.underline(p),
)}. Removing these may improve build performance.`,
codeFrames: [
{
filePath: configPath,
codeHighlights: await getCodeHighlights(
fs,
configPath,
foundRedundantPresets,
),
},
],
hints: [md`Remove the above presets from __${filePath}__`],
documentationURL:
'https://parceljs.org/languages/javascript/#default-presets',
});
}
if (foundRedundantPresets.has('@babel/preset-env')) {
diagnostics.push({
message:
"@babel/preset-env does not support Parcel's targets, which will likely result in unnecessary transpilation and larger bundle sizes.",
codeFrames: [
{
filePath: babelConfig.config ?? babelConfig.babelrc,
codeHighlights: await getCodeHighlights(
fs,
babelConfig.config ?? babelConfig.babelrc,
new Set(['@babel/preset-env']),
),
},
],
hints: [
`Either remove __@babel/preset-env__ to use Parcel's builtin transpilation, or replace with __@parcel/babel-preset-env__`,
],
documentationURL:
'https://parceljs.org/languages/javascript/#custom-plugins',
});
}
if (diagnostics.length > 0) {
logger.warn(diagnostics);
}
}
async function getCodeHighlights(fs, filePath, redundantPresets) {
let ext = path.extname(filePath);
if (ext !== '.js' && ext !== '.cjs' && ext !== '.mjs') {
let contents = await fs.readFile(filePath, 'utf8');
let json = json5.parse(contents);
let presets = json.presets || [];
let pointers = [];
for (let i = 0; i < presets.length; i++) {
if (Array.isArray(presets[i]) && redundantPresets.has(presets[i][0])) {
pointers.push({type: 'value', key: `/presets/${i}/0`});
} else if (redundantPresets.has(presets[i])) {
pointers.push({type: 'value', key: `/presets/${i}`});
}
}
if (pointers.length > 0) {
return generateJSONCodeHighlights(contents, pointers);
}
}
return [
{
start: {
line: 1,
column: 1,
},
end: {
line: 1,
column: 1,
},
},
];
}

View File

@@ -0,0 +1,3 @@
// @flow strict-local
export const BABEL_CORE_RANGE = '^7.12.0';

View File

@@ -0,0 +1,66 @@
// @flow
import type {Config, PluginOptions, PackageJSON} from '@parcel/types';
import type {BabelConfig} from './types';
import typeof * as BabelCore from '@babel/core';
import {BABEL_CORE_RANGE} from './constants';
import path from 'path';
/**
* Generates a babel config for stripping away Flow types.
*/
export default async function getFlowOptions(
config: Config,
options: PluginOptions,
): Promise<?BabelConfig> {
if (!config.isSource) {
return null;
}
// Only add flow plugin if `flow-bin` is listed as a dependency in the root package.json
let conf = await config.getConfigFrom<PackageJSON>(
options.projectRoot + '/index',
['package.json'],
);
let pkg = conf?.contents;
if (
!pkg ||
(!(pkg.dependencies && pkg.dependencies['flow-bin']) &&
!(pkg.devDependencies && pkg.devDependencies['flow-bin']))
) {
return null;
}
const babelCore: BabelCore = await options.packageManager.require(
'@babel/core',
config.searchPath,
{
range: BABEL_CORE_RANGE,
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall,
},
);
await options.packageManager.require(
'@babel/plugin-transform-flow-strip-types',
config.searchPath,
{
range: '^7.0.0',
saveDev: true,
shouldAutoInstall: options.shouldAutoInstall,
},
);
return {
plugins: [
babelCore.createConfigItem(
['@babel/plugin-transform-flow-strip-types', {requireDirective: true}],
{
type: 'plugin',
dirname: path.dirname(config.searchPath),
},
),
],
};
}

View File

@@ -0,0 +1,40 @@
// @flow strict-local
import type {Config, PluginOptions} from '@parcel/types';
import path from 'path';
const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']);
const JSX_LIBRARIES = ['react', 'preact', 'nervejs', 'hyperapp'];
/**
* Returns whether an asset is likely JSX. Attempts to detect react or react-like libraries
* along with
*/
export default async function isJSX(
options: PluginOptions,
config: Config,
): Promise<boolean> {
if (!config.isSource) {
return false;
}
if (JSX_EXTENSIONS.has(path.extname(config.searchPath))) {
return true;
}
let pkg = await config.getPackage();
if (pkg?.alias && pkg.alias['react']) {
// e.g.: `{ alias: { "react": "preact/compat" } }`
return true;
} else {
// Find a dependency that implies JSX syntax.
return JSX_LIBRARIES.some(
libName =>
pkg &&
((pkg.dependencies && pkg.dependencies[libName]) ||
(pkg.devDependencies && pkg.devDependencies[libName]) ||
(pkg.peerDependencies && pkg.peerDependencies[libName])),
);
}
}

View File

@@ -0,0 +1,70 @@
// @flow strict-local
import type {File as BabelNodeFile} from '@babel/types';
import type SourceMap from '@parcel/source-map';
import type {Node} from '@babel/types';
import typeof * as BabelTypes from '@babel/types';
export function remapAstLocations(
t: BabelTypes,
ast: BabelNodeFile,
map: SourceMap,
) {
// remap ast to original mappings
// This improves sourcemap accuracy and fixes sourcemaps when scope-hoisting
traverseAll(t, ast.program, node => {
if (node.loc) {
if (node.loc?.start) {
let mapping = map.findClosestMapping(
node.loc.start.line,
node.loc.start.column,
);
if (mapping?.original) {
// $FlowFixMe
node.loc.start.line = mapping.original.line;
// $FlowFixMe
node.loc.start.column = mapping.original.column;
// $FlowFixMe
let length = node.loc.end.column - node.loc.start.column;
// $FlowFixMe
node.loc.end.line = mapping.original.line;
// $FlowFixMe
node.loc.end.column = mapping.original.column + length;
// $FlowFixMe
node.loc.filename = mapping.source;
} else {
// Maintain null mappings?
node.loc = null;
}
}
}
});
}
function traverseAll(
t: BabelTypes,
node: Node,
visitor: (node: Node) => void,
): void {
if (!node) {
return;
}
visitor(node);
for (let key of t.VISITOR_KEYS[node.type] || []) {
// $FlowFixMe
let subNode: Node | Array<Node> = node[key];
if (Array.isArray(subNode)) {
for (let i = 0; i < subNode.length; i++) {
traverseAll(t, subNode[i], visitor);
}
} else {
traverseAll(t, subNode, visitor);
}
}
}

View File

@@ -0,0 +1,6 @@
// @flow
export type BabelConfig = {|
plugins?: Array<any>,
presets?: Array<any>,
|};

View File

@@ -0,0 +1,86 @@
// @flow
import type {Environment} from '@parcel/types';
import type {Targets as BabelTargets} from '@babel/preset-env';
import invariant from 'assert';
import semver from 'semver';
// Copied from @babel/helper-compilation-targets/lib/options.js
const TargetNames = {
node: 'node',
chrome: 'chrome',
opera: 'opera',
edge: 'edge',
firefox: 'firefox',
safari: 'safari',
ie: 'ie',
ios: 'ios',
android: 'android',
electron: 'electron',
samsung: 'samsung',
rhino: 'rhino',
};
// List of browsers to exclude when the esmodule target is specified.
// Based on https://caniuse.com/#feat=es6-module
const ESMODULE_BROWSERS = [
'not ie <= 11',
'not edge < 16',
'not firefox < 60',
'not chrome < 61',
'not safari < 11',
'not opera < 48',
'not ios_saf < 11',
'not op_mini all',
'not android < 76',
'not blackberry > 0',
'not op_mob > 0',
'not and_chr < 76',
'not and_ff < 68',
'not ie_mob > 0',
'not and_uc > 0',
'not samsung < 8.2',
'not and_qq > 0',
'not baidu > 0',
'not kaios > 0',
];
export function enginesToBabelTargets(env: Environment): BabelTargets {
// "Targets" is the name @babel/preset-env uses for what Parcel calls engines.
// This should not be confused with Parcel's own targets.
// Unlike Parcel's engines, @babel/preset-env expects to work with minimum
// versions, not semver ranges, of its targets.
let targets = {};
for (let engineName of Object.keys(env.engines)) {
let engineValue = env.engines[engineName];
// if the engineValue is a string, it might be a semver range. Use the minimum
// possible version instead.
if (engineName === 'browsers') {
targets[engineName] = engineValue;
} else {
invariant(typeof engineValue === 'string');
if (!TargetNames.hasOwnProperty(engineName)) continue;
let minVersion = semver.minVersion(engineValue)?.toString();
targets[engineName] = minVersion ?? engineValue;
}
}
if (env.outputFormat === 'esmodule' && env.isBrowser()) {
// If there is already a browsers target, add a blacklist to exclude
// instead of using babel's esmodules target. This allows specifying
// a newer set of browsers than the baseline esmodule support list.
// See https://github.com/babel/babel/issues/8809.
if (targets.browsers) {
let browsers = Array.isArray(targets.browsers)
? targets.browsers
: [targets.browsers];
targets.browsers = [...browsers, ...ESMODULE_BROWSERS];
} else {
targets.esmodules = true;
}
}
return targets;
}