ts-intl-astro 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aaakul
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,121 @@
1
+ # ts-intl-astro
2
+
3
+ [English](./README.md) | [简体中文](./README.zh-Hans.md) | [日本語](./README.ja-JP.md)
4
+
5
+ [`ts-intl`](https://github.com/aaakul/ts-intl) をベースにした、軽量・ゼロ設定・厳格な型安全性を備えた Astro 向け国際化(i18n)インテグレーションです。Astro において `next-intl` に近い開発体験を提供します。
6
+
7
+ ## インストール
8
+
9
+ ```bash
10
+ pnpm add ts-intl-astro
11
+ # または
12
+ npm install ts-intl-astro
13
+ # または
14
+ yarn add ts-intl-astro
15
+ ```
16
+
17
+ ## クイック設定
18
+
19
+ ### i18n インスタンスの初期化
20
+
21
+ プロジェクト内に `src/i18n/index.ts` を作成します:
22
+
23
+ ```ts
24
+ import { createAstroI18n } from "ts-intl-astro";
25
+ import enUS from "./messages/en-US";
26
+ import zhHans from "./messages/zh-Hans";
27
+
28
+ export const {
29
+ useTranslations,
30
+ useLocale,
31
+ useFormatter,
32
+ languages,
33
+ defaultLanguage,
34
+ } = createAstroI18n({
35
+ defaultLanguage: "en-US",
36
+ messages: {
37
+ "en-US": enUS,
38
+ "zh-Hans": zhHans,
39
+ },
40
+ });
41
+
42
+ export type SupportedLanguage = (typeof languages)[number];
43
+ ```
44
+
45
+ ### Astro インテグレーションの登録
46
+
47
+ `astro.config.mjs` に `tsIntl` インテグレーションを追加します:
48
+
49
+ ```js
50
+ import { defineConfig } from "astro/config";
51
+ import tsIntl from "ts-intl-astro";
52
+
53
+ export default defineConfig({
54
+ integrations: [tsIntl()],
55
+ });
56
+ ```
57
+
58
+ ## 使い方
59
+
60
+ ### コンポーネント内での利用
61
+
62
+ 任意の Astro コンポーネント内で、`useTranslations` と `useLocale` を直接呼び出します。
63
+
64
+ ```astro
65
+ ---
66
+ import { useTranslations, useLocale } from "@/i18n";
67
+
68
+ const t = useTranslations("hero");
69
+ const currentLang = useLocale();
70
+ ---
71
+
72
+ <section>
73
+ <h1>{t("title")}</h1>
74
+ <p>{t("badge")}</p>
75
+ <a href={`/${currentLang}/docs`}>{t("getStarted")}</a>
76
+ </section>
77
+ ```
78
+
79
+ ### ルートセグメントとページ設定(Route Segments)
80
+
81
+ 動的ルートディレクトリ構造(例:`src/pages/[lang]/index.astro` や `src/pages/[locale]/about.astro`)を用いて多言語ページを管理します。
82
+
83
+ 静的サイト生成(SSG)では、エクスポートされた `languages` と組み合わせて `getStaticPaths` を設定します:
84
+
85
+ ```astro
86
+ ---
87
+ // src/pages/[lang]/index.astro
88
+ import { languages, useTranslations, useLocale } from "@/i18n";
89
+
90
+ export function getStaticPaths() {
91
+ return languages.map((lang) => ({ params: { lang } }));
92
+ }
93
+
94
+ const t = useTranslations("hero");
95
+ const lang = useLocale();
96
+ ---
97
+
98
+ <section>
99
+ <h1>{t("title")}</h1>
100
+ <a href={`/${lang}/docs`}>{t("getStarted")}</a>
101
+ </section>
102
+ ```
103
+
104
+ > **ルートセグメントに関する説明**:
105
+ >
106
+ > - `ts-intl-astro` は、デフォルトで `[lang]` および `[locale]` 動的ルートセグメントを自動認識します。
107
+ > - ミドルウェアがページ実行前にルートセグメントから言語を自動抽出し、コンテキストに書き込みます。ページ内の任意の子コンポーネントから直接 `useTranslations()` / `useLocale()` で現在の言語を取得できるため、`lang` 属性を手動でバケツリレー(Props Drilling)する必要はありません。
108
+ > - カスタムパラメータ名(例:`[localeCode]`)を使用する場合は、`createAstroI18n({ paramNames: ["localeCode"] })` で設定できます。
109
+
110
+ ## よく使う API
111
+
112
+ | API | 説明 | 例 |
113
+ | :-------------------------------- | :--------------------------------------------------------- | :--------------------------------------------- |
114
+ | `useTranslations(namespace?)` | 現在の言語にバインドされた翻訳関数を取得します | `const t = useTranslations("common")` |
115
+ | `useTranslations(ns, { locale })` | 現在のコンポーネントの言語を明示的に上書きします | `useTranslations("hero", { locale: "ja-JP" })` |
116
+ | `useLocale()` | 現在のリクエストコンテキストの言語識別子文字列を取得します | `const lang = useLocale()` |
117
+ | `useFormatter()` | 現在の言語の `Intl` フォーマッターを取得します | `const fmt = useFormatter()` |
118
+
119
+ ## ライセンス
120
+
121
+ [MIT](./LICENSE)
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # ts-intl-astro
2
+
3
+ [English](./README.md) | [简体中文](./README.zh-Hans.md) | [日本語](./README.ja-JP.md)
4
+
5
+ A lightweight, zero-config, strictly type-safe Astro integration for internationalization (i18n), powered by [`ts-intl`](https://github.com/aaakul/ts-intl). Delivers a developer experience similar to `next-intl` in Astro.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pnpm add ts-intl-astro
11
+ # or
12
+ npm install ts-intl-astro
13
+ # or
14
+ yarn add ts-intl-astro
15
+ ```
16
+
17
+ ## Quick Setup
18
+
19
+ ### Initialize the i18n Instance
20
+
21
+ Create `src/i18n/index.ts` in your project:
22
+
23
+ ```ts
24
+ import { createAstroI18n } from "ts-intl-astro";
25
+ import enUS from "./messages/en-US";
26
+ import zhHans from "./messages/zh-Hans";
27
+
28
+ export const {
29
+ useTranslations,
30
+ useLocale,
31
+ useFormatter,
32
+ languages,
33
+ defaultLanguage,
34
+ } = createAstroI18n({
35
+ defaultLanguage: "en-US",
36
+ messages: {
37
+ "en-US": enUS,
38
+ "zh-Hans": zhHans,
39
+ },
40
+ });
41
+
42
+ export type SupportedLanguage = (typeof languages)[number];
43
+ ```
44
+
45
+ ### Register the Astro Integration
46
+
47
+ Add the `tsIntl` integration to `astro.config.mjs`:
48
+
49
+ ```js
50
+ import { defineConfig } from "astro/config";
51
+ import tsIntl from "ts-intl-astro";
52
+
53
+ export default defineConfig({
54
+ integrations: [tsIntl()],
55
+ });
56
+ ```
57
+
58
+ ## Usage
59
+
60
+ ### In Components
61
+
62
+ In any Astro component, call `useTranslations` and `useLocale` directly.
63
+
64
+ ```astro
65
+ ---
66
+ import { useTranslations, useLocale } from "@/i18n";
67
+
68
+ const t = useTranslations("hero");
69
+ const currentLang = useLocale();
70
+ ---
71
+
72
+ <section>
73
+ <h1>{t("title")}</h1>
74
+ <p>{t("badge")}</p>
75
+ <a href={`/${currentLang}/docs`}>{t("getStarted")}</a>
76
+ </section>
77
+ ```
78
+
79
+ ### Route Segments and Page Configuration (Route Segments)
80
+
81
+ Manage multilingual pages using dynamic route directory structures (e.g. `src/pages/[lang]/index.astro` or `src/pages/[locale]/about.astro`).
82
+
83
+ For Static Site Generation (SSG), configure `getStaticPaths` with the exported `languages`:
84
+
85
+ ```astro
86
+ ---
87
+ // src/pages/[lang]/index.astro
88
+ import { languages, useTranslations, useLocale } from "@/i18n";
89
+
90
+ export function getStaticPaths() {
91
+ return languages.map((lang) => ({ params: { lang } }));
92
+ }
93
+
94
+ const t = useTranslations("hero");
95
+ const lang = useLocale();
96
+ ---
97
+
98
+ <section>
99
+ <h1>{t("title")}</h1>
100
+ <a href={`/${lang}/docs`}>{t("getStarted")}</a>
101
+ </section>
102
+ ```
103
+
104
+ > **Route Segments Note**:
105
+ >
106
+ > - `ts-intl-astro` automatically recognizes `[lang]` and `[locale]` dynamic route segments by default.
107
+ > - The middleware automatically extracts the locale from the route segment before page execution and writes it into the context. Any child components within the page can directly access the current locale via `useTranslations()` / `useLocale()`, with no need to drill the `lang` prop down manually.
108
+ > - If you use custom parameter names (e.g. `[localeCode]`), configure them via `createAstroI18n({ paramNames: ["localeCode"] })`.
109
+
110
+ ## Common APIs
111
+
112
+ | API | Description | Example |
113
+ | :-------------------------------- | :------------------------------------------------------- | :--------------------------------------------- |
114
+ | `useTranslations(namespace?)` | Get the translation function bound to the active locale | `const t = useTranslations("common")` |
115
+ | `useTranslations(ns, { locale })` | Explicitly override the locale for the current component | `useTranslations("hero", { locale: "ja-JP" })` |
116
+ | `useLocale()` | Get the locale string from the current request context | `const lang = useLocale()` |
117
+ | `useFormatter()` | Get the `Intl` formatter for the current locale | `const fmt = useFormatter()` |
118
+
119
+ ## License
120
+
121
+ [MIT](./LICENSE)
@@ -0,0 +1,121 @@
1
+ # ts-intl-astro
2
+
3
+ [English](./README.md) | [简体中文](./README.zh-Hans.md) | [日本語](./README.ja-JP.md)
4
+
5
+ 轻量、零配置、严格类型安全的国际化(i18n) Astro 集成,基于 [`ts-intl`](https://github.com/aaakul/ts-intl)。在 Astro 中提供与 `next-intl` 相似的使用体验。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ pnpm add ts-intl-astro
11
+ # 或
12
+ npm install ts-intl-astro
13
+ # 或
14
+ yarn add ts-intl-astro
15
+ ```
16
+
17
+ ## 快速配置
18
+
19
+ ### 初始化 i18n 实例
20
+
21
+ 在项目中创建 `src/i18n/index.ts`:
22
+
23
+ ```ts
24
+ import { createAstroI18n } from "ts-intl-astro";
25
+ import enUS from "./messages/en-US";
26
+ import zhHans from "./messages/zh-Hans";
27
+
28
+ export const {
29
+ useTranslations,
30
+ useLocale,
31
+ useFormatter,
32
+ languages,
33
+ defaultLanguage,
34
+ } = createAstroI18n({
35
+ defaultLanguage: "en-US",
36
+ messages: {
37
+ "en-US": enUS,
38
+ "zh-Hans": zhHans,
39
+ },
40
+ });
41
+
42
+ export type SupportedLanguage = (typeof languages)[number];
43
+ ```
44
+
45
+ ### 注册 Astro 集成
46
+
47
+ 在 `astro.config.mjs` 中添加 `tsIntl` 集成:
48
+
49
+ ```js
50
+ import { defineConfig } from "astro/config";
51
+ import tsIntl from "ts-intl-astro";
52
+
53
+ export default defineConfig({
54
+ integrations: [tsIntl()],
55
+ });
56
+ ```
57
+
58
+ ## 使用
59
+
60
+ ### 组件内使用
61
+
62
+ 在任何 Astro 组件中,直接调用 `useTranslations` 与 `useLocale`。
63
+
64
+ ```astro
65
+ ---
66
+ import { useTranslations, useLocale } from "@/i18n";
67
+
68
+ const t = useTranslations("hero");
69
+ const currentLang = useLocale();
70
+ ---
71
+
72
+ <section>
73
+ <h1>{t("title")}</h1>
74
+ <p>{t("badge")}</p>
75
+ <a href={`/${currentLang}/docs`}>{t("getStarted")}</a>
76
+ </section>
77
+ ```
78
+
79
+ ### 路由段与页面配置(Route Segments)
80
+
81
+ 通过动态路由目录结构管理多语言页面(如 `src/pages/[lang]/index.astro` 或 `src/pages/[locale]/about.astro`)。
82
+
83
+ 在静态生成(SSG)中,配合导出的 `languages` 配置 `getStaticPaths`:
84
+
85
+ ```astro
86
+ ---
87
+ // src/pages/[lang]/index.astro
88
+ import { languages, useTranslations, useLocale} from "@/i18n";
89
+
90
+ export function getStaticPaths() {
91
+ return languages.map((lang) => ({ params: { lang } }));
92
+ }
93
+
94
+ const t = useTranslations("hero");
95
+ const lang = useLocale();
96
+ ---
97
+
98
+ <section>
99
+ <h1>{t("title")}</h1>
100
+ <a href={`/${lang}/docs`}>{t("getStarted")}</a>
101
+ </section>
102
+ ```
103
+
104
+ > **路由段说明**:
105
+ >
106
+ > - `ts-intl-astro` 默认自动识别 `[lang]` 与 `[locale]` 动态路由段。
107
+ > - 中间件会在页面执行前自动提取路由段中的语言并写入上下文,页面内部的任意子组件均可直接通过 `useTranslations()` / `useLocale()` 获取当前语言,无需手动逐层传递 `lang` 属性。
108
+ > - 若使用自定义参数名(如 `[localeCode]`),可在 `createAstroI18n({ paramNames: ["localeCode"] })` 中配置。
109
+
110
+ ## 常用 API
111
+
112
+ | API | 说明 | 示例 |
113
+ | :-------------------------------- | :--------------------------------- | :--------------------------------------------- |
114
+ | `useTranslations(namespace?)` | 获取当前语言绑定的翻译函数 | `const t = useTranslations("common")` |
115
+ | `useTranslations(ns, { locale })` | 显式覆盖当前组件的语言 | `useTranslations("hero", { locale: "ja-JP" })` |
116
+ | `useLocale()` | 获取当前请求上下文的语言标识字符串 | `const lang = useLocale()` |
117
+ | `useFormatter()` | 获取当前语言的 `Intl` 格式化器 | `const fmt = useFormatter()` |
118
+
119
+ ## 开源协议
120
+
121
+ [MIT](./LICENSE)
@@ -0,0 +1,105 @@
1
+ 'use strict';
2
+
3
+ var async_hooks = require('async_hooks');
4
+
5
+ // src/context.ts
6
+ var STORAGE_KEY = /* @__PURE__ */ Symbol.for("ts-intl-astro/storage");
7
+ var FALLBACK_LANG_KEY = /* @__PURE__ */ Symbol.for("ts-intl-astro/fallbackLang");
8
+ var g = globalThis;
9
+ var i18nStorage = g[STORAGE_KEY] || (g[STORAGE_KEY] = new async_hooks.AsyncLocalStorage());
10
+ function setGlobalFallbackLanguage(lang) {
11
+ g[FALLBACK_LANG_KEY] = lang;
12
+ }
13
+ function getGlobalFallbackLanguage() {
14
+ return g[FALLBACK_LANG_KEY] || "en";
15
+ }
16
+ function getActiveLocale(fallback) {
17
+ const store = i18nStorage.getStore();
18
+ if (store?.locale) {
19
+ return store.locale;
20
+ }
21
+ return fallback || getGlobalFallbackLanguage();
22
+ }
23
+ function runWithLocale(locale, fn) {
24
+ return i18nStorage.run({ locale }, fn);
25
+ }
26
+
27
+ // src/resolver.ts
28
+ function resolveRequestLocale(context, options) {
29
+ const {
30
+ supportedLanguages,
31
+ defaultLanguage,
32
+ paramNames = ["lang", "locale"]
33
+ } = options;
34
+ if (context.currentLocale && supportedLanguages.includes(context.currentLocale)) {
35
+ return context.currentLocale;
36
+ }
37
+ if (context.params) {
38
+ for (const name of paramNames) {
39
+ const paramVal = context.params[name];
40
+ if (paramVal && supportedLanguages.includes(paramVal)) {
41
+ return paramVal;
42
+ }
43
+ }
44
+ }
45
+ if (context.url && context.url.pathname) {
46
+ const segments = context.url.pathname.split("/").filter(Boolean);
47
+ for (const segment of segments) {
48
+ if (supportedLanguages.includes(segment)) {
49
+ return segment;
50
+ }
51
+ }
52
+ }
53
+ return defaultLanguage;
54
+ }
55
+
56
+ // src/middleware.ts
57
+ var OPTIONS_KEY = /* @__PURE__ */ Symbol.for("ts-intl-astro/middlewareOptions");
58
+ var SAFE_LOCALE_PATTERN = /^[a-zA-Z0-9_-]{2,16}$/;
59
+ var g2 = globalThis;
60
+ function setGlobalMiddlewareOptions(options) {
61
+ g2[OPTIONS_KEY] = options;
62
+ }
63
+ function getGlobalMiddlewareOptions() {
64
+ return g2[OPTIONS_KEY];
65
+ }
66
+ function createI18nMiddleware(options) {
67
+ return async (context, next) => {
68
+ const locale = resolveRequestLocale(context, options);
69
+ if (!context.locals) {
70
+ context.locals = {};
71
+ }
72
+ context.locals.locale = locale;
73
+ context.locals.lang = locale;
74
+ return runWithLocale(locale, () => next());
75
+ };
76
+ }
77
+ var onRequest = async (context, next) => {
78
+ const options = getGlobalMiddlewareOptions();
79
+ let locale;
80
+ if (options) {
81
+ locale = resolveRequestLocale(context, options);
82
+ } else {
83
+ const candidate = context.currentLocale || context.params?.lang || context.params?.locale;
84
+ const fallback = getGlobalFallbackLanguage();
85
+ locale = candidate && SAFE_LOCALE_PATTERN.test(candidate) ? candidate : fallback;
86
+ }
87
+ if (!context.locals) {
88
+ context.locals = {};
89
+ }
90
+ context.locals.locale = locale;
91
+ context.locals.lang = locale;
92
+ return runWithLocale(locale, () => next());
93
+ };
94
+
95
+ exports.createI18nMiddleware = createI18nMiddleware;
96
+ exports.getActiveLocale = getActiveLocale;
97
+ exports.getGlobalMiddlewareOptions = getGlobalMiddlewareOptions;
98
+ exports.i18nStorage = i18nStorage;
99
+ exports.onRequest = onRequest;
100
+ exports.resolveRequestLocale = resolveRequestLocale;
101
+ exports.runWithLocale = runWithLocale;
102
+ exports.setGlobalFallbackLanguage = setGlobalFallbackLanguage;
103
+ exports.setGlobalMiddlewareOptions = setGlobalMiddlewareOptions;
104
+ //# sourceMappingURL=chunk-25H6BZD6.cjs.map
105
+ //# sourceMappingURL=chunk-25H6BZD6.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.ts","../src/resolver.ts","../src/middleware.ts"],"names":["AsyncLocalStorage","g"],"mappings":";;;;;AAGA,IAAM,WAAA,mBAAc,MAAA,CAAO,GAAA,CAAI,uBAAuB,CAAA;AACtD,IAAM,iBAAA,mBAAoB,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAA;AAOjE,IAAM,CAAA,GAAI,UAAA;AAEH,IAAM,WAAA,GACX,EAAE,WAAW,CAAA,KACZ,EAAE,WAAW,CAAA,GAAI,IAAIA,6BAAA,EAAoC;AAKrD,SAAS,0BAA0B,IAAA,EAAoB;AAC5D,EAAA,CAAA,CAAE,iBAAiB,CAAA,GAAI,IAAA;AACzB;AAEO,SAAS,yBAAA,GAAoC;AAClD,EAAA,OAAO,CAAA,CAAE,iBAAiB,CAAA,IAAK,IAAA;AACjC;AAMO,SAAS,gBAAgB,QAAA,EAA2B;AACzD,EAAA,MAAM,KAAA,GAAQ,YAAY,QAAA,EAAS;AACnC,EAAA,IAAI,OAAO,MAAA,EAAQ;AACjB,IAAA,OAAO,KAAA,CAAM,MAAA;AAAA,EACf;AACA,EAAA,OAAO,YAAY,yBAAA,EAA0B;AAC/C;AAKO,SA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AAO,MAAA;AAEtB,EAAA,OAAO,aAAA,CAAc,MAAA,EAAQ,MAAM,IAAA,EAAM,CAAA;AAC3C","file":"chunk-25H6BZD6.cjs","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { I18nContextStore } from \"./types\";\n\nconst STORAGE_KEY = Symbol.for(\"ts-intl-astro/storage\");\nconst FALLBACK_LANG_KEY = Symbol.for(\"ts-intl-astro/fallbackLang\");\n\ntype GlobalThisWithStorage = typeof globalThis & {\n [STORAGE_KEY]?: AsyncLocalStorage<I18nContextStore>;\n [FALLBACK_LANG_KEY]?: string;\n};\n\nconst g = globalThis as GlobalThisWithStorage;\n\nexport const i18nStorage: AsyncLocalStorage<I18nContextStore> =\n g[STORAGE_KEY] ||\n (g[STORAGE_KEY] = new AsyncLocalStorage<I18nContextStore>());\n\n/**\n * Sets a global fallback language when no active context is found.\n */\nexport function setGlobalFallbackLanguage(lang: string): void {\n g[FALLBACK_LANG_KEY] = lang;\n}\n\nexport function getGlobalFallbackLanguage(): string {\n return g[FALLBACK_LANG_KEY] || \"en\";\n}\n\n/**\n * Gets the current active locale from AsyncLocalStorage.\n * Falls back to globalFallbackLanguage if no context has been established.\n */\nexport function getActiveLocale(fallback?: string): string {\n const store = i18nStorage.getStore();\n if (store?.locale) {\n return store.locale;\n }\n return fallback || getGlobalFallbackLanguage();\n}\n\n/**\n * Executes a callback within an isolated i18n context for the specified locale.\n */\nexport function runWithLocale<T>(locale: string, fn: () => T): T {\n return i18nStorage.run({ locale }, fn);\n}\n","import type { AstroCompatibleContext } from \"./types\";\n\nexport interface ResolveLocaleOptions {\n supportedLanguages: readonly string[];\n defaultLanguage: string;\n paramNames?: string[];\n}\n\n/**\n * Resolves the request locale from context.currentLocale, route params, or URL path segments.\n */\nexport function resolveRequestLocale(\n context: AstroCompatibleContext,\n options: ResolveLocaleOptions,\n): string {\n const {\n supportedLanguages,\n defaultLanguage,\n paramNames = [\"lang\", \"locale\"],\n } = options;\n\n if (\n context.currentLocale &&\n supportedLanguages.includes(context.currentLocale)\n ) {\n return context.currentLocale;\n }\n\n if (context.params) {\n for (const name of paramNames) {\n const paramVal = context.params[name];\n if (paramVal && supportedLanguages.includes(paramVal)) {\n return paramVal;\n }\n }\n }\n\n if (context.url && context.url.pathname) {\n const segments = context.url.pathname.split(\"/\").filter(Boolean);\n for (const segment of segments) {\n if (supportedLanguages.includes(segment)) {\n return segment;\n }\n }\n }\n\n return defaultLanguage;\n}\n","import { getGlobalFallbackLanguage, runWithLocale } from \"./context\";\nimport { resolveRequestLocale, type ResolveLocaleOptions } from \"./resolver\";\nimport type {\n AstroCompatibleContext,\n AstroMiddlewareFn,\n AstroMiddlewareNext,\n} from \"./types\";\n\nconst OPTIONS_KEY = Symbol.for(\"ts-intl-astro/middlewareOptions\");\nconst SAFE_LOCALE_PATTERN = /^[a-zA-Z0-9_-]{2,16}$/;\n\ntype GlobalThisWithOptions = typeof globalThis & {\n [OPTIONS_KEY]?: ResolveLocaleOptions;\n};\n\nconst g = globalThis as GlobalThisWithOptions;\n\n/**\n * Registers global options for the standalone middleware entry point.\n */\nexport function setGlobalMiddlewareOptions(\n options: ResolveLocaleOptions,\n): void {\n g[OPTIONS_KEY] = options;\n}\n\nexport function getGlobalMiddlewareOptions(): ResolveLocaleOptions | undefined {\n return g[OPTIONS_KEY];\n}\n\n/**\n * Factory that creates an Astro-compatible middleware function.\n */\nexport function createI18nMiddleware(\n options: ResolveLocaleOptions,\n): AstroMiddlewareFn {\n return async (\n context: AstroCompatibleContext,\n next: AstroMiddlewareNext,\n ): Promise<Response> => {\n const locale = resolveRequestLocale(context, options);\n\n if (!context.locals) {\n context.locals = {};\n }\n context.locals.locale = locale;\n context.locals.lang = locale;\n\n return runWithLocale(locale, () => next());\n };\n}\n\n/**\n * Standalone Astro middleware handler.\n * Uses options registered via setGlobalMiddlewareOptions or defaults.\n */\nexport const onRequest: AstroMiddlewareFn = async (\n context: AstroCompatibleContext,\n next: AstroMiddlewareNext,\n): Promise<Response> => {\n const options = getGlobalMiddlewareOptions();\n let locale: string;\n\n if (options) {\n locale = resolveRequestLocale(context, options);\n } else {\n const candidate =\n context.currentLocale || context.params?.lang || context.params?.locale;\n const fallback = getGlobalFallbackLanguage();\n locale =\n candidate && SAFE_LOCALE_PATTERN.test(candidate) ? candidate : fallback;\n }\n\n if (!context.locals) {\n context.locals = {};\n }\n context.locals.locale = locale;\n context.locals.lang = locale;\n\n return runWithLocale(locale, () => next());\n};\n"]}
@@ -0,0 +1,95 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+
3
+ // src/context.ts
4
+ var STORAGE_KEY = /* @__PURE__ */ Symbol.for("ts-intl-astro/storage");
5
+ var FALLBACK_LANG_KEY = /* @__PURE__ */ Symbol.for("ts-intl-astro/fallbackLang");
6
+ var g = globalThis;
7
+ var i18nStorage = g[STORAGE_KEY] || (g[STORAGE_KEY] = new AsyncLocalStorage());
8
+ function setGlobalFallbackLanguage(lang) {
9
+ g[FALLBACK_LANG_KEY] = lang;
10
+ }
11
+ function getGlobalFallbackLanguage() {
12
+ return g[FALLBACK_LANG_KEY] || "en";
13
+ }
14
+ function getActiveLocale(fallback) {
15
+ const store = i18nStorage.getStore();
16
+ if (store?.locale) {
17
+ return store.locale;
18
+ }
19
+ return fallback || getGlobalFallbackLanguage();
20
+ }
21
+ function runWithLocale(locale, fn) {
22
+ return i18nStorage.run({ locale }, fn);
23
+ }
24
+
25
+ // src/resolver.ts
26
+ function resolveRequestLocale(context, options) {
27
+ const {
28
+ supportedLanguages,
29
+ defaultLanguage,
30
+ paramNames = ["lang", "locale"]
31
+ } = options;
32
+ if (context.currentLocale && supportedLanguages.includes(context.currentLocale)) {
33
+ return context.currentLocale;
34
+ }
35
+ if (context.params) {
36
+ for (const name of paramNames) {
37
+ const paramVal = context.params[name];
38
+ if (paramVal && supportedLanguages.includes(paramVal)) {
39
+ return paramVal;
40
+ }
41
+ }
42
+ }
43
+ if (context.url && context.url.pathname) {
44
+ const segments = context.url.pathname.split("/").filter(Boolean);
45
+ for (const segment of segments) {
46
+ if (supportedLanguages.includes(segment)) {
47
+ return segment;
48
+ }
49
+ }
50
+ }
51
+ return defaultLanguage;
52
+ }
53
+
54
+ // src/middleware.ts
55
+ var OPTIONS_KEY = /* @__PURE__ */ Symbol.for("ts-intl-astro/middlewareOptions");
56
+ var SAFE_LOCALE_PATTERN = /^[a-zA-Z0-9_-]{2,16}$/;
57
+ var g2 = globalThis;
58
+ function setGlobalMiddlewareOptions(options) {
59
+ g2[OPTIONS_KEY] = options;
60
+ }
61
+ function getGlobalMiddlewareOptions() {
62
+ return g2[OPTIONS_KEY];
63
+ }
64
+ function createI18nMiddleware(options) {
65
+ return async (context, next) => {
66
+ const locale = resolveRequestLocale(context, options);
67
+ if (!context.locals) {
68
+ context.locals = {};
69
+ }
70
+ context.locals.locale = locale;
71
+ context.locals.lang = locale;
72
+ return runWithLocale(locale, () => next());
73
+ };
74
+ }
75
+ var onRequest = async (context, next) => {
76
+ const options = getGlobalMiddlewareOptions();
77
+ let locale;
78
+ if (options) {
79
+ locale = resolveRequestLocale(context, options);
80
+ } else {
81
+ const candidate = context.currentLocale || context.params?.lang || context.params?.locale;
82
+ const fallback = getGlobalFallbackLanguage();
83
+ locale = candidate && SAFE_LOCALE_PATTERN.test(candidate) ? candidate : fallback;
84
+ }
85
+ if (!context.locals) {
86
+ context.locals = {};
87
+ }
88
+ context.locals.locale = locale;
89
+ context.locals.lang = locale;
90
+ return runWithLocale(locale, () => next());
91
+ };
92
+
93
+ export { createI18nMiddleware, getActiveLocale, getGlobalMiddlewareOptions, i18nStorage, onRequest, resolveRequestLocale, runWithLocale, setGlobalFallbackLanguage, setGlobalMiddlewareOptions };
94
+ //# sourceMappingURL=chunk-YRAJZM57.js.map
95
+ //# sourceMappingURL=chunk-YRAJZM57.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.ts","../src/resolver.ts","../src/middleware.ts"],"names":["g"],"mappings":";;;AAGA,IAAM,W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+B,OAC1C,OAAA,EACA,IAAA,KACsB;AACtB,EAAA,MAAM,UAAU,0BAAA,EAA2B;AAC3C,EAAA,IAAI,MAAA;AAEJ,EAAA,IAAI,OAAA,EAAS;AACX,IAAA,MAAA,GAAS,oBAAA,CAAqB,SAAS,OAAO,CAAA;AAAA,EAChD,CAAA,MAAO;AACL,IAAA,MAAM,YACJ,OAAA,CAAQ,aAAA,IAAiB,QAAQ,MAAA,EAAQ,IAAA,IAAQ,QAAQ,MAAA,EAAQ,MAAA;AACnE,IAAA,MAAM,WAAW,yBAAA,EAA0B;AAC3C,IAAA,MAAA,GACE,SAAA,IAAa,mBAAA,CAAoB,IAAA,CAAK,SAAS,IAAI,SAAA,GAAY,QAAA;AAAA,EACnE;AAEA,EAAA,IAAI,CAAC,QAAQ,MAAA,EAAQ;AACnB,IAAA,OAAA,CAAQ,SAAS,EAAC;AAAA,EACpB;AACA,EAAA,OAAA,CAAQ,OAAO,MAAA,GAAS,MAAA;AACxB,EAAA,OAAA,CAAQ,OAAO,IAAA,GAAO,MAAA;AAEtB,EAAA,OAAO,aAAA,CAAc,MAAA,EAAQ,MAAM,IAAA,EAAM,CAAA;AAC3C","file":"chunk-YRAJZM57.js","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { I18nContextStore } from \"./types\";\n\nconst STORAGE_KEY = Symbol.for(\"ts-intl-astro/storage\");\nconst FALLBACK_LANG_KEY = Symbol.for(\"ts-intl-astro/fallbackLang\");\n\ntype GlobalThisWithStorage = typeof globalThis & {\n [STORAGE_KEY]?: AsyncLocalStorage<I18nContextStore>;\n [FALLBACK_LANG_KEY]?: string;\n};\n\nconst g = globalThis as GlobalThisWithStorage;\n\nexport const i18nStorage: AsyncLocalStorage<I18nContextStore> =\n g[STORAGE_KEY] ||\n (g[STORAGE_KEY] = new AsyncLocalStorage<I18nContextStore>());\n\n/**\n * Sets a global fallback language when no active context is found.\n */\nexport function setGlobalFallbackLanguage(lang: string): void {\n g[FALLBACK_LANG_KEY] = lang;\n}\n\nexport function getGlobalFallbackLanguage(): string {\n return g[FALLBACK_LANG_KEY] || \"en\";\n}\n\n/**\n * Gets the current active locale from AsyncLocalStorage.\n * Falls back to globalFallbackLanguage if no context has been established.\n */\nexport function getActiveLocale(fallback?: string): string {\n const store = i18nStorage.getStore();\n if (store?.locale) {\n return store.locale;\n }\n return fallback || getGlobalFallbackLanguage();\n}\n\n/**\n * Executes a callback within an isolated i18n context for the specified locale.\n */\nexport function runWithLocale<T>(locale: string, fn: () => T): T {\n return i18nStorage.run({ locale }, fn);\n}\n","import type { AstroCompatibleContext } from \"./types\";\n\nexport interface ResolveLocaleOptions {\n supportedLanguages: readonly string[];\n defaultLanguage: string;\n paramNames?: string[];\n}\n\n/**\n * Resolves the request locale from context.currentLocale, route params, or URL path segments.\n */\nexport function resolveRequestLocale(\n context: AstroCompatibleContext,\n options: ResolveLocaleOptions,\n): string {\n const {\n supportedLanguages,\n defaultLanguage,\n paramNames = [\"lang\", \"locale\"],\n } = options;\n\n if (\n context.currentLocale &&\n supportedLanguages.includes(context.currentLocale)\n ) {\n return context.currentLocale;\n }\n\n if (context.params) {\n for (const name of paramNames) {\n const paramVal = context.params[name];\n if (paramVal && supportedLanguages.includes(paramVal)) {\n return paramVal;\n }\n }\n }\n\n if (context.url && context.url.pathname) {\n const segments = context.url.pathname.split(\"/\").filter(Boolean);\n for (const segment of segments) {\n if (supportedLanguages.includes(segment)) {\n return segment;\n }\n }\n }\n\n return defaultLanguage;\n}\n","import { getGlobalFallbackLanguage, runWithLocale } from \"./context\";\nimport { resolveRequestLocale, type ResolveLocaleOptions } from \"./resolver\";\nimport type {\n AstroCompatibleContext,\n AstroMiddlewareFn,\n AstroMiddlewareNext,\n} from \"./types\";\n\nconst OPTIONS_KEY = Symbol.for(\"ts-intl-astro/middlewareOptions\");\nconst SAFE_LOCALE_PATTERN = /^[a-zA-Z0-9_-]{2,16}$/;\n\ntype GlobalThisWithOptions = typeof globalThis & {\n [OPTIONS_KEY]?: ResolveLocaleOptions;\n};\n\nconst g = globalThis as GlobalThisWithOptions;\n\n/**\n * Registers global options for the standalone middleware entry point.\n */\nexport function setGlobalMiddlewareOptions(\n options: ResolveLocaleOptions,\n): void {\n g[OPTIONS_KEY] = options;\n}\n\nexport function getGlobalMiddlewareOptions(): ResolveLocaleOptions | undefined {\n return g[OPTIONS_KEY];\n}\n\n/**\n * Factory that creates an Astro-compatible middleware function.\n */\nexport function createI18nMiddleware(\n options: ResolveLocaleOptions,\n): AstroMiddlewareFn {\n return async (\n context: AstroCompatibleContext,\n next: AstroMiddlewareNext,\n ): Promise<Response> => {\n const locale = resolveRequestLocale(context, options);\n\n if (!context.locals) {\n context.locals = {};\n }\n context.locals.locale = locale;\n context.locals.lang = locale;\n\n return runWithLocale(locale, () => next());\n };\n}\n\n/**\n * Standalone Astro middleware handler.\n * Uses options registered via setGlobalMiddlewareOptions or defaults.\n */\nexport const onRequest: AstroMiddlewareFn = async (\n context: AstroCompatibleContext,\n next: AstroMiddlewareNext,\n): Promise<Response> => {\n const options = getGlobalMiddlewareOptions();\n let locale: string;\n\n if (options) {\n locale = resolveRequestLocale(context, options);\n } else {\n const candidate =\n context.currentLocale || context.params?.lang || context.params?.locale;\n const fallback = getGlobalFallbackLanguage();\n locale =\n candidate && SAFE_LOCALE_PATTERN.test(candidate) ? candidate : fallback;\n }\n\n if (!context.locals) {\n context.locals = {};\n }\n context.locals.locale = locale;\n context.locals.lang = locale;\n\n return runWithLocale(locale, () => next());\n};\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var chunk25H6BZD6_cjs = require('./chunk-25H6BZD6.cjs');
6
+ var tsIntl = require('@aaakul/ts-intl');
7
+
8
+ function createAstroI18n(config) {
9
+ const core = tsIntl.createI18n(config);
10
+ chunk25H6BZD6_cjs.setGlobalFallbackLanguage(config.defaultLanguage);
11
+ const resolverOptions = {
12
+ supportedLanguages: core.languages,
13
+ defaultLanguage: core.defaultLanguage,
14
+ paramNames: config.paramNames
15
+ };
16
+ chunk25H6BZD6_cjs.setGlobalMiddlewareOptions(resolverOptions);
17
+ const i18nMiddleware = chunk25H6BZD6_cjs.createI18nMiddleware(resolverOptions);
18
+ function useTranslations(arg1, arg2) {
19
+ let namespace;
20
+ let options;
21
+ if (typeof arg1 === "string") {
22
+ namespace = arg1;
23
+ options = arg2;
24
+ } else if (typeof arg1 === "object" && arg1 !== null) {
25
+ options = arg1;
26
+ }
27
+ const activeLocale = options?.locale || chunk25H6BZD6_cjs.getActiveLocale(config.defaultLanguage);
28
+ return core.getTranslations(activeLocale, namespace);
29
+ }
30
+ function useLocale() {
31
+ return chunk25H6BZD6_cjs.getActiveLocale(config.defaultLanguage);
32
+ }
33
+ function useFormatter(options) {
34
+ const activeLocale = options?.locale || chunk25H6BZD6_cjs.getActiveLocale(config.defaultLanguage);
35
+ return core.getFormatter(activeLocale);
36
+ }
37
+ return {
38
+ languages: core.languages,
39
+ defaultLanguage: core.defaultLanguage,
40
+ isSupportedLanguage: core.isSupportedLanguage,
41
+ useTranslations,
42
+ useLocale,
43
+ useFormatter,
44
+ i18nMiddleware,
45
+ getTranslations: core.getTranslations,
46
+ getFormatter: core.getFormatter
47
+ };
48
+ }
49
+
50
+ // src/integration.ts
51
+ function tsIntlAstro(options = {}) {
52
+ const middlewareEntrypoint = options.middlewareEntrypoint || "ts-intl-astro/middleware";
53
+ return {
54
+ name: "ts-intl-astro",
55
+ hooks: {
56
+ "astro:config:setup": (params) => {
57
+ const { addMiddleware, logger } = params;
58
+ if (typeof addMiddleware === "function") {
59
+ addMiddleware({
60
+ entrypoint: middlewareEntrypoint,
61
+ order: "pre"
62
+ });
63
+ } else if (logger && typeof logger.warn === "function") {
64
+ logger.warn(
65
+ "Current Astro version does not support `addMiddleware`. Please export `onRequest = i18nMiddleware` in `src/middleware.ts` manually."
66
+ );
67
+ }
68
+ }
69
+ }
70
+ };
71
+ }
72
+ var integration_default = tsIntlAstro;
73
+
74
+ Object.defineProperty(exports, "createI18nMiddleware", {
75
+ enumerable: true,
76
+ get: function () { return chunk25H6BZD6_cjs.createI18nMiddleware; }
77
+ });
78
+ Object.defineProperty(exports, "getActiveLocale", {
79
+ enumerable: true,
80
+ get: function () { return chunk25H6BZD6_cjs.getActiveLocale; }
81
+ });
82
+ Object.defineProperty(exports, "i18nStorage", {
83
+ enumerable: true,
84
+ get: function () { return chunk25H6BZD6_cjs.i18nStorage; }
85
+ });
86
+ Object.defineProperty(exports, "onRequest", {
87
+ enumerable: true,
88
+ get: function () { return chunk25H6BZD6_cjs.onRequest; }
89
+ });
90
+ Object.defineProperty(exports, "resolveRequestLocale", {
91
+ enumerable: true,
92
+ get: function () { return chunk25H6BZD6_cjs.resolveRequestLocale; }
93
+ });
94
+ Object.defineProperty(exports, "runWithLocale", {
95
+ enumerable: true,
96
+ get: function () { return chunk25H6BZD6_cjs.runWithLocale; }
97
+ });
98
+ Object.defineProperty(exports, "setGlobalFallbackLanguage", {
99
+ enumerable: true,
100
+ get: function () { return chunk25H6BZD6_cjs.setGlobalFallbackLanguage; }
101
+ });
102
+ Object.defineProperty(exports, "setGlobalMiddlewareOptions", {
103
+ enumerable: true,
104
+ get: function () { return chunk25H6BZD6_cjs.setGlobalMiddlewareOptions; }
105
+ });
106
+ Object.defineProperty(exports, "I18nError", {
107
+ enumerable: true,
108
+ get: function () { return tsIntl.I18nError; }
109
+ });
110
+ Object.defineProperty(exports, "I18nErrorCode", {
111
+ enumerable: true,
112
+ get: function () { return tsIntl.I18nErrorCode; }
113
+ });
114
+ Object.defineProperty(exports, "createI18n", {
115
+ enumerable: true,
116
+ get: function () { return tsIntl.createI18n; }
117
+ });
118
+ exports.createAstroI18n = createAstroI18n;
119
+ exports.default = integration_default;
120
+ exports.tsIntl = tsIntlAstro;
121
+ exports.tsIntlAstro = tsIntlAstro;
122
+ //# sourceMappingURL=index.cjs.map
123
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/factory.ts","../src/integration.ts"],"names":["createI18n","setGlobalFallbackLanguage","setGlobalMiddlewareOptions","createI18nMiddleware","getActiveLocale"],"mappings":";;;;;;;AA0BO,SAAS,gBAId,MAAA,EACiD;AAIjD,EAAA,MAAM,IAAA,GAAOA,kBAAW,MAAM,CAAA;AAE9B,EAAAC,2CAAA,CAA0B,OAAO,eAAe,CAAA;AAEhD,EAAA,MAAM,eAAA,GAAkB;AAAA,IACtB,oBAAoB,IAAA,CAAK,SAAA;AAAA,IACzB,iBAAiB,IAAA,CAAK,eAAA;AAAA,IACtB,YAAY,MAAA,CAAO;AAAA,GACrB;AAEA,EAAAC,4CAAA,CAA2B,eAAe,CAAA;AAE1C,EAAA,MAAM,cAAA,GAAiBC,uCAAqB,eAAe,CAAA;AAS3D,EAAA,SAAS,eAAA,CAAgB,MAAY,IAAA,EAAiB;AACpD,IAAA,IAAI,SAAA;AACJ,IAAA,IAAI,OAAA;AAEJ,IAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,OAAA,GAAU,IAAA;AAAA,IACZ,CAAA,MAAA,IAAW,OAAO,IAAA,KAAS,QAAA,IAAY,SAAS,IAAA,EAAM;AACpD,MAAA,OAAA,GAAU,IAAA;AAAA,IACZ;AAEA,IAAA,MAAM,YAAA,GACJ,OAAA,EAAS,MAAA,IAAUC,iCAAA,CAAgB,OAAO,eAAe,CAAA;AAC3D,IAAA,OAAQ,IAAA,CAAK,eAAA,CAAwB,YAAA,EAAc,SAAS,CAAA;AAAA,EAC9D;AAEA,EAAA,SAAS,SAAA,GAA+B;AACtC,IAAA,OAAOA,iCAAA,CAAgB,OAAO,eAAe,CAAA;AAAA,EAC/C;AAEA,EAAA,SAAS,aAAa,OAAA,EAAqD;AACzE,IAAA,MAAM,YAAA,GACJ,OAAA,EAAS,MAAA,IAAUA,iCAAA,CAAgB,OAAO,eAAe,CAAA;AAC3D,IAAA,OAAO,IAAA,CAAK,aAAa,YAAY,CAAA;AAAA,EACvC;AAEA,EAAA,OAAO;AAAA,IACL,WAAW,IAAA,CAAK,SAAA;AAAA,IAChB,iBAAiB,IAAA,CAAK,eAAA;AAAA,IACtB,qBAAqB,IAAA,CAAK,mBAAA;AAAA,IAC1B,eAAA;AAAA,IACA,SAAA;AAAA,IACA,YAAA;AAAA,IACA,cAAA;AAAA,IACA,iBAAiB,IAAA,CAAK,eAAA;AAAA,IACtB,cAAc,IAAA,CAAK;AAAA,GACrB;AACF;;;AC/EO,SAAS,WAAA,CAAY,OAAA,GAAoC,EAAC,EAG/D;AACA,EAAA,MAAM,oBAAA,GACJ,QAAQ,oBAAA,IAAwB,0BAAA;AAElC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,eAAA;AAAA,IACN,KAAA,EAAO;AAAA,MACL,oBAAA,EAAsB,CAAC,MAAA,KAAgB;AACrC,QAAA,MAAM,EAAE,aAAA,EAAe,MAAA,EAAO,GAAI,MAAA;AAElC,QAAA,IAAI,OAAO,kBAAkB,UAAA,EAAY;AACvC,UAAA,aAAA,CAAc;AAAA,YACZ,UAAA,EAAY,oBAAA;AAAA,YACZ,KAAA,EAAO;AAAA,WACR,CAAA;AAAA,QACH,CAAA,MAAA,IAAW,MAAA,IAAU,OAAO,MAAA,CAAO,SAAS,UAAA,EAAY;AACtD,UAAA,MAAA,CAAO,IAAA;AAAA,YACL;AAAA,WAEF;AAAA,QACF;AAAA,MACF;AAAA;AACF,GACF;AACF;AAEA,IAAO,mBAAA,GAAQ","file":"index.cjs","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n createI18n,\n type I18nConfig,\n type NamespaceKeys,\n type ValueAtPath,\n type Translator,\n type FlatTranslator,\n} from \"@aaakul/ts-intl\";\nimport { getActiveLocale, setGlobalFallbackLanguage } from \"./context\";\nimport { createI18nMiddleware, setGlobalMiddlewareOptions } from \"./middleware\";\nimport type { AstroI18nInstance, UseTranslationsOptions } from \"./types\";\n\nexport interface CreateAstroI18nOptions<\n TDefaultLanguage extends string,\n TLanguages extends Record<TDefaultLanguage, Record<string, any>>,\n> extends I18nConfig<TDefaultLanguage, TLanguages> {\n /**\n * Route parameter names to search for locale (default: ['lang', 'locale']).\n */\n paramNames?: string[];\n}\n\n/**\n * Creates a ts-intl instance configured for Astro, providing context-aware helpers and middleware.\n */\nexport function createAstroI18n<\n TDefaultLanguage extends string,\n TLanguages extends Record<TDefaultLanguage, Record<string, any>>,\n>(\n config: CreateAstroI18nOptions<TDefaultLanguage, TLanguages>,\n): AstroI18nInstance<TDefaultLanguage, TLanguages> {\n type TBase = TLanguages[TDefaultLanguage];\n type SupportedLanguage = keyof TLanguages & string;\n\n const core = createI18n(config);\n\n setGlobalFallbackLanguage(config.defaultLanguage);\n\n const resolverOptions = {\n supportedLanguages: core.languages,\n defaultLanguage: core.defaultLanguage,\n paramNames: config.paramNames,\n };\n\n setGlobalMiddlewareOptions(resolverOptions);\n\n const i18nMiddleware = createI18nMiddleware(resolverOptions);\n\n function useTranslations<N extends NamespaceKeys<TBase>>(\n namespace: N,\n options?: UseTranslationsOptions<SupportedLanguage>,\n ): Translator<ValueAtPath<TBase, N>>;\n function useTranslations(\n options?: UseTranslationsOptions<SupportedLanguage>,\n ): FlatTranslator<TBase>;\n function useTranslations(arg1?: any, arg2?: any): any {\n let namespace: string | undefined;\n let options: UseTranslationsOptions<SupportedLanguage> | undefined;\n\n if (typeof arg1 === \"string\") {\n namespace = arg1;\n options = arg2;\n } else if (typeof arg1 === \"object\" && arg1 !== null) {\n options = arg1;\n }\n\n const activeLocale =\n options?.locale || getActiveLocale(config.defaultLanguage);\n return (core.getTranslations as any)(activeLocale, namespace);\n }\n\n function useLocale(): SupportedLanguage {\n return getActiveLocale(config.defaultLanguage) as SupportedLanguage;\n }\n\n function useFormatter(options?: UseTranslationsOptions<SupportedLanguage>) {\n const activeLocale =\n options?.locale || getActiveLocale(config.defaultLanguage);\n return core.getFormatter(activeLocale);\n }\n\n return {\n languages: core.languages,\n defaultLanguage: core.defaultLanguage,\n isSupportedLanguage: core.isSupportedLanguage,\n useTranslations: useTranslations as any,\n useLocale,\n useFormatter,\n i18nMiddleware,\n getTranslations: core.getTranslations as any,\n getFormatter: core.getFormatter,\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface TsIntlIntegrationOptions {\n /**\n * Custom middleware entrypoint if a custom middleware file is provided.\n * Defaults to 'ts-intl-astro/middleware'.\n */\n middlewareEntrypoint?: string;\n}\n\n/**\n * Astro integration for ts-intl.\n * Injects pre-middleware into the Astro rendering pipeline.\n */\nexport function tsIntlAstro(options: TsIntlIntegrationOptions = {}): {\n name: string;\n hooks: Record<string, any>;\n} {\n const middlewareEntrypoint =\n options.middlewareEntrypoint || \"ts-intl-astro/middleware\";\n\n return {\n name: \"ts-intl-astro\",\n hooks: {\n \"astro:config:setup\": (params: any) => {\n const { addMiddleware, logger } = params;\n\n if (typeof addMiddleware === \"function\") {\n addMiddleware({\n entrypoint: middlewareEntrypoint,\n order: \"pre\",\n });\n } else if (logger && typeof logger.warn === \"function\") {\n logger.warn(\n \"Current Astro version does not support `addMiddleware`. \" +\n \"Please export `onRequest = i18nMiddleware` in `src/middleware.ts` manually.\",\n );\n }\n },\n },\n };\n}\n\nexport default tsIntlAstro;\n"]}
@@ -0,0 +1,51 @@
1
+ import { I18nConfig } from '@aaakul/ts-intl';
2
+ export { FlatTranslator, Formats, Formatter, I18nConfig, I18nError, I18nErrorCode, Translator, createI18n } from '@aaakul/ts-intl';
3
+ import { A as AstroI18nInstance, I as I18nContextStore } from './middleware-BgHN1Pu6.cjs';
4
+ export { a as AstroCompatibleContext, b as AstroMiddlewareFn, c as AstroMiddlewareNext, R as ResolveLocaleOptions, U as UseTranslationsOptions, d as createI18nMiddleware, o as onRequest, r as resolveRequestLocale, s as setGlobalMiddlewareOptions } from './middleware-BgHN1Pu6.cjs';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
+
7
+ interface CreateAstroI18nOptions<TDefaultLanguage extends string, TLanguages extends Record<TDefaultLanguage, Record<string, any>>> extends I18nConfig<TDefaultLanguage, TLanguages> {
8
+ /**
9
+ * Route parameter names to search for locale (default: ['lang', 'locale']).
10
+ */
11
+ paramNames?: string[];
12
+ }
13
+ /**
14
+ * Creates a ts-intl instance configured for Astro, providing context-aware helpers and middleware.
15
+ */
16
+ declare function createAstroI18n<TDefaultLanguage extends string, TLanguages extends Record<TDefaultLanguage, Record<string, any>>>(config: CreateAstroI18nOptions<TDefaultLanguage, TLanguages>): AstroI18nInstance<TDefaultLanguage, TLanguages>;
17
+
18
+ interface TsIntlIntegrationOptions {
19
+ /**
20
+ * Custom middleware entrypoint if a custom middleware file is provided.
21
+ * Defaults to 'ts-intl-astro/middleware'.
22
+ */
23
+ middlewareEntrypoint?: string;
24
+ }
25
+ /**
26
+ * Astro integration for ts-intl.
27
+ * Injects pre-middleware into the Astro rendering pipeline.
28
+ */
29
+ declare function tsIntlAstro(options?: TsIntlIntegrationOptions): {
30
+ name: string;
31
+ hooks: Record<string, any>;
32
+ };
33
+
34
+ declare const i18nStorage: AsyncLocalStorage<I18nContextStore>;
35
+ /**
36
+ * Sets a global fallback language when no active context is found.
37
+ */
38
+ declare function setGlobalFallbackLanguage(lang: string): void;
39
+ /**
40
+ * Gets the current active locale from AsyncLocalStorage.
41
+ * Falls back to globalFallbackLanguage if no context has been established.
42
+ */
43
+ declare function getActiveLocale(fallback?: string): string;
44
+ /**
45
+ * Executes a callback within an isolated i18n context for the specified locale.
46
+ */
47
+ declare function runWithLocale<T>(locale: string, fn: () => T): T;
48
+
49
+ // @ts-ignore
50
+ export = tsIntlAstro;
51
+ export { AstroI18nInstance, type CreateAstroI18nOptions, I18nContextStore, type TsIntlIntegrationOptions, createAstroI18n, getActiveLocale, i18nStorage, runWithLocale, setGlobalFallbackLanguage, tsIntlAstro as tsIntl, tsIntlAstro };
@@ -0,0 +1,49 @@
1
+ import { I18nConfig } from '@aaakul/ts-intl';
2
+ export { FlatTranslator, Formats, Formatter, I18nConfig, I18nError, I18nErrorCode, Translator, createI18n } from '@aaakul/ts-intl';
3
+ import { A as AstroI18nInstance, I as I18nContextStore } from './middleware-BgHN1Pu6.js';
4
+ export { a as AstroCompatibleContext, b as AstroMiddlewareFn, c as AstroMiddlewareNext, R as ResolveLocaleOptions, U as UseTranslationsOptions, d as createI18nMiddleware, o as onRequest, r as resolveRequestLocale, s as setGlobalMiddlewareOptions } from './middleware-BgHN1Pu6.js';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
+
7
+ interface CreateAstroI18nOptions<TDefaultLanguage extends string, TLanguages extends Record<TDefaultLanguage, Record<string, any>>> extends I18nConfig<TDefaultLanguage, TLanguages> {
8
+ /**
9
+ * Route parameter names to search for locale (default: ['lang', 'locale']).
10
+ */
11
+ paramNames?: string[];
12
+ }
13
+ /**
14
+ * Creates a ts-intl instance configured for Astro, providing context-aware helpers and middleware.
15
+ */
16
+ declare function createAstroI18n<TDefaultLanguage extends string, TLanguages extends Record<TDefaultLanguage, Record<string, any>>>(config: CreateAstroI18nOptions<TDefaultLanguage, TLanguages>): AstroI18nInstance<TDefaultLanguage, TLanguages>;
17
+
18
+ interface TsIntlIntegrationOptions {
19
+ /**
20
+ * Custom middleware entrypoint if a custom middleware file is provided.
21
+ * Defaults to 'ts-intl-astro/middleware'.
22
+ */
23
+ middlewareEntrypoint?: string;
24
+ }
25
+ /**
26
+ * Astro integration for ts-intl.
27
+ * Injects pre-middleware into the Astro rendering pipeline.
28
+ */
29
+ declare function tsIntlAstro(options?: TsIntlIntegrationOptions): {
30
+ name: string;
31
+ hooks: Record<string, any>;
32
+ };
33
+
34
+ declare const i18nStorage: AsyncLocalStorage<I18nContextStore>;
35
+ /**
36
+ * Sets a global fallback language when no active context is found.
37
+ */
38
+ declare function setGlobalFallbackLanguage(lang: string): void;
39
+ /**
40
+ * Gets the current active locale from AsyncLocalStorage.
41
+ * Falls back to globalFallbackLanguage if no context has been established.
42
+ */
43
+ declare function getActiveLocale(fallback?: string): string;
44
+ /**
45
+ * Executes a callback within an isolated i18n context for the specified locale.
46
+ */
47
+ declare function runWithLocale<T>(locale: string, fn: () => T): T;
48
+
49
+ export { AstroI18nInstance, type CreateAstroI18nOptions, I18nContextStore, type TsIntlIntegrationOptions, createAstroI18n, tsIntlAstro as default, getActiveLocale, i18nStorage, runWithLocale, setGlobalFallbackLanguage, tsIntlAstro as tsIntl, tsIntlAstro };
package/dist/index.js ADDED
@@ -0,0 +1,74 @@
1
+ import { setGlobalFallbackLanguage, setGlobalMiddlewareOptions, createI18nMiddleware, getActiveLocale } from './chunk-YRAJZM57.js';
2
+ export { createI18nMiddleware, getActiveLocale, i18nStorage, onRequest, resolveRequestLocale, runWithLocale, setGlobalFallbackLanguage, setGlobalMiddlewareOptions } from './chunk-YRAJZM57.js';
3
+ import { createI18n } from '@aaakul/ts-intl';
4
+ export { I18nError, I18nErrorCode, createI18n } from '@aaakul/ts-intl';
5
+
6
+ function createAstroI18n(config) {
7
+ const core = createI18n(config);
8
+ setGlobalFallbackLanguage(config.defaultLanguage);
9
+ const resolverOptions = {
10
+ supportedLanguages: core.languages,
11
+ defaultLanguage: core.defaultLanguage,
12
+ paramNames: config.paramNames
13
+ };
14
+ setGlobalMiddlewareOptions(resolverOptions);
15
+ const i18nMiddleware = createI18nMiddleware(resolverOptions);
16
+ function useTranslations(arg1, arg2) {
17
+ let namespace;
18
+ let options;
19
+ if (typeof arg1 === "string") {
20
+ namespace = arg1;
21
+ options = arg2;
22
+ } else if (typeof arg1 === "object" && arg1 !== null) {
23
+ options = arg1;
24
+ }
25
+ const activeLocale = options?.locale || getActiveLocale(config.defaultLanguage);
26
+ return core.getTranslations(activeLocale, namespace);
27
+ }
28
+ function useLocale() {
29
+ return getActiveLocale(config.defaultLanguage);
30
+ }
31
+ function useFormatter(options) {
32
+ const activeLocale = options?.locale || getActiveLocale(config.defaultLanguage);
33
+ return core.getFormatter(activeLocale);
34
+ }
35
+ return {
36
+ languages: core.languages,
37
+ defaultLanguage: core.defaultLanguage,
38
+ isSupportedLanguage: core.isSupportedLanguage,
39
+ useTranslations,
40
+ useLocale,
41
+ useFormatter,
42
+ i18nMiddleware,
43
+ getTranslations: core.getTranslations,
44
+ getFormatter: core.getFormatter
45
+ };
46
+ }
47
+
48
+ // src/integration.ts
49
+ function tsIntlAstro(options = {}) {
50
+ const middlewareEntrypoint = options.middlewareEntrypoint || "ts-intl-astro/middleware";
51
+ return {
52
+ name: "ts-intl-astro",
53
+ hooks: {
54
+ "astro:config:setup": (params) => {
55
+ const { addMiddleware, logger } = params;
56
+ if (typeof addMiddleware === "function") {
57
+ addMiddleware({
58
+ entrypoint: middlewareEntrypoint,
59
+ order: "pre"
60
+ });
61
+ } else if (logger && typeof logger.warn === "function") {
62
+ logger.warn(
63
+ "Current Astro version does not support `addMiddleware`. Please export `onRequest = i18nMiddleware` in `src/middleware.ts` manually."
64
+ );
65
+ }
66
+ }
67
+ }
68
+ };
69
+ }
70
+ var integration_default = tsIntlAstro;
71
+
72
+ export { createAstroI18n, integration_default as default, tsIntlAstro as tsIntl, tsIntlAstro };
73
+ //# sourceMappingURL=index.js.map
74
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/factory.ts","../src/integration.ts"],"names":[],"mappings":";;;;;AA0BO,SAAS,gBAId,MAAA,EACiD;AAIjD,EAAA,MAAM,IAAA,GAAO,WAAW,MAAM,CAAA;AAE9B,EAAA,yBAAA,CAA0B,OAAO,eAAe,CAAA;AAEhD,EAAA,MAAM,eAAA,GAAkB;AAAA,IACtB,oBAAoB,IAAA,CAAK,SAAA;AAAA,IACzB,iBAAiB,IAAA,CAAK,eAAA;AAAA,IACtB,YAAY,MAAA,CAAO;AAAA,GACrB;AAEA,EAAA,0BAAA,CAA2B,eAAe,CAAA;AAE1C,EAAA,MAAM,cAAA,GAAiB,qBAAqB,eAAe,CAAA;AAS3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O;AAAA,MACL,oBAAA,EAAsB,CAAC,MAAA,KAAgB;AACrC,QAAA,MAAM,EAAE,aAAA,EAAe,MAAA,EAAO,GAAI,MAAA;AAElC,QAAA,IAAI,OAAO,kBAAkB,UAAA,EAAY;AACvC,UAAA,aAAA,CAAc;AAAA,YACZ,UAAA,EAAY,oBAAA;AAAA,YACZ,KAAA,EAAO;AAAA,WACR,CAAA;AAAA,QACH,CAAA,MAAA,IAAW,MAAA,IAAU,OAAO,MAAA,CAAO,SAAS,UAAA,EAAY;AACtD,UAAA,MAAA,CAAO,IAAA;AAAA,YACL;AAAA,WAEF;AAAA,QACF;AAAA,MACF;AAAA;AACF,GACF;AACF;AAEA,IAAO,mBAAA,GAAQ","file":"index.js","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n createI18n,\n type I18nConfig,\n type NamespaceKeys,\n type ValueAtPath,\n type Translator,\n type FlatTranslator,\n} from \"@aaakul/ts-intl\";\nimport { getActiveLocale, setGlobalFallbackLanguage } from \"./context\";\nimport { createI18nMiddleware, setGlobalMiddlewareOptions } from \"./middleware\";\nimport type { AstroI18nInstance, UseTranslationsOptions } from \"./types\";\n\nexport interface CreateAstroI18nOptions<\n TDefaultLanguage extends string,\n TLanguages extends Record<TDefaultLanguage, Record<string, any>>,\n> extends I18nConfig<TDefaultLanguage, TLanguages> {\n /**\n * Route parameter names to search for locale (default: ['lang', 'locale']).\n */\n paramNames?: string[];\n}\n\n/**\n * Creates a ts-intl instance configured for Astro, providing context-aware helpers and middleware.\n */\nexport function createAstroI18n<\n TDefaultLanguage extends string,\n TLanguages extends Record<TDefaultLanguage, Record<string, any>>,\n>(\n config: CreateAstroI18nOptions<TDefaultLanguage, TLanguages>,\n): AstroI18nInstance<TDefaultLanguage, TLanguages> {\n type TBase = TLanguages[TDefaultLanguage];\n type SupportedLanguage = keyof TLanguages & string;\n\n const core = createI18n(config);\n\n setGlobalFallbackLanguage(config.defaultLanguage);\n\n const resolverOptions = {\n supportedLanguages: core.languages,\n defaultLanguage: core.defaultLanguage,\n paramNames: config.paramNames,\n };\n\n setGlobalMiddlewareOptions(resolverOptions);\n\n const i18nMiddleware = createI18nMiddleware(resolverOptions);\n\n function useTranslations<N extends NamespaceKeys<TBase>>(\n namespace: N,\n options?: UseTranslationsOptions<SupportedLanguage>,\n ): Translator<ValueAtPath<TBase, N>>;\n function useTranslations(\n options?: UseTranslationsOptions<SupportedLanguage>,\n ): FlatTranslator<TBase>;\n function useTranslations(arg1?: any, arg2?: any): any {\n let namespace: string | undefined;\n let options: UseTranslationsOptions<SupportedLanguage> | undefined;\n\n if (typeof arg1 === \"string\") {\n namespace = arg1;\n options = arg2;\n } else if (typeof arg1 === \"object\" && arg1 !== null) {\n options = arg1;\n }\n\n const activeLocale =\n options?.locale || getActiveLocale(config.defaultLanguage);\n return (core.getTranslations as any)(activeLocale, namespace);\n }\n\n function useLocale(): SupportedLanguage {\n return getActiveLocale(config.defaultLanguage) as SupportedLanguage;\n }\n\n function useFormatter(options?: UseTranslationsOptions<SupportedLanguage>) {\n const activeLocale =\n options?.locale || getActiveLocale(config.defaultLanguage);\n return core.getFormatter(activeLocale);\n }\n\n return {\n languages: core.languages,\n defaultLanguage: core.defaultLanguage,\n isSupportedLanguage: core.isSupportedLanguage,\n useTranslations: useTranslations as any,\n useLocale,\n useFormatter,\n i18nMiddleware,\n getTranslations: core.getTranslations as any,\n getFormatter: core.getFormatter,\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface TsIntlIntegrationOptions {\n /**\n * Custom middleware entrypoint if a custom middleware file is provided.\n * Defaults to 'ts-intl-astro/middleware'.\n */\n middlewareEntrypoint?: string;\n}\n\n/**\n * Astro integration for ts-intl.\n * Injects pre-middleware into the Astro rendering pipeline.\n */\nexport function tsIntlAstro(options: TsIntlIntegrationOptions = {}): {\n name: string;\n hooks: Record<string, any>;\n} {\n const middlewareEntrypoint =\n options.middlewareEntrypoint || \"ts-intl-astro/middleware\";\n\n return {\n name: \"ts-intl-astro\",\n hooks: {\n \"astro:config:setup\": (params: any) => {\n const { addMiddleware, logger } = params;\n\n if (typeof addMiddleware === \"function\") {\n addMiddleware({\n entrypoint: middlewareEntrypoint,\n order: \"pre\",\n });\n } else if (logger && typeof logger.warn === \"function\") {\n logger.warn(\n \"Current Astro version does not support `addMiddleware`. \" +\n \"Please export `onRequest = i18nMiddleware` in `src/middleware.ts` manually.\",\n );\n }\n },\n },\n };\n}\n\nexport default tsIntlAstro;\n"]}
@@ -0,0 +1,83 @@
1
+ import { NamespaceKeys, Translator, ValueAtPath, FlatTranslator, Formatter } from '@aaakul/ts-intl';
2
+
3
+ /**
4
+ * Minimal interface to decouple from specific Astro versions (compatible with Astro 3.x, 4.x, 5.x).
5
+ */
6
+ interface AstroCompatibleContext {
7
+ url: URL;
8
+ params?: Record<string, string | undefined>;
9
+ currentLocale?: string | undefined;
10
+ preferredLocale?: string | undefined;
11
+ locals?: Record<string, any>;
12
+ [key: string]: any;
13
+ }
14
+ type AstroMiddlewareNext = () => Promise<Response>;
15
+ type AstroMiddlewareFn = (context: AstroCompatibleContext, next: AstroMiddlewareNext) => Promise<Response>;
16
+ interface I18nContextStore {
17
+ locale: string;
18
+ }
19
+ interface UseTranslationsOptions<TLang extends string = string> {
20
+ locale?: TLang | (string & {});
21
+ }
22
+ interface AstroI18nInstance<TDefaultLanguage extends string, TLanguages extends Record<TDefaultLanguage, Record<string, any>>> {
23
+ languages: readonly (keyof TLanguages & string)[];
24
+ defaultLanguage: TDefaultLanguage;
25
+ isSupportedLanguage: (lang: string) => lang is keyof TLanguages & string;
26
+ /**
27
+ * Returns a translator bound to the current rendering context or specified locale.
28
+ */
29
+ useTranslations: {
30
+ <N extends NamespaceKeys<TLanguages[TDefaultLanguage]>>(namespace: N, options?: UseTranslationsOptions<keyof TLanguages & string>): Translator<ValueAtPath<TLanguages[TDefaultLanguage], N>>;
31
+ (options?: UseTranslationsOptions<keyof TLanguages & string>): FlatTranslator<TLanguages[TDefaultLanguage]>;
32
+ };
33
+ /**
34
+ * Returns the active locale in the current rendering context.
35
+ */
36
+ useLocale: () => keyof TLanguages & string;
37
+ /**
38
+ * Returns the cached Intl formatter bound to the active or specified locale.
39
+ */
40
+ useFormatter: (options?: UseTranslationsOptions<keyof TLanguages & string>) => Formatter;
41
+ /**
42
+ * Pre-configured Astro middleware for this i18n instance.
43
+ */
44
+ i18nMiddleware: AstroMiddlewareFn;
45
+ /**
46
+ * Translation accessor for a specified language.
47
+ */
48
+ getTranslations: {
49
+ <N extends NamespaceKeys<TLanguages[TDefaultLanguage]>>(lang: (keyof TLanguages & string) | (string & {}), namespace: N): Translator<ValueAtPath<TLanguages[TDefaultLanguage], N>>;
50
+ (lang: (keyof TLanguages & string) | (string & {})): FlatTranslator<TLanguages[TDefaultLanguage]>;
51
+ };
52
+ /**
53
+ * Formatter accessor for a specified language.
54
+ */
55
+ getFormatter: (lang?: (keyof TLanguages & string) | (string & {})) => Formatter;
56
+ }
57
+
58
+ interface ResolveLocaleOptions {
59
+ supportedLanguages: readonly string[];
60
+ defaultLanguage: string;
61
+ paramNames?: string[];
62
+ }
63
+ /**
64
+ * Resolves the request locale from context.currentLocale, route params, or URL path segments.
65
+ */
66
+ declare function resolveRequestLocale(context: AstroCompatibleContext, options: ResolveLocaleOptions): string;
67
+
68
+ /**
69
+ * Registers global options for the standalone middleware entry point.
70
+ */
71
+ declare function setGlobalMiddlewareOptions(options: ResolveLocaleOptions): void;
72
+ declare function getGlobalMiddlewareOptions(): ResolveLocaleOptions | undefined;
73
+ /**
74
+ * Factory that creates an Astro-compatible middleware function.
75
+ */
76
+ declare function createI18nMiddleware(options: ResolveLocaleOptions): AstroMiddlewareFn;
77
+ /**
78
+ * Standalone Astro middleware handler.
79
+ * Uses options registered via setGlobalMiddlewareOptions or defaults.
80
+ */
81
+ declare const onRequest: AstroMiddlewareFn;
82
+
83
+ export { type AstroI18nInstance as A, type I18nContextStore as I, type ResolveLocaleOptions as R, type UseTranslationsOptions as U, type AstroCompatibleContext as a, type AstroMiddlewareFn as b, type AstroMiddlewareNext as c, createI18nMiddleware as d, getGlobalMiddlewareOptions as g, onRequest as o, resolveRequestLocale as r, setGlobalMiddlewareOptions as s };
@@ -0,0 +1,83 @@
1
+ import { NamespaceKeys, Translator, ValueAtPath, FlatTranslator, Formatter } from '@aaakul/ts-intl';
2
+
3
+ /**
4
+ * Minimal interface to decouple from specific Astro versions (compatible with Astro 3.x, 4.x, 5.x).
5
+ */
6
+ interface AstroCompatibleContext {
7
+ url: URL;
8
+ params?: Record<string, string | undefined>;
9
+ currentLocale?: string | undefined;
10
+ preferredLocale?: string | undefined;
11
+ locals?: Record<string, any>;
12
+ [key: string]: any;
13
+ }
14
+ type AstroMiddlewareNext = () => Promise<Response>;
15
+ type AstroMiddlewareFn = (context: AstroCompatibleContext, next: AstroMiddlewareNext) => Promise<Response>;
16
+ interface I18nContextStore {
17
+ locale: string;
18
+ }
19
+ interface UseTranslationsOptions<TLang extends string = string> {
20
+ locale?: TLang | (string & {});
21
+ }
22
+ interface AstroI18nInstance<TDefaultLanguage extends string, TLanguages extends Record<TDefaultLanguage, Record<string, any>>> {
23
+ languages: readonly (keyof TLanguages & string)[];
24
+ defaultLanguage: TDefaultLanguage;
25
+ isSupportedLanguage: (lang: string) => lang is keyof TLanguages & string;
26
+ /**
27
+ * Returns a translator bound to the current rendering context or specified locale.
28
+ */
29
+ useTranslations: {
30
+ <N extends NamespaceKeys<TLanguages[TDefaultLanguage]>>(namespace: N, options?: UseTranslationsOptions<keyof TLanguages & string>): Translator<ValueAtPath<TLanguages[TDefaultLanguage], N>>;
31
+ (options?: UseTranslationsOptions<keyof TLanguages & string>): FlatTranslator<TLanguages[TDefaultLanguage]>;
32
+ };
33
+ /**
34
+ * Returns the active locale in the current rendering context.
35
+ */
36
+ useLocale: () => keyof TLanguages & string;
37
+ /**
38
+ * Returns the cached Intl formatter bound to the active or specified locale.
39
+ */
40
+ useFormatter: (options?: UseTranslationsOptions<keyof TLanguages & string>) => Formatter;
41
+ /**
42
+ * Pre-configured Astro middleware for this i18n instance.
43
+ */
44
+ i18nMiddleware: AstroMiddlewareFn;
45
+ /**
46
+ * Translation accessor for a specified language.
47
+ */
48
+ getTranslations: {
49
+ <N extends NamespaceKeys<TLanguages[TDefaultLanguage]>>(lang: (keyof TLanguages & string) | (string & {}), namespace: N): Translator<ValueAtPath<TLanguages[TDefaultLanguage], N>>;
50
+ (lang: (keyof TLanguages & string) | (string & {})): FlatTranslator<TLanguages[TDefaultLanguage]>;
51
+ };
52
+ /**
53
+ * Formatter accessor for a specified language.
54
+ */
55
+ getFormatter: (lang?: (keyof TLanguages & string) | (string & {})) => Formatter;
56
+ }
57
+
58
+ interface ResolveLocaleOptions {
59
+ supportedLanguages: readonly string[];
60
+ defaultLanguage: string;
61
+ paramNames?: string[];
62
+ }
63
+ /**
64
+ * Resolves the request locale from context.currentLocale, route params, or URL path segments.
65
+ */
66
+ declare function resolveRequestLocale(context: AstroCompatibleContext, options: ResolveLocaleOptions): string;
67
+
68
+ /**
69
+ * Registers global options for the standalone middleware entry point.
70
+ */
71
+ declare function setGlobalMiddlewareOptions(options: ResolveLocaleOptions): void;
72
+ declare function getGlobalMiddlewareOptions(): ResolveLocaleOptions | undefined;
73
+ /**
74
+ * Factory that creates an Astro-compatible middleware function.
75
+ */
76
+ declare function createI18nMiddleware(options: ResolveLocaleOptions): AstroMiddlewareFn;
77
+ /**
78
+ * Standalone Astro middleware handler.
79
+ * Uses options registered via setGlobalMiddlewareOptions or defaults.
80
+ */
81
+ declare const onRequest: AstroMiddlewareFn;
82
+
83
+ export { type AstroI18nInstance as A, type I18nContextStore as I, type ResolveLocaleOptions as R, type UseTranslationsOptions as U, type AstroCompatibleContext as a, type AstroMiddlewareFn as b, type AstroMiddlewareNext as c, createI18nMiddleware as d, getGlobalMiddlewareOptions as g, onRequest as o, resolveRequestLocale as r, setGlobalMiddlewareOptions as s };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ var chunk25H6BZD6_cjs = require('./chunk-25H6BZD6.cjs');
4
+
5
+
6
+
7
+ Object.defineProperty(exports, "createI18nMiddleware", {
8
+ enumerable: true,
9
+ get: function () { return chunk25H6BZD6_cjs.createI18nMiddleware; }
10
+ });
11
+ Object.defineProperty(exports, "getGlobalMiddlewareOptions", {
12
+ enumerable: true,
13
+ get: function () { return chunk25H6BZD6_cjs.getGlobalMiddlewareOptions; }
14
+ });
15
+ Object.defineProperty(exports, "onRequest", {
16
+ enumerable: true,
17
+ get: function () { return chunk25H6BZD6_cjs.onRequest; }
18
+ });
19
+ Object.defineProperty(exports, "setGlobalMiddlewareOptions", {
20
+ enumerable: true,
21
+ get: function () { return chunk25H6BZD6_cjs.setGlobalMiddlewareOptions; }
22
+ });
23
+ //# sourceMappingURL=middleware.cjs.map
24
+ //# sourceMappingURL=middleware.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"middleware.cjs"}
@@ -0,0 +1,2 @@
1
+ export { d as createI18nMiddleware, g as getGlobalMiddlewareOptions, o as onRequest, s as setGlobalMiddlewareOptions } from './middleware-BgHN1Pu6.cjs';
2
+ import '@aaakul/ts-intl';
@@ -0,0 +1,2 @@
1
+ export { d as createI18nMiddleware, g as getGlobalMiddlewareOptions, o as onRequest, s as setGlobalMiddlewareOptions } from './middleware-BgHN1Pu6.js';
2
+ import '@aaakul/ts-intl';
@@ -0,0 +1,3 @@
1
+ export { createI18nMiddleware, getGlobalMiddlewareOptions, onRequest, setGlobalMiddlewareOptions } from './chunk-YRAJZM57.js';
2
+ //# sourceMappingURL=middleware.js.map
3
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"middleware.js"}
package/package.json ADDED
@@ -0,0 +1,83 @@
1
+ {
2
+ "name": "ts-intl-astro",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight, type-safe Astro integration for internationalization (i18n). Delivers a developer experience inspired by `next-intl`. ",
5
+ "type": "module",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/aaakul/ts-intl.git"
12
+ },
13
+ "homepage": "https://ts-intl.pages.dev/en-US/docs/astro-integration",
14
+ "bugs": {
15
+ "url": "https://github.com/aaakul/ts-intl/issues"
16
+ },
17
+ "keywords": [
18
+ "astro-integration",
19
+ "astro-component",
20
+ "withastro",
21
+ "astro",
22
+ "i18n",
23
+ "internationalization",
24
+ "localization",
25
+ "ts-intl",
26
+ "typescript"
27
+ ],
28
+ "license": "MIT",
29
+ "main": "./dist/index.cjs",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "sideEffects": false,
33
+ "exports": {
34
+ ".": {
35
+ "import": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "require": {
40
+ "types": "./dist/index.d.cts",
41
+ "default": "./dist/index.cjs"
42
+ }
43
+ },
44
+ "./middleware": {
45
+ "import": {
46
+ "types": "./dist/middleware.d.ts",
47
+ "default": "./dist/middleware.js"
48
+ },
49
+ "require": {
50
+ "types": "./dist/middleware.d.cts",
51
+ "default": "./dist/middleware.cjs"
52
+ }
53
+ }
54
+ },
55
+ "files": [
56
+ "dist"
57
+ ],
58
+ "scripts": {
59
+ "dev": "tsup --watch",
60
+ "build": "tsup",
61
+ "test": "vitest run",
62
+ "test:watch": "vitest",
63
+ "typecheck": "tsc --noEmit"
64
+ },
65
+ "dependencies": {
66
+ "@aaakul/ts-intl": "workspace:*"
67
+ },
68
+ "peerDependencies": {
69
+ "astro": ">=3.0.0"
70
+ },
71
+ "peerDependenciesMeta": {
72
+ "astro": {
73
+ "optional": true
74
+ }
75
+ },
76
+ "devDependencies": {
77
+ "@types/node": "^22.20.2",
78
+ "astro": "^5.0.0",
79
+ "tsup": "^8.3.0",
80
+ "typescript": "^5.5.0",
81
+ "vitest": "^5.0.0"
82
+ }
83
+ }