switch to playwright test runner, use esbuild for dev builds, switch to array destructuring

This commit is contained in:
Rene
2022-06-10 10:55:51 +02:00
parent 9d0dd41d7f
commit 35868511ff
156 changed files with 6693 additions and 7793 deletions
-32
View File
@@ -1,32 +0,0 @@
const PlaywrightEnvironment = require('jest-playwright-preset/lib/PlaywrightEnvironment').default;
const { setupRollupTest, cleanupRollupTest } = require('./jest-browser.rollup.js');
const buildTests = [];
class BrowserRollupEnvironment extends PlaywrightEnvironment {
constructor(envConfig, envContext) {
super(envConfig, envContext);
this.watch = (envConfig.displayName.name || '').includes('-dev');
this.ctx = envContext;
this.cfg = envConfig;
}
async setup() {
const { testPath } = this.ctx;
if (!buildTests.includes(testPath)) {
await cleanupRollupTest(testPath, this.cfg.cache);
await setupRollupTest(this.cfg.rootDir, this.ctx.testPath, this.cfg.cache && this.cfg.cacheDirectory, this.watch);
buildTests.push(testPath);
}
await super.setup();
}
async teardown() {
await super.teardown();
}
}
module.exports = BrowserRollupEnvironment;
-5
View File
@@ -1,5 +0,0 @@
const { globalSetup } = require('jest-playwright-preset');
module.exports = async (jestConfig) => {
await globalSetup(jestConfig);
};
-36
View File
@@ -1,36 +0,0 @@
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const del = require('del');
const { globalTeardown } = require('jest-playwright-preset');
const coverageTempDir = './.nyc_output';
const coverageTempDirFile = 'coverage.json';
const reportDir = './.coverage/browser';
module.exports = async (jestConfig) => {
await globalTeardown(jestConfig);
const { rootDir } = jestConfig;
const coverageTempDirPath = path.resolve(rootDir, coverageTempDir);
const coverageTempFilePath = path.resolve(coverageTempDirPath, coverageTempDirFile);
const reportDirPath = path.resolve(rootDir, reportDir);
if (fs.existsSync(coverageTempFilePath)) {
const coverageReportText = ' COVERAGE ';
console.log('');
console.log(`\x1b[1m\x1b[44m${coverageReportText}\x1b[0m`);
console.log(`Reporting from: "${path.relative(rootDir, coverageTempFilePath)}" in "${path.relative(rootDir, reportDirPath)}"`);
del.sync(reportDirPath);
execSync(`npx nyc report --reporter=lcov --report-dir=${reportDir}`, {
cwd: rootDir,
});
const [deletedTempDir] = del.sync(coverageTempDirPath);
if (deletedTempDir) {
console.log('Deleted:', path.relative(rootDir, deletedTempDir));
}
}
};
-19
View File
@@ -1,19 +0,0 @@
const path = require('path');
module.exports = {
port: 8080,
root: path.join(__dirname, '../'),
build: '.build',
html: {
input: 'index.html',
output: 'build.html',
},
js: {
input: 'index.browser',
output: 'build',
},
dev: {
servePort: 18080,
livereloadPort: 28080,
},
};
-337
View File
@@ -1,337 +0,0 @@
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
const del = require('del');
const chalk = require('chalk');
const readline = require('readline');
const rollup = require('rollup');
const rollupPluginHtml = require('@rollup/plugin-html');
const rollupPluginStyles = require('rollup-plugin-styles');
const rollupPluginServe = require('rollup-plugin-serve');
const rollupPluginLivereload = require('rollup-plugin-livereload');
const deploymentConfig = require('./jest-browser.rollup.config.js');
const rollupConfigName = 'rollup.config.js';
const cacheFilePrefix = 'jest-browser-overlayscrollbars-cache-';
const cacheEncoding = 'utf8';
const cacheHash = 'md5';
const rollupAdditionalWatchFiles = (files) => ({
buildStart() {
if (files) {
files.forEach((file) => {
if (fs.existsSync(file)) {
this.addWatchFile(file);
}
});
}
},
});
const makeHtmlAttributes = (attributes) => {
if (!attributes) {
return '';
}
const keys = Object.keys(attributes);
// eslint-disable-next-line no-param-reassign
// eslint-disable-next-line no-return-assign
return keys.reduce((result, key) => (result += ` ${key}="${attributes[key]}"`), '');
};
const genHtmlTemplateFunc = (contentOrContentFn) => ({ attributes, files, meta, publicPath, title }) => {
const scripts = (files.js || [])
.map(({ fileName }) => `<script src="${publicPath}${fileName}"${makeHtmlAttributes(attributes.script)}></script>`)
.join('\n');
const links = (files.css || [])
.map(({ fileName }) => `<link href="${publicPath}${fileName}" rel="stylesheet"${makeHtmlAttributes(attributes.link)}>`)
.join('\n');
const metas = meta.map((input) => `<meta${makeHtmlAttributes(input)}>`).join('\n');
return `<!doctype html>
<html${makeHtmlAttributes(attributes.html)}>
<head>
${metas}
<title>${title}</title>
<style>
html,
body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
box-sizing: border-box;
}
body {
padding: 10px;
}
*::before,
*::after {
box-sizing: border-box;
}
* {
box-sizing: inherit;
}
#testResult {
display: none;
position: fixed;
top: 0;
right: 0;
padding: 5px;
background: white;
}
#testResult.passed {
display: block;
background: lime;
}
#testResult.passed::before {
content: 'passed';
}
#testResult.failed {
display: block;
background: red;
}
#testResult.failed::before {
content: 'failed';
}
</style>
${links}
</head>
<body>
${(typeof contentOrContentFn === 'function' ? contentOrContentFn() : contentOrContentFn) || ''}
${scripts}
<div id="testResult"></div>
</body>
</html>`;
};
const getAllFilesFrom = (dir, except) => {
const result = [];
fs.readdirSync(dir).forEach((dirOrFile) => {
if (!except.includes(dirOrFile)) {
const dirOrFileResolved = path.resolve(dir, dirOrFile);
if (fs.statSync(dirOrFileResolved).isDirectory()) {
result.push(...getAllFilesFrom(dirOrFileResolved));
}
result.push(dirOrFileResolved);
}
});
return result;
};
const createCacheObj = (testPath) => {
const testFileName = path.basename(testPath);
const testFiles = getAllFilesFrom(path.dirname(testPath), [deploymentConfig.build, testFileName]);
const obj = {};
testFiles.forEach((dir) => {
obj[dir] = crypto.createHash(cacheHash).update(fs.readFileSync(dir, cacheEncoding), cacheEncoding).digest('hex');
});
return obj;
};
const filesChanged = (testPath, cacheDir) => {
let result = true;
const cacheObjString = JSON.stringify(createCacheObj(testPath));
const getCacheFile = path.resolve(cacheDir, cacheFilePrefix + crypto.createHash(cacheHash).update(testPath, cacheEncoding).digest('hex'));
if (fs.existsSync(getCacheFile)) {
result = cacheObjString !== fs.readFileSync(getCacheFile, cacheEncoding);
}
if (result) {
fs.writeFileSync(getCacheFile, cacheObjString);
}
return result;
};
const setupRollupTest = async (rootDir, testPath, cacheDir, watch) => {
const rollupWatchers = [];
const rollupServers = [];
const testDir = path.dirname(testPath);
const testName = path.basename(testDir);
const changed = cacheDir && !watch ? filesChanged(testPath, cacheDir) : true;
const buildFolderExists = fs.existsSync(path.resolve(testDir, deploymentConfig.build));
if (changed || !buildFolderExists) {
const rollupConfigPath = path.resolve(rootDir, rollupConfigName);
if (fs.existsSync(rollupConfigPath)) {
const rollupConfig = require(rollupConfigPath); // eslint-disable-line
if (typeof rollupConfig === 'function') {
try {
const htmlFilePath = path.resolve(testDir, deploymentConfig.html.input);
const dist = path.resolve(testDir, deploymentConfig.build);
const getHtmlFileContent = () => (fs.existsSync(htmlFilePath) ? fs.readFileSync(htmlFilePath, 'utf8') : null);
const logBuilding = (re) => {
const text = re ? ' RE-BUILDING ' : ' BUILDING ';
console.log(`${chalk.bgBlue.bold.whiteBright(text)} ${chalk.blackBright(testPath)}`); // eslint-disable-line
};
const logBundleFinish = (duration) => {
if (duration) {
console.log(`Bundle finished after ${Math.round(duration / 1000)} seconds.`); // eslint-disable-line
} else {
console.log(`Bundle finished.`); // eslint-disable-line
}
};
let rollupConfigObj = rollupConfig(undefined, {
project: rootDir,
overwrite: ({ defaultConfig }) => {
return {
dist,
input: path.resolve(testDir, deploymentConfig.js.input),
file: deploymentConfig.js.output,
types: null,
minVersions: false,
esmBuild: false,
sourcemap: true,
name: testName,
pipeline: [
rollupPluginStyles(),
...defaultConfig.pipeline,
rollupPluginHtml({
title: `Jest-Browser: ${testName}`,
fileName: deploymentConfig.html.output,
template: genHtmlTemplateFunc(getHtmlFileContent),
meta: [{ charset: 'utf-8' }, { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' }],
}),
...(watch
? [
rollupAdditionalWatchFiles([htmlFilePath]),
rollupPluginServe({
contentBase: dist,
historyApiFallback: `/${deploymentConfig.html.output}`,
port: deploymentConfig.dev.servePort,
onListening(server) {
rollupServers.push(server);
},
}),
rollupPluginLivereload({
watch: dist,
port: deploymentConfig.dev.livereloadPort,
}),
]
: []),
],
};
},
silent: true,
fast: true,
});
if (!Array.isArray(rollupConfigObj)) {
rollupConfigObj = [rollupConfigObj];
}
for (let i = 0; i < rollupConfigObj.length; i++) {
const inputConfig = rollupConfigObj[i];
let { output } = inputConfig;
if (!Array.isArray(output)) {
output = [output];
}
if (watch) {
let firstWatch = true;
const rollupWatcher = rollup.watch({
...inputConfig,
output,
});
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
rollupWatcher.on('event', ({ code, duration, error, result }) => {
if (code === 'ERROR') {
console.log('Error:', error); // eslint-disable-line
}
if (code === 'START') {
if (firstWatch) {
console.log(''); // eslint-disable-line
}
logBuilding(!firstWatch);
}
if (code === 'BUNDLE_END') {
logBundleFinish(duration);
if (result && result.close) {
result.close();
}
}
if (code === 'END') {
console.log('Watching for changes, press ENTER to continue.'); // eslint-disable-line
console.log(''); // eslint-disable-line
if (firstWatch) {
firstWatch = false;
resolve();
}
}
});
});
rollupWatchers.push(rollupWatcher);
} else {
console.log(''); // eslint-disable-line
logBuilding();
const startTime = Date.now();
// eslint-disable-next-line no-await-in-loop
const bundle = await rollup.rollup(inputConfig);
for (let v = 0; v < output.length; v++) {
const outputConfig = output[i];
// eslint-disable-next-line no-await-in-loop
await bundle.write(outputConfig);
const endTime = Date.now();
logBundleFinish(endTime - startTime);
}
console.log(''); // eslint-disable-line
}
}
if (watch) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
await new Promise((resolve) => {
rl.on('line', () => {
resolve();
});
rl.on('close', () => {
resolve();
});
});
rl.close();
rollupWatchers.forEach((watcher) => {
watcher.close();
});
rollupServers.forEach((server) => {
server.close();
});
if (rollupPluginLivereload && global.PLUGIN_LIVERELOAD && global.PLUGIN_LIVERELOAD.server) {
global.PLUGIN_LIVERELOAD.server.close();
global.PLUGIN_LIVERELOAD.server = null;
}
}
} catch (e) {
console.warn(e);
}
}
}
}
};
const cleanupRollupTest = async (testPath, cache) => {
if (!cache) {
await del(path.resolve(path.dirname(testPath), deploymentConfig.build));
}
};
module.exports = { setupRollupTest, cleanupRollupTest };
-2
View File
@@ -1,2 +0,0 @@
jest.setTimeout(60000 * 5);
context.setDefaultTimeout(60000 * 5);
-7
View File
@@ -1,7 +0,0 @@
const express = require('express');
const deploymentConfig = require('./jest-browser.rollup.config.js');
const app = express();
app.use(express.static(deploymentConfig.root));
app.listen(deploymentConfig.port);
-10
View File
@@ -1,10 +0,0 @@
const path = require('path');
const deploymentConfig = require('./jest-browser.rollup.config.js');
module.exports = {
process: (src, filePath) => {
const deploymentPath = path.relative(deploymentConfig.root, filePath);
const split = deploymentPath.split(path.sep);
return `module.exports = ${JSON.stringify(`http://127.0.0.1:${deploymentConfig.port}/${path.posix.join(...split)}`)}`;
},
};
+73
View File
@@ -0,0 +1,73 @@
const fs = require('fs');
const path = require('path');
const rollupPluginStyles = require('rollup-plugin-styles');
const rollupPluginServe = require('rollup-plugin-serve');
const rollupPluginLivereload = require('rollup-plugin-livereload');
const createRollupConfig = require('../rollup/rollup.config');
const rollupPluginHtml = require('./rollup.pluginHtml');
const rollupAdditionalWatchFiles = require('./rollup.pluginAdditionalWatchFiles');
const portRange = {
min: 20000,
max: 60000,
};
const meta = {
dist: './.build',
html: './index.html',
input: './index.browser',
};
module.exports = (testDir, onListening = null) => {
const name = path.basename(testDir);
const htmlFilePath = path.resolve(testDir, meta.html);
const dist = path.resolve(testDir, meta.dist);
const htmlName = `${name}.html`;
const { min, max } = portRange;
const port = Math.floor(Math.random() * (max - min + 1) + min);
return createRollupConfig({
project: name,
mode: 'dev',
paths: {
dist,
src: path.resolve(testDir, './'),
},
versions: {
minified: false,
module: false,
},
rollup: {
input: path.resolve(testDir, meta.input),
context: 'this',
moduleContext: () => 'this',
output: {
sourcemap: true,
},
plugins: [
rollupPluginStyles(),
rollupPluginHtml(`Playwright: ${name}`, htmlName, () =>
fs.existsSync(htmlFilePath) ? fs.readFileSync(htmlFilePath, 'utf8') : null
),
...(onListening
? [
rollupAdditionalWatchFiles([htmlFilePath]),
rollupPluginServe({
contentBase: dist,
historyApiFallback: `/${htmlName}`,
host: '127.0.0.1',
port,
onListening,
}),
rollupPluginLivereload({
watch: dist,
port: port - 1,
verbose: false,
}),
]
: []),
],
},
});
};
@@ -0,0 +1,13 @@
const fs = require('fs');
module.exports = (files) => ({
buildStart() {
if (files) {
files.forEach((file) => {
if (fs.existsSync(file)) {
this.addWatchFile(file);
}
});
}
},
});
+102
View File
@@ -0,0 +1,102 @@
const rollupPluginHtml = require('@rollup/plugin-html');
const makeHtmlAttributes = (attributes) => {
if (!attributes) {
return '';
}
const keys = Object.keys(attributes);
// eslint-disable-next-line no-param-reassign
// eslint-disable-next-line no-return-assign
return keys.reduce((result, key) => (result += ` ${key}="${attributes[key]}"`), '');
};
const genHtmlTemplateFunc = (contentOrContentFn) => ({
attributes,
files,
meta,
publicPath,
title,
}) => {
const scripts = (files.js || [])
.map(
({ fileName }) =>
`<script src="${publicPath}${fileName}"${makeHtmlAttributes(attributes.script)}></script>`
)
.join('\n');
const links = (files.css || [])
.map(
({ fileName }) =>
`<link href="${publicPath}${fileName}" rel="stylesheet"${makeHtmlAttributes(
attributes.link
)}>`
)
.join('\n');
const metas = meta.map((input) => `<meta${makeHtmlAttributes(input)}>`).join('\n');
return `<!doctype html>
<html${makeHtmlAttributes(attributes.html)}>
<head>
${metas}
<title>${title}</title>
<style>
html,
body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
box-sizing: border-box;
}
body {
padding: 10px;
}
*::before,
*::after {
box-sizing: border-box;
}
* {
box-sizing: inherit;
}
#testResult {
display: none;
position: fixed;
top: 0;
right: 0;
padding: 5px;
background: white;
}
#testResult.passed {
display: block;
background: lime;
}
#testResult.passed::before {
content: 'passed';
}
#testResult.failed {
display: block;
background: red;
}
#testResult.failed::before {
content: 'failed';
}
</style>
${links}
</head>
<body>
${(typeof contentOrContentFn === 'function' ? contentOrContentFn() : contentOrContentFn) || ''}
${scripts}
<div id="testResult"></div>
</body>
</html>`;
};
module.exports = (title, fileName, getHtmlContent) =>
rollupPluginHtml({
title,
fileName,
template: genHtmlTemplateFunc(getHtmlContent),
meta: [{ charset: 'utf-8' }, { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' }],
});
+14
View File
@@ -0,0 +1,14 @@
module.exports = {
presets: [
[
'@babel/preset-env',
{
loose: true,
bugfixes: true,
targets: {
esmodules: true,
},
},
],
],
};
+13
View File
@@ -0,0 +1,13 @@
module.exports = {
presets: [
[
'@babel/preset-env',
{
loose: true,
targets: {
ie: '11',
},
},
],
],
};
+21
View File
@@ -0,0 +1,21 @@
module.exports = {
project: null,
mode: 'build',
paths: {
src: './src',
dist: './dist',
types: './types',
},
versions: {
minified: true,
module: true,
},
alias: {},
rollup: {
input: './src/index',
output: {
sourcemap: true,
exports: 'auto',
},
},
};
+107
View File
@@ -0,0 +1,107 @@
const path = require('path');
const { babel: rollupBabelInputPlugin } = require('@rollup/plugin-babel');
const { terser: rollupTerser } = require('rollup-plugin-terser');
const rollupTs = require('rollup-plugin-ts');
const babelConfigUmd = require('./babel.config.umd');
const babelConfigEsm = require('./babel.config.esm');
const { rollupCommonjs, rollupResolve, rollupAlias } = require('./pipeline.common.plugins');
const { extensions } = require('../../resolve.config.json');
const createOutputWithMinifiedVersion = (output, esm, buildMinifiedVersion) =>
[output].concat(
buildMinifiedVersion
? [
{
...output,
compact: true,
file: output.file.replace('.js', '.min.js'),
sourcemap: false,
plugins: [
...(output.plugins || []),
rollupTerser({
ecma: esm ? 2015 : 5,
safari10: true,
mangle: {
safari10: true,
properties: {
regex: /^_/,
},
},
compress: {
evaluate: false,
},
}),
],
},
]
: []
);
module.exports = (esm, options, declarationFiles = false) => {
const { rollup, paths, versions, alias } = options;
const { output: rollupOutput, input, plugins = [], ...rollupOptions } = rollup;
const { name, file, globals, exports, sourcemap: rawSourcemap, ...outputConfig } = rollupOutput;
const { minified: buildMinifiedVersion } = versions;
const { src: srcPath, dist: distPath, types: typesPath } = paths;
const sourcemap = rawSourcemap;
const output = createOutputWithMinifiedVersion(
{
...outputConfig,
...(!esm && {
name,
globals,
exports,
}),
sourcemap,
format: esm ? 'esm' : 'umd',
generatedCode: esm ? 'es2015' : 'es5',
file: path.resolve(distPath, `${file}${esm ? '.esm' : ''}.js`),
},
esm,
buildMinifiedVersion
);
return {
input,
output,
...rollupOptions,
plugins: [
rollupAlias(alias),
rollupTs({
tsconfig: (resolvedConfig) => ({
...resolvedConfig,
declaration: declarationFiles,
declarationDir: typesPath,
}),
include: ['*.ts+(|x)', '**/*.ts+(|x)'],
exclude: ['node_modules', '**/node_modules/*'],
}),
rollupResolve(srcPath),
rollupCommonjs(sourcemap),
rollupBabelInputPlugin({
...(esm ? babelConfigEsm : babelConfigUmd),
assumptions: {
iterableIsArray: true,
noNewArrows: true,
noClassCalls: true,
ignoreToPrimitiveHint: true,
ignoreFunctionLength: true,
},
plugins: [
'@babel/plugin-transform-runtime',
['@babel/plugin-proposal-class-properties', { loose: true }],
['@babel/plugin-proposal-private-methods', { loose: true }],
],
babelHelpers: 'runtime',
shouldPrintComment: () => false,
caller: {
name: 'babel-rollup-build',
},
extensions,
}),
...plugins,
],
};
};
+23
View File
@@ -0,0 +1,23 @@
const { nodeResolve: rollupPluginResolve } = require('@rollup/plugin-node-resolve');
const rollupPluginCommonjs = require('@rollup/plugin-commonjs');
const rollupPluginAlias = require('@rollup/plugin-alias');
const { extensions, directories } = require('../../resolve.config.json');
module.exports = {
rollupAlias: (aliasEntries) =>
rollupPluginAlias({
entries: aliasEntries,
}),
rollupCommonjs: (sourcemap) =>
rollupPluginCommonjs({
sourceMap: sourcemap,
extensions,
}),
rollupResolve: (srcPath) =>
rollupPluginResolve({
mainFields: ['browser', 'umd:main', 'module', 'main'],
rootDir: srcPath,
moduleDirectories: directories,
extensions,
}),
};
+37
View File
@@ -0,0 +1,37 @@
const path = require('path');
const { default: rollupEsBuild } = require('rollup-plugin-esbuild');
const { rollupCommonjs, rollupResolve, rollupAlias } = require('./pipeline.common.plugins');
module.exports = (options) => {
const { rollup, paths, alias } = options;
const { output: rollupOutput, input, plugins = [], ...rollupOptions } = rollup;
const { file, sourcemap: rawSourcemap, ...outputConfig } = rollupOutput;
const { src: srcPath, dist: distPath } = paths;
const sourcemap = rawSourcemap;
const output = {
...outputConfig,
sourcemap: true,
format: 'esm',
generatedCode: 'es2015',
file: path.resolve(distPath, `${file}.js`),
};
return {
input,
output,
...rollupOptions,
plugins: [
rollupAlias(alias),
rollupResolve(srcPath),
rollupEsBuild({
include: /\.[jt]sx?$/,
sourceMap: true,
target: 'es6',
tsconfig: './tsconfig.json',
}),
rollupCommonjs(sourcemap),
...plugins,
],
};
};
+107
View File
@@ -0,0 +1,107 @@
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const resolve = require('../../resolve.config.json');
const pkg = require('../../package.json');
const defaultOptions = require('./defaultOptions');
const pipelineBuild = require('./pipeline.build');
const pipelineDev = require('./pipeline.dev');
const repoRoot = path.resolve(__dirname, '../../');
const appendExtension = (file) =>
path.extname(file) === '' ? file + resolve.extensions.find((ext) => fs.existsSync(path.resolve(`${file}${ext}`))) : file;
const normalizePath = (pathName) => (pathName ? pathName.split(path.sep).join(path.posix.sep) : pathName);
const resolvePath = (basePath, pathToResolve, appendExt) => {
const result = pathToResolve ? (path.isAbsolute(pathToResolve) ? pathToResolve : path.resolve(basePath, pathToResolve)) : null;
return normalizePath(result && appendExt ? appendExtension(result) : result);
};
const getWorkspaceAliases = () =>
pkg.workspaces
.map((pattern) => glob.sync(pattern, { cwd: repoRoot }))
.flat()
.reduce((obj, resolvedPath) => {
let projTsConfig;
const absolutePath = path.resolve(repoRoot, resolvedPath);
try {
projTsConfig = require(`${path.resolve(repoRoot, resolvedPath)}/tsconfig.json`);
} catch {}
obj[`@/${path.basename(absolutePath)}`] = `${normalizePath(
path.resolve(absolutePath, projTsConfig?.compilerOptions?.baseUrl || defaultOptions.paths.src)
)}`;
return obj;
}, {});
const mergeAndResolveOptions = (userOptions) => {
const { mode: defaultMode, paths: defaultPaths, versions: defaultVersions, alias: defaultAlias, rollup: defaultRollup } = defaultOptions;
const { project, mode: rawMode, paths: rawPaths = {}, versions: rawVersions = {}, alias: rawAlias = {}, rollup: rawRollup = {} } = userOptions;
const projectPath = process.cwd();
const mergedOptions = {
project: project || path.basename(projectPath),
mode: rawMode || defaultMode,
repoRoot,
paths: {
...defaultPaths,
...rawPaths,
},
versions: {
...defaultVersions,
...rawVersions,
},
alias: {
...getWorkspaceAliases(),
...defaultAlias,
...rawAlias,
},
rollup: {
...defaultRollup,
...rawRollup,
output: {
...defaultRollup.output,
...(rawRollup.output || {}),
},
},
};
const { src, dist, types, tests } = mergedOptions.paths;
mergedOptions.paths.src = resolvePath(projectPath, src);
mergedOptions.paths.dist = resolvePath(projectPath, dist);
mergedOptions.paths.types = resolvePath(projectPath, types);
mergedOptions.paths.tests = resolvePath(projectPath, tests);
mergedOptions.rollup.input = resolvePath(projectPath, mergedOptions.rollup.input, true);
mergedOptions.rollup.output = {
...(mergedOptions.rollup.output || {}),
name: mergedOptions.rollup.output?.name || mergedOptions.project,
file: mergedOptions.rollup.output?.file || mergedOptions.project.toLocaleLowerCase(),
};
return mergedOptions;
};
const createConfig = (userOptions = {}) => {
const options = mergeAndResolveOptions(userOptions);
const { project, mode, versions } = options;
const { module: buildModuleVersion } = versions;
const isBuild = mode === 'build';
if (isBuild) {
console.log('');
console.log('PROJECT : ', project);
console.log('OPTIONS : ', options);
const umd = pipelineBuild(false, options, true);
const esm = buildModuleVersion ? pipelineBuild(true, options) : null;
return [umd, esm].filter((build) => !!build);
}
return pipelineDev(options);
};
module.exports = createConfig;