For AI assistants
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.
Packages and composition
Section titled “Packages and composition”-
One app names one
@comvi/<framework>package for the constructor. Do not also importcreateI18nfrom@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 owncreateI18nbuilds theVueI18nwrapper, and.use(installer)on that wrapper composes onto the i18n instance it holds and widens the type ofi18n.core;@comvi/nexthas two runtime entries,@comvi/next/clientand@comvi/next/server, which mirror the same base constructor and installer set, so import from whichever runtime you are in;@comvi/nuxtauto-imports its generated instance, or you supply one in acomvi.i18n.*file (found by convention;i18nModuleoverrides the path) whose@comvi/nuxt/i18nsubpath exports exactly the composition surface (defineComviI18n,createI18n,icuCompiler,loader,attachLoader,plugins,devtools,definePlugin,NuxtInstanceFactory), so the app declares no@comvi/coredependency. -
@comvi/coreis 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 noregisterLoader, noregisterPlugin, no ICU plurals and no tag parsing int(). -
Compose with
.use(installer)beforeinit(); that is the only rule about composition order. Chaining off the constructor or applying later to a variable are both correct. On the@comvi/vuewrapper keep the return value either way, or the binding’scoretype 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 laterinit()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 untildestroy(). On@comvi/vuethat deadline isapp.use(i18n), becauseinstallstartsinit(). -
On the i18n instance,
.useis a pipe:i18n.use(f)isf(i18n), and it returns whatfreturned, having first checked thatfreturned the instance. It is the one composition verb: there is nowith. The@comvi/vuewrapper’s.use(f)runsf(i18n.core)and returns the sameVueI18n, retyped. Whether a second.useis 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 registersB, replacingA; - a plugin package installer (
cdnLoader,localeDetector,inContextEditor) is not idempotent, because it ends inregisterPlugin(…). TwolocaleDetector()installers give you twolocaleChangedsubscribers.
Order between
loader(),plugins()anddevtools()is free. - a bare capability installer (
-
A raw plugin never goes in
.use(). The plugin queue isregisterPlugin(plugin, options?), a member of@comvi/core/plugins, and its installer form isdefinePlugin(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 aPlugin-suffixed factory forregisterPlugin(…)on an instance you composed yourself. An installer put inregisterPlugin()throwsE_INSTALLER_AS_PLUGINatinit(), before anything is attached. A factory put in.use()throwsE_USE_NOT_INSTALLERon that line: the guard is an identity check, so.userefuses anything that is not the instance it handed in, sync orasync. The refusal follows the call, so the plugin body has already run and a rawasyncplugin’s promise is never awaited.package installer for .use(…)plugin for registerPlugin(…)@comvi/plugin-fetch-loadercdnLoadercdnLoaderPlugin@comvi/plugin-fetch-loader/apifetchLoaderfetchLoaderPlugin@comvi/plugin-locale-detectorlocaleDetectorlocaleDetectorPlugin@comvi/plugin-in-context-editorinContextEditorinContextEditorPluginDo not emit
FetchLoader,CdnLoader,LocaleDetectororInContextEditorPlugin. The standalone editor IIFE exposes the factory aswindow.ComviInContextEditor.inContextEditorPlugin.Prefer
cdnLoaderfrom@comvi/plugin-fetch-loaderfor production apps that read published translations.fetchLoaderfrom@comvi/plugin-fetch-loader/apiserves the CDN and the authenticated API, chosen at runtime byif (i18n.apiKey), so it carries the API request path whether or not you use it (Bundle size). Use the/apientry only where the app talks to the API, which is server-side: anapiKeyin a client bundle either goes undefined (a silent degrade to CDN mode) or ships the credential to visitors.
Loading translations
Section titled “Loading translations”-
registerLoader,reloadMessages,addActiveNamespace(s)andonLoadErrorlive on@comvi/core/loader. Callingi18n.registerLoader(fn)on an instance that never composed the loader is a type error at build time and a thrown error at runtime. -
registerLoadertakes a function,(locale, namespace) => Promise<catalog>, not a map. The one exception iscreateNextI18n()’s composed instance, whoseregisterLoaderkeeps both overloads. Everywhere else a static map goes throughloader(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' } }tonav.homeat the point it enters. A non-string leaf is coerced withString()and anullorundefinedleaf is dropped, each with one development warning naming the key.flattenCatalogis exported from the@comvi/coreroot only; it is not on@comvi/core/loaderor 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 nextt()with nonamespaceLoadedorconfigChangedevent. CalladdMessages()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, soconstructor,toStringand__proto__inherited fromObject.prototypeare never translations. -
nson an instance with no loader loads nothing, andinit()warns once in development naming.use(loader(map)).instanceIdorexposeGlobal: truewith no discovery composed gets the same treatment, naming.use(devtools({ instanceId })). Production stays silent.
ICU (plurals, select)
Section titled “ICU (plurals, select)”- The default compiler is simple: text and
{param}only.{count, plural, …}on it throwsE_ICU_SYNTAXin 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.MessageCompileris the type, so a custom compiler goes in the same option. #insidepluralandselectordinalrenders the count formatted for the message’s locale throughIntl.NumberFormatdefaults:1,234inen,1.234inde, a fractional count rounded to three fraction digits, negative zero as0. 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}.
Tags and <T>
Section titled “Tags and <T>”<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 undermissingParam: '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/tagsin the server graph as well as the client, or the first server-rendered paint shows literal angle brackets before hydration replaces them.@comvi/nextis the one exception:createNextI18n()already imports@comvi/core/tagsinternally.
Formatting and locale direction
Section titled “Formatting and locale direction”-
formatNumber,formatDate,formatCurrency,formatRelativeTimeandgetTextDirectionare free functions exported from the package root, taking the i18n instance (or a locale string, forgetTextDirection) as the first argument. Do not writei18n.formatCurrency(…)ori18n.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 boundformatNumber/dirmembers.dirfollows each binding’s reactivity model:binding dirfromuseI18n()read it as @comvi/react,@comvi/next/clientplain value for the current render dir@comvi/vue,@comvi/nuxtComputedRef<'ltr' | 'rtl'>dir.value@comvi/solidaccessor () => 'ltr' | 'rtl'dir()@comvi/svelteReadable<'ltr' | 'rtl'>$dir
Typed keys
Section titled “Typed keys”- Typed translation keys come from
comvi typegen(the CLI), which augments@comvi/core’sTranslationKeysinterface via a generated.d.tsfile. Import that file once and every framework’st()gets autocomplete and compile-time key and param checks. @comvi/vite-pluginand@comvi/cliboth 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.
Two mistakes to check your output for
Section titled “Two mistakes to check your output for”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:
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:
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')});Next.js and Nuxt
Section titled “Next.js and Nuxt”createNextI18n({ … })from@comvi/nextreturns{ 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,devtoolsfrom@comvi/next. Itsuseis core’s installer pipe:result.use(f)isf(result.i18n). Runtime and environment scoping live on the plugin form:nextPlugin(plugin, { runtime, environment })andnextPluginLazy(load, …), from@comvi/next,/clientand/server.use(plugin, { runtime, environment, lazy })and the four delegatesuseClient/useServer/useClientLazy/useServerLazydo not exist.- The locale middleware has two file conventions:
middleware.tswithcreateMiddlewarefrom@comvi/next/middlewareon Next.js 15, andproxy.tswith the same function from@comvi/next/proxyon Next.js 16, which renamed the convention. Both subpaths export one function taking oneMiddlewareConfig; Next 16 runsproxy.tson the Node.js runtime and rejects aruntimeoption in it, so do not emit one. - The Next setup is one config module plus a
next.configplugin:withComvi({ config: './src/i18n/config.ts' })(nextConfig)from@comvi/next/plugin, a module exportingi18nandrouting,<ComviProvider locale>from@comvi/next/serverinapp/[locale]/layout.tsx, andawait getI18n({ locale })in Server Components with the locale fromparams. Do not emit asrc/i18n/server.tswithsetI18n(i18n), a"use client"wrapper around<I18nProvider>, orsetRequestLocale(locale)beforegetI18n({ locale }): those are the manual setup, still supported, and only an app whose config imports server-only code needs them.ComviProvideris 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 firstinit(), finds nothing on the server, and never runs per request. UsenextPlugin(localeDetectorPlugin(…), { runtime: 'client' }). compileris an option onCreateNextI18nOptionsand defaults to nothing: ICU needscompiler: icuCompilerhere 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 }) andlocaleDetection(false, or{ order, queryParam, headerName, resolveAcceptLanguage }; default order['query', 'cookie', 'accept-language'],queryandheaderinert untilqueryParam/headerNameare set). On Next.jslocaleCookiegoes indefineRouting()andlocaleDetectionincreateMiddleware(); on Nuxt both go undercomvi; only the default cookie name differs,NEXT_LOCALEagainsti18n_locale. There is no separate cookie-name option, no cookie flag insidelocaleDetectionand 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 anduseTranslation(event, { locale, ns })on Nuxt, each in its framework’s idiom; both return{ t, hasTranslation, locale }, andnsis the only namespace word.comvi.nslists the namespaces to load at init, as core’snsdoes. - The Nuxt quick start is
nuxt.config.tswithmodules: ['@comvi/nuxt']andcomvi: { defaultLocale, locales, messages }, plusapp.vueand a page.localestakes strings;localePrefix: 'as-needed'is the default, so do not write it; noimport type {} from '@comvi/nuxt'is needed. The module writes<html lang dir>from the active locale (comvi.head, defaulttrue), so do not emituseLocaleHead({ addLang: true, addDir: true })for that;useLocaleHead()is for canonical,hreflangandog:locale. - A Nuxt
comvi.i18n.tsfile is found by convention (./comvi.i18n.*undersrcDir, thenrootDir);comvi.i18nModuleis the explicit override and is not written when the file is at that path. Write it asexport default defineComviI18n((options) => createI18n(options).use(…)), both from@comvi/nuxt/i18n;satisfies NuxtInstanceFactoryis the longer spelling of the same type. The factory returns a core i18n instance, not aVueI18n: the guard requirest()andinit()and rejects the wrapper’scoremember, socreateI18nfrom@comvi/vuethrows aTypeErrorthere. It runs once for the client and once per server request and must return a newcreateI18ninstance each time; in development the module throws[@comvi/nuxt] comvi i18nModule returned an instance it already returnedwhen it gets the same one twice. - A Nuxt
comvi.setuphook needs no type argument for the instance: the module writes the factory’s return type into.nuxt/types/, soNuxtI18nSetup’s default is the instancecomvi.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/nuxtroot) is the fallback for a factory the module cannot see, and codegen cross-checks the claim. comvi.icu: truereachescomvi.i18n.tstoo: it arrives ascompiler: icuCompiler, the last key in the options the factory receives, so a factory that spreads them gets ICU.comvi.messagesinnuxt.config.tsisI18nOptions["messages"]verbatim, nested or flat, forwarded to the client instance and each per-request server instance. It is the only way acomviblock with nocomvi.i18n.tsrenders a translation.comvi.cdnUrlandcomvi.apiBaseUrldo not exist: compose.use(cdnLoader({ cdnUrl }))incomvi.i18n.ts.- Nuxt’s
useI18n()does not carryhasTranslationNow/hasLocaleNow; they are onuseNuxtApp().$i18n. Vue’s are on theVueI18nclass,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.