UNPKG

2.66 kBJavaScriptView Raw
1'use strict';
2
3const { packageJson: pkg, path: packagePath } = require('read-pkg-up').sync();
4const path = require('path');
5const { readFileSync } = require('fs');
6const { render } = require('mustache');
7
8const NAME = '@extensionengine/tailor-ce';
9const PREFIX = '\0virtual:';
10const REGISTRY = '__TAILOR_CONTENT_ELEMENTS__';
11const OPTIONAL_EXPORTS = ['install'];
12const SCOPE = /^@[^/]+\//;
13const TEMPLATE = readFileSync(require.resolve('./dist/plugin'), 'utf-8');
14
15const isObject = arg => arg !== null && typeof arg === 'object';
16const isString = arg => typeof arg === 'string';
17const noop = () => {};
18const normalize = modulePath => path.resolve(process.cwd(), modulePath);
19
20module.exports = function () {
21 let entryId;
22 let entryCode;
23
24 return {
25 name: NAME,
26 /** @param {import('rollup').InputOptions} options */
27 options(options) {
28 // Create virtual entry module.
29 const [entry] = getInput(options.input);
30 const entryPath = normalize(entry);
31 entryId = [PREFIX, entryPath].join('');
32 entryCode = render(TEMPLATE, {
33 packagePath: normalize(packagePath),
34 entryPath
35 });
36 // Set `options.input` to newly created entry.
37 const entryName = pkg.name.replace(SCOPE, '');
38 const input = { [entryName]: entryId };
39 Object.assign(options, { input, shimMissingExports: true });
40 // Override `options.onwarn` handler to silence shimmed export warning.
41 const { onwarn: warn = noop } = options;
42 options.onwarn = function (warning) {
43 if (onwarn.call(this, entry, warning)) return;
44 warn.apply(this, arguments);
45 };
46 return options;
47 },
48 /** @param {import('rollup').OutputOptions} options */
49 outputOptions(options) {
50 const name = [REGISTRY, pkg.name].join('.');
51 return Object.assign(options, { name });
52 },
53 /** @param {string} id */
54 resolveId(id) {
55 return id === entryId ? id : null;
56 },
57 /** @param {string} id */
58 load(id) {
59 return id === entryId ? entryCode : null;
60 }
61 };
62};
63
64/**
65 * @param {string} entryPath
66 * @param {import('rollup').RollupWarning} warning
67 * @returns {boolean}
68 */
69function onwarn(entryPath, warning) {
70 if (isString(warning)) return false;
71 const code = (warning.code || '').toLowerCase();
72 return code === 'shimmed_export' &&
73 OPTIONAL_EXPORTS.includes(warning.exportName) &&
74 normalize(warning.exporter) === normalize(entryPath);
75}
76
77/**
78 * @param {import('rollup').InputOption} input
79 * @return {Array<string>}
80 */
81function getInput(input) {
82 if (isObject(input)) return Object.values(input);
83 if (Array.isArray(input)) return input;
84 return [input];
85}