feat(core): Introduce native implementations for Base64, random generation and normalization; remove runtime plugin dependencies; update tests, docs and package metadata
This commit is contained in:
@@ -1,5 +1,63 @@
|
||||
import * as plugins from './smartstring.plugins.js';
|
||||
|
||||
/**
|
||||
* Cross-platform random number generator
|
||||
* Uses crypto.getRandomValues in browser and Math.random as fallback
|
||||
*/
|
||||
const getRandomInt = (min: number, max: number): number => {
|
||||
if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.getRandomValues) {
|
||||
// Browser environment with crypto API
|
||||
const range = max - min;
|
||||
const array = new Uint32Array(1);
|
||||
globalThis.crypto.getRandomValues(array);
|
||||
return min + (array[0] % range);
|
||||
} else {
|
||||
// Fallback to Math.random for environments without crypto
|
||||
return Math.floor(Math.random() * (max - min)) + min;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Custom implementation of randomatic pattern-based string generator
|
||||
* Pattern characters:
|
||||
* A - Uppercase letter
|
||||
* a - Lowercase letter
|
||||
* 0 - Number (0-9)
|
||||
* ! - Special character
|
||||
* * - Any character (A, a, 0, or !)
|
||||
*/
|
||||
const customRandomatic = (pattern: string, length?: number, options?: any): string => {
|
||||
const charSets = {
|
||||
'A': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
|
||||
'a': 'abcdefghijklmnopqrstuvwxyz',
|
||||
'0': '0123456789',
|
||||
'!': '!@#$%^&*()_+-=[]{}|;:,.<>?',
|
||||
'*': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?'
|
||||
};
|
||||
|
||||
// If length is provided, repeat the pattern to match length
|
||||
let actualPattern = pattern;
|
||||
if (length && length > pattern.length) {
|
||||
actualPattern = pattern.repeat(Math.ceil(length / pattern.length)).slice(0, length);
|
||||
} else if (length) {
|
||||
actualPattern = pattern.slice(0, length);
|
||||
}
|
||||
|
||||
let result = '';
|
||||
for (const char of actualPattern) {
|
||||
if (charSets[char]) {
|
||||
const charSet = charSets[char];
|
||||
const randomIndex = getRandomInt(0, charSet.length);
|
||||
result += charSet[randomIndex];
|
||||
} else {
|
||||
// If not a pattern character, use it literally
|
||||
result += char;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* creates a random string
|
||||
*
|
||||
@@ -17,7 +75,7 @@ export const createRandomString = (
|
||||
lengthArg?: number,
|
||||
optionsArg?: any
|
||||
): string => {
|
||||
return plugins.randomatic(patternArg, lengthArg, optionsArg);
|
||||
return customRandomatic(patternArg, lengthArg, optionsArg);
|
||||
};
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user