@weapp-vite/i18n 0.1.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 +21 -0
- package/README.md +64 -0
- package/bin/weapp-i18n.js +2 -0
- package/dist/cjs/compiler.cjs +78 -0
- package/dist/cjs/compiler2.cjs +190 -0
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/runtime.cjs +154 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +57 -0
- package/dist/compiler.d.mts +13 -0
- package/dist/compiler.mjs +48 -0
- package/dist/compiler2.mjs +149 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +2 -0
- package/dist/miniprogram/index.js +228 -0
- package/dist/miniprogram/package.json +3 -0
- package/dist/runtime.d.mts +5 -0
- package/dist/runtime.mjs +153 -0
- package/dist/types.d.mts +64 -0
- package/package.json +82 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 ice breaker
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# @weapp-vite/i18n
|
|
2
|
+
|
|
3
|
+
一方维护的微信小程序 i18n 运行时与编译器。它不依赖 Vite、Vue、Wevu、Intlify、i18next 或 messageformat,可以直接用于原生微信小程序。
|
|
4
|
+
|
|
5
|
+
## 原生小程序
|
|
6
|
+
|
|
7
|
+
安装运行时并生成 locale catalog:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @weapp-vite/i18n
|
|
11
|
+
pnpm exec weapp-i18n compile \
|
|
12
|
+
--src-root miniprogram \
|
|
13
|
+
--default-locale zh-CN \
|
|
14
|
+
--fallback-locale en-US
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
命令扫描 `<src-root>/**/i18n/*.json`,生成 `<src-root>/i18n/locales.js` 与 `locales.wxs`。在项目工具中执行“构建 npm”后,创建应用内实例:
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
const { createI18n } = require('@weapp-vite/i18n')
|
|
21
|
+
const catalog = require('./i18n/locales')
|
|
22
|
+
|
|
23
|
+
// locales.js 是 compile 命令生成的预编译 catalog
|
|
24
|
+
const i18n = createI18n(catalog)
|
|
25
|
+
|
|
26
|
+
module.exports = i18n
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Component 和使用 Component 构造的 Page 直接接入 Behavior:
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
const { i18n } = require('../../i18n')
|
|
33
|
+
|
|
34
|
+
Component({
|
|
35
|
+
behaviors: [i18n.behavior],
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
传统 `Page({...})` 使用显式适配器:
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
const { i18n } = require('../../i18n')
|
|
43
|
+
|
|
44
|
+
i18n.page({
|
|
45
|
+
data: {},
|
|
46
|
+
})
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
WXML 显式引用生成的 WXS:
|
|
50
|
+
|
|
51
|
+
```xml
|
|
52
|
+
<wxs module="i18n" src="/i18n/locales.wxs" />
|
|
53
|
+
<view>{{ i18n.t(__wv_i18n_locale, 'greeting', { user }) }}</view>
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
本包不提供 `@miniprogram-i18n/core` 的 singleton 兼容入口。迁移时请把词典转换为普通 `locale -> key -> string` 消息对象,并为每个小程序运行时显式创建一个 `createI18n()` 实例;旧包的 select/ICU 消息需要按 v1 占位符语义调整。
|
|
57
|
+
|
|
58
|
+
实例通过 `i18n.global.t()`、`i18n.global.locale` 和 `i18n.global.onLocaleChange()` 访问运行时状态;不自动读写 storage,也不修改宿主的 Page/Component 构造器。
|
|
59
|
+
|
|
60
|
+
## weapp-vite
|
|
61
|
+
|
|
62
|
+
使用 `weapp.i18n` 时继续从 `weapp-vite/i18n` 导入当前构建实例。weapp-vite 负责扫描、WXML 改写、分包资产归属、Vite/Rolldown emit 和 HMR;实际运行时与消息编译语义由本包提供。
|
|
63
|
+
|
|
64
|
+
v1 支持纯文本、fallback、`{name}` 和 `{user.name}` 插值。暂不支持 ICU、plural、select、日期、数字或货币格式化。
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region \0rolldown/runtime.js
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
//#endregion
|
|
24
|
+
const require_compiler = require("./compiler2.cjs");
|
|
25
|
+
let node_fs = require("node:fs");
|
|
26
|
+
let node_path = require("node:path");
|
|
27
|
+
node_path = __toESM(node_path, 1);
|
|
28
|
+
//#region src/native.ts
|
|
29
|
+
async function collectLocaleFiles(root, files) {
|
|
30
|
+
const entries = await node_fs.promises.readdir(root, { withFileTypes: true });
|
|
31
|
+
for (const entry of entries) {
|
|
32
|
+
const filePath = node_path.default.join(root, entry.name);
|
|
33
|
+
if (entry.isDirectory()) {
|
|
34
|
+
if (entry.name !== "node_modules" && !entry.name.startsWith(".")) await collectLocaleFiles(filePath, files);
|
|
35
|
+
} else if (entry.isFile() && node_path.default.basename(root) === "i18n" && node_path.default.extname(entry.name) === ".json") files.push(filePath);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function compileNativeI18n(options) {
|
|
39
|
+
const srcRoot = node_path.default.resolve(options.srcRoot);
|
|
40
|
+
const outDir = node_path.default.resolve(options.outDir ?? node_path.default.join(srcRoot, "i18n"));
|
|
41
|
+
const files = [];
|
|
42
|
+
await collectLocaleFiles(srcRoot, files);
|
|
43
|
+
files.sort();
|
|
44
|
+
if (!files.length) throw new Error(`未在 \`${srcRoot}\` 下找到 i18n/*.json locale 文件。`);
|
|
45
|
+
const inputs = [];
|
|
46
|
+
for (const filePath of files) {
|
|
47
|
+
let messages;
|
|
48
|
+
try {
|
|
49
|
+
messages = JSON.parse(await node_fs.promises.readFile(filePath, "utf8"));
|
|
50
|
+
} catch (error) {
|
|
51
|
+
throw new Error(`无法解析 i18n 文件 \`${filePath}\`:${String(error)}`);
|
|
52
|
+
}
|
|
53
|
+
inputs.push({
|
|
54
|
+
filePath,
|
|
55
|
+
locale: node_path.default.basename(filePath, node_path.default.extname(filePath)),
|
|
56
|
+
messages
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
const catalog = require_compiler.compileI18nCatalog(inputs, options);
|
|
60
|
+
const jsFile = node_path.default.join(outDir, "locales.js");
|
|
61
|
+
const wxsFile = node_path.default.join(outDir, "locales.wxs");
|
|
62
|
+
await node_fs.promises.mkdir(outDir, { recursive: true });
|
|
63
|
+
await Promise.all([node_fs.promises.writeFile(jsFile, require_compiler.generateI18nCatalogModuleSource(catalog), "utf8"), node_fs.promises.writeFile(wxsFile, require_compiler.generateI18nWxsSource(catalog), "utf8")]);
|
|
64
|
+
return {
|
|
65
|
+
catalog,
|
|
66
|
+
files,
|
|
67
|
+
jsFile,
|
|
68
|
+
wxsFile
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
72
|
+
exports.compileI18nCatalog = require_compiler.compileI18nCatalog;
|
|
73
|
+
exports.compileI18nMessage = require_compiler.compileI18nMessage;
|
|
74
|
+
exports.compileI18nMessages = require_compiler.compileI18nMessages;
|
|
75
|
+
exports.compileNativeI18n = compileNativeI18n;
|
|
76
|
+
exports.generateI18nCatalogModuleSource = require_compiler.generateI18nCatalogModuleSource;
|
|
77
|
+
exports.generateI18nRuntimeSource = require_compiler.generateI18nRuntimeSource;
|
|
78
|
+
exports.generateI18nWxsSource = require_compiler.generateI18nWxsSource;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
const WEAPP_I18N_RUNTIME_MARKER = "__WEAPP_VITE_I18N__";
|
|
2
|
+
const WEAPP_I18N_LOCALE_DATA_KEY = "__wv_i18n_locale";
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region src/compiler.ts
|
|
5
|
+
const PLACEHOLDER_PATH_RE = /^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*)*$/i;
|
|
6
|
+
function isPlainObject(value) {
|
|
7
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
8
|
+
const prototype = Object.getPrototypeOf(value);
|
|
9
|
+
return prototype === Object.prototype || prototype === null;
|
|
10
|
+
}
|
|
11
|
+
function flattenLocaleMessages(input, filePath, visit, prefix = "") {
|
|
12
|
+
if (!isPlainObject(input)) throw new Error(`i18n 文件 \`${filePath}\` 顶层必须是对象。`);
|
|
13
|
+
for (const [key, value] of Object.entries(input)) {
|
|
14
|
+
const normalizedKey = key.trim();
|
|
15
|
+
if (!normalizedKey) throw new Error(`i18n 文件 \`${filePath}\` 包含空 key。`);
|
|
16
|
+
const path = prefix ? `${prefix}.${normalizedKey}` : normalizedKey;
|
|
17
|
+
if (typeof value === "string") visit(path, value);
|
|
18
|
+
else if (isPlainObject(value)) flattenLocaleMessages(value, filePath, visit, path);
|
|
19
|
+
else throw new Error(`i18n 文件 \`${filePath}\` 的 \`${path}\` 必须是字符串或嵌套对象。`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function compileI18nMessage(message) {
|
|
23
|
+
const tokens = [];
|
|
24
|
+
let literal = "";
|
|
25
|
+
const pushLiteral = () => {
|
|
26
|
+
if (literal || tokens.length === 0) {
|
|
27
|
+
tokens.push(literal);
|
|
28
|
+
literal = "";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
for (let index = 0; index < message.length;) {
|
|
32
|
+
if (message[index] !== "{") {
|
|
33
|
+
literal += message[index];
|
|
34
|
+
index++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
let depth = 1;
|
|
38
|
+
let end = index + 1;
|
|
39
|
+
while (end < message.length && depth > 0) {
|
|
40
|
+
if (message[end] === "{") depth++;
|
|
41
|
+
else if (message[end] === "}") depth--;
|
|
42
|
+
end++;
|
|
43
|
+
}
|
|
44
|
+
if (depth > 0) {
|
|
45
|
+
literal += message.slice(index);
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
const source = message.slice(index, end);
|
|
49
|
+
const key = source.slice(1, -1);
|
|
50
|
+
if (PLACEHOLDER_PATH_RE.test(key)) {
|
|
51
|
+
if (literal) pushLiteral();
|
|
52
|
+
tokens.push({
|
|
53
|
+
key,
|
|
54
|
+
source
|
|
55
|
+
});
|
|
56
|
+
} else literal += source;
|
|
57
|
+
index = end;
|
|
58
|
+
}
|
|
59
|
+
if (literal || tokens.length === 0) pushLiteral();
|
|
60
|
+
return tokens;
|
|
61
|
+
}
|
|
62
|
+
function compileI18nMessages(messages) {
|
|
63
|
+
const compiled = Object.create(null);
|
|
64
|
+
for (const [locale, localeMessages] of Object.entries(messages)) {
|
|
65
|
+
const target = compiled[locale] ??= Object.create(null);
|
|
66
|
+
flattenLocaleMessages(localeMessages, `${locale}.json`, (key, value) => {
|
|
67
|
+
target[key] = compileI18nMessage(value);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return compiled;
|
|
71
|
+
}
|
|
72
|
+
function compileI18nCatalog(files, options) {
|
|
73
|
+
const defaultLocale = options.defaultLocale.trim();
|
|
74
|
+
const fallbackLocale = options.fallbackLocale?.trim() || defaultLocale;
|
|
75
|
+
if (!defaultLocale) throw new Error("i18n defaultLocale 不能为空。");
|
|
76
|
+
const messages = Object.create(null);
|
|
77
|
+
const sources = /* @__PURE__ */ new Map();
|
|
78
|
+
for (const file of [...files].sort((left, right) => left.filePath.localeCompare(right.filePath))) {
|
|
79
|
+
const localeMessages = messages[file.locale] ??= Object.create(null);
|
|
80
|
+
flattenLocaleMessages(file.messages, file.filePath, (key, value) => {
|
|
81
|
+
const sourceKey = `${file.locale}:${key}`;
|
|
82
|
+
const previous = sources.get(sourceKey);
|
|
83
|
+
if (previous) throw new Error(`i18n locale \`${file.locale}\` 的 key \`${key}\` 重复:\`${previous}\` 与 \`${file.filePath}\`。`);
|
|
84
|
+
sources.set(sourceKey, file.filePath);
|
|
85
|
+
localeMessages[key] = compileI18nMessage(value);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
const locales = Object.keys(messages).sort();
|
|
89
|
+
const sourceFiles = [...new Set(files.map((file) => file.filePath))].sort();
|
|
90
|
+
if (!locales.includes(defaultLocale)) throw new Error(`i18n defaultLocale \`${defaultLocale}\` 没有对应的 locale 文件。已扫描:${sourceFiles.join(", ")}。`);
|
|
91
|
+
if (!locales.includes(fallbackLocale)) throw new Error(`i18n fallbackLocale \`${fallbackLocale}\` 没有对应的 locale 文件。已扫描:${sourceFiles.join(", ")}。`);
|
|
92
|
+
return {
|
|
93
|
+
defaultLocale,
|
|
94
|
+
fallbackLocale,
|
|
95
|
+
locales,
|
|
96
|
+
messages
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function generateI18nCatalogModuleSource(catalog) {
|
|
100
|
+
return `module.exports = ${JSON.stringify(catalog)}\n`;
|
|
101
|
+
}
|
|
102
|
+
function generateI18nWxsSource(catalog) {
|
|
103
|
+
return `var catalog = ${JSON.stringify(catalog)}
|
|
104
|
+
function resolveParam(params, key) {
|
|
105
|
+
var current = params
|
|
106
|
+
var parts = key.split('.')
|
|
107
|
+
for (var index = 0; index < parts.length; index++) {
|
|
108
|
+
if (current == null || current[parts[index]] === undefined) return undefined
|
|
109
|
+
current = current[parts[index]]
|
|
110
|
+
}
|
|
111
|
+
return current
|
|
112
|
+
}
|
|
113
|
+
function render(tokens, params) {
|
|
114
|
+
var result = ''
|
|
115
|
+
for (var index = 0; index < tokens.length; index++) {
|
|
116
|
+
var token = tokens[index]
|
|
117
|
+
if (typeof token === 'string') result += token
|
|
118
|
+
else {
|
|
119
|
+
var value = resolveParam(params, token.key)
|
|
120
|
+
result += value === undefined ? token.source : value + ''
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return result
|
|
124
|
+
}
|
|
125
|
+
function getMessage(messages, key) {
|
|
126
|
+
var tokens = messages[key]
|
|
127
|
+
return tokens && typeof tokens === 'object' && typeof tokens.length === 'number' ? tokens : undefined
|
|
128
|
+
}
|
|
129
|
+
function t(locale, key, params) {
|
|
130
|
+
var current = catalog.messages[locale] || {}
|
|
131
|
+
var fallback = catalog.messages[catalog.fallbackLocale] || {}
|
|
132
|
+
var tokens = getMessage(current, key) || getMessage(fallback, key)
|
|
133
|
+
return tokens ? render(tokens, params || {}) : key
|
|
134
|
+
}
|
|
135
|
+
module.exports = { t: t }
|
|
136
|
+
`;
|
|
137
|
+
}
|
|
138
|
+
function generateI18nRuntimeSource(catalog) {
|
|
139
|
+
return `import { createI18n } from '@weapp-vite/i18n/runtime'
|
|
140
|
+
const i18n = createI18n(${JSON.stringify(catalog)})
|
|
141
|
+
export const ${WEAPP_I18N_RUNTIME_MARKER} = true
|
|
142
|
+
export { i18n }
|
|
143
|
+
export const global = i18n.global
|
|
144
|
+
export const behavior = i18n.behavior
|
|
145
|
+
export const page = i18n.page
|
|
146
|
+
`;
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
149
|
+
Object.defineProperty(exports, "WEAPP_I18N_LOCALE_DATA_KEY", {
|
|
150
|
+
enumerable: true,
|
|
151
|
+
get: function() {
|
|
152
|
+
return WEAPP_I18N_LOCALE_DATA_KEY;
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
Object.defineProperty(exports, "compileI18nCatalog", {
|
|
156
|
+
enumerable: true,
|
|
157
|
+
get: function() {
|
|
158
|
+
return compileI18nCatalog;
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
Object.defineProperty(exports, "compileI18nMessage", {
|
|
162
|
+
enumerable: true,
|
|
163
|
+
get: function() {
|
|
164
|
+
return compileI18nMessage;
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
Object.defineProperty(exports, "compileI18nMessages", {
|
|
168
|
+
enumerable: true,
|
|
169
|
+
get: function() {
|
|
170
|
+
return compileI18nMessages;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
Object.defineProperty(exports, "generateI18nCatalogModuleSource", {
|
|
174
|
+
enumerable: true,
|
|
175
|
+
get: function() {
|
|
176
|
+
return generateI18nCatalogModuleSource;
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
Object.defineProperty(exports, "generateI18nRuntimeSource", {
|
|
180
|
+
enumerable: true,
|
|
181
|
+
get: function() {
|
|
182
|
+
return generateI18nRuntimeSource;
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
Object.defineProperty(exports, "generateI18nWxsSource", {
|
|
186
|
+
enumerable: true,
|
|
187
|
+
get: function() {
|
|
188
|
+
return generateI18nWxsSource;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_compiler = require("./compiler2.cjs");
|
|
3
|
+
//#region src/runtime.ts
|
|
4
|
+
function hasOwn(object, key) {
|
|
5
|
+
return object != null && Object.prototype.hasOwnProperty.call(object, key);
|
|
6
|
+
}
|
|
7
|
+
function resolveParam(params, key) {
|
|
8
|
+
let current = params;
|
|
9
|
+
for (const part of key.split(".")) {
|
|
10
|
+
if (!hasOwn(current, part)) return;
|
|
11
|
+
current = current[part];
|
|
12
|
+
}
|
|
13
|
+
return current;
|
|
14
|
+
}
|
|
15
|
+
function render(tokens, params) {
|
|
16
|
+
let result = "";
|
|
17
|
+
for (const token of tokens) if (typeof token === "string") result += token;
|
|
18
|
+
else {
|
|
19
|
+
const value = resolveParam(params, token.key);
|
|
20
|
+
result += value === void 0 ? token.source : String(value);
|
|
21
|
+
}
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
function validateCatalog(catalog) {
|
|
25
|
+
if (!catalog || !Array.isArray(catalog.locales) || !catalog.locales.length) throw new TypeError("i18n catalog 必须包含至少一个 locale。");
|
|
26
|
+
if (!catalog.locales.includes(catalog.defaultLocale)) throw new RangeError(`i18n defaultLocale 未构建:${catalog.defaultLocale}`);
|
|
27
|
+
if (!catalog.locales.includes(catalog.fallbackLocale)) throw new RangeError(`i18n fallbackLocale 未构建:${catalog.fallbackLocale}`);
|
|
28
|
+
}
|
|
29
|
+
function normalizeOptions(options) {
|
|
30
|
+
if ("defaultLocale" in options && "locales" in options) {
|
|
31
|
+
validateCatalog(options);
|
|
32
|
+
return options;
|
|
33
|
+
}
|
|
34
|
+
const locale = options.locale.trim();
|
|
35
|
+
const fallbackLocale = options.fallbackLocale?.trim() || locale;
|
|
36
|
+
if (!locale) throw new Error("i18n locale 不能为空。");
|
|
37
|
+
const messages = require_compiler.compileI18nMessages(options.messages);
|
|
38
|
+
const catalog = {
|
|
39
|
+
defaultLocale: locale,
|
|
40
|
+
fallbackLocale,
|
|
41
|
+
locales: Object.keys(messages).sort(),
|
|
42
|
+
messages
|
|
43
|
+
};
|
|
44
|
+
validateCatalog(catalog);
|
|
45
|
+
return catalog;
|
|
46
|
+
}
|
|
47
|
+
function resolveHost(host) {
|
|
48
|
+
const behavior = host?.Behavior ?? (typeof Behavior === "function" ? Behavior : void 0);
|
|
49
|
+
const page = host?.Page ?? (typeof Page === "function" ? Page : void 0);
|
|
50
|
+
if (!behavior || !page) throw new Error("i18n 运行时需要小程序 Behavior 和 Page 全局 API。");
|
|
51
|
+
return {
|
|
52
|
+
Behavior: behavior,
|
|
53
|
+
Page: page
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function createState(catalog) {
|
|
57
|
+
let currentLocale = catalog.defaultLocale;
|
|
58
|
+
const instances = /* @__PURE__ */ new Set();
|
|
59
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
60
|
+
function setLocale(locale) {
|
|
61
|
+
if (!catalog.locales.includes(locale)) throw new RangeError(`Unknown i18n locale: ${locale}`);
|
|
62
|
+
if (locale === currentLocale) return;
|
|
63
|
+
currentLocale = locale;
|
|
64
|
+
for (const instance of instances) instance.setData({ [require_compiler.WEAPP_I18N_LOCALE_DATA_KEY]: locale });
|
|
65
|
+
for (const listener of listeners) listener(locale);
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
currentLocale: () => currentLocale,
|
|
69
|
+
global: {
|
|
70
|
+
t(key, params = {}) {
|
|
71
|
+
const current = catalog.messages[currentLocale] ?? {};
|
|
72
|
+
const fallback = catalog.messages[catalog.fallbackLocale] ?? {};
|
|
73
|
+
const tokens = hasOwn(current, key) ? current[key] : hasOwn(fallback, key) ? fallback[key] : void 0;
|
|
74
|
+
return tokens ? render(tokens, params) : key;
|
|
75
|
+
},
|
|
76
|
+
get locale() {
|
|
77
|
+
return currentLocale;
|
|
78
|
+
},
|
|
79
|
+
set locale(locale) {
|
|
80
|
+
setLocale(locale);
|
|
81
|
+
},
|
|
82
|
+
fallbackLocale: catalog.fallbackLocale,
|
|
83
|
+
availableLocales: Object.freeze([...catalog.locales]),
|
|
84
|
+
onLocaleChange(handler) {
|
|
85
|
+
listeners.add(handler);
|
|
86
|
+
let active = true;
|
|
87
|
+
return { off() {
|
|
88
|
+
if (active) {
|
|
89
|
+
active = false;
|
|
90
|
+
listeners.delete(handler);
|
|
91
|
+
}
|
|
92
|
+
} };
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
attach(instance) {
|
|
96
|
+
instances.add(instance);
|
|
97
|
+
instance.setData({ [require_compiler.WEAPP_I18N_LOCALE_DATA_KEY]: currentLocale });
|
|
98
|
+
},
|
|
99
|
+
detach(instance) {
|
|
100
|
+
instances.delete(instance);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function createBehavior(state, host) {
|
|
105
|
+
return host.Behavior({
|
|
106
|
+
data: { [require_compiler.WEAPP_I18N_LOCALE_DATA_KEY]: state.currentLocale() },
|
|
107
|
+
lifetimes: {
|
|
108
|
+
attached() {
|
|
109
|
+
state.attach(this);
|
|
110
|
+
},
|
|
111
|
+
detached() {
|
|
112
|
+
state.detach(this);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
function createPageAdapter(state, host) {
|
|
118
|
+
return ((options) => {
|
|
119
|
+
if (hasOwn(options.data, "__wv_i18n_locale")) throw new Error(`i18n Page data 与保留字段 \`${require_compiler.WEAPP_I18N_LOCALE_DATA_KEY}\` 冲突。`);
|
|
120
|
+
const originalLoad = options.onLoad;
|
|
121
|
+
const originalUnload = options.onUnload;
|
|
122
|
+
const next = Object.assign({}, options, {
|
|
123
|
+
data: Object.assign({}, options.data, { [require_compiler.WEAPP_I18N_LOCALE_DATA_KEY]: state.currentLocale() }),
|
|
124
|
+
onLoad(...args) {
|
|
125
|
+
state.attach(this);
|
|
126
|
+
try {
|
|
127
|
+
return originalLoad?.apply(this, args);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
state.detach(this);
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
onUnload(...args) {
|
|
134
|
+
try {
|
|
135
|
+
return originalUnload?.apply(this, args);
|
|
136
|
+
} finally {
|
|
137
|
+
state.detach(this);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return host.Page(next);
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
function createI18n(options, host) {
|
|
145
|
+
const resolvedHost = resolveHost(host);
|
|
146
|
+
const state = createState(normalizeOptions(options));
|
|
147
|
+
return {
|
|
148
|
+
global: state.global,
|
|
149
|
+
behavior: createBehavior(state, resolvedHost),
|
|
150
|
+
page: createPageAdapter(state, resolvedHost)
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
exports.createI18n = createI18n;
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { compileNativeI18n } from "./compiler.mjs";
|
|
3
|
+
import process from "node:process";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
//#region src/cli.ts
|
|
6
|
+
function printHelp() {
|
|
7
|
+
console.log(`weapp-i18n compile --src-root <dir> --default-locale <locale> [options]
|
|
8
|
+
|
|
9
|
+
Options:
|
|
10
|
+
--fallback-locale <locale> Fallback locale, defaults to defaultLocale
|
|
11
|
+
--out-dir <dir> Generated asset directory, defaults to <src-root>/i18n
|
|
12
|
+
--help Show this help
|
|
13
|
+
`);
|
|
14
|
+
}
|
|
15
|
+
async function main() {
|
|
16
|
+
const [command, ...args] = process.argv.slice(2);
|
|
17
|
+
if (!command || command === "--help" || command === "-h") {
|
|
18
|
+
printHelp();
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (command !== "compile") throw new Error(`未知命令:${command}`);
|
|
22
|
+
const parsed = parseArgs({
|
|
23
|
+
args,
|
|
24
|
+
options: {
|
|
25
|
+
"default-locale": { type: "string" },
|
|
26
|
+
"fallback-locale": { type: "string" },
|
|
27
|
+
"help": {
|
|
28
|
+
type: "boolean",
|
|
29
|
+
short: "h"
|
|
30
|
+
},
|
|
31
|
+
"out-dir": { type: "string" },
|
|
32
|
+
"src-root": { type: "string" }
|
|
33
|
+
},
|
|
34
|
+
strict: true
|
|
35
|
+
});
|
|
36
|
+
if (parsed.values.help) {
|
|
37
|
+
printHelp();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const srcRoot = parsed.values["src-root"];
|
|
41
|
+
const defaultLocale = parsed.values["default-locale"];
|
|
42
|
+
if (!srcRoot || !defaultLocale) throw new Error("compile 需要 --src-root 和 --default-locale。");
|
|
43
|
+
const result = await compileNativeI18n({
|
|
44
|
+
defaultLocale,
|
|
45
|
+
fallbackLocale: parsed.values["fallback-locale"],
|
|
46
|
+
outDir: parsed.values["out-dir"],
|
|
47
|
+
srcRoot
|
|
48
|
+
});
|
|
49
|
+
console.log(`generated ${result.jsFile}`);
|
|
50
|
+
console.log(`generated ${result.wxsFile}`);
|
|
51
|
+
}
|
|
52
|
+
main().catch((error) => {
|
|
53
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
54
|
+
process.exitCode = 1;
|
|
55
|
+
});
|
|
56
|
+
//#endregion
|
|
57
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { _ as I18nPlaceholderToken, a as I18nCompileOptions, d as I18nLocaleFileInput, h as I18nMessages, i as I18nCatalog, n as CompileNativeI18nResult, o as I18nCompiledMessages, p as I18nMessageToken, t as CompileNativeI18nOptions } from "./types.mjs";
|
|
2
|
+
//#region src/compiler.d.ts
|
|
3
|
+
declare function compileI18nMessage(message: string): I18nMessageToken[];
|
|
4
|
+
declare function compileI18nMessages(messages: I18nMessages): I18nCompiledMessages;
|
|
5
|
+
declare function compileI18nCatalog(files: I18nLocaleFileInput[], options: I18nCompileOptions): I18nCatalog;
|
|
6
|
+
declare function generateI18nCatalogModuleSource(catalog: I18nCatalog): string;
|
|
7
|
+
declare function generateI18nWxsSource(catalog: I18nCatalog): string;
|
|
8
|
+
declare function generateI18nRuntimeSource(catalog: I18nCatalog): string;
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/native.d.ts
|
|
11
|
+
declare function compileNativeI18n(options: CompileNativeI18nOptions): Promise<CompileNativeI18nResult>;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { type CompileNativeI18nOptions, type CompileNativeI18nResult, type I18nCatalog, type I18nCompileOptions, type I18nLocaleFileInput, type I18nMessageToken, type I18nPlaceholderToken, compileI18nCatalog, compileI18nMessage, compileI18nMessages, compileNativeI18n, generateI18nCatalogModuleSource, generateI18nRuntimeSource, generateI18nWxsSource };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { a as generateI18nRuntimeSource, i as generateI18nCatalogModuleSource, n as compileI18nMessage, o as generateI18nWxsSource, r as compileI18nMessages, t as compileI18nCatalog } from "./compiler2.mjs";
|
|
2
|
+
import { promises } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
//#region src/native.ts
|
|
5
|
+
async function collectLocaleFiles(root, files) {
|
|
6
|
+
const entries = await promises.readdir(root, { withFileTypes: true });
|
|
7
|
+
for (const entry of entries) {
|
|
8
|
+
const filePath = path.join(root, entry.name);
|
|
9
|
+
if (entry.isDirectory()) {
|
|
10
|
+
if (entry.name !== "node_modules" && !entry.name.startsWith(".")) await collectLocaleFiles(filePath, files);
|
|
11
|
+
} else if (entry.isFile() && path.basename(root) === "i18n" && path.extname(entry.name) === ".json") files.push(filePath);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
async function compileNativeI18n(options) {
|
|
15
|
+
const srcRoot = path.resolve(options.srcRoot);
|
|
16
|
+
const outDir = path.resolve(options.outDir ?? path.join(srcRoot, "i18n"));
|
|
17
|
+
const files = [];
|
|
18
|
+
await collectLocaleFiles(srcRoot, files);
|
|
19
|
+
files.sort();
|
|
20
|
+
if (!files.length) throw new Error(`未在 \`${srcRoot}\` 下找到 i18n/*.json locale 文件。`);
|
|
21
|
+
const inputs = [];
|
|
22
|
+
for (const filePath of files) {
|
|
23
|
+
let messages;
|
|
24
|
+
try {
|
|
25
|
+
messages = JSON.parse(await promises.readFile(filePath, "utf8"));
|
|
26
|
+
} catch (error) {
|
|
27
|
+
throw new Error(`无法解析 i18n 文件 \`${filePath}\`:${String(error)}`);
|
|
28
|
+
}
|
|
29
|
+
inputs.push({
|
|
30
|
+
filePath,
|
|
31
|
+
locale: path.basename(filePath, path.extname(filePath)),
|
|
32
|
+
messages
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const catalog = compileI18nCatalog(inputs, options);
|
|
36
|
+
const jsFile = path.join(outDir, "locales.js");
|
|
37
|
+
const wxsFile = path.join(outDir, "locales.wxs");
|
|
38
|
+
await promises.mkdir(outDir, { recursive: true });
|
|
39
|
+
await Promise.all([promises.writeFile(jsFile, generateI18nCatalogModuleSource(catalog), "utf8"), promises.writeFile(wxsFile, generateI18nWxsSource(catalog), "utf8")]);
|
|
40
|
+
return {
|
|
41
|
+
catalog,
|
|
42
|
+
files,
|
|
43
|
+
jsFile,
|
|
44
|
+
wxsFile
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { compileI18nCatalog, compileI18nMessage, compileI18nMessages, compileNativeI18n, generateI18nCatalogModuleSource, generateI18nRuntimeSource, generateI18nWxsSource };
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
const WEAPP_I18N_RUNTIME_MARKER = "__WEAPP_VITE_I18N__";
|
|
2
|
+
const WEAPP_I18N_LOCALE_DATA_KEY = "__wv_i18n_locale";
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region src/compiler.ts
|
|
5
|
+
const PLACEHOLDER_PATH_RE = /^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*)*$/i;
|
|
6
|
+
function isPlainObject(value) {
|
|
7
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
8
|
+
const prototype = Object.getPrototypeOf(value);
|
|
9
|
+
return prototype === Object.prototype || prototype === null;
|
|
10
|
+
}
|
|
11
|
+
function flattenLocaleMessages(input, filePath, visit, prefix = "") {
|
|
12
|
+
if (!isPlainObject(input)) throw new Error(`i18n 文件 \`${filePath}\` 顶层必须是对象。`);
|
|
13
|
+
for (const [key, value] of Object.entries(input)) {
|
|
14
|
+
const normalizedKey = key.trim();
|
|
15
|
+
if (!normalizedKey) throw new Error(`i18n 文件 \`${filePath}\` 包含空 key。`);
|
|
16
|
+
const path = prefix ? `${prefix}.${normalizedKey}` : normalizedKey;
|
|
17
|
+
if (typeof value === "string") visit(path, value);
|
|
18
|
+
else if (isPlainObject(value)) flattenLocaleMessages(value, filePath, visit, path);
|
|
19
|
+
else throw new Error(`i18n 文件 \`${filePath}\` 的 \`${path}\` 必须是字符串或嵌套对象。`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function compileI18nMessage(message) {
|
|
23
|
+
const tokens = [];
|
|
24
|
+
let literal = "";
|
|
25
|
+
const pushLiteral = () => {
|
|
26
|
+
if (literal || tokens.length === 0) {
|
|
27
|
+
tokens.push(literal);
|
|
28
|
+
literal = "";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
for (let index = 0; index < message.length;) {
|
|
32
|
+
if (message[index] !== "{") {
|
|
33
|
+
literal += message[index];
|
|
34
|
+
index++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
let depth = 1;
|
|
38
|
+
let end = index + 1;
|
|
39
|
+
while (end < message.length && depth > 0) {
|
|
40
|
+
if (message[end] === "{") depth++;
|
|
41
|
+
else if (message[end] === "}") depth--;
|
|
42
|
+
end++;
|
|
43
|
+
}
|
|
44
|
+
if (depth > 0) {
|
|
45
|
+
literal += message.slice(index);
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
const source = message.slice(index, end);
|
|
49
|
+
const key = source.slice(1, -1);
|
|
50
|
+
if (PLACEHOLDER_PATH_RE.test(key)) {
|
|
51
|
+
if (literal) pushLiteral();
|
|
52
|
+
tokens.push({
|
|
53
|
+
key,
|
|
54
|
+
source
|
|
55
|
+
});
|
|
56
|
+
} else literal += source;
|
|
57
|
+
index = end;
|
|
58
|
+
}
|
|
59
|
+
if (literal || tokens.length === 0) pushLiteral();
|
|
60
|
+
return tokens;
|
|
61
|
+
}
|
|
62
|
+
function compileI18nMessages(messages) {
|
|
63
|
+
const compiled = Object.create(null);
|
|
64
|
+
for (const [locale, localeMessages] of Object.entries(messages)) {
|
|
65
|
+
const target = compiled[locale] ??= Object.create(null);
|
|
66
|
+
flattenLocaleMessages(localeMessages, `${locale}.json`, (key, value) => {
|
|
67
|
+
target[key] = compileI18nMessage(value);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return compiled;
|
|
71
|
+
}
|
|
72
|
+
function compileI18nCatalog(files, options) {
|
|
73
|
+
const defaultLocale = options.defaultLocale.trim();
|
|
74
|
+
const fallbackLocale = options.fallbackLocale?.trim() || defaultLocale;
|
|
75
|
+
if (!defaultLocale) throw new Error("i18n defaultLocale 不能为空。");
|
|
76
|
+
const messages = Object.create(null);
|
|
77
|
+
const sources = /* @__PURE__ */ new Map();
|
|
78
|
+
for (const file of [...files].sort((left, right) => left.filePath.localeCompare(right.filePath))) {
|
|
79
|
+
const localeMessages = messages[file.locale] ??= Object.create(null);
|
|
80
|
+
flattenLocaleMessages(file.messages, file.filePath, (key, value) => {
|
|
81
|
+
const sourceKey = `${file.locale}:${key}`;
|
|
82
|
+
const previous = sources.get(sourceKey);
|
|
83
|
+
if (previous) throw new Error(`i18n locale \`${file.locale}\` 的 key \`${key}\` 重复:\`${previous}\` 与 \`${file.filePath}\`。`);
|
|
84
|
+
sources.set(sourceKey, file.filePath);
|
|
85
|
+
localeMessages[key] = compileI18nMessage(value);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
const locales = Object.keys(messages).sort();
|
|
89
|
+
const sourceFiles = [...new Set(files.map((file) => file.filePath))].sort();
|
|
90
|
+
if (!locales.includes(defaultLocale)) throw new Error(`i18n defaultLocale \`${defaultLocale}\` 没有对应的 locale 文件。已扫描:${sourceFiles.join(", ")}。`);
|
|
91
|
+
if (!locales.includes(fallbackLocale)) throw new Error(`i18n fallbackLocale \`${fallbackLocale}\` 没有对应的 locale 文件。已扫描:${sourceFiles.join(", ")}。`);
|
|
92
|
+
return {
|
|
93
|
+
defaultLocale,
|
|
94
|
+
fallbackLocale,
|
|
95
|
+
locales,
|
|
96
|
+
messages
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function generateI18nCatalogModuleSource(catalog) {
|
|
100
|
+
return `module.exports = ${JSON.stringify(catalog)}\n`;
|
|
101
|
+
}
|
|
102
|
+
function generateI18nWxsSource(catalog) {
|
|
103
|
+
return `var catalog = ${JSON.stringify(catalog)}
|
|
104
|
+
function resolveParam(params, key) {
|
|
105
|
+
var current = params
|
|
106
|
+
var parts = key.split('.')
|
|
107
|
+
for (var index = 0; index < parts.length; index++) {
|
|
108
|
+
if (current == null || current[parts[index]] === undefined) return undefined
|
|
109
|
+
current = current[parts[index]]
|
|
110
|
+
}
|
|
111
|
+
return current
|
|
112
|
+
}
|
|
113
|
+
function render(tokens, params) {
|
|
114
|
+
var result = ''
|
|
115
|
+
for (var index = 0; index < tokens.length; index++) {
|
|
116
|
+
var token = tokens[index]
|
|
117
|
+
if (typeof token === 'string') result += token
|
|
118
|
+
else {
|
|
119
|
+
var value = resolveParam(params, token.key)
|
|
120
|
+
result += value === undefined ? token.source : value + ''
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return result
|
|
124
|
+
}
|
|
125
|
+
function getMessage(messages, key) {
|
|
126
|
+
var tokens = messages[key]
|
|
127
|
+
return tokens && typeof tokens === 'object' && typeof tokens.length === 'number' ? tokens : undefined
|
|
128
|
+
}
|
|
129
|
+
function t(locale, key, params) {
|
|
130
|
+
var current = catalog.messages[locale] || {}
|
|
131
|
+
var fallback = catalog.messages[catalog.fallbackLocale] || {}
|
|
132
|
+
var tokens = getMessage(current, key) || getMessage(fallback, key)
|
|
133
|
+
return tokens ? render(tokens, params || {}) : key
|
|
134
|
+
}
|
|
135
|
+
module.exports = { t: t }
|
|
136
|
+
`;
|
|
137
|
+
}
|
|
138
|
+
function generateI18nRuntimeSource(catalog) {
|
|
139
|
+
return `import { createI18n } from '@weapp-vite/i18n/runtime'
|
|
140
|
+
const i18n = createI18n(${JSON.stringify(catalog)})
|
|
141
|
+
export const ${WEAPP_I18N_RUNTIME_MARKER} = true
|
|
142
|
+
export { i18n }
|
|
143
|
+
export const global = i18n.global
|
|
144
|
+
export const behavior = i18n.behavior
|
|
145
|
+
export const page = i18n.page
|
|
146
|
+
`;
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
149
|
+
export { generateI18nRuntimeSource as a, generateI18nCatalogModuleSource as i, compileI18nMessage as n, generateI18nWxsSource as o, compileI18nMessages as r, WEAPP_I18N_LOCALE_DATA_KEY as s, compileI18nCatalog as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { _ as I18nPlaceholderToken, c as I18nHost, f as I18nLocaleMessages, g as I18nOptions, h as I18nMessages, i as I18nCatalog, l as I18nInstance, m as I18nMessageValue, o as I18nCompiledMessages, p as I18nMessageToken, r as I18nBehavior, s as I18nGlobal, u as I18nLocaleChangeSubscription } from "./types.mjs";
|
|
2
|
+
import { createI18n } from "./runtime.mjs";
|
|
3
|
+
export { type I18nBehavior, type I18nCatalog, type I18nCompiledMessages, type I18nGlobal, type I18nHost, type I18nInstance, type I18nLocaleChangeSubscription, type I18nLocaleMessages, type I18nMessageToken, type I18nMessageValue, type I18nMessages, type I18nOptions, type I18nPlaceholderToken, createI18n };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const WEAPP_I18N_LOCALE_DATA_KEY = "__wv_i18n_locale";
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region src/compiler.ts
|
|
5
|
+
const PLACEHOLDER_PATH_RE = /^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*)*$/i;
|
|
6
|
+
function isPlainObject(value) {
|
|
7
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
8
|
+
const prototype = Object.getPrototypeOf(value);
|
|
9
|
+
return prototype === Object.prototype || prototype === null;
|
|
10
|
+
}
|
|
11
|
+
function flattenLocaleMessages(input, filePath, visit, prefix = "") {
|
|
12
|
+
if (!isPlainObject(input)) throw new Error(`i18n 文件 \`${filePath}\` 顶层必须是对象。`);
|
|
13
|
+
for (const [key, value] of Object.entries(input)) {
|
|
14
|
+
const normalizedKey = key.trim();
|
|
15
|
+
if (!normalizedKey) throw new Error(`i18n 文件 \`${filePath}\` 包含空 key。`);
|
|
16
|
+
const path = prefix ? `${prefix}.${normalizedKey}` : normalizedKey;
|
|
17
|
+
if (typeof value === "string") visit(path, value);
|
|
18
|
+
else if (isPlainObject(value)) flattenLocaleMessages(value, filePath, visit, path);
|
|
19
|
+
else throw new Error(`i18n 文件 \`${filePath}\` 的 \`${path}\` 必须是字符串或嵌套对象。`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function compileI18nMessage(message) {
|
|
23
|
+
const tokens = [];
|
|
24
|
+
let literal = "";
|
|
25
|
+
const pushLiteral = () => {
|
|
26
|
+
if (literal || tokens.length === 0) {
|
|
27
|
+
tokens.push(literal);
|
|
28
|
+
literal = "";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
for (let index = 0; index < message.length;) {
|
|
32
|
+
if (message[index] !== "{") {
|
|
33
|
+
literal += message[index];
|
|
34
|
+
index++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
let depth = 1;
|
|
38
|
+
let end = index + 1;
|
|
39
|
+
while (end < message.length && depth > 0) {
|
|
40
|
+
if (message[end] === "{") depth++;
|
|
41
|
+
else if (message[end] === "}") depth--;
|
|
42
|
+
end++;
|
|
43
|
+
}
|
|
44
|
+
if (depth > 0) {
|
|
45
|
+
literal += message.slice(index);
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
const source = message.slice(index, end);
|
|
49
|
+
const key = source.slice(1, -1);
|
|
50
|
+
if (PLACEHOLDER_PATH_RE.test(key)) {
|
|
51
|
+
if (literal) pushLiteral();
|
|
52
|
+
tokens.push({
|
|
53
|
+
key,
|
|
54
|
+
source
|
|
55
|
+
});
|
|
56
|
+
} else literal += source;
|
|
57
|
+
index = end;
|
|
58
|
+
}
|
|
59
|
+
if (literal || tokens.length === 0) pushLiteral();
|
|
60
|
+
return tokens;
|
|
61
|
+
}
|
|
62
|
+
function compileI18nMessages(messages) {
|
|
63
|
+
const compiled = Object.create(null);
|
|
64
|
+
for (const [locale, localeMessages] of Object.entries(messages)) {
|
|
65
|
+
var _compiled$locale;
|
|
66
|
+
const target = (_compiled$locale = compiled[locale]) !== null && _compiled$locale !== void 0 ? _compiled$locale : compiled[locale] = Object.create(null);
|
|
67
|
+
flattenLocaleMessages(localeMessages, `${locale}.json`, (key, value) => {
|
|
68
|
+
target[key] = compileI18nMessage(value);
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return compiled;
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/runtime.ts
|
|
75
|
+
function hasOwn(object, key) {
|
|
76
|
+
return object != null && Object.prototype.hasOwnProperty.call(object, key);
|
|
77
|
+
}
|
|
78
|
+
function resolveParam(params, key) {
|
|
79
|
+
let current = params;
|
|
80
|
+
for (const part of key.split(".")) {
|
|
81
|
+
if (!hasOwn(current, part)) return;
|
|
82
|
+
current = current[part];
|
|
83
|
+
}
|
|
84
|
+
return current;
|
|
85
|
+
}
|
|
86
|
+
function render(tokens, params) {
|
|
87
|
+
let result = "";
|
|
88
|
+
for (const token of tokens) if (typeof token === "string") result += token;
|
|
89
|
+
else {
|
|
90
|
+
const value = resolveParam(params, token.key);
|
|
91
|
+
result += value === void 0 ? token.source : String(value);
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
function validateCatalog(catalog) {
|
|
96
|
+
if (!catalog || !Array.isArray(catalog.locales) || !catalog.locales.length) throw new TypeError("i18n catalog 必须包含至少一个 locale。");
|
|
97
|
+
if (!catalog.locales.includes(catalog.defaultLocale)) throw new RangeError(`i18n defaultLocale 未构建:${catalog.defaultLocale}`);
|
|
98
|
+
if (!catalog.locales.includes(catalog.fallbackLocale)) throw new RangeError(`i18n fallbackLocale 未构建:${catalog.fallbackLocale}`);
|
|
99
|
+
}
|
|
100
|
+
function normalizeOptions(options) {
|
|
101
|
+
var _options$fallbackLoca;
|
|
102
|
+
if ("defaultLocale" in options && "locales" in options) {
|
|
103
|
+
validateCatalog(options);
|
|
104
|
+
return options;
|
|
105
|
+
}
|
|
106
|
+
const locale = options.locale.trim();
|
|
107
|
+
const fallbackLocale = ((_options$fallbackLoca = options.fallbackLocale) === null || _options$fallbackLoca === void 0 ? void 0 : _options$fallbackLoca.trim()) || locale;
|
|
108
|
+
if (!locale) throw new Error("i18n locale 不能为空。");
|
|
109
|
+
const messages = compileI18nMessages(options.messages);
|
|
110
|
+
const catalog = {
|
|
111
|
+
defaultLocale: locale,
|
|
112
|
+
fallbackLocale,
|
|
113
|
+
locales: Object.keys(messages).sort(),
|
|
114
|
+
messages
|
|
115
|
+
};
|
|
116
|
+
validateCatalog(catalog);
|
|
117
|
+
return catalog;
|
|
118
|
+
}
|
|
119
|
+
function resolveHost(host) {
|
|
120
|
+
var _host$Behavior, _host$Page;
|
|
121
|
+
const behavior = (_host$Behavior = host === null || host === void 0 ? void 0 : host.Behavior) !== null && _host$Behavior !== void 0 ? _host$Behavior : typeof Behavior === "function" ? Behavior : void 0;
|
|
122
|
+
const page = (_host$Page = host === null || host === void 0 ? void 0 : host.Page) !== null && _host$Page !== void 0 ? _host$Page : typeof Page === "function" ? Page : void 0;
|
|
123
|
+
if (!behavior || !page) throw new Error("i18n 运行时需要小程序 Behavior 和 Page 全局 API。");
|
|
124
|
+
return {
|
|
125
|
+
Behavior: behavior,
|
|
126
|
+
Page: page
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function createState(catalog) {
|
|
130
|
+
let currentLocale = catalog.defaultLocale;
|
|
131
|
+
const instances = /* @__PURE__ */ new Set();
|
|
132
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
133
|
+
function setLocale(locale) {
|
|
134
|
+
if (!catalog.locales.includes(locale)) throw new RangeError(`Unknown i18n locale: ${locale}`);
|
|
135
|
+
if (locale === currentLocale) return;
|
|
136
|
+
currentLocale = locale;
|
|
137
|
+
for (const instance of instances) instance.setData({ [WEAPP_I18N_LOCALE_DATA_KEY]: locale });
|
|
138
|
+
for (const listener of listeners) listener(locale);
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
currentLocale: () => currentLocale,
|
|
142
|
+
global: {
|
|
143
|
+
t(key, params = {}) {
|
|
144
|
+
var _catalog$messages$cur, _catalog$messages$cat;
|
|
145
|
+
const current = (_catalog$messages$cur = catalog.messages[currentLocale]) !== null && _catalog$messages$cur !== void 0 ? _catalog$messages$cur : {};
|
|
146
|
+
const fallback = (_catalog$messages$cat = catalog.messages[catalog.fallbackLocale]) !== null && _catalog$messages$cat !== void 0 ? _catalog$messages$cat : {};
|
|
147
|
+
const tokens = hasOwn(current, key) ? current[key] : hasOwn(fallback, key) ? fallback[key] : void 0;
|
|
148
|
+
return tokens ? render(tokens, params) : key;
|
|
149
|
+
},
|
|
150
|
+
get locale() {
|
|
151
|
+
return currentLocale;
|
|
152
|
+
},
|
|
153
|
+
set locale(locale) {
|
|
154
|
+
setLocale(locale);
|
|
155
|
+
},
|
|
156
|
+
fallbackLocale: catalog.fallbackLocale,
|
|
157
|
+
availableLocales: Object.freeze([...catalog.locales]),
|
|
158
|
+
onLocaleChange(handler) {
|
|
159
|
+
listeners.add(handler);
|
|
160
|
+
let active = true;
|
|
161
|
+
return { off() {
|
|
162
|
+
if (active) {
|
|
163
|
+
active = false;
|
|
164
|
+
listeners.delete(handler);
|
|
165
|
+
}
|
|
166
|
+
} };
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
attach(instance) {
|
|
170
|
+
instances.add(instance);
|
|
171
|
+
instance.setData({ [WEAPP_I18N_LOCALE_DATA_KEY]: currentLocale });
|
|
172
|
+
},
|
|
173
|
+
detach(instance) {
|
|
174
|
+
instances.delete(instance);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function createBehavior(state, host) {
|
|
179
|
+
return host.Behavior({
|
|
180
|
+
data: { [WEAPP_I18N_LOCALE_DATA_KEY]: state.currentLocale() },
|
|
181
|
+
lifetimes: {
|
|
182
|
+
attached() {
|
|
183
|
+
state.attach(this);
|
|
184
|
+
},
|
|
185
|
+
detached() {
|
|
186
|
+
state.detach(this);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
function createPageAdapter(state, host) {
|
|
192
|
+
return ((options) => {
|
|
193
|
+
if (hasOwn(options.data, "__wv_i18n_locale")) throw new Error(`i18n Page data 与保留字段 \`${WEAPP_I18N_LOCALE_DATA_KEY}\` 冲突。`);
|
|
194
|
+
const originalLoad = options.onLoad;
|
|
195
|
+
const originalUnload = options.onUnload;
|
|
196
|
+
const next = Object.assign({}, options, {
|
|
197
|
+
data: Object.assign({}, options.data, { [WEAPP_I18N_LOCALE_DATA_KEY]: state.currentLocale() }),
|
|
198
|
+
onLoad(...args) {
|
|
199
|
+
state.attach(this);
|
|
200
|
+
try {
|
|
201
|
+
return originalLoad === null || originalLoad === void 0 ? void 0 : originalLoad.apply(this, args);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
state.detach(this);
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
onUnload(...args) {
|
|
208
|
+
try {
|
|
209
|
+
return originalUnload === null || originalUnload === void 0 ? void 0 : originalUnload.apply(this, args);
|
|
210
|
+
} finally {
|
|
211
|
+
state.detach(this);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
return host.Page(next);
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
function createI18n(options, host) {
|
|
219
|
+
const resolvedHost = resolveHost(host);
|
|
220
|
+
const state = createState(normalizeOptions(options));
|
|
221
|
+
return {
|
|
222
|
+
global: state.global,
|
|
223
|
+
behavior: createBehavior(state, resolvedHost),
|
|
224
|
+
page: createPageAdapter(state, resolvedHost)
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
//#endregion
|
|
228
|
+
exports.createI18n = createI18n;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { c as I18nHost, g as I18nOptions, i as I18nCatalog, l as I18nInstance, r as I18nBehavior, s as I18nGlobal, u as I18nLocaleChangeSubscription } from "./types.mjs";
|
|
2
|
+
//#region src/runtime.d.ts
|
|
3
|
+
declare function createI18n(options: I18nOptions | I18nCatalog, host?: Partial<I18nHost>): I18nInstance;
|
|
4
|
+
//#endregion
|
|
5
|
+
export { type I18nBehavior, type I18nCatalog, type I18nGlobal, type I18nHost, type I18nInstance, type I18nLocaleChangeSubscription, type I18nOptions, createI18n };
|
package/dist/runtime.mjs
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { r as compileI18nMessages, s as WEAPP_I18N_LOCALE_DATA_KEY } from "./compiler2.mjs";
|
|
2
|
+
//#region src/runtime.ts
|
|
3
|
+
function hasOwn(object, key) {
|
|
4
|
+
return object != null && Object.prototype.hasOwnProperty.call(object, key);
|
|
5
|
+
}
|
|
6
|
+
function resolveParam(params, key) {
|
|
7
|
+
let current = params;
|
|
8
|
+
for (const part of key.split(".")) {
|
|
9
|
+
if (!hasOwn(current, part)) return;
|
|
10
|
+
current = current[part];
|
|
11
|
+
}
|
|
12
|
+
return current;
|
|
13
|
+
}
|
|
14
|
+
function render(tokens, params) {
|
|
15
|
+
let result = "";
|
|
16
|
+
for (const token of tokens) if (typeof token === "string") result += token;
|
|
17
|
+
else {
|
|
18
|
+
const value = resolveParam(params, token.key);
|
|
19
|
+
result += value === void 0 ? token.source : String(value);
|
|
20
|
+
}
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
function validateCatalog(catalog) {
|
|
24
|
+
if (!catalog || !Array.isArray(catalog.locales) || !catalog.locales.length) throw new TypeError("i18n catalog 必须包含至少一个 locale。");
|
|
25
|
+
if (!catalog.locales.includes(catalog.defaultLocale)) throw new RangeError(`i18n defaultLocale 未构建:${catalog.defaultLocale}`);
|
|
26
|
+
if (!catalog.locales.includes(catalog.fallbackLocale)) throw new RangeError(`i18n fallbackLocale 未构建:${catalog.fallbackLocale}`);
|
|
27
|
+
}
|
|
28
|
+
function normalizeOptions(options) {
|
|
29
|
+
if ("defaultLocale" in options && "locales" in options) {
|
|
30
|
+
validateCatalog(options);
|
|
31
|
+
return options;
|
|
32
|
+
}
|
|
33
|
+
const locale = options.locale.trim();
|
|
34
|
+
const fallbackLocale = options.fallbackLocale?.trim() || locale;
|
|
35
|
+
if (!locale) throw new Error("i18n locale 不能为空。");
|
|
36
|
+
const messages = compileI18nMessages(options.messages);
|
|
37
|
+
const catalog = {
|
|
38
|
+
defaultLocale: locale,
|
|
39
|
+
fallbackLocale,
|
|
40
|
+
locales: Object.keys(messages).sort(),
|
|
41
|
+
messages
|
|
42
|
+
};
|
|
43
|
+
validateCatalog(catalog);
|
|
44
|
+
return catalog;
|
|
45
|
+
}
|
|
46
|
+
function resolveHost(host) {
|
|
47
|
+
const behavior = host?.Behavior ?? (typeof Behavior === "function" ? Behavior : void 0);
|
|
48
|
+
const page = host?.Page ?? (typeof Page === "function" ? Page : void 0);
|
|
49
|
+
if (!behavior || !page) throw new Error("i18n 运行时需要小程序 Behavior 和 Page 全局 API。");
|
|
50
|
+
return {
|
|
51
|
+
Behavior: behavior,
|
|
52
|
+
Page: page
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function createState(catalog) {
|
|
56
|
+
let currentLocale = catalog.defaultLocale;
|
|
57
|
+
const instances = /* @__PURE__ */ new Set();
|
|
58
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
59
|
+
function setLocale(locale) {
|
|
60
|
+
if (!catalog.locales.includes(locale)) throw new RangeError(`Unknown i18n locale: ${locale}`);
|
|
61
|
+
if (locale === currentLocale) return;
|
|
62
|
+
currentLocale = locale;
|
|
63
|
+
for (const instance of instances) instance.setData({ [WEAPP_I18N_LOCALE_DATA_KEY]: locale });
|
|
64
|
+
for (const listener of listeners) listener(locale);
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
currentLocale: () => currentLocale,
|
|
68
|
+
global: {
|
|
69
|
+
t(key, params = {}) {
|
|
70
|
+
const current = catalog.messages[currentLocale] ?? {};
|
|
71
|
+
const fallback = catalog.messages[catalog.fallbackLocale] ?? {};
|
|
72
|
+
const tokens = hasOwn(current, key) ? current[key] : hasOwn(fallback, key) ? fallback[key] : void 0;
|
|
73
|
+
return tokens ? render(tokens, params) : key;
|
|
74
|
+
},
|
|
75
|
+
get locale() {
|
|
76
|
+
return currentLocale;
|
|
77
|
+
},
|
|
78
|
+
set locale(locale) {
|
|
79
|
+
setLocale(locale);
|
|
80
|
+
},
|
|
81
|
+
fallbackLocale: catalog.fallbackLocale,
|
|
82
|
+
availableLocales: Object.freeze([...catalog.locales]),
|
|
83
|
+
onLocaleChange(handler) {
|
|
84
|
+
listeners.add(handler);
|
|
85
|
+
let active = true;
|
|
86
|
+
return { off() {
|
|
87
|
+
if (active) {
|
|
88
|
+
active = false;
|
|
89
|
+
listeners.delete(handler);
|
|
90
|
+
}
|
|
91
|
+
} };
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
attach(instance) {
|
|
95
|
+
instances.add(instance);
|
|
96
|
+
instance.setData({ [WEAPP_I18N_LOCALE_DATA_KEY]: currentLocale });
|
|
97
|
+
},
|
|
98
|
+
detach(instance) {
|
|
99
|
+
instances.delete(instance);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function createBehavior(state, host) {
|
|
104
|
+
return host.Behavior({
|
|
105
|
+
data: { [WEAPP_I18N_LOCALE_DATA_KEY]: state.currentLocale() },
|
|
106
|
+
lifetimes: {
|
|
107
|
+
attached() {
|
|
108
|
+
state.attach(this);
|
|
109
|
+
},
|
|
110
|
+
detached() {
|
|
111
|
+
state.detach(this);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
function createPageAdapter(state, host) {
|
|
117
|
+
return ((options) => {
|
|
118
|
+
if (hasOwn(options.data, "__wv_i18n_locale")) throw new Error(`i18n Page data 与保留字段 \`${WEAPP_I18N_LOCALE_DATA_KEY}\` 冲突。`);
|
|
119
|
+
const originalLoad = options.onLoad;
|
|
120
|
+
const originalUnload = options.onUnload;
|
|
121
|
+
const next = Object.assign({}, options, {
|
|
122
|
+
data: Object.assign({}, options.data, { [WEAPP_I18N_LOCALE_DATA_KEY]: state.currentLocale() }),
|
|
123
|
+
onLoad(...args) {
|
|
124
|
+
state.attach(this);
|
|
125
|
+
try {
|
|
126
|
+
return originalLoad?.apply(this, args);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
state.detach(this);
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
onUnload(...args) {
|
|
133
|
+
try {
|
|
134
|
+
return originalUnload?.apply(this, args);
|
|
135
|
+
} finally {
|
|
136
|
+
state.detach(this);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
return host.Page(next);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function createI18n(options, host) {
|
|
144
|
+
const resolvedHost = resolveHost(host);
|
|
145
|
+
const state = createState(normalizeOptions(options));
|
|
146
|
+
return {
|
|
147
|
+
global: state.global,
|
|
148
|
+
behavior: createBehavior(state, resolvedHost),
|
|
149
|
+
page: createPageAdapter(state, resolvedHost)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
//#endregion
|
|
153
|
+
export { createI18n };
|
package/dist/types.d.mts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
interface I18nPlaceholderToken {
|
|
3
|
+
key: string;
|
|
4
|
+
source: string;
|
|
5
|
+
}
|
|
6
|
+
type I18nMessageToken = string | I18nPlaceholderToken;
|
|
7
|
+
type I18nCompiledMessages = Record<string, Record<string, I18nMessageToken[]>>;
|
|
8
|
+
type I18nMessageValue = string | {
|
|
9
|
+
[key: string]: I18nMessageValue;
|
|
10
|
+
};
|
|
11
|
+
type I18nLocaleMessages = Record<string, I18nMessageValue>;
|
|
12
|
+
type I18nMessages = Record<string, I18nLocaleMessages>;
|
|
13
|
+
interface I18nOptions {
|
|
14
|
+
locale: string;
|
|
15
|
+
fallbackLocale?: string;
|
|
16
|
+
messages: I18nMessages;
|
|
17
|
+
}
|
|
18
|
+
interface I18nCatalog {
|
|
19
|
+
defaultLocale: string;
|
|
20
|
+
fallbackLocale: string;
|
|
21
|
+
locales: string[];
|
|
22
|
+
messages: I18nCompiledMessages;
|
|
23
|
+
}
|
|
24
|
+
interface I18nLocaleFileInput {
|
|
25
|
+
filePath: string;
|
|
26
|
+
locale: string;
|
|
27
|
+
messages: unknown;
|
|
28
|
+
}
|
|
29
|
+
interface I18nCompileOptions {
|
|
30
|
+
defaultLocale: string;
|
|
31
|
+
fallbackLocale?: string;
|
|
32
|
+
}
|
|
33
|
+
interface I18nLocaleChangeSubscription {
|
|
34
|
+
off: () => void;
|
|
35
|
+
}
|
|
36
|
+
type I18nBehavior = WechatMiniprogram.Behavior.Identifier<WechatMiniprogram.IAnyObject, WechatMiniprogram.IAnyObject, WechatMiniprogram.IAnyObject, []>;
|
|
37
|
+
interface I18nGlobal {
|
|
38
|
+
t: (key: string, params?: Record<string, unknown>) => string;
|
|
39
|
+
locale: string;
|
|
40
|
+
readonly fallbackLocale: string;
|
|
41
|
+
readonly availableLocales: readonly string[];
|
|
42
|
+
onLocaleChange: (handler: (locale: string) => void) => I18nLocaleChangeSubscription;
|
|
43
|
+
}
|
|
44
|
+
interface I18nHost {
|
|
45
|
+
Behavior: typeof Behavior;
|
|
46
|
+
Page: typeof Page;
|
|
47
|
+
}
|
|
48
|
+
interface I18nInstance {
|
|
49
|
+
global: I18nGlobal;
|
|
50
|
+
behavior: I18nBehavior;
|
|
51
|
+
page: typeof Page;
|
|
52
|
+
}
|
|
53
|
+
interface CompileNativeI18nOptions extends I18nCompileOptions {
|
|
54
|
+
outDir?: string;
|
|
55
|
+
srcRoot: string;
|
|
56
|
+
}
|
|
57
|
+
interface CompileNativeI18nResult {
|
|
58
|
+
catalog: I18nCatalog;
|
|
59
|
+
files: string[];
|
|
60
|
+
jsFile: string;
|
|
61
|
+
wxsFile: string;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { I18nPlaceholderToken as _, I18nCompileOptions as a, I18nHost as c, I18nLocaleFileInput as d, I18nLocaleMessages as f, I18nOptions as g, I18nMessages as h, I18nCatalog as i, I18nInstance as l, I18nMessageValue as m, CompileNativeI18nResult as n, I18nCompiledMessages as o, I18nMessageToken as p, I18nBehavior as r, I18nGlobal as s, CompileNativeI18nOptions as t, I18nLocaleChangeSubscription as u };
|
package/package.json
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@weapp-vite/i18n",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "First-party i18n runtime and compiler for native WeChat mini programs",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/weapp-vite/weapp-vite.git",
|
|
10
|
+
"directory": "packages-runtime/i18n"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/weapp-vite/weapp-vite/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"i18n",
|
|
17
|
+
"miniprogram",
|
|
18
|
+
"weapp",
|
|
19
|
+
"wechat"
|
|
20
|
+
],
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.mts",
|
|
25
|
+
"import": "./dist/index.mjs",
|
|
26
|
+
"require": "./dist/cjs/index.cjs"
|
|
27
|
+
},
|
|
28
|
+
"./runtime": {
|
|
29
|
+
"types": "./dist/runtime.d.mts",
|
|
30
|
+
"import": "./dist/runtime.mjs",
|
|
31
|
+
"require": "./dist/cjs/runtime.cjs"
|
|
32
|
+
},
|
|
33
|
+
"./compiler": {
|
|
34
|
+
"types": "./dist/compiler.d.mts",
|
|
35
|
+
"import": "./dist/compiler.mjs",
|
|
36
|
+
"require": "./dist/cjs/compiler.cjs"
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"main": "./dist/cjs/index.cjs",
|
|
41
|
+
"module": "./dist/index.mjs",
|
|
42
|
+
"types": "./dist/index.d.mts",
|
|
43
|
+
"miniprogram": "./dist/miniprogram",
|
|
44
|
+
"bin": {
|
|
45
|
+
"weapp-i18n": "./bin/weapp-i18n.js"
|
|
46
|
+
},
|
|
47
|
+
"files": [
|
|
48
|
+
"README.md",
|
|
49
|
+
"bin",
|
|
50
|
+
"dist"
|
|
51
|
+
],
|
|
52
|
+
"engines": {
|
|
53
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"miniprogram-api-typings": "^5.0.0"
|
|
60
|
+
},
|
|
61
|
+
"peerDependenciesMeta": {
|
|
62
|
+
"miniprogram-api-typings": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
"dependencies": {
|
|
67
|
+
"@weapp-core/constants": "0.1.17"
|
|
68
|
+
},
|
|
69
|
+
"devDependencies": {
|
|
70
|
+
"miniprogram-api-typings": "^5.2.3"
|
|
71
|
+
},
|
|
72
|
+
"scripts": {
|
|
73
|
+
"pretest": "pnpm build",
|
|
74
|
+
"dev": "tsdown -w --sourcemap",
|
|
75
|
+
"build": "tsdown",
|
|
76
|
+
"test": "vitest run",
|
|
77
|
+
"test:types": "pnpm build && tsd",
|
|
78
|
+
"typecheck": "tsc --noEmit",
|
|
79
|
+
"lint": "eslint .",
|
|
80
|
+
"lint:fix": "eslint . --fix"
|
|
81
|
+
}
|
|
82
|
+
}
|