or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

backend.mdconfiguration.mdindex.mdrequest.mdutils.md
tile.json

utils.mddocs/

Utilities

Helper functions for environment detection, promise handling, and object manipulation. These utilities support the core backend functionality and can be imported directly for use in custom implementations.

Capabilities

Object Defaults

Merges default values into objects, similar to lodash's defaults function.

/**
 * Merge default values into object
 * Only sets properties that are undefined in the target object
 * @param obj - Target object to receive defaults
 * @param sources - Source objects containing default values
 * @returns Modified target object
 */
function defaults(obj: object, ...sources: object[]): object;

Usage Examples:

import { defaults } from "i18next-http-backend/lib/utils";

const config = {};
const result = defaults(config, 
  { loadPath: '/locales/{{lng}}/{{ns}}.json' },
  { reloadInterval: false },
  { customHeaders: {} }
);

console.log(result);
// {
//   loadPath: '/locales/{{lng}}/{{ns}}.json',
//   reloadInterval: false,
//   customHeaders: {}
// }

// Only undefined properties are set
const existing = { loadPath: '/custom/path' };
defaults(existing, { loadPath: '/default/path', addPath: '/add' });
console.log(existing);
// { loadPath: '/custom/path', addPath: '/add' }

XMLHttpRequest Detection

Detects if XMLHttpRequest is available in the current environment.

/**
 * Check if XMLHttpRequest is available in current environment
 * Tests for both function and object types to handle different implementations
 * @returns true if XMLHttpRequest is available, false otherwise
 */
function hasXMLHttpRequest(): boolean;

Usage Examples:

import { hasXMLHttpRequest } from "i18next-http-backend/lib/utils";

if (hasXMLHttpRequest()) {
  console.log('XMLHttpRequest is available');
  // Use XMLHttpRequest-based implementation
} else {
  console.log('XMLHttpRequest not available, using fetch');
  // Fall back to fetch API
}

// Environment detection
const httpClient = hasXMLHttpRequest() ? 'xhr' : 'fetch';
console.log(`Using HTTP client: ${httpClient}`);

Promise Conversion

Converts any value to a Promise, useful for handling both synchronous and asynchronous path functions.

/**
 * Convert any value to a Promise that resolves to that value
 * If input is already a Promise, returns it unchanged
 * Otherwise wraps the value in Promise.resolve()
 * @param maybePromise - Value that may or may not be a Promise
 * @returns Promise that resolves to the input value
 */
function makePromise(maybePromise: any): Promise<any>;

Usage Examples:

import { makePromise } from "i18next-http-backend/lib/utils";

// Synchronous value
const syncPath = '/api/translations/en/common';
makePromise(syncPath).then(path => {
  console.log('Path:', path); // '/api/translations/en/common'
});

// Already a Promise
const asyncPath = Promise.resolve('/api/translations/en/common');
makePromise(asyncPath).then(path => {
  console.log('Path:', path); // '/api/translations/en/common'
});

// Function that might return sync or async
const loadPath = (languages, namespaces) => {
  if (useCache) {
    return '/cached/translations/{{lng}}/{{ns}}';
  }
  return fetch('/api/config').then(res => res.json()).then(config => config.translationPath);
};

// Handle both cases uniformly
makePromise(loadPath(['en'], ['common'])).then(path => {
  console.log('Resolved path:', path);
});

Promise Detection

Internal helper function used by makePromise to detect if a value is a Promise.

/**
 * Determine whether the given value is a Promise
 * Checks for the presence of a 'then' method
 * @param maybePromise - Value to test
 * @returns true if value appears to be a Promise, false otherwise
 */
function isPromise(maybePromise: any): boolean;

Usage Examples:

// Direct usage (internal function, not exported)
const isPromise = (maybePromise) => {
  return !!maybePromise && typeof maybePromise.then === 'function';
};

console.log(isPromise(Promise.resolve('test'))); // true
console.log(isPromise('string')); // false
console.log(isPromise({ then: () => {} })); // true (thenable)
console.log(isPromise(null)); // false

Implementation Details

Environment Compatibility

The utilities are designed to work across all supported environments:

  • Node.js: Full compatibility with all Node.js versions
  • Browsers: Works in all modern browsers and IE 11+
  • Deno: Full compatibility with Deno runtime
  • Web Workers: Compatible with Web Worker environments

Performance Considerations

  • defaults: Uses efficient property iteration and only sets undefined properties
  • hasXMLHttpRequest: Performs lightweight type checking without instantiation
  • makePromise: Minimal overhead for already-promised values

Type Safety

All utility functions are fully typed and work seamlessly with TypeScript:

// Type preservation
const config: BackendOptions = {};
const withDefaults = defaults(config, { loadPath: '/default' });
// withDefaults maintains BackendOptions type

// Promise type inference
const stringPath = '/api/translations';
const promisedPath = makePromise(stringPath);
// promisedPath is Promise<string>

Error Handling

The utilities handle edge cases gracefully:

// defaults with null/undefined sources
defaults({}, null, undefined, { valid: 'option' }); // Works safely

// makePromise with various inputs
makePromise(null);       // Promise.resolve(null)
makePromise(undefined);  // Promise.resolve(undefined)
makePromise(0);          // Promise.resolve(0)
makePromise(false);      // Promise.resolve(false)