botpress
Version:
The world's first CMS for bots. Easily create, manage and extend chatbots.
218 lines (169 loc) • 6.22 kB
JavaScript
;
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _module = require('module');
var _module2 = _interopRequireDefault(_module);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _knex = require('knex');
var _knex2 = _interopRequireDefault(_knex);
var _generate = require('nanoid/generate');
var _generate2 = _interopRequireDefault(_generate);
var _semver = require('semver');
var _semver2 = _interopRequireDefault(_semver);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const IS_DEV = process.env.NODE_ENV !== 'production';
const NPM_CMD = /^win/.test(process.platform) ? 'npm.cmd' : 'npm';
const PRINT_LEVELS = {
info: _chalk2.default.white,
warn: _chalk2.default.yellow.bind(_chalk2.default, 'WARN'),
error: _chalk2.default.red.bind(_chalk2.default, 'ERR'),
success: _chalk2.default.green.bind(_chalk2.default, 'OK')
};
const print = (level, ...args) => {
let method = PRINT_LEVELS[level];
if (!method) {
args = [level].concat(args);
method = PRINT_LEVELS.info;
}
console.log(_chalk2.default.black.bgWhite('[botpress]'), '\t', method(...args));
};
Object.keys(PRINT_LEVELS).forEach(level => {
print[level] = (...args) => print(level, ...args);
});
const resolveFromDir = (fromDir, moduleId) => {
fromDir = _path2.default.resolve(fromDir);
const fromFile = _path2.default.join(fromDir, 'noop.js');
try {
return _module2.default._resolveFilename(moduleId, {
id: fromFile,
filename: fromFile,
paths: _module2.default._nodeModulePaths(fromDir)
});
} catch (err) {
return null;
}
};
const resolveModuleRootPath = entryPath => {
let current = _path2.default.dirname(entryPath);
while (current !== '/') {
const lookup = _path2.default.join(current, 'package.json');
if (_fs2.default.existsSync(lookup)) {
return current;
}
current = _path2.default.resolve(_path2.default.join(current, '..'));
}
return null;
};
const resolveProjectFile = (file, projectLocation, throwIfNotExist) => {
const packagePath = _path2.default.resolve(projectLocation || './', file);
if (!_fs2.default.existsSync(packagePath)) {
if (throwIfNotExist) {
throw new Error("Could not find bot's package.json file");
}
return null;
}
return packagePath;
};
const getDataLocation = (dataDir, projectLocation) => dataDir && _path2.default.isAbsolute(dataDir) ? _path2.default.resolve(dataDir) : _path2.default.resolve(projectLocation, dataDir || 'data');
const getBotpressVersion = () => {
const botpressPackagePath = _path2.default.join(__dirname, '../package.json');
const botpressJson = JSON.parse(_fs2.default.readFileSync(botpressPackagePath));
return botpressJson.version;
};
const collectArgs = (val, memo) => {
memo.push(val);
return memo;
};
// https://github.com/tgriesser/knex/issues/1871#issuecomment-273721116
const getInMemoryDb = () => (0, _knex2.default)({
client: 'sqlite3',
connection: ':memory:',
pool: {
min: 1,
max: 1,
disposeTimeout: 360000000 * 1000,
idleTimeoutMillis: 360000000 * 1000
},
useNullAsDefault: true
});
const safeId = (length = 10) => (0, _generate2.default)('1234567890abcdefghijklmnopqrsuvwxyz', length);
const getPackageName = pkg => {
const isScoped = pkg.startsWith('@');
if (isScoped) {
const [scope, name] = pkg.match(/^@(.*)\/(.*)/).slice(1);
return [scope, name];
} else {
return [null, pkg];
}
};
const isBotpressPackage = pkg => {
const [scope, name] = getPackageName(pkg);
const isBotpress = scope === 'botpress' || name.startsWith('botpress-');
return isBotpress;
};
const getModuleShortname = pkg => {
const [, name] = getPackageName(pkg);
const withoutPrefix = name.replace(/^botpress-/i, '');
return withoutPrefix;
};
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[cyclic reference]';
}
seen.add(value);
}
return value;
};
};
const safeStringify = o => JSON.stringify(o, getCircularReplacer());
const validateBotVersion = (bpVersion, botfileVersion) => {
if (botfileVersion == null) {
throw new Error(`The version field doesn't exist in botfile.js. Set it to "${bpVersion}".`);
}
if (_lodash2.default.isEmpty(botfileVersion) || !_lodash2.default.isString(botfileVersion)) {
throw new Error(`Version in botfile.js must be non-empty string specifying the valid semver (e.g. "${bpVersion}").`);
}
try {
// TODO: change this method if "semver" module will implement semver.isValid()
_semver2.default.valid(botfileVersion);
} catch (err) {
throw new Error(`Version in botfile.js must have proper semver format (e.g. "${bpVersion}").`);
}
const msgPreamble = `Your bot may be incompatible with botpress v${bpVersion}
because it looks like it was originally created with botpress v${botfileVersion}.
To address this `;
if (_semver2.default.lt(bpVersion, botfileVersion)) {
throw new Error(msgPreamble + 'update the versions of botpress and any @botpress/* modules' + ` in your package.json to "${botfileVersion}".`);
}
const botfileMajorVersion = Number(_semver2.default.major(botfileVersion));
const bpMajorVersion = Number(_semver2.default.major(bpVersion));
if (bpMajorVersion > botfileMajorVersion) {
throw new Error(msgPreamble + 'check https://github.com/botpress/botpress/blob/master/CHANGELOG.md' + ' and update your bot for any breaking changes listed there,' + ` then update the version in your botfile.js to "${bpVersion}".`);
}
};
module.exports = {
print,
resolveFromDir,
isDeveloping: IS_DEV,
resolveModuleRootPath,
resolveProjectFile,
getDataLocation,
npmCmd: NPM_CMD,
getBotpressVersion,
collectArgs,
getInMemoryDb,
safeId,
isBotpressPackage,
getModuleShortname,
safeStringify,
validateBotVersion
};
//# sourceMappingURL=util.js.map