or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli.mdindex.mdparser.mdstream.md
tile.json

parser.mddocs/

Parser API

Core parsing functionality for extracting translation keys from source code. The Parser class provides methods for parsing function calls, JSX components, and HTML attributes with configurable options and chainable method calls.

Capabilities

Parser Constructor

Creates a new parser instance with configurable options for languages, namespaces, and parsing behavior.

/**
 * Creates a new parser instance
 * @param options - Parser configuration options
 */
constructor(options?: ParserOptions): Parser

Usage Examples:

const Parser = require('i18next-scanner').Parser;

// Basic parser with minimal configuration
const parser = new Parser({
  lngs: ['en', 'de'],
  ns: ['translation']
});

// Advanced parser with full configuration
const parser = new Parser({
  compatibilityJSON: 'v3',
  debug: true,
  sort: true,
  lngs: ['en', 'de', 'fr'],
  ns: ['common', 'validation', 'navigation'],
  defaultLng: 'en',
  defaultNs: 'common',
  defaultValue: '__STRING_NOT_TRANSLATED__',
  func: {
    list: ['i18next.t', 'i18n.t', 't'],
    extensions: ['.js', '.jsx', '.ts', '.tsx']
  },
  trans: {
    component: 'Trans',
    i18nKey: 'i18nKey',
    defaultsKey: 'defaults',
    extensions: ['.jsx', '.tsx'],
    fallbackKey: function(ns, value) {
      return value;
    }
  },
  resource: {
    loadPath: 'locales/{{lng}}/{{ns}}.json',
    savePath: 'locales/{{lng}}/{{ns}}.json',
    jsonIndent: 2,
    lineEnding: '\\n'
  }
});

Function Parsing

Parses translation function calls from source code (e.g.,

i18next.t('key')
,
t('key')
).

/**
 * Parses translation functions from source code
 * @param content - Source code content to parse
 * @param opts - Optional parsing options to override defaults
 * @param customHandler - Optional custom handler for processing found keys
 * @returns Parser instance for method chaining
 */
parseFuncFromString(content: string, opts?: ParseOptions, customHandler?: CustomHandler): Parser

Usage Examples:

const fs = require('fs');
const parser = new Parser();

// Parse with default options
const content = fs.readFileSync('src/app.js', 'utf-8');
parser.parseFuncFromString(content);

// Parse with custom function list
parser.parseFuncFromString(content, {
  list: ['__', '_t', 'translate']
});

// Parse with custom handler
parser.parseFuncFromString(content, {}, (key, options) => {
  console.log('Found key:', key, 'with options:', options);
  parser.set(key, options);
});

// Chain multiple parsing operations
parser
  .parseFuncFromString(appContent)
  .parseFuncFromString(utilsContent, { list: ['i18n.t'] });

Trans Component Parsing

Parses React Trans components from JSX source code (e.g.,

<Trans i18nKey="key">Default text</Trans>
).

/**
 * Parses Trans components from JSX source code
 * @param content - JSX source code content to parse
 * @param opts - Optional parsing options to override defaults
 * @param customHandler - Optional custom handler for processing found keys
 * @returns Parser instance for method chaining
 */
parseTransFromString(content: string, opts?: ParseOptions, customHandler?: CustomHandler): Parser

Usage Examples:

const jsxContent = fs.readFileSync('src/components/App.jsx', 'utf-8');

// Parse with default Trans component
parser.parseTransFromString(jsxContent);

// Parse with custom component name
parser.parseTransFromString(jsxContent, {
  component: 'Translation'
});

// Parse with RegExp component matcher
parser.parseTransFromString(jsxContent, {
  component: /^Trans/
});

// Parse with fallback key generation
parser.parseTransFromString(jsxContent, {
  fallbackKey: true, // Uses defaultValue as fallback when i18nKey is missing
  supportBasicHtmlNodes: true,
  keepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p']
});

HTML Attribute Parsing

Parses HTML attributes for translation keys (e.g.,

<div data-i18n="key"></div>
).

/**
 * Parses HTML attributes for translation keys
 * @param content - HTML content to parse
 * @param opts - Optional parsing options to override defaults
 * @param customHandler - Optional custom handler for processing found keys
 * @returns Parser instance for method chaining
 */
parseAttrFromString(content: string, opts?: ParseOptions, customHandler?: CustomHandler): Parser

Usage Examples:

const htmlContent = fs.readFileSync('public/index.html', 'utf-8');

// Parse with default data-i18n attribute
parser.parseAttrFromString(htmlContent);

// Parse with custom attribute list
parser.parseAttrFromString(htmlContent, {
  list: ['data-i18n', 'data-translate', 'i18n']
});

// Chain HTML parsing with other parsing methods
parser
  .parseFuncFromString(jsContent)
  .parseTransFromString(jsxContent)
  .parseAttrFromString(htmlContent);

Data Access Methods

Get Translation Data

Retrieves parsed translation keys and values with optional filtering and sorting.

/**
 * Retrieves parsed translation data
 * @param key - Optional specific key to retrieve
 * @param opts - Optional retrieval options
 * @returns Translation data object or specific key value
 */
get(key?: string, opts?: GetOptions): any

Usage Examples:

// Get all translation data
const allData = parser.get();

// Get sorted data
const sortedData = parser.get({ sort: true });

// Get data for specific language
const englishData = parser.get({ lng: 'en' });

// Get specific key
const specificKey = parser.get('common:welcome.title');

// Get specific key for specific language
const specificLangKey = parser.get('validation:required', { lng: 'de' });

Set Translation Key

Sets a translation key with options like default value, context, and pluralization.

/**
 * Sets a translation key with options
 * @param key - Translation key to set
 * @param options - Key options and metadata
 * @returns Parser instance for method chaining
 */
set(key: string, options?: SetOptions): Parser

Usage Examples:

// Set simple key with default value
parser.set('welcome.message', { defaultValue: 'Welcome!' });

// Set key with context
parser.set('button.save', { 
  defaultValue: 'Save',
  context: 'form'
});

// Set key with pluralization
parser.set('item.count', {
  defaultValue: 'One item',
  defaultValue_plural: '{{count}} items',
  count: 1
});

// Set key with namespace
parser.set('greeting', {
  defaultValue: 'Hello',
  ns: 'common'
});

// Chain multiple set operations
parser
  .set('title', { defaultValue: 'Application Title' })
  .set('subtitle', { defaultValue: 'Welcome to our app' });

Data Export Methods

JSON Export

Exports parser data as JSON string with formatting options.

/**
 * Exports parser data as JSON string
 * @param options - JSON formatting options
 * @returns JSON string representation of parser data
 */
toJSON(options?: JSONOptions): string

Usage Examples:

// Basic JSON export
const jsonData = parser.toJSON();

// Pretty-printed JSON
const prettyJson = parser.toJSON({ space: 2 });

// JSON with custom replacer
const customJson = parser.toJSON({
  replacer: (key, value) => {
    // Custom transformation logic
    return value;
  },
  space: 2
});

Utility Methods

Debug Logging

Outputs debug information when debug mode is enabled in parser options.

/**
 * Debug logging (only outputs if debug option is enabled)
 * @param args - Arguments to log
 */
log(...args: any[]): void

Error Logging

Outputs error messages to console for debugging parsing issues.

/**
 * Error logging to console
 * @param args - Error messages to log
 */
error(...args: any[]): void

Resource Path Formatting

Formats file paths for loading and saving translation resources with language and namespace placeholders.

/**
 * Formats path for loading translation resources
 * @param lng - Language code
 * @param ns - Namespace
 * @returns Formatted file path
 */
formatResourceLoadPath(lng: string, ns: string): string

/**
 * Formats path for saving translation resources
 * @param lng - Language code
 * @param ns - Namespace
 * @returns Formatted file path
 */
formatResourceSavePath(lng: string, ns: string): string

Usage Examples:

// Get formatted paths
const loadPath = parser.formatResourceLoadPath('en', 'common');
// Returns: 'i18n/en/common.json' (based on parser options)

const savePath = parser.formatResourceSavePath('de', 'validation');
// Returns: 'i18n/de/validation.json' (based on parser options)

Types

interface ParseOptions {
  list?: string[];           // Override function/attribute list
  extensions?: string[];     // Override file extensions
  transformOptions?: {
    filepath?: string;       // Current file path for context
  };
  component?: string | RegExp;     // Trans component name/pattern
  i18nKey?: string;               // i18nKey attribute name
  defaultsKey?: string;           // defaults attribute name
  fallbackKey?: boolean | ((ns: string, value: string) => string);
  supportBasicHtmlNodes?: boolean;
  keepBasicHtmlNodesFor?: string[];
  acorn?: AcornOptions;           // Acorn parser options
  propsFilter?: (code: string) => string;  // Filter function props
}

interface GetOptions {
  sort?: boolean;    // Sort keys alphabetically
  lng?: string;      // Filter by language
}

interface SetOptions {
  defaultValue?: string;              // Default translation value
  defaultValue_plural?: string;       // Plural form default value
  count?: number;                     // Count for plural forms
  context?: string;                   // Context for contextual translations
  ns?: string;                        // Override namespace
  keySeparator?: string | false;      // Override key separator
  nsSeparator?: string | false;       // Override namespace separator
  metadata?: Record<string, any>;     // Additional metadata
  fallbackKey?: boolean | string | ((ns: string, value: string) => string);
}

interface JSONOptions {
  replacer?: (key: string, value: any) => any;  // JSON replacer function
  space?: number | string;                      // JSON indentation
}

type CustomHandler = (key: string, options: SetOptions) => void;