UNPKG

tiny-essentials

Version:

Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.

516 lines (302 loc) โ€ข 13.5 kB
# TinyI18 Documentation ๐Ÿ“šโœจ ## Class: `TinyI18` ๐Ÿท๏ธ Professional and flexible i18n manager with dual mode (local/file), regex-based keys, and function-based entries for advanced rendering. * **Mode `"local"`**: in-memory resources (Node + Browser). * **Mode `"file"`**: JSON files on disk via fs/path (Node only). * Keeps only default + selected locale in memory. * Selected locale overrides default; fallback resolves to default. * Supports string entries, regex pattern entries, and function-backed entries. * Safe: no dynamic code eval from files; functions in file mode are referenced by name (`$fn`). --- ### Static Methods โšก #### `mergeLocaleFiles({ files, output, spaces = 0 })` ๐Ÿ”— Merges multiple JSON locale files into a single file for TinyI18 usage (file mode only). **Parameters:** | Name | Type | Description | | -------- | ---------- | ---------------------------------------------------------------------------- | | `files` | `string[]` | List of JSON file paths to merge. | | `output` | `string` | Path where the merged JSON file will be written. | | `spaces` | `number` | Optional. Number of spaces for indentation in the output JSON (default `0`). | **Throws:** * `TypeError` โ†’ if arguments are invalid. * `Error` โ†’ if file reading or writing fails. **Example Usage:** ```js await TinyI18.mergeLocaleFiles({ files: ['./en.json', './pt.json'], output: './merged.json', spaces: 2, }); ``` --- ### Properties ๐Ÿ› ๏ธ #### `currentLocale` ๐Ÿ”น The currently selected locale, or `null` if only the default locale is active. * **Type:** `LocaleCode | null` --- #### `defaultLocale` ๐Ÿ”น The default locale code chosen at construction. Always kept in memory as a fallback. * **Type:** `LocaleCode` --- #### `mode` ๐Ÿ”น The current operating mode of this instance: * `"local"` โ†’ all translations managed in memory. * `"file"` โ†’ translations loaded from JSON files. * **Type:** `ModeTypes` --- #### `strict` ๐Ÿ”น Whether strict mode is enabled. * `true` โ†’ Missing keys, invalid regex, or helper errors throw exceptions. * `false` โ†’ Failures are ignored silently, returning fallback values. * **Type:** `boolean` --- #### `basePath` ๐Ÿ”น Base directory path used in `"file"` mode to locate locale JSON files. * `"local"` mode โ†’ always `null` * `"file"` mode โ†’ root folder passed to the constructor * **Type:** `string | null` --- #### `stats` ๐Ÿ“Š Returns basic stats for debugging/memory insights. * **Type:** `StatLocale[]` * **Example:** ```js console.log(i18.stats); // [ // { locale: 'en', strings: 12, patterns: 2, isDefault: true, isCurrent: false }, // { locale: 'pt', strings: 10, patterns: 1, isDefault: false, isCurrent: true }, // ] ``` --- #### `stringTables` ๐Ÿ”น Deep-cloned view of string tables (Map โ†’ Object). Preserves strings, `$fn` objects, and functions. * **Type:** `Record<string, Dict>` --- #### `patternTables` ๐Ÿ”น Deep-cloned view of regex pattern tables (Map โ†’ Object). Recreates `RegExp` objects to avoid mutation. * **Type:** `Record<string, PatternEntry[]>` --- #### `helpers` ๐Ÿ”น Deep-cloned view of registered helper functions (Map โ†’ Object). Functions are referenced (cannot deep-clone functions). * **Type:** `Record<string, HelperCallback>` --- #### `regexCache` ๐Ÿ”น Deep-cloned view of compiled regex cache (Map โ†’ Object). Recreates `RegExp` objects to avoid mutation. * **Type:** `Record<string, RegExp>` --- โœ… **Note:** All private internal maps are accessible via these getters as **read-only snapshots** to safely inspect memory without affecting runtime behavior. --- ## Internal Utilities & Resolution ๐Ÿ”ง ### `#deepClone(value)` ๐ŸŒ€ Deep clones a value for internal use. * Strings, numbers, and functions โ†’ returned as-is * Objects/arrays โ†’ recursively cloned * `RegExp` โ†’ cloned **Parameters:** | Name | Type | Description | | ------- | ----- | ------------------- | | `value` | `any` | Value to deep clone | **Returns:** `any` โ€“ cloned value --- ### `#resolveOrder(forceLocale)` ๐Ÿ”„ Determines the resolution order of locales for key lookup. **Parameters:** | Name | Type | Description | | ------------- | -------- | ---------------------------------------- | | `forceLocale` | `string` | Optional locale code to prioritize first | **Returns:** `string[]` โ€“ Ordered list of locale codes to try --- ### `#resolveExact(order, key)` ๐ŸŽฏ Resolves a key exactly in the provided locale order. **Parameters:** | Name | Type | Description | | ------- | ---------- | ------------------------------ | | `order` | `string[]` | Array of locale codes to check | | `key` | `string` | Exact key to look up | **Returns:** `any` โ€“ Found value, or `undefined` if not found --- ### `#resolveByPattern(order, key)` ๐Ÿ” Resolves a key by matching regex patterns in locale tables. **Parameters:** | Name | Type | Description | | ------- | ---------- | ----------------------------------------- | | `order` | `string[]` | Array of locale codes in resolution order | | `key` | `string` | Key to match against patterns | **Returns:** `any` โ€“ Value associated with matched pattern, or `undefined` --- ### `#materialize(value, params)` ๐Ÿ—๏ธ Converts a raw translation entry into a final string for display. **Value can be:** * String * Function `(params, helpers) => any` * `{ $fn: string, args?: any }` (file mode placeholder) **Parameters:** | Name | Type | Description | | | | -------- | -------- | ------------------------------------- | ------------------------------ | --------------------- | | `value` | `string` | HelperCallback | { \$fn: string; args?: any }\` | Raw translation entry | | `params` | `Dict` | Optional parameters for interpolation | | | **Returns:** `string` โ€“ Materialized result --- ### `#interpolate(template, params)` โœ๏ธ Interpolates `{named}` placeholders in a string using given parameters. **Parameters:** | Name | Type | Description | | ---------- | -------- | --------------------------------- | | `template` | `string` | Template string with placeholders | | `params` | `Dict` | Values to interpolate | **Returns:** `string` โ€“ Interpolated string --- ### `#dotGet(obj, path)` ๐Ÿ“Œ Safely retrieves a nested property using dot notation. **Parameters:** | Name | Type | Description | | ------ | -------- | ------------------------------------ | | `obj` | `Dict` | Object to retrieve from | | `path` | `string` | Dot-separated path (e.g., `"a.b.c"`) | **Returns:** `any` โ€“ Value at path or `undefined` --- ### `#helpersReadonly()` ๐Ÿ›ก๏ธ Provides a read-only facade for safely accessing registered helpers. **Returns:** `HelpersReadonly<any, any>` โ€“ Safe helper access with: * `has(name)` โ†’ check if helper exists * `call(name, arg, extras)` โ†’ invoke helper safely --- ## Internal Locale Ingestion ๐ŸŒ ### `#ingestLocale(locale, raw)` ๐Ÿ“ฅ Flattens and registers raw locale data into internal string & pattern tables. **Parameters:** | Name | Type | Description | | -------- | -------- | --------------------------- | | `locale` | `string` | Locale code | | `raw` | `Dict` | Raw locale object to ingest | --- ### `#unloadLocale(locale)` โŒ Removes a previously loaded locale from memory (except default). **Parameters:** | Name | Type | Description | | -------- | -------- | --------------------- | | `locale` | `string` | Locale code to unload | --- ## File Mode Loading ๐Ÿ“‚ ### `#loadLocaleFromFile(locale)` ๐Ÿ“„ Loads a locale JSON file and flattens it into internal maps (file mode only). **Behavior:** * Dot-flattens nested keys * Compiles `$pattern` entries into RegExp * Preserves `$fn` placeholders for helper resolution **Parameters:** | Name | Type | Description | | -------- | ------------ | ------------------- | | `locale` | `LocaleCode` | Locale code to load | **Returns:** `Promise<void>` --- ### `#safeRegExp(src)` ๐Ÿงต Returns a cached `RegExp` from source, compiling if needed. Strict mode โ†’ throws on invalid regex; otherwise returns a never-matching regex. **Parameters:** | Name | Type | Description | | ----- | -------- | ------------------------------ | | `src` | `string` | Regex source string (no flags) | **Returns:** `RegExp` --- ### `#coerceFileValue(v)` โš™๏ธ Normalizes a JSON value from file mode into internal representation. * `string` โ†’ returned as-is * `{ $fn: string, args?: any }` โ†’ preserved for helper resolution **Parameters:** | Name | Type | Description | | | ---- | -------- | ----------- | -------------- | | `v` | \`string | FileValue\` | Raw JSON value | **Returns:** `string | { $fn: string, args?: any }` --- ## Constructor & External API ๐Ÿ—๏ธ ### `constructor(options)` โš™๏ธ Creates a new TinyI18 instance for managing localized strings and patterns. **Modes Supported:** * `"local"` โ†’ loads translations from provided objects * `"file"` โ†’ loads translations from JSON files on demand **Notes:** * Ensures default locale is always initialized * `basePath` is required in `"file"` mode **Parameters:** | Name | Type | Description | | --------- | ---------------- | -------------------- | | `options` | `TinyI18Options` | Configuration object | --- ### `clearRegexCache()` ๐Ÿงน Clears the internal regex cache. * Avoids recompiling frequently used patterns * Always managed via API, not direct access **Returns:** `void` --- ### `registerHelper(name, fn)` ๐Ÿ› ๏ธ Registers a helper function for function-based entries or `$fn` references. **Parameters:** | Name | Type | Description | | ------ | ---------------- | -------------------- | | `name` | `string` | Helper function name | | `fn` | `HelperCallback` | Callback function | --- ### `unregisterHelper(name)` โŒ Removes a previously registered helper function. **Parameters:** | Name | Type | Description | | ------ | -------- | ------------------------ | | `name` | `string` | Name of helper to remove | **Returns:** `boolean` โ€“ `true` if removed, `false` if not found --- ### `loadLocaleLocal(locale, data)` ๐Ÿ“ฆ Loads or updates locale data in-memory (local mode only). **Parameters:** | Name | Type | Description | | -------- | ------------ | ---------------- | | `locale` | `LocaleCode` | Locale code | | `data` | `Dict` | Translation data | --- ### `setLocale(locale)` ๐ŸŒ Sets the currently selected locale. In file mode, loads from disk. * Keeps only default + selected locale in memory * Unloads previous selected locale **Parameters:** | Name | Type | Description | | | -------- | ------------ | ----------- | ------------------------------------------- | | `locale` | \`LocaleCode | null\` | Locale code, or `null` to keep only default | **Returns:** `Promise<void>` --- ### `t(key, params, options)` ๐ŸŽฏ Resolves a translation by **exact key**. **Resolution order:** Current locale โ†’ Default locale **Parameters:** | Name | Type | Description | | --------- | ---------------- | ------------------------------------------------ | | `key` | `string` | Translation key (dot.notation) | | `params` | `Dict` | Optional parameters for interpolation or helpers | | `options` | `ResolveOptions` | Optional resolution overrides | **Returns:** `any` โ€“ Usually `string`, but may be HTMLElement, DocumentFragment, or helper return type **Alias:** `get(key, params, options)` --- ### `p(key, options)` ๐Ÿ” Resolves a translation by **regex pattern match**. * Returns first matching entry if multiple patterns exist **Parameters:** | Name | Type | Description | | --------- | ---------------- | -------------------------------------- | | `key` | `string` | Input string to match against patterns | | `options` | `ResolveOptions` | Optional resolution overrides | **Returns:** `any` โ€“ Translation value **Alias:** `resolveByPattern(key, options)` --- ### `resetToDefaultOnly()` ๐Ÿ  Clears all loaded locales except the default. * Selected locale becomes `null` * In file mode, non-default locales are unloaded **Returns:** `void` --- ### `getStatsForLocale(locale)` ๐Ÿ“Š Returns statistics for a specific locale. **Parameters:** | Name | Type | Description | | -------- | ------------ | ---------------------- | | `locale` | `LocaleCode` | Locale code to inspect | **Returns:** `StatLocale` โ€“ Locale stats including number of strings, patterns, and flags **Throws:** Error if locale is not registered