UNPKG

express-transform-bare-module-specifiers

Version:
70 lines 2.77 kB
"use strict"; /** * Based entirely on: * https://github.com/Polymer/tools/blob/e731b880a0d94a551f5781111f2f9c81cb64c642/packages/polyserve/src/compile-middleware.ts */ Object.defineProperty(exports, "__esModule", { value: true }); const content_type_1 = require("content-type"); const LRU = require("lru-cache"); const path = require("path"); const babel = require("@babel/core"); const transform_middleware_1 = require("./transform-middleware"); const javaScriptMimeTypes = [ 'application/javascript', 'application/ecmascript', 'text/javascript', 'text/ecmascript' ]; const compileMimeTypes = [...javaScriptMimeTypes]; function getContentType(response) { const contentTypeHeader = response.get('Content-Type'); return contentTypeHeader && content_type_1.parse(contentTypeHeader).type; } exports.babelCompileCache = LRU({ length: (n, key) => n.length + key.length, max: 52428800 }); // TODO(justinfagnani): see if we can just use the request path as the key // See https://github.com/Polymer/polyserve/issues/248 exports.getCompileCacheKey = (requestPath, body) => requestPath + body; function babelCompile({ rootDir = process.cwd(), modulesUrl = '/node_modules' } = {}) { return transform_middleware_1.transformResponse({ shouldTransform(request, response) { if ('nocompile' in request.query) { return false; } if (!compileMimeTypes.includes(getContentType(response))) { return false; } return true; }, transform(request, response, body) { const cacheKey = exports.getCompileCacheKey(request.baseUrl + request.path, body); const cached = exports.babelCompileCache.get(cacheKey); if (cached !== undefined) { return cached; } const contentType = getContentType(response); let transformed = body; if (javaScriptMimeTypes.includes(contentType)) { const result = babel.transformSync(body, { filename: path.resolve(rootDir, request.path.replace(/^\//, '')), plugins: [ ['bare-import-rewrite', { modulesDir: modulesUrl, rootBaseDir: rootDir }] ], sourceMaps: 'inline' }); if (result && result.code) { transformed = result.code; } } exports.babelCompileCache.set(cacheKey, transformed); return transformed; } }); } exports.babelCompile = babelCompile; //# sourceMappingURL=compile-middleware.js.map