npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@languager-ai/sdk

v0.1.0

Published

Languager.ai SDK — AI-native i18n for React and JavaScript

Readme

@languager-ai/sdk

Cliente JavaScript/TypeScript y helpers React para la API de Languager.

Instalación

npm install @languager-ai/sdk

Claves SERVER vs CLIENT y token de sesión

  • El endpoint HTTP de traducción puede ser uno solo (POST /translations); HIT de caché exige scope translations:read y MISS (LLM) exige translations:create o un token de sesión emitido con clave SERVER (POST /v1/translation-sessions). Ese token va en la cabecera X-Languager-Session-Token junto con X-API-Key (clave CLIENT recomendada en el navegador, solo translations:read).
  • Las claves CLIENT requieren patrones allowedOrigins en el servidor. Origin/Referer son una capa débil fuera del navegador; el modelo más seguro es SERVER solo en tu backend + token de sesión de corta duración para el front.
  • Activar translations:create en una clave CLIENT es posible pero no recomendado (modo avanzado con cuotas y rate limit en API).

Uso (JavaScript)

import { LanguagerClient } from '@languager-ai/sdk';

const client = new LanguagerClient({
  apiKey: process.env.LANGUAGER_API_KEY!,
  baseUrl: 'http://localhost:3001/v1',
  defaultSourceLang: 'en',
  httpBatchChunkSize: 64,
  requestTimeoutMs: 60_000,
});
client.setLanguage('es');
const s = await client.translate('Hello');

React

import { LanguagerProvider, useTranslation, Translate } from '@languager-ai/sdk/react';

// Secure browser setup (Next.js): CLIENT key + session endpoint
<LanguagerProvider
  config={{
    apiKey: process.env.NEXT_PUBLIC_LANGUAGER_API_KEY!,
    baseUrl: 'https://api.languager.ai/v1',
    sessionEndpoint: '/api/languager/session', // your backend issues short-lived tokens
  }}
  defaultLanguage="en"
  initialTranslations={prefetchedFromServer} // optional SSR hydration
  fallback={(text) => <span className="animate-pulse">{text}</span>}
>
  <App />
</LanguagerProvider>
function MyComponent() {
  const { t, language, setLanguage, isTranslating } = useTranslation();

  return (
    <>
      <select value={language} onChange={(e) => setLanguage(e.target.value)}>
        <option value="en">English</option>
        <option value="es">Español</option>
      </select>
      <h1>{t('Welcome')}</h1>
      <Translate fallback="…">Save changes</Translate>
      {isTranslating && <p>Loading translations…</p>}
    </>
  );
}

Loading fallback and language switching

  • Set fallback on LanguagerProvider for a global loading UI (React node or (text) => node).
  • Override per string with <Translate fallback={…}>.
  • When switching languages, the SDK keeps the previous language visible until the new translation arrives (no flash to source text).
  • Pass initialTranslations from server prefetch to avoid client-side waits on first paint.

Session token (recommended for browser)

  1. Create a CLIENT API key with only translations:read and your allowed origins.
  2. Create a SERVER API key with translations:create (no origins).
  3. Add a backend route using createTranslationSessionHandler() from @languager-ai/sdk/next/server.
  4. Point sessionEndpoint at that route. The SDK fetches tokens automatically on cache misses.
// app/api/languager/session/route.ts (Next.js App Router)
import { createTranslationSessionHandler } from '@languager-ai/sdk/next/server';
export const POST = createTranslationSessionHandler();

Environment: LANGUAGER_API_KEY (SERVER) on the server; NEXT_PUBLIC_LANGUAGER_API_KEY (CLIENT) in the browser.

Servidor (singleton)

import { getServerClient, t } from '@languager-ai/sdk/server';

getServerClient(); // usa LANGUAGER_API_KEY / LANGUAGER_BASE_URL
await t('Hello', 'es');

getServerClient() solo crea un cliente nuevo la primera vez. Si pasas un objeto de configuración con algún campo definido (apiKey, baseUrl, etc.), se reconstruye el cliente. Un objeto vacío {} no fuerza reinicialización.

Widget por script (página completa)

Incluye el bundle IIFE generado en dist/widget.global.js (en npm: @languager-ai/sdk/widget./dist/widget.global.js).

<script
  src="https://cdn.tudominio.com/widget.global.js?from=en&to=es"
  data-languager-widget
  data-api-key="TU_API_KEY"
  defer
></script>

Parámetros de URL del script

| Query | Alternativa | Descripción | |-------|----------------|-------------| | from | sourceLang | Idioma de origen (opcional; si falta, detección en servidor). | | to | targetLang | Idioma de destino (por defecto en). |

Atributos data-* en la etiqueta script

| Atributo | Obligatorio | Descripción | |-----------|-------------|-------------| | data-api-key | Sí | Clave de proyecto. No pongas la clave solo en la query del src (queda en logs de CDN, historiales y HTML público). | | data-base-url | No | Base de la API (por defecto https://api.languager.ai/v1). | | data-http-chunk | No | Tamaño máximo de strings por petición HTTP al endpoint batch (por defecto 80). | | data-autostart | No | false desactiva la traducción automática al cargar; puedes llamar LanguagerWidget.run(scriptElement) manualmente. |

Seguridad

  • Cualquier clave expuesta en el front puede ser copiada. Mitigación: rotación de claves, límites de uso en el panel, o un proxy en tu backend que oculte la clave secreta.
  • CSP: añade la API a connect-src (por ejemplo https://api.languager.ai o tu data-base-url).

Contenido excluido

No se traduce texto dentro de script, style, noscript, textarea, code, pre, ni nodos bajo un ancestro con data-languager-skip.

Build del paquete

npm run build -w @languager-ai/sdk

Genera dist/index.*, dist/react.*, dist/server.* y dist/widget.global.js.