### Configuration Reference - Environment Variables and Examples Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Covers the use of environment variables in astro-i18n configuration and presents four detailed configuration examples. Includes best practices and related resources for effective setup. ```markdown - Environment variables ``` ```markdown - 4 detailed configuration examples ``` ```markdown - Best practices ``` ```markdown - Related resources ``` -------------------------------- ### CLI Reference - `astro-i18n install` Command Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Details the `astro-i18n install` command for project initialization. Covers syntax, options, behavior, examples, and output structure for setting up astro-i18n. ```markdown - `astro-i18n install` — Project initialization ``` -------------------------------- ### Setup CLI Commands Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Provides a list of essential npm commands for managing astro-i18n, including installation, route generation, type generation, translation extraction, and synchronization. ```bash # Initialize project npm run i18n:install # Generate routes for all locales npm run i18n:generate:pages # Generate TypeScript types npm run i18n:generate:types # Extract translation keys from code npm run i18n:extract # Run both generate commands npm run i18n:sync ``` -------------------------------- ### CLI Reference - Command Examples and Workflow Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Provides examples for each CLI command, including generated types, error handling, shell integration, and npm script best practices. Demonstrates full workflow examples. ```markdown - Each command includes: syntax, options, behavior, examples, output structure ``` ```markdown - Generated types examples ``` ```markdown - Error handling and solutions ``` ```markdown - Shell integration ``` ```markdown - npm scripts best practices ``` ```markdown - Full workflow examples ``` -------------------------------- ### astro-i18n Middleware Setup Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Example of the middleware file created by `astro-i18n install`. This sets up the i18n routing for your Astro application. ```typescript import { sequence } from "astro/middleware" import { useAstroI18n } from "astro-i18n" const astroI18n = useAstroI18n() export const onRequest = sequence(astroI18n) ``` -------------------------------- ### Install astro-i18n Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md Run the quick install command for astro-i18n. Use the --serverless flag for serverless environments. ```bash ./node_modules/.bin/astro-i18n install ``` ```bash ./node_modules/.bin/astro-i18n install --serverless ``` -------------------------------- ### astro-i18n Configuration File Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Example of the default configuration file created by `astro-i18n install`. Customize locale settings, routing, and translation rules here. ```typescript import { defineAstroI18nConfig } from "astro-i18n" export default defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: [], fallbackLocale: "en", trailingSlash: "never", run: "client+server", showPrimaryLocale: false, translationLoadingRules: [], translationDirectory: {}, translations: {}, routes: {} }) ``` -------------------------------- ### Basic Dynamic Routes Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/static-generation.md Example of using createGetStaticPaths to generate dynamic routes based on fetched posts. Ensure fetchPosts() is defined elsewhere. ```astro --- // src/pages/posts/[slug].astro import { createGetStaticPaths } from "astro-i18n" export const getStaticPaths = createGetStaticPaths(async () => { const posts = await fetchPosts() return posts.map(post => ({ params: { slug: post.slug }, props: { post } })) }) const { post } = Astro.props ---

{post.title}

{post.content}

``` -------------------------------- ### Configuration Guide Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Comprehensive guide to configuring astro-i18n, covering methods, options, and file structure. ```APIDOC ## Configuration Guide ### Description Details all methods and options for configuring astro-i18n. ### Configuration Methods - File-based, inline, and hybrid configurations. ### Configuration Options - Core locale settings - URL/routing settings - Execution context options - Translation content structure - Translation loading rules (with regex patterns) - Directory customization - Filesystem translation structure - File naming patterns - Environment variables ### Examples & Best Practices - Includes 4 detailed configuration examples. - Provides best practices and points to related resources. ``` -------------------------------- ### Quick Install Astro-i18n Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Run this command to quickly install astro-i18n. Use the --serverless flag for environments without filesystem or Node.js access. ```bash ./node_modules/.bin/astro-i18n install # serverless (no filesystem/node.js setup) ./node_modules/.bin/astro-i18n install --serverless ``` -------------------------------- ### Example Workflow for Full Sync Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Illustrates a typical workflow involving updating configuration and then running the sync command. ```bash # 1. Update config with new locale # Edit astro-i18n.config.ts to add "de": {} # 2. Sync everything npm run i18n:sync # 3. Now generate pages for all locales # And recreate TypeScript types ``` -------------------------------- ### Complex Data Loading Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/static-generation.md An advanced example of createGetStaticPaths demonstrating complex data loading and filtering for generating product routes across categories and locales. Assumes fetchCategories() and fetchProducts() are defined. ```astro --- // src/pages/products/[category]/[id].astro import { createGetStaticPaths, astroI18n } from "astro-i18n" export const getStaticPaths = createGetStaticPaths(async () => { const categories = await fetchCategories() const allProducts = await fetchProducts() const paths = [] for (const locale of astroI18n.locales) { for (const category of categories) { // Filter products by category const products = allProducts.filter(p => p.categoryId === category.id) for (const product of products) { paths.push({ params: { category: category.slug, id: product.id }, props: { product, category, locale } }) } } } return paths }) const { product, category, locale } = Astro.props ---

{product.name}

{product.description}

{product.price}
``` -------------------------------- ### Comprehensive Astro-i18n Configuration Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/middleware.md An example demonstrating a full configuration object for astro-i18n, including primary and secondary locales, fallback, URL settings, translations, route definitions, loading rules, and directory configurations. ```typescript const config = defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr", "de", "es"], fallbackLocale: "en", showPrimaryLocale: true, trailingSlash: "always", run: "client+server", translations: { "common": { "en": { "navbar": { "home": "Home", "about": "About" } }, "fr": { "navbar": { "home": "Accueil", "about": "À propos" } } }, "/about": { "en": { "title": "About Us" }, "fr": { "title": "À propos de nous" } } }, routes: { "fr": { "about": "a-propos", "contact": "nous-contacter" }, "de": { "about": "uber-uns", "contact": "kontakt" } }, translationLoadingRules: [ { routes: ["^/admin.*"], groups: ["^admin$", "^settings$"] } ], translationDirectory: { i18n: "i18n", pages: "i18n" }, srcDir: "src" }) export default config ``` -------------------------------- ### Install astro-i18n with npm Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md Install the astro-i18n package using npm. This is the standard way to add the library to your project. ```yml npm install astro-i18n ``` -------------------------------- ### Example with Translations Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/static-generation.md Demonstrates using createGetStaticPaths with multiple locales and translating content using the t function. Assumes fetchPosts() is defined. ```astro --- // src/pages/[locale]/blog/[slug].astro import { createGetStaticPaths, astroI18n, t } from "astro-i18n" export const getStaticPaths = createGetStaticPaths(async (props) => { const posts = await fetchPosts() const locales = ["en", "fr", "de"] const paths = [] for (const locale of locales) { for (const post of posts) { paths.push({ params: { locale, slug: post.slug }, props: { post } }) } } return paths }) const { post } = Astro.props ---

{t("blog.title")}

{post.title}

{post.content}

``` -------------------------------- ### Example with Route Params and Locale Detection Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/static-generation.md Shows how to generate routes for all available locales and specific parameters using createGetStaticPaths. Assumes fetchAuthors() is defined. ```astro --- // src/pages/authors/[slug].astro import { createGetStaticPaths, astroI18n } from "astro-i18n" export const getStaticPaths = createGetStaticPaths(async () => { const authors = await fetchAuthors() // Generate routes for all locales and author slugs const paths = [] for (const locale of astroI18n.locales) { for (const author of authors) { paths.push({ params: { slug: author.slug }, props: { author, locale // Pass locale to props for access in component } }) } } return paths }) const { author, locale } = Astro.props ---

{author.name}

{author.bio}

``` -------------------------------- ### Install astro-i18n with npm, yarn, or pnpm Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Use the appropriate package manager command to install the astro-i18n library. This is the first step to integrating internationalization into your Astro project. ```yml # npm npm install astro-i18n # yarn yarn add astro-i18n # pnpm pnpm add astro-i18n ``` -------------------------------- ### Translation Loading Rule Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/configuration.md An example of a translation loading rule that specifies routes and the groups to load for those routes. ```typescript { routes: ["^/admin.*"], groups: ["^admin$"] } ``` -------------------------------- ### Install astro-i18n with pnpm Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md Install the astro-i18n package using pnpm. This command is another alternative for package management. ```yml pnpm add astro-i18n ``` -------------------------------- ### List All Configured Locales Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Get an array of all configured locales, including both primary and secondary ones. For example: ["en", "fr", "de"] ```typescript get locales(): string[] ``` -------------------------------- ### Translation Variants and Interpolation Examples Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Illustrates the structure of translation strings that support variants based on properties and interpolation with variables. Includes examples for pluralization and custom formatting. ```json { "items": "You have items", "items{{ count: 0 }}": "No items", "items{{ count: 1 }}": "One item", "items{{ count: 5 }}": "{# count #} items", "welcome": "Welcome, {# name>capitalize !}!" } ``` -------------------------------- ### Interpolate Function Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/translation-functions.md Provides an example of using the interpolate function with custom formatters and properties. ```typescript const value = "{# name>uppercase #} says {# greeting #}" const properties = { name: "alice", greeting: "hello" } const formatters = { uppercase: (v) => String(v).toUpperCase() } interpolate(value, properties, formatters) // "ALICE says hello" ``` -------------------------------- ### Handle Config File Not Found Error Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Displays the error when the configuration file is missing and provides the necessary setup step. ```bash npm run i18n:generate:types # Error: Config not found ``` -------------------------------- ### Install astro-i18n with yarn Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md Install the astro-i18n package using yarn. This command is an alternative to npm for package management. ```yml yarn add astro-i18n ``` -------------------------------- ### Errors Reference - Error Handling Patterns and Techniques Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Details error handling patterns and defensive programming techniques for astro-i18n. Includes code examples for each error type to guide developers in robust implementation. ```markdown - Each error includes: trigger condition, example code, handling solution ``` ```markdown - Error handling patterns with code examples ``` ```markdown - Defensive programming techniques ``` -------------------------------- ### UntrimmedString: Correct Variant Syntax Examples Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/errors.md Examples of correctly formatted variant syntax to avoid UntrimmedString errors. Ensure proper spacing and types for properties. ```typescript "items{{ count: 0 }}" "greeting{{ type: 'formal' }}" "{# name>uppercase #}" "{# value>format(5, 'x') #}" ``` -------------------------------- ### Install astro-i18n Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Initializes astro-i18n in your project. Creates config files, middleware, and adds npm scripts. Use `--root` to specify the project directory and `--serverless` for serverless environments. ```bash npm run i18n:install ``` ```bash npm run i18n:install --root /path/to/project ``` ```bash npm run i18n:install --serverless ``` -------------------------------- ### Custom Interpolation Formatter Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md Example of a custom interpolation formatter `xXify` that can be added to the middleware. Ensure custom formatters do not rely on external scope for client-side functionality. ```typescript export function xXify(value: unknown, repeats: unknown = 1) { if (typeof repeats !== "number") { throw new Error("repeats must be a number") } if (repeats <= 0) return value return `${"xX".repeat(repeats)}${value}${"Xx".repeat(repeats)}` } ``` ```typescript // example that wouldn't work client-side : const error = new Error("repeats must be a number") function xXify(value: unknown, repeats: unknown = 1) { if (typeof repeats !== "number") throw error // cannot use anything outside of scope // ... } ``` -------------------------------- ### Initialize astro-i18n Middleware with Config File Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/middleware.md This example shows how to initialize the astro-i18n middleware without providing an explicit configuration object, relying instead on auto-detection of a configuration file. ```typescript import { sequence } from "astro/middleware" import { useAstroI18n } from "astro-i18n" export const onRequest = sequence(useAstroI18n()) ``` -------------------------------- ### Variant Matching Examples Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Illustrates how variant matching works with translation strings based on provided properties. Shows successful and unsuccessful matches. ```json { "message": "Default", "message{{ count: 0, type: 'empty' }}": "Empty", "message{{ count: 1 }}": "One item" } ``` ```typescript t("message", { count: 1 }) // "One item" (score: 1) t("message", { count: 0, type: "empty" }) // "Empty" (score: 2) t("message", { count: 0, type: "error" }) // "Default" (no match) t("message", { count: 2 }) // "Default" (no match) ``` -------------------------------- ### Define Astro-i18n Configuration Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/errors.md Example of creating a configuration file for astro-i18n, specifying primary and secondary locales. ```typescript // astro-i18n.config.ts import { defineAstroI18nConfig } from "astro-i18n" export default defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr"] }) ``` -------------------------------- ### Formatter Arguments with Interpolation Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/variant-system.md Example of using interpolation values within formatter arguments for dynamic configuration. Keep such arguments simple for readability. ```json { "amount": "{# value>intl_format_number({ currency: '{# currencyCode #}' }) #}" } ``` -------------------------------- ### Astro Middleware Setup Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Integrate the astro-i18n middleware into your Astro project by importing and using `useAstroI18n`. For serverless environments, pass your configuration directly. ```typescript // src/middleware.ts import { sequence } from "astro/middleware" import { useAstroI18n } from "astro-i18n" const astroI18n = useAstroI18n(/* astro-i18n config, custom formatters */) export const onRequest = sequence(astroI18n) ``` -------------------------------- ### Minimal Astro-i18n Configuration Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Sets up the primary locale and secondary locales for internationalization. Use this for basic setup. ```typescript defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr"] }) ``` -------------------------------- ### Implement and Use Named Formatters Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/types.md Provides an example of implementing a `Formatters` object with several named formatters, including `uppercase`, `reverse`, `repeat`, and `json`. Demonstrates registering these formatters with the Astro-i18n middleware. ```typescript const formatters: Formatters = { uppercase: (v) => String(v).toUpperCase(), reverse: (v) => String(v).split("").reverse().join(""), repeat: (v, times = 1) => String(v).repeat(Number(times)), json: (v, format = true) => { const str = JSON.stringify(v) return format ? JSON.stringify(JSON.parse(str), null, 2) : str } } export const onRequest = sequence( useAstroI18n(config, formatters) ) ``` -------------------------------- ### Setup Astro Middleware Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Configure the onRequest middleware to enable astro-i18n functionality in your Astro application. This should be placed in `src/middleware.ts`. ```typescript // src/middleware.ts import { sequence } from "astro/middleware" import { useAstroI18n } from "astro-i18n" export const onRequest = sequence(useAstroI18n()) ``` -------------------------------- ### Get All Supported Locales Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Provides an array listing all locales that are configured and supported by the application. ```typescript locales: string[] ``` -------------------------------- ### Get Current Environment Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Provides the detected runtime environment, which can be 'node', 'none', or 'browser'. ```typescript environment: "node" | "none" | "browser" ``` -------------------------------- ### Static Generation Reference - `createGetStaticPaths()` Function Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Explains the `createGetStaticPaths()` function for generating dynamic routes in Astro applications. Includes examples, context details (`GetStaticPathsProps`), and error handling patterns. ```markdown - `createGetStaticPaths()` function ``` -------------------------------- ### CLI Reference - `astro-i18n sync` Command Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Explains the `astro-i18n sync` command, which combines generate commands. Covers syntax, options, behavior, examples, and output structure for synchronizing i18n assets. ```markdown - `astro-i18n sync` — Combined generate commands ``` -------------------------------- ### Errors Reference - Initialization Errors Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Documents initialization errors in astro-i18n, such as `AlreadyInitialized`, `NotInitialized`, `InvalidEnvironment`, and `NoFilesystem`. Provides trigger conditions, example code, and handling solutions. ```markdown - Initialization errors (AlreadyInitialized, NotInitialized, InvalidEnvironment, NoFilesystem) ``` -------------------------------- ### Error Handling in getStaticPaths Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/static-generation.md Example of implementing error handling within the `createGetStaticPaths` callback. This snippet demonstrates fetching data, formatting it for static generation, and gracefully handling potential errors by returning fallback routes. ```astro --- import { createGetStaticPaths, astroI18n } from "astro-i18n" export const getStaticPaths = createGetStaticPaths(async () => { try { const data = await fetchData() return formatForStaticGen(data) } catch (error) { console.error("Failed to generate static paths:", error) // Return empty paths or default routes return [{ params: { slug: "error" } }] } }) ---

Page content

``` -------------------------------- ### Inline Configuration with Middleware Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/configuration.md Configure astro-i18n directly within your middleware using `useAstroI18n`. This method is suitable for simpler configurations or when integrating with existing middleware setups. ```typescript // src/middleware.ts import { sequence } from "astro/middleware" import { useAstroI18n, defineAstroI18nConfig } from "astro-i18n" const config = defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr"], translations: { "common": { "en": { "hello": "Hello" }, "fr": { "hello": "Bonjour" } } } }) export const onRequest = sequence(useAstroI18n(config)) ``` -------------------------------- ### Get Current Route Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Retrieves the current route path, excluding the locale. For example, '/fr/about' would return '/about'. ```typescript route: string ``` -------------------------------- ### CLI Reference - `astro-i18n generate:pages` Command Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Explains the `astro-i18n generate:pages` command for dynamic route generation. Includes syntax, options, behavior, examples, and output structure for creating i18n routes. ```markdown - `astro-i18n generate:pages` — Dynamic route generation ``` -------------------------------- ### Translation File Naming Conventions Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md Examples of valid translation file naming conventions for local page translations, including regular, private, and translated segment formats. ```typescript const regular = `${locale}.json` // fr.json const private = `_${locale}.json` // _fr.json const regularWithTranslation = `${locale}.${segmentTranslation}.json` // fr.translated-page-name.json const privateWithTranslation = `_${locale}.${segmentTranslation}.json` // _fr.translated-page-name.json ``` -------------------------------- ### Equivalent Commands for Full Sync Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Shows the equivalent commands that `npm run i18n:sync` executes. ```bash npm run i18n:generate:pages && npm run i18n:generate:types ``` -------------------------------- ### Create and Use Simple Formatters Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/types.md Illustrates creating simple formatters for interpolation. Includes a basic uppercase formatter and a padding formatter with arguments. Shows how to reference these formatters within translation strings. ```typescript // Simple formatter with no args const uppercase: Formatter = (value) => { return String(value).toUpperCase() } // Formatter with arguments const padLeft: Formatter = (value, length = 5, char = " ") => { return String(value).padStart(Number(length), String(char)) } // Use in translation t("text") // {# text>uppercase #} t("code") // {# value>padLeft(10, '0') #} ``` -------------------------------- ### Working with Deep Translation Structures Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/types.md Example of using `DeepStringRecord` for type-safe access to nested translation strings. The example shows valid and invalid access patterns. ```typescript import type { DeepStringRecord } from "astro-i18n" const menu: DeepStringRecord = { "main": { "home": "Home", "products": { "electronics": "Electronics", "clothing": "Clothing" } } } t("main.home") // ✓ t("main.products.electronics") // ✓ t("main.products") // ✗ Not a string ``` -------------------------------- ### initialize Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Initializes astro-i18n with configuration and formatters. This is typically called automatically by the `useAstroI18n` middleware. ```APIDOC ## `initialize(config?, formatters?)` ### Description Initialize astro-i18n with configuration and formatters. Called automatically by `useAstroI18n` middleware. Should not be called manually in most cases. ### Parameters #### Path Parameters - **config** (Partial | string) - Optional - Config object or path to config file (Node.js only) - **formatters** (Record) - Optional - Default: `{}` - Custom formatter functions ### Throws - `AlreadyInitialized` if called more than once - `InvalidEnvironment` if called in a browser environment - `ConfigNotFound` if config path is not provided and cannot be auto-detected - `NoFilesystem` if config path is a string in a non-Node environment ### Request Example ```typescript // Typically done via middleware import { useAstroI18n } from "astro-i18n" const astroI18nMiddleware = useAstroI18n({ primaryLocale: "en", secondaryLocales: ["fr", "de"], translations: { /* ... */ } }) ``` ### Returns A Promise that resolves when initialization is complete. ``` -------------------------------- ### Configuration Reference - File-Based and Inline Methods Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Discusses the different methods for configuring astro-i18n, including file-based and inline approaches. Covers core locale settings, URL/routing, and execution context options. ```markdown - Configuration methods (file-based, inline, hybrid) ``` -------------------------------- ### Provide Inline Configuration Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/errors.md An alternative to a config file, this shows how to provide configuration directly within the `useAstroI18n` call. ```typescript export const onRequest = sequence( useAstroI18n({ primaryLocale: "en", secondaryLocales: ["fr"] }) ) ``` -------------------------------- ### Handle Project Root Not Found Error Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Illustrates the error when the project root cannot be located and the required solution. ```bash npm run i18n:install --root /invalid/path # Error: Root not found ``` -------------------------------- ### Run Full Sync Workflow Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Combines `generate:pages` and `generate:types` for complete synchronization. Run after adding new locales, pages, updating routes, or modifying translation structure. ```bash npm run i18n:sync ``` -------------------------------- ### Get Secondary Locales Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Returns the configured secondary locales for the application. ```typescript secondaryLocales: string ``` -------------------------------- ### Set Working Directory for CLI Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md Demonstrates how to set the working directory for the CLI command using `cd`. ```bash cd /path/to/project && npm run i18n:sync ``` -------------------------------- ### Get Primary Locale Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Retrieve the default or primary locale configured for the application. ```typescript get primaryLocale(): string ``` -------------------------------- ### Core API Reference - AstroI18n Singleton Methods Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Details the available methods for the AstroI18n singleton, including translation (`t()`, `l()`), configuration (`addTranslations()`, `addFormatters()`, `addRoutes()`), and redirection (`redirect()`). Essential for implementing i18n features in server and client contexts. ```markdown - All methods: `t()`, `l()`, `addTranslations()`, `addFormatters()`, `addRoutes()`, `redirect()`, etc. ``` -------------------------------- ### astroI18n.route Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md The current route path, excluding the locale. For example, for `/fr/about`, this would return `/about`. ```APIDOC ## astroI18n.route ### Description The current route (without the locale, for example `/fr/about` will return `/about`). ### Type ```ts string ``` ``` -------------------------------- ### Simple Two-Language Site Configuration Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/configuration.md Configure a basic two-language site with primary and secondary locales, and define common translations and route mappings. ```typescript defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr"], translations: { "common": { "en": { "hello": "Hello", "goodbye": "Goodbye" }, "fr": { "hello": "Bonjour", "goodbye": "Au revoir" } } }, routes: { "fr": { "about": "a-propos" } } }) ``` -------------------------------- ### npm Scripts for astro-i18n Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/cli.md These npm scripts are added to your `package.json` by `astro-i18n install` for common i18n tasks. ```json { "scripts": { "i18n:extract": "astro-i18n extract", "i18n:generate:pages": "astro-i18n generate:pages --purge", "i18n:generate:types": "astro-i18n generate:types", "i18n:sync": "npm run i18n:generate:pages && npm run i18n:generate:types" } } ``` -------------------------------- ### List Secondary Locales Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Get an array of all secondary locales configured for the application, excluding the primary locale. ```typescript get secondaryLocales(): string[] ``` -------------------------------- ### Trigger AlreadyInitialized Error Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/errors.md Calling `astroI18n.initialize()` more than once will throw an `AlreadyInitialized` error. This example shows the direct cause of the error. ```typescript await astroI18n.initialize(config1) await astroI18n.initialize(config2) // Throws AlreadyInitialized ``` -------------------------------- ### astroI18n.l (instance method) Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md The main routing function accessible via the astroI18n instance. ```APIDOC ## `astroI18n.l` ### Description The main routing function (`l` is an alias). ### Signature ```ts function l( route: string, parameters?: Record, options?: { targetLocale?: string routeLocale?: string showPrimaryLocale?: boolean query?: Record }, ): string ``` ``` -------------------------------- ### Core API Singleton Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Documentation for the AstroI18n singleton, including its properties and methods for managing internationalization within Astro. ```APIDOC ## AstroI18n Singleton ### Description Provides access to the core i18n functionalities, including locale, route, and page management. ### Properties - **locale** (string): The current locale. - **route** (string): The current route. - **pages** (object): All available pages. - **page** (object): The current page data. - **locales** (array): All configured locales. ### Methods - **t(key: string, params?: object): string** - Translates a given key. - Usage example: `AstroI18n.t('greeting', { name: 'World' })` - **l(path: string): string** - Generates a locale-aware URL. - Usage example: `AstroI18n.l('/about')` - **addTranslations(translations: object): void** - Adds translation data. - **addFormatters(formatters: object): void** - Adds custom formatters. - **addRoutes(routes: object): void** - Adds route configurations. - **redirect(url: string): void** - Performs a redirect. ``` -------------------------------- ### Middleware Reference - `defineAstroI18nConfig()` Utility Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Details the `defineAstroI18nConfig()` utility for defining AstroI18n configurations. It covers configuration options, defaults, and file discovery mechanisms. ```markdown - `defineAstroI18nConfig()` utility ``` -------------------------------- ### Initialize astro-i18n Middleware with Configuration Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/middleware.md Use this snippet to create the Astro middleware with a fully defined configuration object, including primary and secondary locales, and translation data. ```typescript import { sequence } from "astro/middleware" import { useAstroI18n } from "astro-i18n" export const onRequest = sequence( useAstroI18n({ primaryLocale: "en", secondaryLocales: ["fr", "de"], translations: { "common": { "en": { "hello": "Hello" }, "fr": { "hello": "Bonjour" }, "de": { "hello": "Hallo" } } } }) ) ``` -------------------------------- ### Get Fallback Locale Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Retrieve the fallback locale used when a translation is missing in the current locale. Defaults to the primary locale. ```typescript get fallbackLocale(): string ``` -------------------------------- ### CLI Commands Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Reference for the astro-i18n command-line interface commands for project management and utility functions. ```APIDOC ## CLI Commands ### Description Reference for the astro-i18n command-line interface. ### Commands - **`astro-i18n install`**: Project initialization. - **`astro-i18n generate:pages`**: Dynamic route generation. - **`astro-i18n generate:types`**: TypeScript type generation. - **`astro-i18n extract`**: Translation key extraction. - **`astro-i18n sync`**: Combined generate commands. ### Details Each command includes: syntax, options, behavior, examples, and output structure. Covers generated types examples, error handling, shell integration, npm scripts, and full workflow examples. ``` -------------------------------- ### addTranslations(translations) Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Dynamically adds or updates translations at runtime. This is useful for loading additional translation groups after the initial setup. ```APIDOC ## addTranslations(translations) ### Description Dynamically add or update translations at runtime. Useful for loading additional translation groups after initialization. ### Parameters #### Path Parameters - **translations** (ConfigTranslations) - Required - Translation object with structure: `{ group: { locale: { key: value } } }` ### Returns Returns the AstroI18n instance for method chaining. ### Example ```typescript astroI18n.addTranslations({ "admin": { "en": { "dashboard": "Dashboard" }, "fr": { "dashboard": "Tableau de bord" } } }) ``` ``` -------------------------------- ### Get Available Pages Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/README.md Returns an array of all available page routes for which translations exist. This includes pages with even empty translations. ```typescript pages: string[] ``` -------------------------------- ### Middleware and Configuration Utilities Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Details on the `useAstroI18n` middleware and `defineAstroI18nConfig` utility for setting up and managing internationalization configurations. ```APIDOC ## Middleware and Configuration ### Description Manages the Astro i18n middleware and configuration definition. ### Middleware - **useAstroI18n()** - Middleware function to integrate i18n into Astro. ### Configuration Utility - **defineAstroI18nConfig(config: object): object** - Utility to define the Astro i18n configuration. - Supports complete configuration options, defaults, and discovery patterns. - Handles translation loading rules and filesystem structure. ``` -------------------------------- ### Get Runtime Environment Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Access the detected runtime environment. Returns 'node' in Node.js, 'browser' in browsers, or 'none' in other SSR scenarios. ```typescript get environment(): "node" | "none" | "browser" ``` -------------------------------- ### Dynamically Add Translations Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Use `addTranslations` to load or update translation groups at runtime. This is useful for extending translations after the initial setup. ```typescript astroI18n.addTranslations({ "admin": { "en": { "dashboard": "Dashboard" }, "fr": { "dashboard": "Tableau de bord" } } }) ``` -------------------------------- ### astroI18n.page Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/astro-i18n/README.md The page identifier corresponding to the current route. For example, `/posts/my-cool-slug` would map to `/posts/[slug]`. This is only detected if a translation exists for the page. ```APIDOC ## astroI18n.page ### Description The corresponding page for the current route, for example `/posts/my-cool-slug` will be `/posts/[slug]`. Only gets detected if you have a translation for that page (even if it's empty). ### Type ```ts string ``` ``` -------------------------------- ### Handle NoFilesystem Error with Config Object Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/errors.md In serverless environments, provide the astro-i18n configuration directly as an object to `useAstroI18n` instead of a file path to avoid `NoFilesystem` errors. ```typescript import { defineAstroI18nConfig } from "astro-i18n" const config = defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr"] }) export const onRequest = sequence(useAstroI18n(config)) ``` -------------------------------- ### Initialize astro-i18n Middleware Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Set up the astro-i18n middleware in your Astro project. This involves configuring primary and secondary locales, and providing translation data. ```typescript import { sequence } from "astro/middleware" import { useAstroI18n } from "astro-i18n" const middleware = useAstroI18n({ primaryLocale: "en", secondaryLocales: ["fr", "de"], translations: { /* ... */ } }) export const onRequest = sequence(middleware) ``` -------------------------------- ### Errors Reference - Translation Errors Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Lists translation-related errors in astro-i18n, such as `UntrimmedString`, `FormatterNotFound`, and `InvalidDate`. Includes examples and solutions for handling these issues. ```markdown - Translation errors (UntrimmedString, FormatterNotFound, InvalidDate, etc.) ``` -------------------------------- ### Match Interpolation Variables Function Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/translation-functions.md Demonstrates extracting unique variable names from translation strings with interpolation syntax, including deduplication. ```typescript matchInterpolationVariables("{# name #} says {# greeting #}") // ["name", "greeting"] matchInterpolationVariables("{# name>upper #} - {# name #}") // ["name"] (deduplicated) ``` -------------------------------- ### Get Current Locale Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Access the locale of the current page (e.g., 'en', 'fr'). This is automatically detected from the route or defaults to the primary locale. ```typescript get locale(): string ``` -------------------------------- ### Import and use l function Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/translation-functions.md Demonstrates how to import and use the l function for translating routes with parameters and target locales. ```typescript import { l } from "astro-i18n" const frenchAbout = l("/about", {}, { targetLocale: "fr" }) const postLink = l("/posts/[slug]", { slug: "my-post" }) ``` -------------------------------- ### Get a Translation Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Retrieve translated strings using the `t()` function. Supports basic retrieval, translations with variants based on properties, and interpolation with variables. ```typescript import { t } from "astro-i18n" // Basic t("greeting") // With variants t("items", { count: 5 }) // With interpolation t("welcome", { name: "Alice" }) // Override locale/route t("key", {}, { locale: "fr", route: "/about" }) ``` -------------------------------- ### Variant Matching Priority in Translation Function Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/variant-system.md Shows the output of the `t()` function with different parameters, illustrating the variant matching priority explained in the JSON example. ```typescript t("message", { count: 5 }) // "Five items" (score: 1) t("message", { count: 5, type: "error" }) // "Five error items" (score: 2) t("message", { type: "error" }) // "Default" (no count match) ``` -------------------------------- ### Initialize Astro-i18n Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Initialize astro-i18n with configuration and formatters. This is typically handled automatically by the `useAstroI18n` middleware and should not be called manually in most scenarios. ```typescript // Typically done via middleware import { useAstroI18n } from "astro-i18n" const astroI18nMiddleware = useAstroI18n({ primaryLocale: "en", secondaryLocales: ["fr", "de"], translations: { /* ... */ } }) ``` -------------------------------- ### Variant Matching Priority Example Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/variant-system.md Demonstrates how Astro-i18n prioritizes variant matches based on the number of properties matched. More specific variants take precedence. ```json { "message": "Default", "message{{ count: 5 }}": "Five items", "message{{ count: 5, type: 'error' }}": "Five error items" } ``` -------------------------------- ### Add Custom Formatters Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/README.md Demonstrates how to add custom formatting functions to `astro-i18n` for use within translation strings. The example shows a 'bold' formatter. ```typescript import { astroI18n } from "astro-i18n" function bold(value: unknown) { return `${value}` } astroI18n.addFormatters({ bold }) // Use in translation: "{# text>bold #}" t("title", { text: "Important" }) // Important ``` -------------------------------- ### Handle NoFilesystem Error with Environment Variables Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/errors.md Alternatively, in serverless environments, load the astro-i18n configuration from environment variables to prevent `NoFilesystem` errors when `useAstroI18n` is used with a file path. ```typescript const config = JSON.parse(process.env.ASTRO_I18N_CONFIG || "{}") export const onRequest = sequence(useAstroI18n(config)) ``` -------------------------------- ### Implementing Custom Formatters Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/translation-functions.md Shows the correct way to implement custom formatters for client-side use. Custom formatters must be pure functions without external scope dependencies or non-serializable objects. ```typescript // ✅ GOOD: Pure function with no external scope function reverse(value: unknown) { return String(value).split("").reverse().join("") } function greet(name: unknown, greeting = "Hello") { return `${greeting}, ${name}!` } astroI18n.addFormatters({ reverse, greet }) // ❌ BAD: References external variable (won't work client-side) const prefix = ">> " function addPrefix(value: unknown) { return prefix + value // Error: 'prefix' not in scope } // ❌ BAD: Creates new object (won't serialize) const error = new Error("Invalid") function checkValue(value: unknown) { if (!value) throw error // Error: Cannot serialize Error object } ``` -------------------------------- ### Get Current Page Template Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Obtain the template pattern for the current route if a translation exists. Returns null if no matching page template is found. ```typescript get page(): string | null ``` -------------------------------- ### Check Initialization Status Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/astro-i18n-core.md Determine if the AstroI18n instance has been fully initialized, including configuration loading and translations. ```typescript get isInitialized(): boolean ``` -------------------------------- ### Complex Contextual Variants Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/api-reference/variant-system.md Combine variants with interpolation for complex contextual translations. This example demonstrates handling different messages based on a `count` and an `urgent` flag. ```json { "notification": "You have updates", "notification{{ count: 0 }}": "No new messages", "notification{{ count: 1 }}": "You have {# count #} new message", "notification{{ count: 2 }}": "You have {# count #} new messages", "notification{{ urgent: true }}": "URGENT: {# count #} new messages!" } ``` ```typescript t("notification") // "You have updates" t("notification", { count: 0 }) // "No new messages" t("notification", { count: 1 }) // "You have 1 new message" t("notification", { count: 5 }) // "You have 5 new messages" t("notification", { count: 3, urgent: true }) // "URGENT: 3 new messages!" ``` -------------------------------- ### Complex Multi-Language e-Commerce Configuration Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/configuration.md Set up a complex multi-language e-commerce site with multiple secondary locales, fallback locale, custom trailing slash behavior, and advanced translation loading rules. ```typescript defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr", "de", "es", "ja"], fallbackLocale: "en", showPrimaryLocale: true, trailingSlash: "always", run: "client+server", translations: { "common": { "en": { /* navbar, footer, etc */ }, "fr": { /* ... */ }, // ... other locales } }, routes: { "fr": { "products": "produits", "checkout": "paiement" }, "de": { "products": "produkte", "checkout": "kasse" } // ... other locales }, translationLoadingRules: [ { routes: ["^/shop.*"], groups: ["^shop$", "^products$", "^checkout$"] }, { routes: ["^/account.*"], groups: ["^account$", "^settings$"] } ] }) ``` -------------------------------- ### Define Astro-i18n Configuration Source: https://github.com/alexandre-fernandez/astro-i18n/blob/main/_autodocs/types.md Examples of defining type-safe configurations for Astro-i18n. You can use `Partial` for full control or `defineAstroI18nConfig` for enhanced type safety and autocompletion. ```typescript import { defineAstroI18nConfig } from "astro-i18n" import type { AstroI18nConfig, Translations } from "astro-i18n" // Full config with types const config: Partial = { primaryLocale: "en", secondaryLocales: ["fr", "de"], showPrimaryLocale: false, trailingSlash: "never", run: "client+server" } // Or use the helper for even better types const typedConfig = defineAstroI18nConfig({ primaryLocale: "en", secondaryLocales: ["fr"] // TS will error on unknown properties }) ```