UNPKG

flipper-babel-transformer

Version:

Babel transformer for Flipper plugins

65 lines 2.91 kB
"use strict"; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ Object.defineProperty(exports, "__esModule", { value: true }); const types_1 = require("@babel/types"); const path_1 = require("path"); const replace_flipper_requires_1 = require("./replace-flipper-requires"); const sourceRootDir = (0, path_1.resolve)(__dirname, '../..'); const pluginRootDir = (0, path_1.resolve)(__dirname, '../../plugin'); // do not apply this transform for these paths const EXCLUDE_PATHS = ['relay-devtools/DevtoolsUI']; function isExcludedPath(path) { // Replace requires and React for plugins, but not for the Flipper core code which can access bundled React and other Flipper packages if (path.startsWith(sourceRootDir) && !path.startsWith(pluginRootDir)) { return true; } for (const epath of EXCLUDE_PATHS) { if (path.indexOf(epath) > -1) { return true; } } return false; } module.exports = () => ({ visitor: { CallExpression(path, state) { if (isExcludedPath(state.file.opts.filename)) { return; } if (!(0, replace_flipper_requires_1.tryReplaceFlipperRequire)(path)) { const node = path.node; const args = node.arguments || []; if (node.callee.type === 'Identifier' && node.callee.name === 'require' && args.length === 1 && (0, types_1.isStringLiteral)(args[0]) && // require a file not a pacakge args[0].value.indexOf('/') > -1 && // in the plugin itself and not inside one of its dependencies state.file.opts.filename.startsWith(state.file.opts.root) && // the resolved path for this file is outside the plugins root !(0, path_1.resolve)((0, path_1.dirname)(state.file.opts.filename), args[0].value).startsWith(state.file.opts.root)) { throw new Error(`Plugins cannot require files from outside their folder. ` + `Attempted to require "${args[0].value}" ` + `from file "${state.file.opts.filename}" resolved to ` + `"${(0, path_1.resolve)((0, path_1.dirname)(state.file.opts.filename), args[0].value)}" ` + `which isn't inside plugin dir "${state.file.opts.root}".`); } } }, Identifier(path, state) { if (isExcludedPath(state.file.opts.filename)) { return; } (0, replace_flipper_requires_1.tryReplaceGlobalReactUsage)(path); }, }, }); //# sourceMappingURL=plugin-flipper-requires.js.map