Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'ansi-colors' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
function checkProjectName(name, dependencies) {
// Validate project name against NPM naming restriction
// https://github.com/npm/cli/blob/latest/doc/files/package.json.md#name
const validationResult = validateProjectName(name);
if (!validationResult.validForNewPackages) {
console.error(`Could not create a project called ${colors.red(`"${name}"`)} because of npm naming restrictions:`);
printValidationResults(validationResult.errors);
printValidationResults(validationResult.warnings);
process.exit(1);
}
// Check if project name conflicts with existing NPM packages
if (dependencies.indexOf(name) >= 0) {
console.error(
colors.red(`We cannot create a project called `) +
colors.green(name) +
colors.red(
` because a dependency with the same name exists.\n` +
`Due to the way npm works, the following names are not allowed:\n\n`
) +
colors.cyan(dependencies.map(depName => ` ${depName}`).join('\n')) +
colors.red('\n\nPlease choose a different project name.')
);
process.exit(1);
}
}
function renderChain(currentChain) {
// If it's a lerna dependency, ignore it.
if (currentChain.filter(item => lernaRegex.test(item)).length) {
return;
}
//currentChain.reverse();
console.log(currentChain.join(colors.bold(" ← "))); // →
}
try {
// TODO: DRY with "up" command
const knex = db.connect(db.thisUrl(name));
const [batch, filenames] = await knex.migrate.latest();
if (filenames.length > 0) {
console.log(`Migration batch #${batch} applied!`);
filenames.forEach(filename =>
console.log(`↑ ${c.yellowBright(filename)}`));
console.log();
}
} catch (err) {
console.error(c.redBright('Knex migration failed:'), err);
if (opts.switch) {
console.log(
`Switching back to ${c.yellowBright(current)}`
+ ' and dropping the new database...',
);
db.switchTo(current);
}
await knexFallback.raw(`drop database "${name}"`);
console.log('Done.');
throw new Error('Migration failed; database dropped.');
}
await printLatest();
}
return name;
};
};
exports.handler = async (yargs) => {
const db = require('../db')();
const { verbose: explictlyVerbose } = yargs;
const showMigrations = explictlyVerbose !== undefined ? explictlyVerbose : !!db.config.migrations;
try {
// TODO: refactor to use printLatestMigration (maybe that func can not print them?)
const name = db.thisDb();
let migration = [];
if (showMigrations) {
const knex = db.connectAsSuper(db.thisUrl(name));
migration = await migrationOutput(knex, true);
}
console.log(`* ${c.yellowBright(name)} ${migration.join(' ')}`);
process.exit(0);
} catch (err) {
const { message } = err;
console.error(`postgres: ${c.redBright(message)}`);
process.exit(1);
}
};
const thisDbMigration = appliedMigrations.find(m => m.name === vcsMigrations[i].name);
if (!thisDbMigration) {
console.error(
`Trying to cascade deletion but migration ${c.redBright(vcsMigrations[i].name)} `
+ 'could not be found in the database! Exiting.',
);
endProgram(1);
}
// execute the migration in our database and record it in the knex migrations table
const { name, fullPath } = vcsMigrations[i];
const { down: runDownMigration } = require(fullPath);
try {
await runDownMigration(knex, Promise);
await deleteMigration(knex, thisDbMigration.id);
console.log(`↓ ${c.redBright(name)}`);
} catch (err) {
console.error(`something went wrong running down from: ${fullPath}`);
console.error(err);
}
}
/* eslint-enable no-await-in-loop */
/* eslint-enable import/no-dynamic-require */
// close our database connection
await printLatest();
return new Promise(resolve =>
knex.destroy(() => {
debug(`Down-migration to <${userInput}> finished!`);
resolve();
}));
};
requiredConfigUpdates.map( (requiredConfigField) => {
// Error if config that must be set is still the default value.
if ( nameFieldDefaults[requiredConfigField] === config.theme[requiredConfigField] ){
log(colors.red(`${colors.bold('Error:')} the theme ${requiredConfigField} must be different than the default value ${nameFieldDefaults[requiredConfigField]}.`));
process.exit(1);
}
});
function loadConfig() {
log('Loading config file...');
if (checkFileExists('config.yml')) {
// config.yml exists, load it
log(colors.bold(colors.cyan('config.yml')), 'exists, loading', colors.bold(colors.cyan('config.yml')));
let ymlFile = fs.readFileSync('config.yml', 'utf8');
return yaml.load(ymlFile);
} else if(checkFileExists('config-default.yml')) {
// config-default.yml exists, load it
log(colors.bold(colors.cyan('config.yml')), 'does not exist, loading', colors.bold(colors.cyan('config-default.yml')));
let ymlFile = fs.readFileSync('config-default.yml', 'utf8');
return yaml.load(ymlFile);
} else {
// Exit if config.yml & config-default.yml do not exist
log('Exiting process, no config file exists.');
log('Error Code:', err.code);
process.exit(1);
}
}
minViewport = contextMinViewport
if (argv.minviewport !== undefined) {
minViewport = Math.max(contextMinViewport, argv.minviewport)
}
maxViewport = contextMaxViewport
if (argv.maxviewport !== undefined) {
maxViewport = Math.min(contextMaxViewport, argv.maxviewport)
}
if (argv.verbose) {
console.log(
color.green(
`Viewports will be considered from ${color.white(
minViewport + 'px',
)} to ${color.white(maxViewport + 'px')}`,
),
)
}
/* ======================================================================== */
if (argv.verbose) {
console.log(
color.bgCyan.black(
'\nStep 2: get variations of image width across viewport widths',
),
)
}
const VIEWPORT = {
width: minViewport,
height: 2000,
export async function builder(version: string, config: BuildSchema): Promise {
// log we are starting the shared build tasks
log(`${colors.bgBlue(" ")} Beginning shared build tasks.`);
try {
// run global tasks
await Promise.all(config.tasks.map(task => task(version, config)));
log(`${colors.bgGreen(" ")} Finished shared build tasks.`);
} catch (e) {
log(`${colors.bgRed(" ")} ${colors.bold(colors.red(`Error in shared build tasks.`))}.`);
log(`${colors.bgRed(" ")} ${colors.bold(colors.red("Error:"))} ${colors.bold(colors.white(typeof e === "string" ? e : JSON.stringify(e)))}`);
throw e;
}
// run the per package tasks
return config.packages.reduce((pipe: Promise, pkg) => {
if (typeof pkg === "string") {
pkg = { name: pkg };
}
// gate the package names so folks don't try and run code down the line
if (!/^[\w-]+$/i.test(pkg.name)) {
throw Error(`Bad package name "${pkg.name}".`);
}
const projectFolder = path.join(config.packageRoot, pkg.name);
// throw error to console
log(colors.bold(colors.red(err.name + ': ' + err.message)));
// throw notification
notifier.notify({
title: 'ROARRRRRRRRRR!',
message: 'JavaScript gone wrong.',
sound: 'Basso',
contentImage: __dirname + '/../assets/trex.png'
});
})
.pipe(source('script.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(process.env.APP_ENV === 'production' ? uglify() : through())
.pipe(through((log(colors.white('JS files generated:')))))
.pipe(size({title: 'Scripts:', showFiles: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(config.scripts.destinationFolder))
.pipe(browserSync.stream());
}