Skip to content
Comvi

For AI assistants

View .md

Check generated Comvi i18n code against these rules before suggesting it. Every non-default feature is composed, so code that assumes a feature is on compiles in some places and throws in others. For a walkthrough, start at Quick start.

  • One app names one @comvi/<framework> package for the constructor. Do not also import createI18n from @comvi/core. React, Vue, Solid and Svelte re-export the base constructor and every capability installer by name on their one entry. Three exceptions: @comvi/vue’s own createI18n builds the VueI18n wrapper, and .use(installer) on that wrapper composes onto the i18n instance it holds and widens the type of i18n.core; @comvi/next has two runtime entries, @comvi/next/client and @comvi/next/server, which mirror the same base constructor and installer set, so import from whichever runtime you are in; @comvi/nuxt auto-imports its generated instance, or you supply one in a comvi.i18n.* file (found by convention; i18nModule overrides the path) whose @comvi/nuxt/i18n subpath exports exactly the composition surface (defineComviI18n, createI18n, icuCompiler, loader, attachLoader, plugins, devtools, definePlugin, NuxtInstanceFactory), so the app declares no @comvi/core dependency.

  • @comvi/core is still the source of every subpath: @comvi/core/tags, /icu, /loader, /plugins, /devtools, /rich-text, and the free format helpers and types from its root. Only the constructor comes from the framework package.

  • A capability that is not composed is absent, not disabled. createI18n({ locale: 'en' }) has no registerLoader, no registerPlugin, no ICU plurals and no tag parsing in t().

  • Compose with .use(installer) before init(); that is the only rule about composition order. Chaining off the constructor or applying later to a variable are both correct. On the @comvi/vue wrapper keep the return value either way, or the binding’s core type stays unwidened. init() is what drains the plugin queue, so a plugin queued after it does not run then (a development-only warning, a silent no-op in production). It stays in the queue: a later init() is a second attempt and drains the queue again, running that plugin together with every plugin already registered, and the cleanups of both drains accumulate until destroy(). On @comvi/vue that deadline is app.use(i18n), because install starts init().

  • On the i18n instance, .use is a pipe: i18n.use(f) is f(i18n), and it returns what f returned, having first checked that f returned the instance. It is the one composition verb: there is no with. The @comvi/vue wrapper’s .use(f) runs f(i18n.core) and returns the same VueI18n, retyped. Whether a second .use is a no-op depends on what you hand it:

    • a bare capability installer (plugins(), attachLoader, devtools()) attaches once; a second one installs nothing and keeps every plugin already registered;
    • a configured capability installer still applies its configuration: .use(loader(A)).use(loader(B)) attaches once but registers B, replacing A;
    • a plugin package installer (cdnLoader, localeDetector, inContextEditor) is not idempotent, because it ends in registerPlugin(…). Two localeDetector() installers give you two localeChanged subscribers.

    Order between loader(), plugins() and devtools() is free.

  • A raw plugin never goes in .use(). The plugin queue is registerPlugin(plugin, options?), a member of @comvi/core/plugins, and its installer form is definePlugin(fn, options?) from the same subpath, so an app’s own plugin is written .use(definePlugin(fn)).

  • Each plugin package exports two names for one plugin: the plain installer for .use(…), and a Plugin-suffixed factory for registerPlugin(…) on an instance you composed yourself. An installer put in registerPlugin() throws E_INSTALLER_AS_PLUGIN at init(), before anything is attached. A factory put in .use() throws E_USE_NOT_INSTALLER on that line: the guard is an identity check, so .use refuses anything that is not the instance it handed in, sync or async. The refusal follows the call, so the plugin body has already run and a raw async plugin’s promise is never awaited.

    package installer for .use(…) plugin for registerPlugin(…)
    @comvi/plugin-fetch-loader cdnLoader cdnLoaderPlugin
    @comvi/plugin-fetch-loader/api fetchLoader fetchLoaderPlugin
    @comvi/plugin-locale-detector localeDetector localeDetectorPlugin
    @comvi/plugin-in-context-editor inContextEditor inContextEditorPlugin

    Do not emit FetchLoader, CdnLoader, LocaleDetector or InContextEditorPlugin. The standalone editor IIFE exposes the factory as window.ComviInContextEditor.inContextEditorPlugin.

    Prefer cdnLoader from @comvi/plugin-fetch-loader for production apps that read published translations. fetchLoader from @comvi/plugin-fetch-loader/api serves the CDN and the authenticated API, chosen at runtime by if (i18n.apiKey), so it carries the API request path whether or not you use it (Bundle size). Use the /api entry only where the app talks to the API, which is server-side: an apiKey in a client bundle either goes undefined (a silent degrade to CDN mode) or ships the credential to visitors.

  • registerLoader, reloadMessages, addActiveNamespace(s) and onLoadError live on @comvi/core/loader. Calling i18n.registerLoader(fn) on an instance that never composed the loader is a type error at build time and a thrown error at runtime.

  • registerLoader takes a function, (locale, namespace) => Promise<catalog>, not a map. The one exception is createNextI18n()’s composed instance, whose registerLoader keeps both overloads. Everywhere else a static map goes through loader(map), which attaches the capability and registers the map in one call:

    import { createI18n } from '@comvi/core';
    import { loader } from '@comvi/core/loader';
    export const i18n = createI18n({ locale: 'en' }).use(
    loader({ en: () => import('./locales/en.json') }),
    );
  • A catalog handed to any i18n instance may be nested or flat: the instance flattens { nav: { home: 'Home' } } to nav.home at the point it enters. A non-string leaf is coerced with String() and a null or undefined leaf is dropped, each with one development warning naming the key. flattenCatalog is exported from the @comvi/core root only; it is not on @comvi/core/loader or any binding root.

  • An already flat catalog, one whose own values are all strings, is kept by reference, not copied: getMessages() returns the object you passed, the library never writes to it, and an edit you make to it afterwards is read by the next t() with no namespaceLoaded or configChanged event. Call addMessages() when bindings have to re-render, and pass a copy for a snapshot; the first merge into that locale and namespace copies into a new object. Only a non-empty string resolves, so constructor, toString and __proto__ inherited from Object.prototype are never translations.

  • ns on an instance with no loader loads nothing, and init() warns once in development naming .use(loader(map)). instanceId or exposeGlobal: true with no discovery composed gets the same treatment, naming .use(devtools({ instanceId })). Production stays silent.

  • The default compiler is simple: text and {param} only. {count, plural, …} on it throws E_ICU_SYNTAX in development and renders the braces literally in production. It never renders an approximation of the plural.
  • Turn ICU on one way: compiler: icuCompiler (from @comvi/core/icu) as a constructor option. It covers the catalog the constructor ingests and every catalog that arrives later from a loader, a CDN or the platform API. There is no second form and no ordering to get right. MessageCompiler is the type, so a custom compiler goes in the same option.
  • # inside plural and selectordinal renders the count formatted for the message’s locale through Intl.NumberFormat defaults: 1,234 in en, 1.234 in de, a fractional count rounded to three fraction digits, negative zero as 0. Write {count} where the raw digits are wanted. Exact selectors (=0, =1) compare the number itself.
  • An argument whose only comma sits inside a nested brace pair, {{count, plural, …}}, is not a parameter: it fails as unsupported ICU syntax, like {price, number}.
  • <T> parses <tag> syntax on any i18n instance, including one with nothing composed, because it passes the tag grammar per call through @comvi/core/rich-text. It never needs a side-effect import.
  • Plain t() renders <tag> markup literally until something imports @comvi/core/tags. That import is process-wide and affects every instance in the bundle, including ones already constructed. It is not a per-instance option, and no framework package re-exports it.
  • A function passed for a {placeholder} is not an interpolation value: it renders as a missing parameter, the literal {name} by default or an empty string under missingParam: 'drop', with a development warning naming it as a function. A handler belongs to <link>…</link> markup, so emit the tag form in the message, never {link} with a handler.
  • An SSR app that wants tags in t() must import @comvi/core/tags in the server graph as well as the client, or the first server-rendered paint shows literal angle brackets before hydration replaces them. @comvi/next is the one exception: createNextI18n() already imports @comvi/core/tags internally.
  • formatNumber, formatDate, formatCurrency, formatRelativeTime and getTextDirection are free functions exported from the package root, taking the i18n instance (or a locale string, for getTextDirection) as the first argument. Do not write i18n.formatCurrency(…) or i18n.dir.

    import { createI18n, formatCurrency, getTextDirection } from '@comvi/core';
    const i18n = createI18n({ locale: 'en' });
    formatCurrency(i18n, 1234.5, 'EUR');
    getTextDirection(i18n.locale); // "ltr" | "rtl"
  • The React, Vue, Solid and Svelte bindings are the one exception: their useI18n() / composable return does carry bound formatNumber / dir members. dir follows each binding’s reactivity model:

    binding dir from useI18n() read it as
    @comvi/react, @comvi/next/client plain value for the current render dir
    @comvi/vue, @comvi/nuxt ComputedRef<'ltr' | 'rtl'> dir.value
    @comvi/solid accessor () => 'ltr' | 'rtl' dir()
    @comvi/svelte Readable<'ltr' | 'rtl'> $dir
  • Typed translation keys come from comvi typegen (the CLI), which augments @comvi/core’s TranslationKeys interface via a generated .d.ts file. Import that file once and every framework’s t() gets autocomplete and compile-time key and param checks.
  • @comvi/vite-plugin and @comvi/cli both generate through the same internal emitter, so a project running the CLI in CI and the plugin in dev cannot see the two disagree.

Most E_* names are production strings, not error codes

Section titled “Most E_* names are production strings, not error codes”

Three of them carry a real code own-property, and only those three are branchable:

code carries .code where it comes from
E_ICU_SYNTAX yes, plus argumentType an ICU argument the active compiler does not implement
E_USE_INSTANCE_IDENTITY yes the .use() of @comvi/vue’s wrapper and of createNextI18n()’s result, when an installer returns something other than the i18n instance
E_USE_NOT_INSTALLER yes the i18n instance’s .use(), when the function it was handed returned something else: a raw plugin, or a Plugin-suffixed factory

IcuSyntaxError is exported as a type from @comvi/core, so (error as IcuSyntaxError).code === 'E_ICU_SYNTAX' is a real branch. Development throws it, at ingestion or compile, while production renders the braces literally and reports an error of the same shape through onError rather than throwing.

Every other E_* name is the message a production build throws; a development build throws a longer message describing the fix instead, and the value is a plain Error with no code either way. So catch (e) { if (e.code === 'E_PLUGIN_INIT_RETURN') … } never fires, and matching on error.message is matching on the build mode. Those names include E_PLUGIN_INIT_RETURN, E_INSTALLER_AS_PLUGIN, E_PLUGIN_INIT_FAILED, E_PLUGIN_INIT_TIMEOUT, E_REGISTER_LOADER_ARG and E_REGISTER_POST_PROCESSOR; the complete set is in the error-code table.

Both compile, and both are what general JS idiom produces by default.

An expression-bodied plugin arrow. A plugin may return only undefined or a cleanup function; an arrow with an expression body returns whatever the expression evaluates to, so the assignment leaks out and init() throws. Use a statement body:

src/plugins/ready.ts
import type { I18nPlugin } from '@comvi/core';
let ready = false;
// ✗ export const ReadyFlag: I18nPlugin = (i18n) => (ready = true);
export const ReadyFlag: I18nPlugin = () => {
ready = true;
};

A flattenCatalog import from a binding root or @comvi/core/loader. The function is on the @comvi/core root only, and a nested catalog needs no call at all:

src/i18n.ts
import { createI18n } from '@comvi/core';
// ✗ import { flattenCatalog } from '@comvi/react'; (not exported there)
// ✗ messages: { en: flattenCatalog({ nav: { home: 'Home' } }) } (a needless call)
export const i18n = createI18n({
locale: 'en',
messages: { en: { nav: { home: 'Home' } } }, // -> t('nav.home')
});
  • createNextI18n({ … }) from @comvi/next returns { i18n, routing, use }. The i18n instance comes composed with the loader and plugin capabilities and the tag grammar, not with devtools discovery: an app the Comvi browser extension should see adds .use(devtools()) to the result, devtools from @comvi/next. Its use is core’s installer pipe: result.use(f) is f(result.i18n). Runtime and environment scoping live on the plugin form: nextPlugin(plugin, { runtime, environment }) and nextPluginLazy(load, …), from @comvi/next, /client and /server. use(plugin, { runtime, environment, lazy }) and the four delegates useClient / useServer / useClientLazy / useServerLazy do not exist.
  • The locale middleware has two file conventions: middleware.ts with createMiddleware from @comvi/next/middleware on Next.js 15, and proxy.ts with the same function from @comvi/next/proxy on Next.js 16, which renamed the convention. Both subpaths export one function taking one MiddlewareConfig; Next 16 runs proxy.ts on the Node.js runtime and rejects a runtime option in it, so do not emit one.
  • The Next setup is one config module plus a next.config plugin: withComvi({ config: './src/i18n/config.ts' })(nextConfig) from @comvi/next/plugin, a module exporting i18n and routing, <ComviProvider locale> from @comvi/next/server in app/[locale]/layout.tsx, and await getI18n({ locale }) in Server Components with the locale from params. Do not emit a src/i18n/server.ts with setI18n(i18n), a "use client" wrapper around <I18nProvider>, or setRequestLocale(locale) before getI18n({ locale }): those are the manual setup, still supported, and only an app whose config imports server-only code needs them. ComviProvider is not exported from @comvi/next/client. The config module runs in the client build too, so nothing server-only goes in it.
  • Never compose localeDetector() on a Next i18n instance: it is module-scope and process-wide on the App Router, so the detector runs once at the first init(), finds nothing on the server, and never runs per request. Use nextPlugin(localeDetectorPlugin(…), { runtime: 'client' }).
  • compiler is an option on CreateNextI18nOptions and defaults to nothing: ICU needs compiler: icuCompiler here as on every other constructor. createNextI18nFromInstance(factory, routing) is eager: the factory runs once, inside the call.
  • Locale routing takes two options with one vocabulary in both frameworks: localeCookie (false, a name, or { name, maxAge, secure, sameSite, domain }) and localeDetection (false, or { order, queryParam, headerName, resolveAcceptLanguage }; default order ['query', 'cookie', 'accept-language'], query and header inert until queryParam / headerName are set). On Next.js localeCookie goes in defineRouting() and localeDetection in createMiddleware(); on Nuxt both go under comvi; only the default cookie name differs, NEXT_LOCALE against i18n_locale. There is no separate cookie-name option, no cookie flag inside localeDetection and no detection object under another name; the Nuxt module fails the build on an unknown key, naming the option to write.
  • The server helper is getI18n({ locale, ns }) on Next.js and useTranslation(event, { locale, ns }) on Nuxt, each in its framework’s idiom; both return { t, hasTranslation, locale }, and ns is the only namespace word. comvi.ns lists the namespaces to load at init, as core’s ns does.
  • The Nuxt quick start is nuxt.config.ts with modules: ['@comvi/nuxt'] and comvi: { defaultLocale, locales, messages }, plus app.vue and a page. locales takes strings; localePrefix: 'as-needed' is the default, so do not write it; no import type {} from '@comvi/nuxt' is needed. The module writes <html lang dir> from the active locale (comvi.head, default true), so do not emit useLocaleHead({ addLang: true, addDir: true }) for that; useLocaleHead() is for canonical, hreflang and og:locale.
  • A Nuxt comvi.i18n.ts file is found by convention (./comvi.i18n.* under srcDir, then rootDir); comvi.i18nModule is the explicit override and is not written when the file is at that path. Write it as export default defineComviI18n((options) => createI18n(options).use(…)), both from @comvi/nuxt/i18n; satisfies NuxtInstanceFactory is the longer spelling of the same type. The factory returns a core i18n instance, not a VueI18n: the guard requires t() and init() and rejects the wrapper’s core member, so createI18n from @comvi/vue throws a TypeError there. It runs once for the client and once per server request and must return a new createI18n instance each time; in development the module throws [@comvi/nuxt] comvi i18nModule returned an instance it already returned when it gets the same one twice.
  • A Nuxt comvi.setup hook needs no type argument for the instance: the module writes the factory’s return type into .nuxt/types/, so NuxtI18nSetup’s default is the instance comvi.i18n.ts’s factory returns, and a capability call compiles exactly when that file composed it. Naming the type by hand (satisfies NuxtI18nSetup<I18n & I18nLoaderApi>, types from the @comvi/nuxt root) is the fallback for a factory the module cannot see, and codegen cross-checks the claim.
  • comvi.icu: true reaches comvi.i18n.ts too: it arrives as compiler: icuCompiler, the last key in the options the factory receives, so a factory that spreads them gets ICU.
  • comvi.messages in nuxt.config.ts is I18nOptions["messages"] verbatim, nested or flat, forwarded to the client instance and each per-request server instance. It is the only way a comvi block with no comvi.i18n.ts renders a translation. comvi.cdnUrl and comvi.apiBaseUrl do not exist: compose .use(cdnLoader({ cdnUrl })) in comvi.i18n.ts.
  • Nuxt’s useI18n() does not carry hasTranslationNow / hasLocaleNow; they are on useNuxtApp().$i18n. Vue’s are on the VueI18n class, inject(I18N_INJECTION_KEY)!.hasTranslationNow(…).

Copy-paste for your own AGENTS.md or .cursorrules

Section titled “Copy-paste for your own AGENTS.md or .cursorrules”
When writing Comvi i18n code:
- The CONSTRUCTOR comes from one `@comvi/<framework>` package per app; don't import
`createI18n` from `@comvi/core` as well. Subpaths still come from core:
`@comvi/core/tags`, `/icu`, `/loader`, `/plugins`, `/devtools`, `/rich-text`, and the
free format helpers from its root.
- `createI18n()` returns the i18n instance. A capability (loader, plugins, devtools, tags)
is absent until composed with `.use(installer)`, any time BEFORE `init()` — chained or
on a variable, both fine. Don't call `registerLoader`, `registerPlugin`, or expect tags
on an uncomposed instance, and don't compose after `init()` (that is what drains the
plugin queue, so a plugin registered later waits for another `init()` to run it). On
`@comvi/vue` compose before `app.use(i18n)`, which starts `init()` for you.
- On the i18n instance, `.use(f)` is `f(i18n)`. On the `@comvi/vue` wrapper, `.use(f)` runs
`f(i18n.core)` and returns the same `VueI18n`, retyped; keep that return value.
Attaching a capability twice is a no-op, but composing a
PLUGIN installer twice (`cdnLoader`, `localeDetector`, `inContextEditor`) registers
that plugin twice.
- `.use()` is the ONE composition verb and it takes INSTALLERS. There is no `with` verb.
A raw plugin goes to `registerPlugin(plugin, options?)` from `@comvi/core/plugins`, or
to `definePlugin(fn, options?)` from the same subpath so it stays a `.use(definePlugin(fn))` step.
Installer in `.use()`, `Plugin`-suffixed factory in `registerPlugin()`. Both
cross-uses throw: `E_INSTALLER_AS_PLUGIN` at `init()` one way, `E_USE_NOT_INSTALLER`
on the line the other way.
- `loader(map)` for a static map, and the map is REQUIRED — a bare `loader()` is a compile
error (`E_LOADER_IMPORT_MAP` for a JS caller). `attachLoader` is the one attach-only loader
installer: `registerLoader(fn)` only after `.use(attachLoader)`. `registerLoader` takes a map
only on `createNextI18n()`'s instance.
- `attachPlugins` / `attachDevtools` are on `@comvi/core/plugins` / `@comvi/core/devtools`
only; no binding root re-exports them, and neither does `@comvi/nuxt/i18n`. `I18n` is a
TYPE-only export from the four SPA binding roots, and `@comvi/vue` does not re-export
`createCore` — use `import { createI18n as createCore } from '@comvi/core'`.
- `useI18nInstance()` returns the i18n instance on react, solid and svelte; vue's equivalent is
`inject(I18N_INJECTION_KEY).core`. `useI18n(ns)` is namespace-bound in all four.
`<T markers={false}>` turns the in-context editor's markers off for one element when they cause a problem, in all four.
`ComponentMap` is the `<T components>` map type in all four.
- React and solid have `<I18nProvider fallback>` (gated on `!isInitialized`) and accept
`ssrLocale`, the one name for the server-rendered locale. React is the
only binding with `ssrInitialIsLoading` / `ssrInitialIsInitializing`. Svelte and vue gate with
`{#if $isInitializing}` / `v-if="isInitializing"` instead.
- Production loader: `cdnLoader` from `@comvi/plugin-fetch-loader`. `fetchLoader` from the
`/api` entry also carries the authenticated API path — server-side only, since an
`apiKey` in a client bundle either goes undefined or ships to visitors.
- ICU: `compiler: icuCompiler` on the constructor, and nothing else. It works for
inline, loader, CDN and API catalogs alike, and carries no ordering rule.
- Nested catalogs need nothing: every i18n instance flattens them on ingestion. `flattenCatalog`
is on the `@comvi/core` root only, for pre-flattening data by hand.
- Plugins return `undefined` or a cleanup function — never an expression-bodied arrow.
- Most `E_*` names are PRODUCTION message strings, not codes; dev throws prose. Exactly
three set `error.code`: `E_USE_INSTANCE_IDENTITY` (the `.use()` of the `@comvi/vue`
wrapper and of `createNextI18n()`'s result, when an installer returns something other than
the instance it was given), `E_USE_NOT_INSTALLER` (the i18n instance's `.use()`, when what it was handed
returned something else) and `E_ICU_SYNTAX` (which also carries
`argumentType`, is thrown in development and only REPORTED via `onError` in production).
- Use `<T>` for tag markup in JSX/templates. Plain `t()` only renders tags after
`import '@comvi/core/tags'` (process-wide, needed in both server and client for SSR).
- `formatNumber`/`formatDate`/`formatCurrency`/`formatRelativeTime`/`getTextDirection`
are free functions taking the i18n instance or a locale, not methods — except the
bound helpers a framework binding's `useI18n()` returns.
- Typed keys come from `comvi typegen`; import the generated `.d.ts` once.
- `createNextI18n()` returns `{ i18n, routing, use }`. The instance is composed except for the
compiler and browser-extension discovery, so ICU still needs `compiler: icuCompiler` and the
Comvi browser extension still needs `.use(devtools())` on the result; that
`use` is core's INSTALLER pipe. Scope a plugin with `nextPlugin(p, { runtime, environment })`
or `nextPluginLazy(load, …)`; `useClient` / `useServer` / `useClientLazy` / `useServerLazy`
do not exist.
- Next.js setup: `withComvi({ config: './src/i18n/config.ts' })(nextConfig)` in next.config
(from `@comvi/next/plugin`), a client-safe config module exporting `i18n` and `routing`,
`<ComviProvider locale>` from `@comvi/next/server` in the `[locale]` layout, and
`await getI18n({ locale })` in Server Components. No `setI18n()` module, no own
`"use client"` wrapper, no `setRequestLocale()` before `getI18n({ locale })`; those belong
to the manual setup for configs that import server-only code.
- Locale routing on Next.js and Nuxt: `localeCookie` (`false` | name | `{ name, maxAge,
secure, sameSite, domain }`) and `localeDetection` (`false` | `{ order, queryParam,
headerName, resolveAcceptLanguage }`), same names and defaults in both: `localeCookie` in
`defineRouting()`, `localeDetection` in `createMiddleware()`, both under `comvi` on Nuxt. Server helpers: `getI18n({ locale, ns })` on Next, `useTranslation(event,
{ locale, ns })` on Nuxt; both return `{ t, hasTranslation, locale }`. `ns`, never another word.