2019-03-20 22:45:57 -05:00
|
|
|
const glob = require('glob');
|
2019-04-14 20:10:44 -05:00
|
|
|
const {getOptions} = require('loader-utils');
|
|
|
|
const path = require('path');
|
2019-03-20 22:45:57 -05:00
|
|
|
|
|
|
|
// Dynamically require all traits.
|
2019-04-14 20:10:44 -05:00
|
|
|
module.exports = function(source) {
|
|
|
|
const options = getOptions(this);
|
|
|
|
if (!options.paths) {
|
|
|
|
options.paths = [];
|
|
|
|
}
|
|
|
|
// Search avocado.
|
|
|
|
options.paths.push(path.resolve(
|
|
|
|
__dirname, 'node_modules', '@avocado',
|
|
|
|
));
|
|
|
|
// Get all trait source paths.
|
|
|
|
const sourcePaths = [];
|
|
|
|
options.paths.forEach((path) => {
|
|
|
|
const files = glob.sync(`${path}/**/*.trait.js`, {
|
|
|
|
follow: true,
|
2019-03-20 22:45:57 -05:00
|
|
|
});
|
2019-04-14 20:10:44 -05:00
|
|
|
sourcePaths.push(...files);
|
|
|
|
});
|
|
|
|
// Build import definitions.
|
|
|
|
const importDefinitions = sourcePaths.map((sourcePath) => {
|
|
|
|
const relativePath = path.relative(__dirname, sourcePath);
|
|
|
|
const basename = path.basename(relativePath, '.trait.js');
|
|
|
|
const parts = relativePath.split('/');
|
|
|
|
// Chop off basename.
|
|
|
|
parts.pop();
|
|
|
|
// Module or local?
|
|
|
|
let importDirectory;
|
|
|
|
if ('node_modules' === parts[0]) {
|
|
|
|
importDirectory = `${parts.slice(1).join('/')}`;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
importDirectory = `./${parts.join('/')}`
|
|
|
|
}
|
|
|
|
const importPath = `${importDirectory}/${basename}.trait`;
|
|
|
|
// Extract class name.
|
|
|
|
const baseparts = basename.split('-');
|
|
|
|
const className = baseparts.reduce((className, part) => {
|
|
|
|
const firstLetter = part.charAt(0).toUpperCase();
|
|
|
|
const rest = part.substr(1).toLowerCase();
|
|
|
|
return className + firstLetter + rest;
|
|
|
|
}, '');
|
|
|
|
// Import and register.
|
|
|
|
return [
|
|
|
|
`import {${className}} from '${importPath}';`,
|
|
|
|
`registerTrait(${className});`,
|
|
|
|
].join('\n');
|
2019-03-20 22:45:57 -05:00
|
|
|
});
|
2019-04-14 20:10:44 -05:00
|
|
|
// Import trait registry first.
|
|
|
|
return [
|
|
|
|
`import {registerTrait} from '@avocado/entity/trait-registry'`,
|
|
|
|
'',
|
|
|
|
...importDefinitions
|
|
|
|
].join('\n');
|
2019-03-20 22:45:57 -05:00
|
|
|
}
|