Compare commits

..

8 Commits

Author SHA1 Message Date
18261dc5da Global TTS interrupt suppression (its being a bitch)
All checks were successful
Build / Publish Docs (push) Successful in 49s
Build / Build NPM Project (push) Successful in 1m9s
Build / Tag Version (push) Successful in 10s
2026-01-19 15:29:01 -05:00
e32e5d6f71 Better TTS stoping error suppression
All checks were successful
Build / Publish Docs (push) Successful in 56s
Build / Build NPM Project (push) Successful in 1m15s
Build / Tag Version (push) Successful in 10s
2026-01-19 10:28:35 -05:00
41bc5e7eb5 Fixed TTS incorrect voice race condition, errors on stop and speakStream done response
All checks were successful
Build / Publish Docs (push) Successful in 36s
Build / Build NPM Project (push) Successful in 47s
Build / Tag Version (push) Successful in 6s
2026-01-18 13:37:55 -05:00
fda92e46d5 Added TTS helper
All checks were successful
Build / Publish Docs (push) Successful in 33s
Build / Build NPM Project (push) Successful in 44s
Build / Tag Version (push) Successful in 6s
2026-01-18 12:56:20 -05:00
1be2c1118f Added emoji filter
All checks were successful
Build / Publish Docs (push) Successful in 42s
Build / Build NPM Project (push) Successful in 1m7s
Build / Tag Version (push) Successful in 9s
2026-01-18 12:16:12 -05:00
ead8fcffc0 Added matchesCidr utility
All checks were successful
Build / Publish Docs (push) Successful in 49s
Build / Build NPM Project (push) Successful in 1m8s
Build / Tag Version (push) Successful in 9s
2026-01-17 21:11:26 -05:00
367b026cea Added new error code (429 - too many requests)
All checks were successful
Build / Publish Docs (push) Successful in 49s
Build / Build NPM Project (push) Successful in 1m3s
Build / Tag Version (push) Successful in 9s
2026-01-17 13:20:55 -05:00
1b5e16ae5f Added parent dir helper to path events
All checks were successful
Build / Publish Docs (push) Successful in 40s
Build / Build NPM Project (push) Successful in 50s
Build / Tag Version (push) Successful in 6s
2026-01-16 18:07:32 -05:00
7 changed files with 192 additions and 2 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.28.4",
"version": "0.28.12",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@@ -113,6 +113,18 @@ export class NotAcceptableError extends CustomError {
}
}
export class TooManyRequestsError extends CustomError {
static code = 429;
constructor(message: string = 'Rate Limit Reached') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
export class InternalServerError extends CustomError {
static code = 500;

View File

@@ -21,5 +21,6 @@ export * from './search';
export * from './string';
export * from './template';
export * from './time';
export * from './tts';
export * from './types';
export * from 'var-persist';

View File

@@ -76,6 +76,23 @@ export function gravatar(email: string, def='mp') {
return `https://www.gravatar.com/avatar/${md5(email)}?d=${def}`;
}
/**
* Check if IP address falls within CIDR range
* @param {string} ip IPV4 to check (192.168.0.12)
* @param {string} cidr IP range to check against (example: 192.168.0.0/24)
* @returns {boolean} Whether IP address is within range
*/
export function matchesCidr(ip: string, cidr: string): boolean {
if(!cidr) return true;
if(!ip) return false;
if(!cidr?.includes('/')) return ip === cidr; // Single IP
const [range, bits] = cidr.split('/');
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
const ipToInt = (str: string) => str.split('.')
.reduce((int, octet) => (int << 8) + parseInt(octet), 0) >>> 0;
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
}
/**
* Convert IPv6 to v4 because who uses that, NAT4Life
* @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334

View File

@@ -65,6 +65,8 @@ export class PathEvent {
module!: string;
/** Entire path, including the module & name */
fullPath!: string;
/** Parent directory, excludes module & name */
dir!: string;
/** Path including the name, excluding the module */
path!: string;
/** Last segment of path */
@@ -121,6 +123,7 @@ export class PathEvent {
if(p === '' || p === undefined || p === '*') {
this.module = '';
this.path = '';
this.dir = '';
this.fullPath = '**';
this.name = '';
this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split(''));
@@ -132,6 +135,7 @@ export class PathEvent {
let temp = p.split('/').filter(p => !!p);
this.module = temp.splice(0, 1)[0] || '';
this.path = temp.join('/');
this.dir = temp.length > 2 ? temp.slice(0, -1).join('/') : '';
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
this.name = temp.pop() || '';
this.hasGlob = this.fullPath.includes('*');

View File

@@ -135,7 +135,15 @@ export function pascalCase(str?: string): string {
.join('');
}
/**
* Remove all emojis from a string
* @param {string} str Input string with emojis
* @returns {string} Sanitized string without emojis
*/
export function removeEmojis(str: string): string {
const emojiRegex = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud83c[\udde6-\uddff]|[\ud83d[\ude00-\ude4f]|[\ud83d[\ude80-\udeff]|[\ud83c[\udd00-\uddff]|[\ud83d[\ude50-\ude7f]|[\u2600-\u26ff]|[\u2700-\u27bf]|[\ud83e[\udd00-\uddff]|[\ud83c[\udf00-\uffff]|[\ud83d[\ude00-\udeff]|[\ud83c[\udde6-\uddff])/g;
return str.replace(emojiRegex, '');
}
/**
* Generate a random hexadecimal value

148
src/tts.ts Normal file
View File

@@ -0,0 +1,148 @@
import {removeEmojis} from './string.ts';
export class TTS {
private static readonly QUALITY_PATTERNS = ['Google', 'Microsoft', 'Samantha', 'Premium', 'Natural', 'Neural'];
private static _errorHandlerInstalled = false;
private _currentUtterance: SpeechSynthesisUtterance | null = null;
private _voicesLoaded: Promise<void>;
private _stoppedUtterances = new WeakSet<SpeechSynthesisUtterance>();
private _rate: number = 1.0;
get rate(): number { return this._rate; }
set rate(value: number) {
this._rate = value;
if(this._currentUtterance) this._currentUtterance.rate = value;
}
private _pitch: number = 1.0;
get pitch(): number { return this._pitch; }
set pitch(value: number) {
this._pitch = value;
if(this._currentUtterance) this._currentUtterance.pitch = value;
}
private _volume: number = 1.0;
get volume(): number { return this._volume; }
set volume(value: number) {
this._volume = value;
if(this._currentUtterance) this._currentUtterance.volume = value;
}
private _voice: SpeechSynthesisVoice | undefined;
get voice(): SpeechSynthesisVoice | undefined { return this._voice; }
set voice(value: SpeechSynthesisVoice | undefined) {
this._voice = value;
if(this._currentUtterance && value) this._currentUtterance.voice = value;
}
constructor(config?: {rate?: number; pitch?: number; volume?: number; voice?: SpeechSynthesisVoice | null}) {
TTS.installErrorHandler();
this._voicesLoaded = this.initializeVoices();
if(config) {
if(config.rate !== undefined) this._rate = config.rate;
if(config.pitch !== undefined) this._pitch = config.pitch;
if(config.volume !== undefined) this._volume = config.volume;
this._voice = config.voice === null ? undefined : (config.voice || undefined);
}
}
private static installErrorHandler(): void {
if(this._errorHandlerInstalled) return;
window.addEventListener('unhandledrejection', (event) => {
if(event.reason?.error === 'interrupted' && event.reason instanceof SpeechSynthesisErrorEvent) event.preventDefault();
});
this._errorHandlerInstalled = true;
}
private initializeVoices(): Promise<void> {
return new Promise((resolve) => {
const voices = window.speechSynthesis.getVoices();
if(voices.length > 0) {
if(!this._voice) this._voice = TTS.bestVoice();
resolve();
} else {
const handler = () => {
window.speechSynthesis.removeEventListener('voiceschanged', handler);
if(!this._voice) this._voice = TTS.bestVoice();
resolve();
};
window.speechSynthesis.addEventListener('voiceschanged', handler);
}
});
}
private static bestVoice(lang = 'en'): SpeechSynthesisVoice | undefined {
const voices = window.speechSynthesis.getVoices();
for (const pattern of this.QUALITY_PATTERNS) {
const voice = voices.find(v => v.name.includes(pattern) && v.lang.startsWith(lang));
if(voice) return voice;
}
return voices.find(v => v.lang.startsWith(lang));
}
private static cleanText(text: string): string {
return removeEmojis(text)
.replace(/```[\s\S]*?```/g, ' code block ')
.replace(/[#*_~`]/g, '');
}
private createUtterance(text: string): SpeechSynthesisUtterance {
const cleanedText = TTS.cleanText(text);
const utterance = new SpeechSynthesisUtterance(cleanedText);
const voice = this._voice || TTS.bestVoice();
if(voice) utterance.voice = voice;
utterance.rate = this._rate;
utterance.pitch = this._pitch;
utterance.volume = this._volume;
return utterance;
}
async speak(text: string): Promise<void> {
if(!text.trim()) return Promise.resolve();
await this._voicesLoaded;
return new Promise((resolve, reject) => {
this._currentUtterance = this.createUtterance(text);
const utterance = this._currentUtterance;
utterance.onend = () => {
this._currentUtterance = null;
resolve();
};
utterance.onerror = (error) => {
this._currentUtterance = null;
if(this._stoppedUtterances.has(utterance) && error.error === 'interrupted') resolve();
else reject(error);
};
window.speechSynthesis.speak(utterance);
});
}
stop(): void {
if(this._currentUtterance) this._stoppedUtterances.add(this._currentUtterance);
window.speechSynthesis.cancel();
this._currentUtterance = null;
}
speakStream(): {next: (text: string) => void, done: () => Promise<void>} {
let buffer = '';
let streamPromise: Promise<void> = Promise.resolve();
const sentenceRegex = /[^.!?\n]+[.!?\n]+/g;
return {
next: (text: string): void => {
buffer += text;
const sentences = buffer.match(sentenceRegex);
if(sentences) {
sentences.forEach(sentence => streamPromise = this.speak(sentence.trim()));
buffer = buffer.replace(sentenceRegex, '');
}
},
done: async (): Promise<void> => {
if(buffer.trim()) {
streamPromise = this.speak(buffer.trim());
buffer = '';
}
await streamPromise;
}
};
}
}