@beweco/utils-js
v0.0.23
Published
Utilidades de validación para BeWe
Readme
@beweco/utils
Utility library for phone number validation and Tolgee localization management.
Installation
npm install @beweco/utils-jsUsage
Phone Validation
import { validatePhone } from '@beweco/utils-js';
// Validate a Chilean mobile number
const { isValid, formattedNumber, error } = validatePhone('912345678');
if (isValid) {
console.log(formattedNumber); // '+56912345678'
} else {
console.log(error);
}
// Validate with different country code
const result = validatePhone('912345678', '+1');Tolgee Localization
import {
getAllKeysTolgee,
downloadTranslations,
uploadOnlyNewKeysToTolgee,
uploadToTolgee,
getAvailableLanguages
} from '@beweco/utils-js';
// Configuration
const config = {
apiKey: 'your-tolgee-api-key',
projectId: 'your-project-id',
baseUrl: 'https://app.tolgee.io' // optional, defaults to this value
};
// Get all available languages
const languages = await getAvailableLanguages(config);
// Get all keys from project
const keys = await getAllKeysTolgee(config);
// Download all translations
const translations = await downloadTranslations(config);
// Upload new keys only
const uploadResult = await uploadOnlyNewKeysToTolgee({
...config,
language: 'es-AR',
namespace: 'common',
data: {
'welcome': 'Bienvenido',
'hello': 'Hola'
}
});
// Upload all keys (including duplicates)
const uploadAllResult = await uploadToTolgee({
...config,
language: 'es-AR',
namespace: 'common',
data: {
'welcome': 'Bienvenido',
'hello': 'Hola'
}
});API Reference
Phone Validation
validatePhone(phone: string, countryCode?: string): PhoneValidationResult
Validates and formats a phone number.
Parameters:
phone- The phone number to validatecountryCode- Optional country code (default: '+56' for Chile)
Returns: PhoneValidationResult
interface PhoneValidationResult {
isValid: boolean;
formattedNumber?: string;
error?: string;
}Validation Rules:
- Must be a mobile number (starts with 9)
- Must be 9 digits long (excluding country code)
- Can be provided with or without country code
- Automatically formats to international format (e.g., '+56912345678')
Tolgee Localization
Types
interface TolgeeConfig {
apiKey: string;
projectId: string;
baseUrl?: string;
}
interface Language {
tag: string;
name: string;
originalName: string;
}
interface TranslationData {
[key: string]: string;
}
interface DownloadTranslationsResult {
languages: Language[];
translations: {
[language: string]: {
[namespace: string]: {
[key: string]: string;
};
};
};
}
interface UploadResult {
uploaded?: number;
[key: string]: unknown;
}Functions
getAvailableLanguages(config: TolgeeConfig): Promise<Language[]>
Gets all available languages in the Tolgee project.
getAllKeysTolgee(config: TolgeeConfig): Promise<string[]>
Gets all keys from the Tolgee project with pagination support.
downloadTranslations(config: TolgeeConfig & { namespace?: string }): Promise
Downloads all translations organized by language and namespace.
Parameters:
config- Tolgee configurationnamespace- Optional namespace filter
uploadOnlyNewKeysToTolgee(config: TolgeeConfig & { language: string; namespace: string; data: TranslationData }): Promise
Uploads only new keys that don't exist in the project.
Parameters:
config- Tolgee configurationlanguage- Target language (e.g., 'es-AR')namespace- Namespace (e.g., 'common')data- Translation data object
uploadToTolgee(config: TolgeeConfig & { language: string; namespace: string; data: TranslationData }): Promise
Uploads all keys without checking for duplicates.
Parameters:
config- Tolgee configurationlanguage- Target language (e.g., 'es-AR')namespace- Namespace (e.g., 'common')data- Translation data object
Constants
const DEFAULT_BASE_URL = 'https://app.tolgee.io';
const DEFAULT_PAGE_SIZE = 1000;HTTP client
createHttpClient(baseURL, options) returns an axios instance that unwraps response.data. Failed requests do not reject: they resolve with error.response.data (the gateway error envelope, or undefined when no response is received, e.g. network error or timeout).
401 handling:
- A
401triggers a token refresh againstrefreshPathand retries the original request with the new access token. Concurrent401s share a single refresh. - A
401whose envelope haserror.code(or top-levelmessage) equal toaccess_deniedis an account access denial (e.g. an expired free trial), not an expired token: it is returned as-is, with no refresh and no retry. onAuthErroris called only when the refresh endpoint rejects the credentials (any 4xx). On network errors, timeouts and 5xx the reactive refresh retries once and keeps the session.
Voice recording core (@beweco/utils-js/voice)
Framework-agnostic (no React, no UI framework) core for batch voice recording with MediaRecorder. It is a separate subpath export on purpose — consumers who only need to record audio should not pull in axios, cookies or locale handling.
import { createVoiceRecorder, toTranscriptionFormData } from '@beweco/utils-js/voice';
const recorder = createVoiceRecorder();
const unsubscribe = recorder.subscribe(() => {
// re-read recorder.state / recorder.stream (e.g. from useSyncExternalStore)
});
const result = await recorder.start(); // "ok" | "denied" | "unavailable" | "unsupported" | "busy"
// ... later
const blob = await recorder.stop(); // Blob | null
if (blob) {
const formData = toTranscriptionFormData(blob); // File "audio.<ext>" under field "audio"
}
recorder.dispose(); // release the microphone for good (e.g. on unmount)This module only owns the recording primitive: it does not transcribe, upload, debounce clicks or invalidate stale starts across multiple calls to start() on a screen. The React hook, the record button and the HTTP adapter that talks to a transcription service live in each consuming app.
Level meter for a decorative waveform (Web Audio; returns 0 without it):
import { createAudioLevelMeter } from '@beweco/utils-js/voice';
const meter = createAudioLevelMeter(recorder.stream!); // after start() === "ok"
const level = meter.getLevel(); // RMS 0..1, read it from your own rAF loop
meter.dispose(); // disconnects and closes the AudioContext; idempotentNote: the
exportsfield inpackage.jsonrestricts imports to@beweco/utils-jsand@beweco/utils-js/voice— deep paths like@beweco/utils-js/dist/...no longer resolve. No current consumer uses them.
Development
Prerequisites
- Node.js >= 24
- npm
Important: This project requires Node.js version 24 or later. You can use .nvmrc file with:
nvm useAvailable Scripts
npm run clean- Removes the dist directorynpm run build- Compiles TypeScript codenpm test- Runs Jest testsnpm run lint- Runs ESLintnpm run dev- Runs TypeScript compiler in watch mode
Publishing
This package uses automated publishing to NPM through GitHub Actions.
Manual Release
- Go to
Actions→Publish NPMin GitHub - Click
Run workflow - Select version bump type:
- patch: Bug fixes (0.0.11 → 0.0.12)
- minor: New features (0.0.11 → 0.1.0)
- major: Breaking changes (0.0.11 → 1.0.0)
The workflow will automatically:
- Run tests and build
- Bump version in package.json
- Create git tag and commit
- Publish to NPM
- Push changes back to repository
First-time Setup
Repository admins need to configure the "production" environment with NPM_TOKEN. See .github/DEPLOYMENT.md for detailed instructions.
Contributing
- Create a new branch from
main - Make your changes
- Write/update tests if necessary
- Run linting and tests:
npm run lint && npm test - Create a pull request
- After merge, use GitHub Actions to publish new version
License
MIT
