UNPKG

babel-plugin-logger-namespace

Version:

Babel plugin that generates the namespace for creating a logger based on the path of the module

66 lines (61 loc) 2.66 kB
import { __makeTemplateObject } from 'tslib'; import path from 'path'; import template from '@babel/template'; function pathToNamespace (path, _a) { var stripPrefix = _a.stripPrefix, stripSubfix = _a.stripSubfix, prefix = _a.prefix; var result = path.replace(/[/|\\]/g, ':'); if (stripPrefix !== undefined) { result = result.replace(new RegExp("^(".concat(stripPrefix, ")")), ''); } if (stripSubfix !== undefined) { result = result.replace(new RegExp("(".concat(stripSubfix, ")$")), ''); } if (prefix !== undefined) { result = prefix + result; } return result; } var isNodeModulesInPath = function (pathString) { var segments = path.normalize(pathString).split(path.sep); return segments.includes('node_modules'); }; var ast = template.ast; function index () { return { name: 'transform-import-meta', visitor: { Program: function (path$1, state) { var _a; if (state.file.opts.filename == null || state.file.opts.root == null || isNodeModulesInPath(state.file.opts.filename) || !state.file.opts.filename.startsWith(state.file.opts.root)) { return; } // make sure it does end with one and only one slash var rootFullPath = path.normalize(state.file.opts.root + '/'); var moduleFullPath = state.file.opts.filename; var moduleLocalPath = moduleFullPath.slice(rootFullPath.length); var namespace = pathToNamespace(moduleLocalPath, (_a = state.opts) !== null && _a !== void 0 ? _a : {}); var metas = []; path$1.traverse({ Identifier: function (idPath) { var _a, _b; if (idPath.node.name === ((_b = (_a = state.opts) === null || _a === void 0 ? void 0 : _a.placeholder) !== null && _b !== void 0 ? _b : 'NAMESPACE')) { metas.push(idPath); } } }); if (metas.length === 0) { return; } for (var _i = 0, metas_1 = metas; _i < metas_1.length; _i++) { var meta = metas_1[_i]; meta.replaceWith(ast(templateObject_1 || (templateObject_1 = __makeTemplateObject(["", ""], ["", ""])), JSON.stringify(namespace))); } } } }; } var templateObject_1; export { index as default };