chore(i18n): commit generated paraglide code and disable output gitignore

This commit is contained in:
yiling
2026-06-26 12:10:37 +08:00
parent cd4a22d20b
commit ba5f7296a8
53 changed files with 4116 additions and 4 deletions
+2 -2
View File
@@ -13,8 +13,8 @@
],
"scripts": {
"dev": "bun run --hot apps/web/src/index.ts",
"i18n:compile": "paraglide-js compile --project ./packages/webui/project.inlang --outdir ./packages/webui/src/paraglide --emit-ts-declarations",
"i18n:watch": "paraglide-js compile --project ./packages/webui/project.inlang --outdir ./packages/webui/src/paraglide --watch --emit-ts-declarations",
"i18n:compile": "paraglide-js compile --project ./packages/webui/project.inlang --outdir ./packages/webui/src/paraglide --emit-ts-declarations --no-emit-git-ignore",
"i18n:watch": "paraglide-js compile --project ./packages/webui/project.inlang --outdir ./packages/webui/src/paraglide --watch --emit-ts-declarations --no-emit-git-ignore",
"typecheck": "tsc --noEmit",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"test": "bun --bun vitest run",
+2 -2
View File
@@ -86,8 +86,8 @@
"ulid": "3.0.2"
},
"scripts": {
"i18n:compile": "paraglide-js compile --project ./project.inlang --outdir ./src/paraglide --emit-ts-declarations",
"i18n:watch": "paraglide-js compile --project ./project.inlang --outdir ./src/paraglide --watch --emit-ts-declarations"
"i18n:compile": "paraglide-js compile --project ./project.inlang --outdir ./src/paraglide --emit-ts-declarations --no-emit-git-ignore",
"i18n:watch": "paraglide-js compile --project ./project.inlang --outdir ./src/paraglide --watch --emit-ts-declarations --no-emit-git-ignore"
},
"devDependencies": {
"typescript": "6.0.3",
@@ -0,0 +1,3 @@
# ignore everything because the directory is auto-generated by inlang paraglide-js
# for more info visit https://paraglidejs.com
*
+162
View File
@@ -0,0 +1,162 @@
# Paraglide JS Compiled Output
> Auto-generated i18n message functions. Import `messages.js` to use translated strings.
Compiled from: `/Users/yiling/Projects/shumai/packages/webui/project.inlang`
## What is this folder?
This folder contains compiled [Paraglide JS](https://github.com/opral/paraglide-js) output. Paraglide JS compiles your translation messages into tree-shakeable JavaScript functions.
## At a glance
Purpose:
- This folder stores compiled i18n message functions.
- Source translations live outside this folder in your inlang project.
Safe to import:
- `messages.js` — all message functions
- `runtime.js` — locale utilities
- `server.js` — server-side middleware
Do not edit:
- All files in this folder are auto-generated.
- Changes will be overwritten on next compilation.
```
paraglide/
├── messages.js # Message exports (import this)
├── messages/ # Individual message functions
├── runtime.js # Locale detection & configuration
├── registry.js # Formatting utilities (plural, number, datetime, relativetime)
├── server.js # Server-side middleware
└── .gitignore # Marks folder as generated
```
## Usage
```js
import * as m from "./paraglide/messages.js";
// Messages are functions that return localized strings
m.hello_world(); // "Hello, World!" (in current locale)
m.greeting({ name: "Sam" }); // "Hello, Sam!"
// Override locale per-call
m.hello_world({}, { locale: "de" }); // "Hallo, Welt!"
m.greeting({ name: "Sam" }, { locale: "de" }); // "Hallo, Sam!"
```
## Runtime API
```js
import { getLocale, getTextDirection, setLocale, locales, baseLocale } from "./paraglide/runtime.js";
getLocale(); // Current locale, e.g., "en"
getTextDirection(); // "ltr" | "rtl" for current locale
setLocale("de"); // Set locale
locales; // Available locales, e.g., ["en", "de", "fr"]
baseLocale; // Default locale, e.g., "en"
```
## Strategy
The strategy determines how the current locale is detected and persisted:
- **Cookie**: Stores locale preference in a cookie.
- **URL**: Derives locale from URL patterns (e.g., `/en/about`, `en.example.com`).
- **GlobalVariable**: Uses a global variable (client-side only).
- **BaseLocale**: Always returns the base locale.
Strategies can be combined. The order defines precedence:
```js
await compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie", "baseLocale"],
});
```
See the [strategy documentation](https://paraglidejs.com/strategy) for details.
## Markup (Rich Text)
Messages can contain markup tags for bold, links, and other inline elements. Translators control where tags appear; developers control how they render.
Important:
- Tag names are app-defined. There is no built-in list of HTML tags.
- `{#b}...{/b}` does not automatically render as `<b>...</b>`.
- Renderers/snippets are looked up by the same tag name used in the message.
### Message syntax
```json
{
"cta": "{#link to=|/docs| rel=$relationship @track}Read the docs{/link}",
"welcome": "{#b}Hi {name}{/b}{#icon/}"
}
```
- `{#tagName}` opens a tag, `{/tagName}` closes it.
- `{#tagName/}` creates a standalone tag.
- Options: `to=|/docs|` or `rel=$relationship` (accessed via `options.*`).
- Attributes: `@track` or `@variant=|hero|` (accessed via `attributes.*`).
This is the default inlang message syntax. Paraglide's message format is plugin-based — you can use [ICU MessageFormat 1](https://inlang.com/m/p7c8m1d2/plugin-inlang-icu-messageformat-1), [i18next](https://inlang.com/m/3i8bor92/plugin-inlang-i18next), or other [plugins](https://inlang.com/c/plugins) instead.
### Rendering markup
Calling the message function still returns **plain text** (markup stripped):
```js
m.cta({ relationship: "noopener" }); // "Read the docs"
```
To render markup, use the framework adapter or the low-level `parts()` API:
```js
const parts = m.cta.parts({ relationship: "noopener" });
// [
// { type: "markup-start", name: "link", options: { to: "/docs", rel: "noopener" }, attributes: { track: true } },
// { type: "text", value: "Read the docs" },
// { type: "markup-end", name: "link" }
// ]
```
Framework adapters provide a `<ParaglideMessage>` component that accepts markup renderers:
- `@inlang/paraglide-js-react`
- `@inlang/paraglide-js-vue`
- `@inlang/paraglide-js-svelte`
- `@inlang/paraglide-js-solid`
```jsx
import { ParaglideMessage } from "@inlang/paraglide-js-react"; // or -vue, -svelte, -solid
<ParaglideMessage
message={m.welcome}
inputs={{ name: "Ada" }}
markup={{
b: ({ children }) => <b>{children}</b>,
icon: () => <span aria-hidden="true" className="icon-wave" />,
}}
/>
```
The available renderer/snippet names come from the message itself. You can inspect them through `message.parts()`, and TypeScript uses the same names to type-check your markup renderers.
See the [markup documentation](https://paraglidejs.com/markup) for details.
## Key concepts
- **Tree-shakeable**: Each message is a function, enabling [up to 70% smaller i18n bundle sizes](https://paraglidejs.com/benchmark) than traditional i18n libraries.
- **Typesafe**: Full TypeScript/JSDoc support with autocomplete.
- **Variants**: Messages can have variants for pluralization, gender, etc.
- **Fallbacks**: Missing translations fall back to the base locale.
## Links
- [Paraglide JS Documentation](https://paraglidejs.com)
- [Source Repository](https://github.com/opral/paraglide-js)
+2
View File
@@ -0,0 +1,2 @@
export * from "./messages/_index.js";
export * as m from "./messages/_index.js";
+4
View File
@@ -0,0 +1,4 @@
/* eslint-disable */
export * from './messages/_index.js'
// enabling auto-import by exposing all messages as m
export * as m from './messages/_index.js'
+20
View File
@@ -0,0 +1,20 @@
export * from "./dashboard.js";
export * from "./notifications.js";
export * from "./uploads.js";
export * from "./language.js";
export * from "./personal_info.js";
export * from "./language_settings.js";
export * from "./select_preferred_language.js";
export * from "./settings.js";
export * from "./welcome_back.js";
export * from "./create_account.js";
export * from "./select_a_team.js";
export * from "./projects.js";
export * from "./select_asset_to_view_details.js";
export * from "./all_collections.js";
export * from "./file_not_found.js";
export * from "./recently_deleted_notice.js";
export * from "./all_share_links.js";
export * from "./link_visibility.js";
export * from "./password_protected.js";
export type LocalizedString = import("../runtime.js").LocalizedString;
@@ -0,0 +1,21 @@
/* eslint-disable */
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
export * from './dashboard.js'
export * from './notifications.js'
export * from './uploads.js'
export * from './language.js'
export * from './personal_info.js'
export * from './language_settings.js'
export * from './select_preferred_language.js'
export * from './settings.js'
export * from './welcome_back.js'
export * from './create_account.js'
export * from './select_a_team.js'
export * from './projects.js'
export * from './select_asset_to_view_details.js'
export * from './all_collections.js'
export * from './file_not_found.js'
export * from './recently_deleted_notice.js'
export * from './all_share_links.js'
export * from './link_visibility.js'
export * from './password_protected.js'
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "All Collections" |
*
* @param {All_CollectionsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const all_collections: ((inputs?: All_CollectionsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<All_CollectionsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type All_CollectionsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} All_CollectionsInputs */
const en_all_collections = /** @type {(inputs: All_CollectionsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`All Collections`)
};
const zh_all_collections = /** @type {(inputs: All_CollectionsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`所有收藏`)
};
/**
* | output |
* | --- |
* | "All Collections" |
*
* @param {All_CollectionsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const all_collections = /** @type {((inputs?: All_CollectionsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<All_CollectionsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_all_collections(inputs)
return zh_all_collections(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "All Share Links" |
*
* @param {All_Share_LinksInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const all_share_links: ((inputs?: All_Share_LinksInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<All_Share_LinksInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type All_Share_LinksInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} All_Share_LinksInputs */
const en_all_share_links = /** @type {(inputs: All_Share_LinksInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`All Share Links`)
};
const zh_all_share_links = /** @type {(inputs: All_Share_LinksInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`所有分享链接`)
};
/**
* | output |
* | --- |
* | "All Share Links" |
*
* @param {All_Share_LinksInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const all_share_links = /** @type {((inputs?: All_Share_LinksInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<All_Share_LinksInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_all_share_links(inputs)
return zh_all_share_links(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Create Account" |
*
* @param {Create_AccountInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const create_account: ((inputs?: Create_AccountInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Create_AccountInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Create_AccountInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Create_AccountInputs */
const en_create_account = /** @type {(inputs: Create_AccountInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Create Account`)
};
const zh_create_account = /** @type {(inputs: Create_AccountInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`创建账户`)
};
/**
* | output |
* | --- |
* | "Create Account" |
*
* @param {Create_AccountInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const create_account = /** @type {((inputs?: Create_AccountInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Create_AccountInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_create_account(inputs)
return zh_create_account(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Dashboard" |
*
* @param {DashboardInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const dashboard: ((inputs?: DashboardInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<DashboardInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type DashboardInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} DashboardInputs */
const en_dashboard = /** @type {(inputs: DashboardInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Dashboard`)
};
const zh_dashboard = /** @type {(inputs: DashboardInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`控制台`)
};
/**
* | output |
* | --- |
* | "Dashboard" |
*
* @param {DashboardInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const dashboard = /** @type {((inputs?: DashboardInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<DashboardInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_dashboard(inputs)
return zh_dashboard(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "File not found." |
*
* @param {File_Not_FoundInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const file_not_found: ((inputs?: File_Not_FoundInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<File_Not_FoundInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type File_Not_FoundInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} File_Not_FoundInputs */
const en_file_not_found = /** @type {(inputs: File_Not_FoundInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`File not found.`)
};
const zh_file_not_found = /** @type {(inputs: File_Not_FoundInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`文件未找到。`)
};
/**
* | output |
* | --- |
* | "File not found." |
*
* @param {File_Not_FoundInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const file_not_found = /** @type {((inputs?: File_Not_FoundInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<File_Not_FoundInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_file_not_found(inputs)
return zh_file_not_found(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Language" |
*
* @param {LanguageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const language: ((inputs?: LanguageInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<LanguageInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type LanguageInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} LanguageInputs */
const en_language = /** @type {(inputs: LanguageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Language`)
};
const zh_language = /** @type {(inputs: LanguageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`语言`)
};
/**
* | output |
* | --- |
* | "Language" |
*
* @param {LanguageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const language = /** @type {((inputs?: LanguageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<LanguageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_language(inputs)
return zh_language(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Language Settings" |
*
* @param {Language_SettingsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const language_settings: ((inputs?: Language_SettingsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Language_SettingsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Language_SettingsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Language_SettingsInputs */
const en_language_settings = /** @type {(inputs: Language_SettingsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Language Settings`)
};
const zh_language_settings = /** @type {(inputs: Language_SettingsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`语言设置`)
};
/**
* | output |
* | --- |
* | "Language Settings" |
*
* @param {Language_SettingsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const language_settings = /** @type {((inputs?: Language_SettingsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Language_SettingsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_language_settings(inputs)
return zh_language_settings(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Link Visibility" |
*
* @param {Link_VisibilityInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const link_visibility: ((inputs?: Link_VisibilityInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Link_VisibilityInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Link_VisibilityInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Link_VisibilityInputs */
const en_link_visibility = /** @type {(inputs: Link_VisibilityInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Link Visibility`)
};
const zh_link_visibility = /** @type {(inputs: Link_VisibilityInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`链接可见性`)
};
/**
* | output |
* | --- |
* | "Link Visibility" |
*
* @param {Link_VisibilityInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const link_visibility = /** @type {((inputs?: Link_VisibilityInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Link_VisibilityInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_link_visibility(inputs)
return zh_link_visibility(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Notifications" |
*
* @param {NotificationsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const notifications: ((inputs?: NotificationsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<NotificationsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type NotificationsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} NotificationsInputs */
const en_notifications = /** @type {(inputs: NotificationsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Notifications`)
};
const zh_notifications = /** @type {(inputs: NotificationsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`通知中心`)
};
/**
* | output |
* | --- |
* | "Notifications" |
*
* @param {NotificationsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const notifications = /** @type {((inputs?: NotificationsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<NotificationsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_notifications(inputs)
return zh_notifications(inputs)
});
@@ -0,0 +1,4 @@
{
"type": "module",
"sideEffects": false
}
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Password Protected" |
*
* @param {Password_ProtectedInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const password_protected: ((inputs?: Password_ProtectedInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Password_ProtectedInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Password_ProtectedInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Password_ProtectedInputs */
const en_password_protected = /** @type {(inputs: Password_ProtectedInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Password Protected`)
};
const zh_password_protected = /** @type {(inputs: Password_ProtectedInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`密码保护`)
};
/**
* | output |
* | --- |
* | "Password Protected" |
*
* @param {Password_ProtectedInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const password_protected = /** @type {((inputs?: Password_ProtectedInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Password_ProtectedInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_password_protected(inputs)
return zh_password_protected(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Personal Info" |
*
* @param {Personal_InfoInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const personal_info: ((inputs?: Personal_InfoInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Personal_InfoInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Personal_InfoInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Personal_InfoInputs */
const en_personal_info = /** @type {(inputs: Personal_InfoInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Personal Info`)
};
const zh_personal_info = /** @type {(inputs: Personal_InfoInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`个人信息`)
};
/**
* | output |
* | --- |
* | "Personal Info" |
*
* @param {Personal_InfoInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const personal_info = /** @type {((inputs?: Personal_InfoInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Personal_InfoInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_personal_info(inputs)
return zh_personal_info(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Projects" |
*
* @param {ProjectsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const projects: ((inputs?: ProjectsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<ProjectsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type ProjectsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} ProjectsInputs */
const en_projects = /** @type {(inputs: ProjectsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Projects`)
};
const zh_projects = /** @type {(inputs: ProjectsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`项目`)
};
/**
* | output |
* | --- |
* | "Projects" |
*
* @param {ProjectsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const projects = /** @type {((inputs?: ProjectsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<ProjectsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_projects(inputs)
return zh_projects(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Items are automatically deleted after 30 days." |
*
* @param {Recently_Deleted_NoticeInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const recently_deleted_notice: ((inputs?: Recently_Deleted_NoticeInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Recently_Deleted_NoticeInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Recently_Deleted_NoticeInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Recently_Deleted_NoticeInputs */
const en_recently_deleted_notice = /** @type {(inputs: Recently_Deleted_NoticeInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Items are automatically deleted after 30 days.`)
};
const zh_recently_deleted_notice = /** @type {(inputs: Recently_Deleted_NoticeInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`项目将在 30 天后自动删除。`)
};
/**
* | output |
* | --- |
* | "Items are automatically deleted after 30 days." |
*
* @param {Recently_Deleted_NoticeInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const recently_deleted_notice = /** @type {((inputs?: Recently_Deleted_NoticeInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Recently_Deleted_NoticeInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_recently_deleted_notice(inputs)
return zh_recently_deleted_notice(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Select a Team" |
*
* @param {Select_A_TeamInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_a_team: ((inputs?: Select_A_TeamInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Select_A_TeamInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Select_A_TeamInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Select_A_TeamInputs */
const en_select_a_team = /** @type {(inputs: Select_A_TeamInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Select a Team`)
};
const zh_select_a_team = /** @type {(inputs: Select_A_TeamInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`选择团队`)
};
/**
* | output |
* | --- |
* | "Select a Team" |
*
* @param {Select_A_TeamInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_a_team = /** @type {((inputs?: Select_A_TeamInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Select_A_TeamInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_select_a_team(inputs)
return zh_select_a_team(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Select an asset to view details" |
*
* @param {Select_Asset_To_View_DetailsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_asset_to_view_details: ((inputs?: Select_Asset_To_View_DetailsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Select_Asset_To_View_DetailsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Select_Asset_To_View_DetailsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Select_Asset_To_View_DetailsInputs */
const en_select_asset_to_view_details = /** @type {(inputs: Select_Asset_To_View_DetailsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Select an asset to view details`)
};
const zh_select_asset_to_view_details = /** @type {(inputs: Select_Asset_To_View_DetailsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`选择资产查看详情`)
};
/**
* | output |
* | --- |
* | "Select an asset to view details" |
*
* @param {Select_Asset_To_View_DetailsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_asset_to_view_details = /** @type {((inputs?: Select_Asset_To_View_DetailsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Select_Asset_To_View_DetailsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_select_asset_to_view_details(inputs)
return zh_select_asset_to_view_details(inputs)
});
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Select your preferred display language." |
*
* @param {Select_Preferred_LanguageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_preferred_language: ((inputs?: Select_Preferred_LanguageInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Select_Preferred_LanguageInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Select_Preferred_LanguageInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Select_Preferred_LanguageInputs */
const en_select_preferred_language = /** @type {(inputs: Select_Preferred_LanguageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Select your preferred display language.`)
};
const zh_select_preferred_language = /** @type {(inputs: Select_Preferred_LanguageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`选择您首选的显示语言。`)
};
/**
* | output |
* | --- |
* | "Select your preferred display language." |
*
* @param {Select_Preferred_LanguageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_preferred_language = /** @type {((inputs?: Select_Preferred_LanguageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Select_Preferred_LanguageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_select_preferred_language(inputs)
return zh_select_preferred_language(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Settings" |
*
* @param {SettingsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const settings: ((inputs?: SettingsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<SettingsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type SettingsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} SettingsInputs */
const en_settings = /** @type {(inputs: SettingsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Settings`)
};
const zh_settings = /** @type {(inputs: SettingsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`设置`)
};
/**
* | output |
* | --- |
* | "Settings" |
*
* @param {SettingsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const settings = /** @type {((inputs?: SettingsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<SettingsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_settings(inputs)
return zh_settings(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Uploads" |
*
* @param {UploadsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const uploads: ((inputs?: UploadsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<UploadsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type UploadsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} UploadsInputs */
const en_uploads = /** @type {(inputs: UploadsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Uploads`)
};
const zh_uploads = /** @type {(inputs: UploadsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`上传管理`)
};
/**
* | output |
* | --- |
* | "Uploads" |
*
* @param {UploadsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const uploads = /** @type {((inputs?: UploadsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<UploadsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_uploads(inputs)
return zh_uploads(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Welcome Back" |
*
* @param {Welcome_BackInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const welcome_back: ((inputs?: Welcome_BackInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Welcome_BackInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Welcome_BackInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Welcome_BackInputs */
const en_welcome_back = /** @type {(inputs: Welcome_BackInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Welcome Back`)
};
const zh_welcome_back = /** @type {(inputs: Welcome_BackInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`欢迎回来`)
};
/**
* | output |
* | --- |
* | "Welcome Back" |
*
* @param {Welcome_BackInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const welcome_back = /** @type {((inputs?: Welcome_BackInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Welcome_BackInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_welcome_back(inputs)
return zh_welcome_back(inputs)
});
+34
View File
@@ -0,0 +1,34 @@
/**
* @typedef {"year" | "years" | "quarter" | "quarters" | "month" | "months" | "week" | "weeks" | "day" | "days" | "hour" | "hours" | "minute" | "minutes" | "second" | "seconds"} RelativeTimeFormatUnit
*/
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.PluralRulesOptions} [options]
* @returns {string}
*/
export function plural(locale: import("./runtime.js").Locale, input: unknown, options?: Intl.PluralRulesOptions): string;
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.NumberFormatOptions} [options]
* @returns {string}
*/
export function number(locale: import("./runtime.js").Locale, input: unknown, options?: Intl.NumberFormatOptions): string;
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.DateTimeFormatOptions} [options]
* @returns {string}
*/
export function datetime(locale: import("./runtime.js").Locale, input: unknown, options?: Intl.DateTimeFormatOptions): string;
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.RelativeTimeFormatOptions & { unit: RelativeTimeFormatUnit }} options
* @returns {string}
*/
export function relativetime(locale: import("./runtime.js").Locale, input: unknown, options: Intl.RelativeTimeFormatOptions & {
unit: RelativeTimeFormatUnit;
}): string;
export type RelativeTimeFormatUnit = "year" | "years" | "quarter" | "quarters" | "month" | "months" | "week" | "weeks" | "day" | "days" | "hour" | "hours" | "minute" | "minutes" | "second" | "seconds";
+46
View File
@@ -0,0 +1,46 @@
/* eslint-disable */
/**
* @typedef {"year" | "years" | "quarter" | "quarters" | "month" | "months" | "week" | "weeks" | "day" | "days" | "hour" | "hours" | "minute" | "minutes" | "second" | "seconds"} RelativeTimeFormatUnit
*/
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.PluralRulesOptions} [options]
* @returns {string}
*/
export function plural(locale, input, options) {
return new Intl.PluralRules(locale, options).select(Number(input))
};
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.NumberFormatOptions} [options]
* @returns {string}
*/
export function number(locale, input, options) {
return new Intl.NumberFormat(locale, options).format(Number(input))
};
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.DateTimeFormatOptions} [options]
* @returns {string}
*/
export function datetime(locale, input, options) {
return new Intl.DateTimeFormat(locale, options).format(new Date(/** @type {string} */ (input)))
};
/**
* @param {import("./runtime.js").Locale} locale
* @param {unknown} input
* @param {Intl.RelativeTimeFormatOptions & { unit: RelativeTimeFormatUnit }} options
* @returns {string}
*/
export function relativetime(locale, input, options) {
const { unit, ...intlOptions } = options;
return new Intl.RelativeTimeFormat(locale, intlOptions).format(Number(input), unit);
};
+758
View File
@@ -0,0 +1,758 @@
/**
* Returns the strategy to use for a specific URL.
*
* If no route strategy matches (or the matching rule is `exclude: true`),
* the global strategy is returned.
*
* @param {string | URL} url
* @returns {typeof strategy}
*/
export function getStrategyForUrl(url: string | URL): typeof strategy;
/**
* Returns whether the given URL is excluded from middleware i18n processing.
*
* @param {string | URL} url
* @returns {boolean}
*/
export function isExcludedByRouteStrategy(url: string | URL): boolean;
/**
* Sets the server side async local storage.
*
* The function is needed because the `runtime.js` file
* must define the `serverAsyncLocalStorage` variable to
* avoid a circular import between `runtime.js` and
* `server.js` files.
*
* @param {ParaglideAsyncLocalStorage | undefined} value
*/
export function overwriteServerAsyncLocalStorage(value: ParaglideAsyncLocalStorage | undefined): void;
/**
* Resolve locale for a given URL using route-aware strategies.
*
* @param {string | URL} url
* @returns {Locale}
*/
export function getLocaleForUrl(url: string | URL): Locale;
/**
* Get writing direction for a locale.
*
* Uses `Intl.Locale` text info when available and falls back to a
* language-based RTL check for runtimes without `getTextInfo()`.
*
* @example
* getTextDirection(); // "ltr" or "rtl" for current locale
* getTextDirection("ar"); // "rtl"
* getTextDirection("en"); // "ltr"
*
* @param {string} [locale] - Target locale. If not provided, uses `getLocale()`
* @returns {"ltr" | "rtl"}
*/
export function getTextDirection(locale?: string): "ltr" | "rtl";
/**
* Coerces a locale-like string to the canonical locale value used by the runtime.
*
* @param {unknown} value
* @returns {Locale | undefined}
*/
export function toLocale(value: unknown): Locale | undefined;
/**
* Check if something is an available locale with the canonical project casing.
*
* @example
* if (isLocale(params.locale)) {
* setLocale(params.locale);
* } else {
* setLocale('en');
* }
*
* Use `toLocale()` when you want case-insensitive matching and canonicalization.
*
* @param {unknown} locale
* @returns {locale is Locale}
*/
export function isLocale(locale: unknown): locale is Locale;
/**
* Asserts that the input can be normalized to a locale.
*
* @param {unknown} input - The input to check.
* @returns {Locale} The input normalized to a Locale.
* @throws {Error} If the input is not a locale.
*/
export function assertIsLocale(input: unknown): Locale;
/**
* Extracts a cookie from the document.
*
* Will return undefined if the document is not available or if the cookie is not set.
* The `document` object is not available in server-side rendering, so this function should not be called in that context.
*
* @returns {Locale | undefined}
*/
export function extractLocaleFromCookie(): Locale | undefined;
/**
* Extracts a locale from the accept-language header.
*
* Use the function on the server to extract the locale
* from the accept-language header that is sent by the client.
*
* @example
* const locale = extractLocaleFromHeader(request);
*
* @param {Request} request - The request object to extract the locale from.
* @returns {Locale | undefined} The negotiated preferred language.
*/
export function extractLocaleFromHeader(request: Request): Locale | undefined;
/**
* Negotiates a preferred language from navigator.languages.
*
* Use the function on the client to extract the locale
* from the navigator.languages array.
*
* @example
* const locale = extractLocaleFromNavigator();
*
* @returns {Locale | undefined}
*/
export function extractLocaleFromNavigator(): Locale | undefined;
/**
* Extracts the locale from a given URL using native URLPattern.
*
* The built-in default `/:locale/...` routing is case-insensitive because it
* canonicalizes the first path segment with `toLocale()`. Custom `urlPatterns`
* keep URLPattern's normal exact matching semantics for path segments.
*
* @param {URL|string} url - The full URL from which to extract the locale.
* @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
*/
export function extractLocaleFromUrl(url: URL | string): Locale | undefined;
/**
* Lower-level URL localization function, primarily used in server contexts.
*
* This function is designed for server-side usage where you need precise control
* over URL localization, such as in middleware or request handlers. It works with
* URL objects and always returns absolute URLs.
*
* For client-side UI components, use `localizeHref()` instead, which provides
* a more convenient API with relative paths and automatic locale detection.
*
* @see https://paraglidejs.com/i18n-routing
*
* @example
* ```typescript
* // Server middleware example
* app.use((req, res, next) => {
* const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
* const localized = localizeUrl(url, { locale: "de" });
*
* if (localized.href !== url.href) {
* return res.redirect(localized.href);
* }
* next();
* });
* ```
*
* @example
* ```typescript
* // Using with URL patterns
* const url = new URL("https://example.com/about");
* localizeUrl(url, { locale: "de" });
* // => URL("https://example.com/de/about")
*
* // Using with domain-based localization
* const url = new URL("https://example.com/store");
* localizeUrl(url, { locale: "de" });
* // => URL("https://de.example.com/store")
* ```
*
* @param {string | URL} url - The URL to localize. If string, must be absolute.
* @param {object} [options] - Options for localization
* @param {Locale} [options.locale] - Target locale. If not provided, uses getLocale()
* @returns {URL} The localized URL, always absolute
*/
export function localizeUrl(url: string | URL, options?: {
locale?: Locale;
}): URL;
/**
* Low-level URL de-localization function, primarily used in server contexts.
*
* This function is designed for server-side usage where you need precise control
* over URL de-localization, such as in middleware or request handlers. It works with
* URL objects and always returns absolute URLs.
*
* For client-side UI components, use `deLocalizeHref()` instead, which provides
* a more convenient API with relative paths.
*
* @see https://paraglidejs.com/i18n-routing
*
* @example
* ```typescript
* // Server middleware example
* app.use((req, res, next) => {
* const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
* const baseUrl = deLocalizeUrl(url);
*
* // Store the base URL for later use
* req.baseUrl = baseUrl;
* next();
* });
* ```
*
* @example
* ```typescript
* // Using with URL patterns
* const url = new URL("https://example.com/de/about");
* deLocalizeUrl(url); // => URL("https://example.com/about")
*
* // Using with domain-based localization
* const url = new URL("https://de.example.com/store");
* deLocalizeUrl(url); // => URL("https://example.com/store")
* ```
*
* @param {string | URL} url - The URL to de-localize. If string, must be absolute.
* @returns {URL} The de-localized URL, always absolute
*/
export function deLocalizeUrl(url: string | URL): URL;
/**
* Aggregates named groups from various parts of the URLPattern match result.
*
*
* @param {any} match - The URLPattern match result object.
* @returns {Record<string, string | null | undefined>} An object containing all named groups from the match.
*/
export function aggregateGroups(match: any): Record<string, string | null | undefined>;
/**
* @typedef {object} ShouldRedirectServerInput
* @property {Request} request
* @property {string | URL} [effectiveRequestUrl] - Effective request URL to use for route matching, locale detection with the URL strategy, and redirect targets.
* @property {Locale} [locale]
*
* @typedef {object} ShouldRedirectClientInput
* @property {undefined} [request]
* @property {string | URL} [url]
* @property {Locale} [locale]
*
* @typedef {ShouldRedirectServerInput | ShouldRedirectClientInput} ShouldRedirectInput
*
* @typedef {object} ShouldRedirectResult
* @property {boolean} shouldRedirect - Indicates whether the consumer should perform a redirect.
* @property {Locale} locale - Locale resolved using the configured strategies.
* @property {URL | undefined} redirectUrl - Destination URL when a redirect is required.
*/
/**
* Determines whether a redirect is required to align the current URL with the active locale.
*
* This helper mirrors the logic that powers `paraglideMiddleware`, but works in both server
* and client environments. It evaluates the configured strategies in order, computes the
* canonical localized URL, and reports when the current URL does not match.
*
* When called in the browser without arguments, the current `window.location.href` is used.
*
* @see https://paraglidejs.com/i18n-routing#redirects
*
* @example
* // Client side usage (e.g. TanStack Router beforeLoad hook)
* async function beforeLoad({ location }) {
* const decision = await shouldRedirect({ url: location.href });
*
* if (decision.shouldRedirect) {
* throw redirect({ to: decision.redirectUrl.href });
* }
* }
*
* @example
* // Server side usage with a Request
* export async function handle(request) {
* const decision = await shouldRedirect({ request });
*
* if (decision.shouldRedirect) {
* return Response.redirect(decision.redirectUrl, 307);
* }
*
* return render(request, decision.locale);
* }
*
* @example
* // Server side usage behind a proxy where request.url is not public-facing
* export async function handle(request) {
* const effectiveRequestUrl = new URL(request.url);
* effectiveRequestUrl.protocol = "https:";
* effectiveRequestUrl.host = "example.com";
*
* const decision = await shouldRedirect({
* request,
* effectiveRequestUrl,
* });
*
* if (decision.shouldRedirect) {
* return Response.redirect(decision.redirectUrl, 307);
* }
* }
*
* @param {ShouldRedirectInput} [input]
* @returns {Promise<ShouldRedirectResult>}
*/
export function shouldRedirect(input?: ShouldRedirectInput): Promise<ShouldRedirectResult>;
/**
* High-level URL localization function optimized for client-side UI usage.
*
* This is a convenience wrapper around `localizeUrl()` that provides features
* needed in UI:
*
* - Accepts relative paths (e.g., "/about")
* - Returns relative paths when possible
* - Automatically detects current locale if not specified
* - Handles string input/output instead of URL objects
*
* @see https://paraglidejs.com/i18n-routing
*
* @example
* ```typescript
* // In a React/Vue/Svelte component
* const NavLink = ({ href }) => {
* // Automatically uses current locale, keeps path relative
* return <a href={localizeHref(href)}>...</a>;
* };
*
* // Examples:
* localizeHref("/about")
* // => "/de/about" (if current locale is "de")
* localizeHref("/store", { locale: "fr" })
* // => "/fr/store" (explicit locale)
*
* // Cross-origin links remain absolute
* localizeHref("https://other-site.com/about")
* // => "https://other-site.com/de/about"
* ```
*
* For server-side URL localization (e.g., in middleware), use `localizeUrl()`
* which provides more precise control over URL handling.
*
* @param {string} href - The href to localize (can be relative or absolute)
* @param {object} [options] - Options for localization
* @param {Locale} [options.locale] - Target locale. If not provided, uses `getLocale()`
* @returns {string} The localized href, relative if input was relative
*/
export function localizeHref(href: string, options?: {
locale?: Locale;
}): string;
/**
* High-level URL de-localization function optimized for client-side UI usage.
*
* This is a convenience wrapper around `deLocalizeUrl()` that provides features
* needed in the UI:
*
* - Accepts relative paths (e.g., "/de/about")
* - Returns relative paths when possible
* - Handles string input/output instead of URL objects
*
* @see https://paraglidejs.com/i18n-routing
*
* @example
* ```typescript
* // In a React/Vue/Svelte component
* const LocaleSwitcher = ({ href }) => {
* // Remove locale prefix before switching
* const baseHref = deLocalizeHref(href);
* return locales.map(locale =>
* <a href={localizeHref(baseHref, { locale })}>
* Switch to {locale}
* </a>
* );
* };
*
* // Examples:
* deLocalizeHref("/de/about") // => "/about"
* deLocalizeHref("/fr/store") // => "/store"
*
* // Cross-origin links remain absolute
* deLocalizeHref("https://example.com/de/about")
* // => "https://example.com/about"
* ```
*
* For server-side URL de-localization (e.g., in middleware), use `deLocalizeUrl()`
* which provides more precise control over URL handling.
*
* @param {string} href - The href to de-localize (can be relative or absolute)
* @returns {string} The de-localized href, relative if input was relative
*/
export function deLocalizeHref(href: string): string;
/**
* @param {string} safeModuleId
* @param {Locale} locale
*/
export function trackMessageCall(safeModuleId: string, locale: Locale): void;
/**
* Generates localized URL variants for all provided URLs based on your configured locales and URL patterns.
*
* This function is essential for Static Site Generation (SSG) where you need to tell your framework
* which pages to pre-render at build time. It's also useful for generating sitemaps and
* `<link rel="alternate" hreflang>` tags for SEO.
*
* The function respects your `urlPatterns` configuration - if you have translated pathnames
* (e.g., `/about` → `/ueber-uns` for German), it will generate the correct localized paths.
*
* @see https://paraglidejs.com/static-site-generation
*
* @example
* // Basic usage - generate all locale variants for a list of paths
* const localizedUrls = generateStaticLocalizedUrls([
* "/",
* "/about",
* "/blog/post-1",
* ]);
* // Returns URL objects for each locale:
* // ["/en/", "/de/", "/en/about", "/de/about", "/en/blog/post-1", "/de/blog/post-1"]
*
* @example
* // Use with framework SSG APIs
* // SvelteKit
* export function entries() {
* const paths = ["/", "/about", "/contact"];
* return generateStaticLocalizedUrls(paths).map(url => ({
* locale: extractLocaleFromUrl(url)
* }));
* }
*
* @example
* // Sitemap generation
* const allPages = ["/", "/about", "/blog"];
* const sitemapUrls = generateStaticLocalizedUrls(allPages);
*
* @param {(string | URL)[]} urls - List of canonical URLs or paths to generate localized versions for.
* Can be absolute URLs (`https://example.com/about`) or paths (`/about`).
* Paths are resolved against `http://localhost` internally.
* @returns {URL[]} Array of URL objects representing all localized variants.
* The order follows each input URL with all its locale variants before moving to the next URL.
*/
export function generateStaticLocalizedUrls(urls: (string | URL)[]): URL[];
/**
* Checks if the given strategy is a custom strategy.
*
* @param {unknown} strategy The name of the custom strategy to validate.
* Must be a string that starts with "custom-" followed by alphanumeric characters, hyphens, or underscores.
* @returns {boolean} Returns true if it is a custom strategy, false otherwise.
*/
export function isCustomStrategy(strategy: unknown): boolean;
/**
* Defines a custom strategy that is executed on the server.
*
* @see https://paraglidejs.com/strategy#write-your-own-strategy
*
* @param {string} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
* @param {CustomServerStrategyHandler} handler The handler for the custom strategy, which should implement
* the method getLocale.
* @returns {void}
*/
export function defineCustomServerStrategy(strategy: string, handler: CustomServerStrategyHandler): void;
/**
* Defines a custom strategy that is executed on the client.
*
* @see https://paraglidejs.com/strategy#write-your-own-strategy
*
* @param {string} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
* @param {CustomClientStrategyHandler} handler The handler for the custom strategy, which should implement the
* methods getLocale and setLocale.
* @returns {void}
*/
export function defineCustomClientStrategy(strategy: string, handler: CustomClientStrategyHandler): void;
/**
* The project's base locale.
*
* @example
* if (locale === baseLocale) {
* // do something
* }
*/
export const baseLocale: "en";
/**
* The project's locales that have been specified in the settings.
*
* @example
* if (locales.includes(userSelectedLocale) === false) {
* throw new Error('Locale is not available');
* }
*/
export const locales: readonly ["en", "zh"];
/** @type {string} */
export const cookieName: string;
/** @type {number} */
export const cookieMaxAge: number;
/** @type {string} */
export const cookieDomain: string;
/** @type {string} */
export const localStorageKey: string;
/**
* @type {Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>}
*/
export const strategy: Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>;
/**
* Route-level strategy overrides.
*
* `match` uses URLPattern syntax.
*
* @type {Array<{
* match: string;
* strategy?: Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>;
* exclude?: boolean;
* }>}
*/
export const routeStrategies: Array<{
match: string;
strategy?: Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>;
exclude?: boolean;
}>;
/**
* The used URL patterns.
*
* @type {Array<{ pattern: string, localized: Array<[Locale, string]> }>}
*/
export const urlPatterns: Array<{
pattern: string;
localized: Array<[Locale, string]>;
}>;
/**
* @typedef {{
* getStore(): {
* locale?: Locale,
* origin?: string,
* messageCalls?: Set<string>
* } | undefined,
* run: (store: { locale?: Locale, origin?: string, messageCalls?: Set<string>},
* cb: any) => any
* }} ParaglideAsyncLocalStorage
*/
/**
* Server side async local storage that is set by `serverMiddleware()`.
*
* The variable is used to retrieve the locale and origin in a server-side
* rendering context without effecting other requests.
*
* @type {ParaglideAsyncLocalStorage | undefined}
*/
export let serverAsyncLocalStorage: ParaglideAsyncLocalStorage | undefined;
export const disableAsyncLocalStorage: false;
export const experimentalMiddlewareLocaleSplitting: false;
export const isServer: boolean;
/** @type {Locale | undefined} */
export const experimentalStaticLocale: Locale | undefined;
export function getLocale(): Locale;
export function overwriteGetLocale(fn: () => Locale): void;
/**
* @typedef {(newLocale: Locale, options?: { reload?: boolean }) => void | Promise<void>} SetLocaleFn
*/
/**
* Set the locale.
*
* Updates the locale using your configured strategies (cookie, localStorage, URL, etc.).
* By default, this reloads the page on the client to reflect the new locale. Reloading
* can be disabled by passing `reload: false` as an option, but you'll need to ensure
* the UI updates to reflect the new locale.
*
* If any custom strategy's `setLocale` function is async, then this function
* will become async as well.
*
* @see https://paraglidejs.com/strategy
*
* @example
* setLocale('en');
*
* @example
* setLocale('en', { reload: false });
*
* @type {SetLocaleFn}
*/
export let setLocale: SetLocaleFn;
export function overwriteSetLocale(fn: SetLocaleFn): void;
/**
* The origin of the current URL.
*
* Defaults to "http://y.com" in non-browser environments. If this
* behavior is not desired, the implementation can be overwritten
* by `overwriteGetUrlOrigin()`.
*
* @type {() => string}
*/
export let getUrlOrigin: () => string;
export function overwriteGetUrlOrigin(fn: () => string): void;
export function extractLocaleFromRequest(request: Request, options?: ExtractLocaleFromRequestOptions): Locale;
export function extractLocaleFromRequestWithStrategies(request: Request, strategies: typeof strategy, url?: string | URL): Locale;
export function extractLocaleFromRequestAsync(request: Request, options?: {
effectiveRequestUrl?: string | URL;
}): Promise<Locale>;
/**
* @typedef {"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage"} BuiltInStrategy
*/
/**
* @typedef {`custom_${string}`} CustomStrategy
*/
/**
* @typedef {BuiltInStrategy | CustomStrategy} Strategy
*/
/**
* @typedef {Array<Strategy>} Strategies
*/
/**
* @typedef {{ getLocale: (request?: Request) => Promise<string | undefined> | (string | undefined) }} CustomServerStrategyHandler
*/
/**
* @typedef {{ getLocale: () => Promise<string|undefined> | (string | undefined), setLocale: (locale: string) => Promise<void> | void }} CustomClientStrategyHandler
*/
/** @type {Map<string, CustomServerStrategyHandler>} */
export const customServerStrategies: Map<string, CustomServerStrategyHandler>;
/** @type {Map<string, CustomClientStrategyHandler>} */
export const customClientStrategies: Map<string, CustomClientStrategyHandler>;
export type ShouldRedirectServerInput = {
request: Request;
/**
* - Effective request URL to use for route matching, locale detection with the URL strategy, and redirect targets.
*/
effectiveRequestUrl?: string | URL;
locale?: Locale;
};
export type ShouldRedirectClientInput = {
request?: undefined;
url?: string | URL;
locale?: Locale;
};
export type ShouldRedirectInput = ShouldRedirectServerInput | ShouldRedirectClientInput;
export type ShouldRedirectResult = {
/**
* - Indicates whether the consumer should perform a redirect.
*/
shouldRedirect: boolean;
/**
* - Locale resolved using the configured strategies.
*/
locale: Locale;
/**
* - Destination URL when a redirect is required.
*/
redirectUrl: URL | undefined;
};
export type ParaglideAsyncLocalStorage = {
getStore(): {
locale?: Locale;
origin?: string;
messageCalls?: Set<string>;
} | undefined;
run: (store: {
locale?: Locale;
origin?: string;
messageCalls?: Set<string>;
}, cb: any) => any;
};
export type SetLocaleFn = (newLocale: Locale, options?: {
reload?: boolean;
}) => void | Promise<void>;
export type ExtractLocaleFromRequestOptions = {
/**
* - Effective request URL to use for route matching and locale detection with the URL strategy.
*/
effectiveRequestUrl?: string | URL;
};
export type BuiltInStrategy = "cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage";
export type CustomStrategy = `custom_${string}`;
export type Strategy = BuiltInStrategy | CustomStrategy;
export type Strategies = Array<Strategy>;
export type CustomServerStrategyHandler = {
getLocale: (request?: Request) => Promise<string | undefined> | (string | undefined);
};
export type CustomClientStrategyHandler = {
getLocale: () => Promise<string | undefined> | (string | undefined);
setLocale: (locale: string) => Promise<void> | void;
};
/**
* A locale that is available in the project.
*/
export type Locale = (typeof locales)[number];
/**
* A branded type representing a localized string.
*
* Message functions return this type instead of \`string\`, enabling TypeScript
* to distinguish translated strings from regular strings at compile time.
* This allows you to enforce that only properly localized content is used
* in your UI components.
*
* Since \`LocalizedString\` is a branded subtype of \`string\`, it remains fully
* backward compatible—you can pass it anywhere a \`string\` is expected.
*/
export type LocalizedString = string & {
readonly __brand: "LocalizedString";
};
/**
* A single markup option passed to a tag instance.
*/
export type MessageMarkupOption = {
name: string;
value: unknown;
};
/**
* A single static markup attribute attached to a tag instance.
*/
export type MessageMarkupAttribute = {
name: string;
value: string | true;
};
/**
* Record of markup options for a tag instance.
*/
export type MessageMarkupOptions = Record<string, unknown>;
/**
* Record of markup attributes for a tag instance.
*/
export type MessageMarkupAttributes = Record<string, string | true>;
/**
* Type-level schema for a single markup tag.
*/
export type MessageMarkupTag = {
options: MessageMarkupOptions;
attributes: MessageMarkupAttributes;
children: boolean;
};
/**
* Type-level schema for all markup tags in a message.
*/
export type MessageMarkupSchema = Record<string, MessageMarkupTag>;
/**
* Type-only metadata attached to compiled message functions.
*/
export type MessageMetadata<Inputs, Options, Markup extends MessageMarkupSchema = Record<string, MessageMarkupTag>> = {
readonly __paraglide?: {
inputs: Inputs;
options: Options;
markup: Markup;
};
};
/**
* A compiled, framework-neutral message part.
*/
export type MessagePart = {
type: "text";
value: string;
} | {
type: "markup-start";
name: string;
options: MessageMarkupOptions;
attributes: MessageMarkupAttributes;
} | {
type: "markup-end";
name: string;
options: MessageMarkupOptions;
attributes: MessageMarkupAttributes;
} | {
type: "markup-standalone";
name: string;
options: MessageMarkupOptions;
attributes: MessageMarkupAttributes;
};
/**
* A message function is a message for a specific locale.
*/
export type MessageFunction = (inputs?: Record<string, never>) => LocalizedString;
/**
* A message bundle function that selects the message to be returned.
*
* Uses `getLocale()` under the hood to determine the locale with an option.
*/
export type MessageBundleFunction<T extends string> = (params: Record<string, never>, options: {
locale: T;
}) => LocalizedString;
File diff suppressed because it is too large Load Diff
+96
View File
@@ -0,0 +1,96 @@
/**
* Server middleware that handles locale-based routing and request processing.
*
* Configure `disableAsyncLocalStorage` when generating Paraglide with
* `paraglideVitePlugin()` or `compile()`, not when calling
* `paraglideMiddleware()`. Keep AsyncLocalStorage enabled by default and
* only disable it for runtimes that lack `AsyncLocalStorage` support and
* guarantee request isolation.
*
* This middleware performs several key functions:
*
* 1. Determines the locale for the incoming request using configured strategies
* 2. Handles URL localization and redirects (only for document requests)
* 3. Maintains locale state using AsyncLocalStorage to prevent request interference
*
* When URL strategy is used:
*
* - The locale is extracted from the URL for all request types
* - If URL doesn't match the determined locale, redirects to localized URL (only for document requests)
* - De-localizes URLs before passing to server (e.g., `/fr/about` → `/about`)
*
* @see https://paraglidejs.com/middleware
*
* @template T - The return type of the resolve function
*
* @param {Request} request - The incoming request object
* @param {(args: { request: Request, locale: import("./runtime.js").Locale }) => T | Promise<T>} resolve - Function to handle the request. The callback receives:
* - `request`: A modified request with a delocalized URL when the URL strategy is used (e.g., `/fr/about` → `/about`).
* If your framework handles URL localization itself (e.g., TanStack Router's `rewrite` option), use the original
* request instead to avoid redirect loops.
* - `locale`: The determined locale for this request.
* @param {{
* effectiveRequestUrl?: string | URL | ((request: Request) => string | URL),
* onRedirect?: (response: Response) => void
* }} [options] - Options to control middleware behavior. `effectiveRequestUrl` sets the effective request URL used for route matching, URL-based locale detection, redirects, and `getUrlOrigin()`.
* @returns {Promise<Response>}
*
* @example
* ```typescript
* // Basic usage in metaframeworks like NextJS, SvelteKit, Astro, Nuxt, etc.
* export const handle = async ({ event, resolve }) => {
* return paraglideMiddleware(event.request, ({ request, locale }) => {
* // let the framework further resolve the request
* return resolve(request);
* });
* };
* ```
*
* @example
* ```typescript
* // Usage in a framework like Express JS or Hono
* app.use(async (req, res, next) => {
* const result = await paraglideMiddleware(req, ({ request, locale }) => {
* // If a redirect happens this won't be called
* return next(request);
* });
* });
* ```
*
* @example
* ```typescript
* // Usage with frameworks that handle URL localization/delocalization themselves
* //
* // Some frameworks like TanStack Router handle URL localization and delocalization
* // themselves via their own rewrite APIs (e.g., `rewrite.input`/`rewrite.output`).
* //
* // When the framework handles this, the middleware's URL delocalization is not needed.
* // Using the modified `request` from the callback would cause a redirect loop because
* // both the middleware and the framework would attempt to delocalize the URL.
* //
* // Solution: Pass the original request to the handler instead of the modified one.
* // The middleware still handles locale detection, cookies, and AsyncLocalStorage context.
* //
* // ❌ WRONG - causes redirect loop when framework handles URL rewriting:
* // paraglideMiddleware(req, ({ request }) => handler.fetch(request))
* //
* // ✅ CORRECT - use original request when framework handles URL localization:
* // paraglideMiddleware(req, () => handler.fetch(req))
*
* * *
* export default {
* fetch(req: Request): Promise<Response> {
* // TanStack Router handles URL rewriting via deLocalizeUrl/localizeUrl
* // so we pass the original `req` instead of the modified `request`
* return paraglideMiddleware(req, () => handler.fetch(req))
* },
* }
* ```
*/
export function paraglideMiddleware<T>(request: Request, resolve: (args: {
request: Request;
locale: import("./runtime.js").Locale;
}) => T | Promise<T>, options?: {
effectiveRequestUrl?: string | URL | ((request: Request) => string | URL);
onRedirect?: (response: Response) => void;
}): Promise<Response>;
+282
View File
@@ -0,0 +1,282 @@
/* eslint-disable */
import * as runtime from "./runtime.js";
/**
* Server middleware that handles locale-based routing and request processing.
*
* Configure `disableAsyncLocalStorage` when generating Paraglide with
* `paraglideVitePlugin()` or `compile()`, not when calling
* `paraglideMiddleware()`. Keep AsyncLocalStorage enabled by default and
* only disable it for runtimes that lack `AsyncLocalStorage` support and
* guarantee request isolation.
*
* This middleware performs several key functions:
*
* 1. Determines the locale for the incoming request using configured strategies
* 2. Handles URL localization and redirects (only for document requests)
* 3. Maintains locale state using AsyncLocalStorage to prevent request interference
*
* When URL strategy is used:
*
* - The locale is extracted from the URL for all request types
* - If URL doesn't match the determined locale, redirects to localized URL (only for document requests)
* - De-localizes URLs before passing to server (e.g., `/fr/about` → `/about`)
*
* @see https://paraglidejs.com/middleware
*
* @template T - The return type of the resolve function
*
* @param {Request} request - The incoming request object
* @param {(args: { request: Request, locale: import("./runtime.js").Locale }) => T | Promise<T>} resolve - Function to handle the request. The callback receives:
* - `request`: A modified request with a delocalized URL when the URL strategy is used (e.g., `/fr/about` → `/about`).
* If your framework handles URL localization itself (e.g., TanStack Router's `rewrite` option), use the original
* request instead to avoid redirect loops.
* - `locale`: The determined locale for this request.
* @param {{
* effectiveRequestUrl?: string | URL | ((request: Request) => string | URL),
* onRedirect?: (response: Response) => void
* }} [options] - Options to control middleware behavior. `effectiveRequestUrl` sets the effective request URL used for route matching, URL-based locale detection, redirects, and `getUrlOrigin()`.
* @returns {Promise<Response>}
*
* @example
* ```typescript
* // Basic usage in metaframeworks like NextJS, SvelteKit, Astro, Nuxt, etc.
* export const handle = async ({ event, resolve }) => {
* return paraglideMiddleware(event.request, ({ request, locale }) => {
* // let the framework further resolve the request
* return resolve(request);
* });
* };
* ```
*
* @example
* ```typescript
* // Usage in a framework like Express JS or Hono
* app.use(async (req, res, next) => {
* const result = await paraglideMiddleware(req, ({ request, locale }) => {
* // If a redirect happens this won't be called
* return next(request);
* });
* });
* ```
*
* @example
* ```typescript
* // Usage with frameworks that handle URL localization/delocalization themselves
* //
* // Some frameworks like TanStack Router handle URL localization and delocalization
* // themselves via their own rewrite APIs (e.g., `rewrite.input`/`rewrite.output`).
* //
* // When the framework handles this, the middleware's URL delocalization is not needed.
* // Using the modified `request` from the callback would cause a redirect loop because
* // both the middleware and the framework would attempt to delocalize the URL.
* //
* // Solution: Pass the original request to the handler instead of the modified one.
* // The middleware still handles locale detection, cookies, and AsyncLocalStorage context.
* //
* // ❌ WRONG - causes redirect loop when framework handles URL rewriting:
* // paraglideMiddleware(req, ({ request }) => handler.fetch(request))
* //
* // ✅ CORRECT - use original request when framework handles URL localization:
* // paraglideMiddleware(req, () => handler.fetch(req))
*
* * *
* export default {
* fetch(req: Request): Promise<Response> {
* // TanStack Router handles URL rewriting via deLocalizeUrl/localizeUrl
* // so we pass the original `req` instead of the modified `request`
* return paraglideMiddleware(req, () => handler.fetch(req))
* },
* }
* ```
*/
export async function paraglideMiddleware(request, resolve, options) {
if (!runtime.disableAsyncLocalStorage && !runtime.serverAsyncLocalStorage) {
const { AsyncLocalStorage } = await import("async_hooks");
runtime.overwriteServerAsyncLocalStorage(new AsyncLocalStorage());
} else if (!runtime.serverAsyncLocalStorage) {
runtime.overwriteServerAsyncLocalStorage(createMockAsyncLocalStorage());
}
const url = resolveMiddlewareUrl(request, options?.effectiveRequestUrl);
const origin = url.origin;
if (runtime.isExcludedByRouteStrategy(url.href)) {
const locale = runtime.baseLocale;
const newRequest = cloneRequestWithFallback(request, url);
/** @type {Set<string>} */
const messageCalls = new Set();
return /** @type {Response} */ (await runtime.serverAsyncLocalStorage?.run({ locale, origin, messageCalls }, () => resolve({ locale, request: newRequest })));
}
const strategy = runtime.getStrategyForUrl(url.href);
const decision = await runtime.shouldRedirect({ request, effectiveRequestUrl: url });
const locale = decision.locale;
// if the client makes a request to a URL that doesn't match
// the localizedUrl, redirect the client to the localized URL
if (request.headers.get("Sec-Fetch-Dest") === "document" &&
decision.shouldRedirect &&
decision.redirectUrl) {
// Create headers object with Vary header if preferredLanguage strategy is used
/** @type {Record<string, string>} */
const headers = {};
if (strategy.includes("preferredLanguage")) {
headers["Vary"] = "Accept-Language";
}
const response = new Response(null, {
status: 307,
headers: {
Location: decision.redirectUrl.href,
...headers,
},
});
options?.onRedirect?.(response);
return response;
}
// If the strategy includes "url", we need to de-localize the URL
// before passing it to the server middleware.
//
// The middleware is responsible for mapping a localized URL to the
// de-localized URL e.g. `/en/about` to `/about`. Otherwise,
// the server can't render the correct page.
let newRequest;
if (strategy.includes("url")) {
newRequest = cloneRequestWithFallback(request, runtime.deLocalizeUrl(url));
}
else {
newRequest = cloneRequestWithFallback(request, url);
}
// the message functions that have been called in this request
/** @type {Set<string>} */
const messageCalls = new Set();
const response = await runtime.serverAsyncLocalStorage?.run({ locale, origin, messageCalls }, () => resolve({ locale, request: newRequest }));
// Only modify HTML responses
if (runtime.experimentalMiddlewareLocaleSplitting &&
response.headers.get("Content-Type")?.includes("html")) {
const body = await response.text();
const messages = [];
// using .values() to avoid polyfilling in older projects. else the following error is thrown
// Type 'Set<string>' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher.
for (const messageCall of Array.from(messageCalls)) {
const [id, locale] =
/** @type {[string, import("./runtime.js").Locale]} */ (messageCall.split(":"));
messages.push(`${id}: ${compiledBundles[id]?.[locale]}`);
}
// Prevent translated content from terminating the inline script tag.
const escapedMessages = messages
.join(",")
.replace(/<\/(script)/gi, "<\\/$1");
// Reuse the request's CSP nonce (if any) so the injected script is allowed under a strict CSP
const nonce = response.headers
.get("Content-Security-Policy")
?.match(/'nonce-([\w+/=-]+)'/)?.[1];
const nonceAttr = nonce ? `nonce="${nonce}"` : "";
const script = `<script ${nonceAttr}>globalThis.__paraglide = globalThis.__paraglide ?? {}; globalThis.__paraglide.ssr = { ${escapedMessages} }</script>`;
// Insert the script before the closing head tag
const newBody = body.replace("</head>", `${script}</head>`);
// Create a new response with the modified body
// Clone all headers except Content-Length which will be set automatically
const newHeaders = new Headers(response.headers);
newHeaders.delete("Content-Length"); // Let the browser calculate the correct length
return new Response(newBody, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
}
return response;
}
/**
* @param {Request} request
* @param {string | URL | ((request: Request) => string | URL) | undefined} effectiveRequestUrl
* @returns {URL}
*/
function resolveMiddlewareUrl(request, effectiveRequestUrl) {
if (typeof effectiveRequestUrl === "function") {
return new URL(effectiveRequestUrl(request), request.url);
}
if (typeof effectiveRequestUrl === "string" || effectiveRequestUrl instanceof URL) {
return new URL(effectiveRequestUrl, request.url);
}
return new URL(request.url);
}
/**
* Some metaframeworks (NextJS) require a new Request object.
* https://github.com/opral/inlang-paraglide-js/issues/411
*
* However, some frameworks (TanStack Start 1.143+) use custom Request
* implementations that cannot be cloned with `new Request(request)`.
* https://github.com/opral/paraglide-js/issues/573
*
* Effective request URL overrides behind proxies:
* https://github.com/opral/paraglide-js/issues/652
*
* @param {Request} request
* @param {string | URL} [url]
* @returns {Request}
*/
function cloneRequestWithFallback(request, url = request.url) {
const targetUrl = typeof url === "string" ? url : url.href;
if (targetUrl === request.url) {
try {
// Clone first so building a new Request does not consume the original body stream.
return new Request(request.clone());
}
catch {
try {
return new Request(request);
}
catch {
return request;
}
}
}
try {
// Clone first so building a new Request does not consume the original body stream.
return new Request(targetUrl, request.clone());
}
catch {
try {
return new Request(targetUrl, request);
}
catch {
return request;
}
}
}
/**
* Creates a mock AsyncLocalStorage implementation for environments where
* native AsyncLocalStorage is not available or disabled.
*
* This mock implementation mimics the behavior of the native AsyncLocalStorage
* but doesn't require the async_hooks module. It's used as a fallback when
* the runtime does not expose AsyncLocalStorage or when it has been disabled.
*
* @returns {import("./runtime.js").ParaglideAsyncLocalStorage}
*/
function createMockAsyncLocalStorage() {
/** @type {any} */
let currentStore = undefined;
return {
getStore() {
return currentStore;
},
async run(store, callback) {
currentStore = store;
try {
return await callback();
}
finally {
currentStore = undefined;
}
},
};
}
// Used in generated server.js when async local storage is disabled.
void createMockAsyncLocalStorage;
/**
* The compiled messages for the server middleware.
*
* Only populated if `enableMiddlewareOptimizations` is set to `true`.
*
* @type {Record<string, Record<import("./runtime.js").Locale, string>>}
*/
const compiledBundles = {};