Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 30 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,32 +154,35 @@ randomString.generateUnicodeEmoji(1); //🍍

## Command Line Usage

First the package should be installed globally
The package includes a powerful CLI tool. First, install the package globally:

```js
```bash
$ npm install randomized-string -g
# or
$ yarn global add randomized-string
```

$ yarn add randomized-string
### Basic Usage

```bash
$ randomized-string
# Outputs: Urp0YDaIHWn7YCCF

// Urp0YDaIHWn7YCCF

$ randomized-string upperCaseOnly=true charset=alphanumeric
$ randomized-string --upper-case-only -c alphanumeric
# Outputs: DX5ACJP1FJN5Q79Z

// DX5ACJP1FJN5Q79Z
$ randomized-string -c alphanumeric --insert-symbol -l 8
# Outputs: S8Cza8v^

$ randomized-string charset=alphanumeric insertSymbol=true length=8
// S8Cza8v^
$ randomized-string -p pre-
# Outputs: pre-KOyWstwcpA6sLaH3

$ randomized-string prefix=pre-
//pre-KOyWstwcpA6sLaH3

$ randomized-string generateUnicodeEmoji length=5

// ⏺️💤👇😰🗳️
$ randomized-string --emoji -l 5
# Outputs: ⏺️💤👇😰🗳️
```

For detailed CLI documentation with all available options, see the [CLI Documentation](./docs/CLI.md).

## API

randomString
Expand Down Expand Up @@ -228,6 +231,18 @@ randomString
- generates random emojis
<!-- ROADMAP -->

## Interactive CLI

The package now includes a beautiful interactive CLI powered by [@clack/prompts](https://github.com/natemoo-re/clack).

To use the interactive mode:

```bash
npx randomized-string -i
```

This will guide you through generating a random string with a user-friendly interface.

## Tests

- npm install
Expand Down
203 changes: 203 additions & 0 deletions bin/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
#!/usr/bin/env node

const { program } = require('commander');
const randomString = require('..');
const packageJson = require('../package.json');
const { intro, outro, text, select, multiselect, spinner, note, confirm, isCancel } = require('@clack/prompts');

// Handle CLI arguments with commander
program
.name('randomized-string')
.description('Generate random strings with various options')
.version(packageJson.version)
.option('-l, --length <number>', 'Length of the generated string', parseInt, 16)
.option('-c, --charset <type>', 'Character set to use (alphanumeric, number, alphabet, hex, binary, octal)')
.option('--lower-case-only', 'Use only lowercase letters')
.option('--upper-case-only', 'Use only uppercase letters')
.option('--insert-symbol', 'Insert symbols into the generated string')
.option('--symbols-only', 'Use only symbols')
.option('-p, --prefix <string>', 'Add a prefix to the generated string')
.option('-s, --suffix <string>', 'Add a suffix to the generated string')
.option('-r, --range <string>', 'Specify a custom character range')
.option('-e, --emoji', 'Generate Unicode emojis instead of a string')
.option('-i, --interactive', 'Use interactive mode')
.option('--no-color', 'Disable colored output')
.option('--copy', 'Copy the generated string to clipboard (if available)')
.parse(process.argv);

const options = program.opts();

// Interactive mode with @clack/prompts
async function runInteractiveMode() {
intro('✨ Randomized String Generator ✨');

const length = await text({
message: 'How long should the string be?',
placeholder: '16',
initialValue: '16',
validate(value) {
if (value && isNaN(Number(value))) return 'Please enter a number';
if (Number(value) < 1) return 'Length must be at least 1';
return;
},
});

if (isCancel(length)) {
outro('Operation cancelled');
return null;
}

const stringType = await select({
message: 'What type of string do you want to generate?',
options: [
{ value: 'default', label: 'Default (alphanumeric)' },
{ value: 'alphanumeric', label: 'Alphanumeric' },
{ value: 'number', label: 'Numbers only' },
{ value: 'alphabet', label: 'Alphabet only' },
{ value: 'hex', label: 'Hexadecimal' },
{ value: 'binary', label: 'Binary' },
{ value: 'octal', label: 'Octal' },
{ value: 'emoji', label: 'Emoji' },
{ value: 'symbols', label: 'Symbols only' },
],
});

if (isCancel(stringType)) {
outro('Operation cancelled');
return null;
}

let additionalOptions = {};

if (stringType !== 'emoji' && stringType !== 'symbols') {
const stringOptions = await multiselect({
message: 'Select string options:',
options: [
{ value: 'lower', label: 'Lowercase only' },
{ value: 'upper', label: 'Uppercase only' },
{ value: 'symbols', label: 'Include symbols' },
],
required: false,
});

if (isCancel(stringOptions)) {
outro('Operation cancelled');
return null;
}

if (stringOptions.includes('lower')) additionalOptions.lowerCaseOnly = true;
if (stringOptions.includes('upper')) additionalOptions.upperCaseOnly = true;
if (stringOptions.includes('symbols')) additionalOptions.insertSymbol = true;

// Validate incompatible options
if (additionalOptions.lowerCaseOnly && additionalOptions.upperCaseOnly) {
note('Cannot use both lowercase and uppercase options together. Using mixed case.', 'Warning');
delete additionalOptions.lowerCaseOnly;
delete additionalOptions.upperCaseOnly;
}
}

const copyToClipboard = await confirm({
message: 'Copy result to clipboard?',
});

if (isCancel(copyToClipboard)) {
outro('Operation cancelled');
return null;
}

const s = spinner();
s.start('Generating your random string');

// Prepare options for generation
const generatorOptions = {
length: Number(length),
charset: stringType === 'default' ? 'alphanumeric' : (stringType === 'symbols' ? undefined : stringType),
symbolsOnly: stringType === 'symbols',
...additionalOptions
};

// Generate the string or emoji
let result;
if (stringType === 'emoji') {
result = randomString.generateUnicodeEmoji(Number(length));
} else {
result = randomString.generate(generatorOptions);
}

s.stop('Generated!');

note(result, 'Your randomized string');

// Copy to clipboard if requested
if (copyToClipboard) {
try {
// Import clipboardy only when needed
const clipboardy = require('clipboardy');
// Use writeSync for clipboardy v3+
clipboardy.writeSync(result);
note('String copied to clipboard!', 'Success');
} catch (error) {
note('Could not copy to clipboard: ' + error.message, 'Error');
}
}

outro('Thanks for using Randomized String Generator!');
return result;
}

// Main execution
async function main() {
if (options.interactive) {
await runInteractiveMode();
return;
}

// Non-interactive mode - original functionality
const generatorOptions = {
length: options.length,
charset: options.charset,
lowerCaseOnly: options.lowerCaseOnly,
upperCaseOnly: options.upperCaseOnly,
insertSymbol: options.insertSymbol,
symbolsOnly: options.symbolsOnly,
prefix: options.prefix,
suffix: options.suffix,
range: options.range
};

// Generate the string or emoji
let result;
if (options.emoji) {
result = randomString.generateUnicodeEmoji(options.length);
} else {
result = randomString.generate(generatorOptions);
}

// Output the result
if (program.color) {
if (options.emoji) {
console.log('\x1b[34m', result);
} else {
console.log('\x1b[32m', result);
}
console.log('\x1b[0m'); // Reset color
} else {
console.log(result);
}

// Copy to clipboard if requested and available
if (options.copy) {
try {
// Import clipboardy only when needed
const clipboardy = require('clipboardy');
// Use writeSync for clipboardy v3+
clipboardy.writeSync(result);
console.log('\x1b[33mCopied to clipboard!\x1b[0m');
} catch (error) {
console.error('\x1b[31mCould not copy to clipboard: ' + error.message + '\x1b[0m');
}
}
}

main().catch(console.error);
2 changes: 2 additions & 0 deletions bin/randomized-string.cmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@echo off
node "%~dp0cli.js" %*
99 changes: 99 additions & 0 deletions docs/CLI.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Randomized String CLI

The `randomized-string` package includes a powerful command-line interface (CLI) that allows you to generate random strings directly from your terminal.

## Installation

To use the CLI globally, install the package with:

```bash
npm install -g randomized-string
# or
yarn global add randomized-string
```

## Basic Usage

Generate a random string with default settings (16 characters, alphanumeric):

```bash
randomized-string
```

## Options

The CLI supports all the options available in the JavaScript API:

```bash
Options:
-V, --version output the version number
-l, --length <number> Length of the generated string (default: 16)
-c, --charset <type> Character set to use (alphanumeric, number, alphabet, hex, binary, octal)
--lower-case-only Use only lowercase letters
--upper-case-only Use only uppercase letters
--insert-symbol Insert symbols into the generated string
--symbols-only Use only symbols
-p, --prefix <string> Add a prefix to the generated string
-s, --suffix <string> Add a suffix to the generated string
-r, --range <string> Specify a custom character range
-e, --emoji Generate Unicode emojis instead of a string
--no-color Disable colored output
--copy Copy the generated string to clipboard (if available)
-h, --help display help information
```

## Examples

Generate a 10-character random string:

```bash
randomized-string -l 10
# or
randomized-string --length 10
```

Generate a random string with only uppercase letters:

```bash
randomized-string --upper-case-only
```

Generate a random hexadecimal string:

```bash
randomized-string -c hex
# or
randomized-string --charset hex
```

Generate random emojis:

```bash
randomized-string -e
# or
randomized-string --emoji
```

Add a prefix and suffix:

```bash
randomized-string -p "id-" -s "-token"
# or
randomized-string --prefix "id-" --suffix "-token"
```

Copy the generated string to clipboard:

```bash
randomized-string --copy
```

## Combining Options

You can combine multiple options:

```bash
randomized-string -l 8 -c alphabet --upper-case-only --insert-symbol
```

This will generate an 8-character string using only uppercase letters from the alphabet with symbols inserted.
Loading