babel-plugin-flask-urls
Version:
Adds support for importing Flask routing rules to generate URLs client-side.
103 lines (86 loc) • 3.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperModuleImports = require("@babel/helper-module-imports");
const flaskURLPlugin = function flaskURLPlugin(_ref) {
let {
types: t,
template
} = _ref;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const buildFunc = template.expression('FUNC.bind(null, RULE, BASE)');
const buildFuncMock = template.expression('FUNC.bind(null, ENDPOINT)');
const importPrefix = opts.importPrefix || 'flask-url';
const builderImportLocation = opts.builderImportLocation || 'flask-urls';
const urlMap = opts.urlMap || {};
const mock = opts.mock;
const basePath = opts.basePath || '';
const importRegex = new RegExp("^".concat(importPrefix, ":(.+)$"));
return {
name: 'flask-urls',
visitor: {
ImportDeclaration: {
exit(path) {
const importTarget = path.node.source.value;
const match = importTarget.match(importRegex);
if (!match) {
return;
}
const endpoint = match[1];
if (path.node.specifiers.length === 0) {
throw path.buildCodeFrameError("".concat(importPrefix, " imports must use a default import"));
} else if (path.node.specifiers.length > 1) {
throw path.get('specifiers.1').buildCodeFrameError("".concat(importPrefix, " imports must use exactly one import"));
} else if (!t.isImportDefaultSpecifier(path.node.specifiers[0])) {
throw path.get('specifiers.0').buildCodeFrameError("".concat(importPrefix, " imports must use a default import"));
}
const importName = path.node.specifiers[0].local.name;
let builderFuncId = this.builderFuncId;
if (builderFuncId) {
builderFuncId = t.cloneDeep(builderFuncId);
}
let variable;
if (mock) {
if (!builderFuncId) {
builderFuncId = this.builderFuncId = (0, _helperModuleImports.addNamed)(path, 'mockFlaskURL', builderImportLocation, {
nameHint: 'mockFlaskURL'
});
}
variable = t.variableDeclarator(t.identifier(importName), buildFuncMock({
FUNC: builderFuncId,
ENDPOINT: t.stringLiteral(endpoint)
}));
} else {
const data = urlMap[endpoint];
if (!data) {
throw path.get('source').buildCodeFrameError("".concat(importPrefix, " imports must reference a valid flask endpoint"));
}
if (!builderFuncId) {
builderFuncId = this.builderFuncId = (0, _helperModuleImports.addDefault)(path, builderImportLocation, {
nameHint: 'buildFlaskURL'
});
}
variable = t.variableDeclarator(t.identifier(importName), buildFunc({
FUNC: builderFuncId,
RULE: t.valueToNode(data),
BASE: t.stringLiteral(basePath)
}));
}
path.replaceWith({
type: 'VariableDeclaration',
kind: 'const',
declarations: [variable],
leadingComments: [{
type: 'CommentBlock',
value: " ".concat(mock ? 'mocked ' : '', "flask url builder for '").concat(endpoint, "' ")
}]
});
}
}
}
};
};
var _default = flaskURLPlugin;
exports.default = _default;