@hyphacommerce/i18n 0.0.0-stage → 0.1.0-beta.4
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-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +276 -2
- package/dist/bin.mjs +250 -0
- package/dist/check.d.ts +49 -0
- package/dist/check.js +139 -0
- package/dist/index.d.ts +79 -0
- package/dist/index.js +122 -0
- package/dist/react.d.ts +28 -0
- package/dist/react.js +57 -0
- package/dist/translator-B9SeoqOu.js +241 -0
- package/dist/translator-BxDsP96P.d.ts +60 -0
- package/package.json +63 -3
package/dist/bin.mjs
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { TYPE } from "@formatjs/icu-messageformat-parser";
|
|
6
|
+
import { IntlMessageFormat } from "intl-messageformat";
|
|
7
|
+
// package.json
|
|
8
|
+
var version = "0.1.0-beta.4";
|
|
9
|
+
// src/check.ts
|
|
10
|
+
/**
|
|
11
|
+
* The placeholders and tags of an ICU message, in every branch of its plurals and
|
|
12
|
+
* selects. Throws what the parser throws when it isn't one.
|
|
13
|
+
*/
|
|
14
|
+
function placeholdersOf(message) {
|
|
15
|
+
const names = /* @__PURE__ */ new Set();
|
|
16
|
+
const tags = /* @__PURE__ */ new Set();
|
|
17
|
+
const walk = (elements) => {
|
|
18
|
+
for (const element of elements) {
|
|
19
|
+
if (element.type === TYPE.literal || element.type === TYPE.pound) continue;
|
|
20
|
+
if (element.type === TYPE.tag) {
|
|
21
|
+
tags.add(element.value);
|
|
22
|
+
walk(element.children);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
names.add(element.value);
|
|
26
|
+
if (element.type === TYPE.plural || element.type === TYPE.select) for (const option of Object.values(element.options)) walk(option.value);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
walk(new IntlMessageFormat(message, "en").getAst());
|
|
30
|
+
return {
|
|
31
|
+
arguments: [...names].toSorted(),
|
|
32
|
+
tags: [...tags].toSorted()
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Checks the catalogs of an app, by language. Fails (a problem) on: a message that
|
|
37
|
+
* isn't ICU MessageFormat, a key the source lacks, placeholders or tags that differ
|
|
38
|
+
* from the source's, and a missing key in a language that must be complete. What other
|
|
39
|
+
* languages still lack is reported, not a problem. An empty message isn't a translation:
|
|
40
|
+
* the key counts as lacking, and an empty message in the source is a problem.
|
|
41
|
+
*/
|
|
42
|
+
function checkCatalogs(catalogs, options = {}) {
|
|
43
|
+
const source = options.source ?? "en";
|
|
44
|
+
const complete = new Set(options.complete);
|
|
45
|
+
const problems = [];
|
|
46
|
+
const missing = {};
|
|
47
|
+
const parsed = /* @__PURE__ */ new Map();
|
|
48
|
+
for (const [language, catalog] of Object.entries(catalogs)) {
|
|
49
|
+
const messages = /* @__PURE__ */ new Map();
|
|
50
|
+
for (const [key, message] of Object.entries(catalog)) {
|
|
51
|
+
if (typeof message !== "string") {
|
|
52
|
+
problems.push({
|
|
53
|
+
code: "invalid_message",
|
|
54
|
+
language,
|
|
55
|
+
key,
|
|
56
|
+
message: "isn't a string"
|
|
57
|
+
});
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (isBlank(message)) {
|
|
61
|
+
if (language === source) problems.push({
|
|
62
|
+
code: "invalid_message",
|
|
63
|
+
language,
|
|
64
|
+
key,
|
|
65
|
+
message: "is empty"
|
|
66
|
+
});
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
messages.set(key, placeholdersOf(message));
|
|
71
|
+
} catch (error) {
|
|
72
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
73
|
+
problems.push({
|
|
74
|
+
code: "invalid_message",
|
|
75
|
+
language,
|
|
76
|
+
key,
|
|
77
|
+
message: why
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
parsed.set(language, messages);
|
|
82
|
+
}
|
|
83
|
+
for (const language of [source, ...complete]) if (!Object.hasOwn(catalogs, language)) problems.push({
|
|
84
|
+
code: "missing_language",
|
|
85
|
+
language,
|
|
86
|
+
message: "has no catalog"
|
|
87
|
+
});
|
|
88
|
+
const sourceCatalog = Object.hasOwn(catalogs, source) ? catalogs[source] : void 0;
|
|
89
|
+
if (sourceCatalog === void 0) return {
|
|
90
|
+
source,
|
|
91
|
+
problems,
|
|
92
|
+
missing
|
|
93
|
+
};
|
|
94
|
+
const sourceParsed = parsed.get(source);
|
|
95
|
+
for (const [language, catalog] of Object.entries(catalogs)) {
|
|
96
|
+
if (language === source) continue;
|
|
97
|
+
for (const key of Object.keys(catalog)) {
|
|
98
|
+
if (!Object.hasOwn(sourceCatalog, key)) {
|
|
99
|
+
problems.push({
|
|
100
|
+
code: "unknown_key",
|
|
101
|
+
language,
|
|
102
|
+
key,
|
|
103
|
+
message: `${source} has no such key`
|
|
104
|
+
});
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const expected = sourceParsed?.get(key);
|
|
108
|
+
const found = parsed.get(language)?.get(key);
|
|
109
|
+
if (!expected || !found) continue;
|
|
110
|
+
const difference = [...differences("placeholder", expected.arguments, found.arguments), ...differences("tag", expected.tags, found.tags)];
|
|
111
|
+
if (difference.length > 0) problems.push({
|
|
112
|
+
code: "placeholder_mismatch",
|
|
113
|
+
language,
|
|
114
|
+
key,
|
|
115
|
+
message: difference.join("; ")
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
const lacks = Object.keys(sourceCatalog).filter((key) => !Object.hasOwn(catalog, key) || isBlank(catalog[key])).toSorted();
|
|
119
|
+
missing[language] = lacks;
|
|
120
|
+
if (complete.has(language)) for (const key of lacks) problems.push({
|
|
121
|
+
code: "missing_key",
|
|
122
|
+
language,
|
|
123
|
+
key,
|
|
124
|
+
message: "must be translated"
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
source,
|
|
129
|
+
problems,
|
|
130
|
+
missing
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/** An empty message: a key someone added without its translation. */
|
|
134
|
+
function isBlank(message) {
|
|
135
|
+
return typeof message === "string" && message.trim() === "";
|
|
136
|
+
}
|
|
137
|
+
function differences(what, expected, found) {
|
|
138
|
+
const out = [];
|
|
139
|
+
const lacks = expected.filter((name) => !found.includes(name));
|
|
140
|
+
const extra = found.filter((name) => !expected.includes(name));
|
|
141
|
+
if (lacks.length > 0) out.push(`lacks ${what} ${lacks.join(", ")}`);
|
|
142
|
+
if (extra.length > 0) out.push(`has ${what} ${extra.join(", ")} the source doesn't`);
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
// scripts/check.ts
|
|
146
|
+
const USAGE = "usage: hypha-i18n-check <messages> [--source en] [--complete <language>]…";
|
|
147
|
+
/** Why the directory couldn't be read as catalogs. */
|
|
148
|
+
var UsageError = class extends Error {};
|
|
149
|
+
/** The catalogs under `dir`, by language. */
|
|
150
|
+
async function readCatalogs(dir) {
|
|
151
|
+
const catalogs = {};
|
|
152
|
+
const entries = (await readdir(dir, { withFileTypes: true }).catch(() => {
|
|
153
|
+
throw new UsageError(`${dir} isn't a directory`);
|
|
154
|
+
})).filter((entry) => !entry.name.startsWith(".")).filter((entry) => entry.isDirectory() || entry.name.endsWith(".json")).toSorted((a, b) => a.name.localeCompare(b.name));
|
|
155
|
+
const folder = entries.find((entry) => entry.isDirectory());
|
|
156
|
+
const loose = entries.find((entry) => !entry.isDirectory());
|
|
157
|
+
if (folder && loose) throw new UsageError(`${dir} mixes two layouts: ${folder.name}/ (a folder per language) and ${loose.name} (a file per language). Keep one.`);
|
|
158
|
+
for (const entry of entries) {
|
|
159
|
+
const path = join(dir, entry.name);
|
|
160
|
+
if (entry.isDirectory()) {
|
|
161
|
+
const catalog = {};
|
|
162
|
+
catalogs[entry.name] = catalog;
|
|
163
|
+
const files = (await readdir(path)).filter((name) => name.endsWith(".json")).toSorted();
|
|
164
|
+
for (const file of files) {
|
|
165
|
+
const namespace = file.slice(0, -5);
|
|
166
|
+
for (const [key, message] of Object.entries(await readJson(join(path, file)))) catalog[`${namespace}.${key}`] = message;
|
|
167
|
+
}
|
|
168
|
+
} else catalogs[entry.name.slice(0, -5)] = await readJson(path);
|
|
169
|
+
}
|
|
170
|
+
return catalogs;
|
|
171
|
+
}
|
|
172
|
+
async function readJson(path) {
|
|
173
|
+
let value;
|
|
174
|
+
try {
|
|
175
|
+
value = JSON.parse(await readFile(path, "utf8"));
|
|
176
|
+
} catch (error) {
|
|
177
|
+
throw new UsageError(`${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
178
|
+
}
|
|
179
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new UsageError(`${path}: a catalog is an object of key: message`);
|
|
180
|
+
return { ...value };
|
|
181
|
+
}
|
|
182
|
+
async function main(argv) {
|
|
183
|
+
const { values, positionals } = parseArgs({
|
|
184
|
+
args: argv,
|
|
185
|
+
allowPositionals: true,
|
|
186
|
+
options: {
|
|
187
|
+
source: {
|
|
188
|
+
type: "string",
|
|
189
|
+
default: "en"
|
|
190
|
+
},
|
|
191
|
+
complete: {
|
|
192
|
+
type: "string",
|
|
193
|
+
multiple: true,
|
|
194
|
+
default: []
|
|
195
|
+
},
|
|
196
|
+
version: {
|
|
197
|
+
type: "boolean",
|
|
198
|
+
default: false
|
|
199
|
+
},
|
|
200
|
+
help: {
|
|
201
|
+
type: "boolean",
|
|
202
|
+
short: "h",
|
|
203
|
+
default: false
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
if (values.version) {
|
|
208
|
+
console.log(version);
|
|
209
|
+
return 0;
|
|
210
|
+
}
|
|
211
|
+
if (values.help) {
|
|
212
|
+
console.log(USAGE);
|
|
213
|
+
return 0;
|
|
214
|
+
}
|
|
215
|
+
const [dir, ...rest] = positionals;
|
|
216
|
+
if (dir === void 0 || rest.length > 0) throw new UsageError(USAGE);
|
|
217
|
+
const catalogs = await readCatalogs(dir);
|
|
218
|
+
const report = checkCatalogs(catalogs, {
|
|
219
|
+
source: values.source,
|
|
220
|
+
complete: values.complete
|
|
221
|
+
});
|
|
222
|
+
for (const language of Object.keys(catalogs)) {
|
|
223
|
+
const count = Object.keys(catalogs[language] ?? {}).length;
|
|
224
|
+
const messages = `${language}: ${count} message${count === 1 ? "" : "s"}`;
|
|
225
|
+
if (language === report.source) {
|
|
226
|
+
console.log(`${messages} (the source)`);
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
const missing = report.missing[language] ?? [];
|
|
230
|
+
console.log(missing.length === 0 ? `${messages}, complete` : `${messages}, ${missing.length} missing`);
|
|
231
|
+
for (const key of missing) console.log(` ${key}`);
|
|
232
|
+
}
|
|
233
|
+
for (const problem of report.problems) {
|
|
234
|
+
const where = problem.key === void 0 ? problem.language : `${problem.language}: ${problem.key}`;
|
|
235
|
+
console.error(`error: ${where}: ${problem.message} (${problem.code})`);
|
|
236
|
+
}
|
|
237
|
+
if (report.problems.length > 0) {
|
|
238
|
+
console.error(`${report.problems.length} problem${report.problems.length === 1 ? "" : "s"}`);
|
|
239
|
+
return 1;
|
|
240
|
+
}
|
|
241
|
+
return 0;
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (!(error instanceof UsageError || error instanceof TypeError)) throw error;
|
|
247
|
+
console.error(error.message);
|
|
248
|
+
process.exitCode = 2;
|
|
249
|
+
}
|
|
250
|
+
export {};
|
package/dist/check.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export type ProblemCode =
|
|
2
|
+
/** The message isn't a string, or isn't ICU MessageFormat. */
|
|
3
|
+
"invalid_message" |
|
|
4
|
+
/** A key the source language doesn't have. */
|
|
5
|
+
"unknown_key" |
|
|
6
|
+
/** Placeholders or tags other than the source's for the key. */
|
|
7
|
+
"placeholder_mismatch" |
|
|
8
|
+
/** A language that must be complete lacks the key. */
|
|
9
|
+
"missing_key" |
|
|
10
|
+
/** A language named (the source, or one that must be complete) has no catalog. */
|
|
11
|
+
"missing_language";
|
|
12
|
+
export interface Problem {
|
|
13
|
+
code: ProblemCode;
|
|
14
|
+
language: string;
|
|
15
|
+
/** The key, or undefined for a problem with the language as a whole. */
|
|
16
|
+
key?: string;
|
|
17
|
+
message: string;
|
|
18
|
+
}
|
|
19
|
+
export interface CheckOptions {
|
|
20
|
+
/** The language every other is held to. `en` by default. */
|
|
21
|
+
source?: string;
|
|
22
|
+
/** Languages that must have every key of the source. */
|
|
23
|
+
complete?: readonly string[];
|
|
24
|
+
}
|
|
25
|
+
export interface CheckReport {
|
|
26
|
+
source: string;
|
|
27
|
+
/** What fails the check. */
|
|
28
|
+
problems: Problem[];
|
|
29
|
+
/** Per language other than the source, the source's keys it still lacks. */
|
|
30
|
+
missing: Record<string, string[]>;
|
|
31
|
+
}
|
|
32
|
+
/** What a message takes: its placeholders' names and its tags', each sorted. */
|
|
33
|
+
export interface Placeholders {
|
|
34
|
+
arguments: string[];
|
|
35
|
+
tags: string[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The placeholders and tags of an ICU message, in every branch of its plurals and
|
|
39
|
+
* selects. Throws what the parser throws when it isn't one.
|
|
40
|
+
*/
|
|
41
|
+
export declare function placeholdersOf(message: string): Placeholders;
|
|
42
|
+
/**
|
|
43
|
+
* Checks the catalogs of an app, by language. Fails (a problem) on: a message that
|
|
44
|
+
* isn't ICU MessageFormat, a key the source lacks, placeholders or tags that differ
|
|
45
|
+
* from the source's, and a missing key in a language that must be complete. What other
|
|
46
|
+
* languages still lack is reported, not a problem. An empty message isn't a translation:
|
|
47
|
+
* the key counts as lacking, and an empty message in the source is a problem.
|
|
48
|
+
*/
|
|
49
|
+
export declare function checkCatalogs(catalogs: Readonly<Record<string, Readonly<Record<string, unknown>>>>, options?: CheckOptions): CheckReport;
|
package/dist/check.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { IntlMessageFormat } from "intl-messageformat";
|
|
2
|
+
import { TYPE } from "@formatjs/icu-messageformat-parser";
|
|
3
|
+
// src/check.ts
|
|
4
|
+
/**
|
|
5
|
+
* The placeholders and tags of an ICU message, in every branch of its plurals and
|
|
6
|
+
* selects. Throws what the parser throws when it isn't one.
|
|
7
|
+
*/
|
|
8
|
+
function placeholdersOf(message) {
|
|
9
|
+
const names = /* @__PURE__ */ new Set();
|
|
10
|
+
const tags = /* @__PURE__ */ new Set();
|
|
11
|
+
const walk = (elements) => {
|
|
12
|
+
for (const element of elements) {
|
|
13
|
+
if (element.type === TYPE.literal || element.type === TYPE.pound) continue;
|
|
14
|
+
if (element.type === TYPE.tag) {
|
|
15
|
+
tags.add(element.value);
|
|
16
|
+
walk(element.children);
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
names.add(element.value);
|
|
20
|
+
if (element.type === TYPE.plural || element.type === TYPE.select) for (const option of Object.values(element.options)) walk(option.value);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
walk(new IntlMessageFormat(message, "en").getAst());
|
|
24
|
+
return {
|
|
25
|
+
arguments: [...names].toSorted(),
|
|
26
|
+
tags: [...tags].toSorted()
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Checks the catalogs of an app, by language. Fails (a problem) on: a message that
|
|
31
|
+
* isn't ICU MessageFormat, a key the source lacks, placeholders or tags that differ
|
|
32
|
+
* from the source's, and a missing key in a language that must be complete. What other
|
|
33
|
+
* languages still lack is reported, not a problem. An empty message isn't a translation:
|
|
34
|
+
* the key counts as lacking, and an empty message in the source is a problem.
|
|
35
|
+
*/
|
|
36
|
+
function checkCatalogs(catalogs, options = {}) {
|
|
37
|
+
const source = options.source ?? "en";
|
|
38
|
+
const complete = new Set(options.complete);
|
|
39
|
+
const problems = [];
|
|
40
|
+
const missing = {};
|
|
41
|
+
const parsed = /* @__PURE__ */ new Map();
|
|
42
|
+
for (const [language, catalog] of Object.entries(catalogs)) {
|
|
43
|
+
const messages = /* @__PURE__ */ new Map();
|
|
44
|
+
for (const [key, message] of Object.entries(catalog)) {
|
|
45
|
+
if (typeof message !== "string") {
|
|
46
|
+
problems.push({
|
|
47
|
+
code: "invalid_message",
|
|
48
|
+
language,
|
|
49
|
+
key,
|
|
50
|
+
message: "isn't a string"
|
|
51
|
+
});
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (isBlank(message)) {
|
|
55
|
+
if (language === source) problems.push({
|
|
56
|
+
code: "invalid_message",
|
|
57
|
+
language,
|
|
58
|
+
key,
|
|
59
|
+
message: "is empty"
|
|
60
|
+
});
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
messages.set(key, placeholdersOf(message));
|
|
65
|
+
} catch (error) {
|
|
66
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
67
|
+
problems.push({
|
|
68
|
+
code: "invalid_message",
|
|
69
|
+
language,
|
|
70
|
+
key,
|
|
71
|
+
message: why
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
parsed.set(language, messages);
|
|
76
|
+
}
|
|
77
|
+
for (const language of [source, ...complete]) if (!Object.hasOwn(catalogs, language)) problems.push({
|
|
78
|
+
code: "missing_language",
|
|
79
|
+
language,
|
|
80
|
+
message: "has no catalog"
|
|
81
|
+
});
|
|
82
|
+
const sourceCatalog = Object.hasOwn(catalogs, source) ? catalogs[source] : void 0;
|
|
83
|
+
if (sourceCatalog === void 0) return {
|
|
84
|
+
source,
|
|
85
|
+
problems,
|
|
86
|
+
missing
|
|
87
|
+
};
|
|
88
|
+
const sourceParsed = parsed.get(source);
|
|
89
|
+
for (const [language, catalog] of Object.entries(catalogs)) {
|
|
90
|
+
if (language === source) continue;
|
|
91
|
+
for (const key of Object.keys(catalog)) {
|
|
92
|
+
if (!Object.hasOwn(sourceCatalog, key)) {
|
|
93
|
+
problems.push({
|
|
94
|
+
code: "unknown_key",
|
|
95
|
+
language,
|
|
96
|
+
key,
|
|
97
|
+
message: `${source} has no such key`
|
|
98
|
+
});
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const expected = sourceParsed?.get(key);
|
|
102
|
+
const found = parsed.get(language)?.get(key);
|
|
103
|
+
if (!expected || !found) continue;
|
|
104
|
+
const difference = [...differences("placeholder", expected.arguments, found.arguments), ...differences("tag", expected.tags, found.tags)];
|
|
105
|
+
if (difference.length > 0) problems.push({
|
|
106
|
+
code: "placeholder_mismatch",
|
|
107
|
+
language,
|
|
108
|
+
key,
|
|
109
|
+
message: difference.join("; ")
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
const lacks = Object.keys(sourceCatalog).filter((key) => !Object.hasOwn(catalog, key) || isBlank(catalog[key])).toSorted();
|
|
113
|
+
missing[language] = lacks;
|
|
114
|
+
if (complete.has(language)) for (const key of lacks) problems.push({
|
|
115
|
+
code: "missing_key",
|
|
116
|
+
language,
|
|
117
|
+
key,
|
|
118
|
+
message: "must be translated"
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
source,
|
|
123
|
+
problems,
|
|
124
|
+
missing
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** An empty message: a key someone added without its translation. */
|
|
128
|
+
function isBlank(message) {
|
|
129
|
+
return typeof message === "string" && message.trim() === "";
|
|
130
|
+
}
|
|
131
|
+
function differences(what, expected, found) {
|
|
132
|
+
const out = [];
|
|
133
|
+
const lacks = expected.filter((name) => !found.includes(name));
|
|
134
|
+
const extra = found.filter((name) => !expected.includes(name));
|
|
135
|
+
if (lacks.length > 0) out.push(`lacks ${what} ${lacks.join(", ")}`);
|
|
136
|
+
if (extra.length > 0) out.push(`has ${what} ${extra.join(", ")} the source doesn't`);
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
export { checkCatalogs, placeholdersOf };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { a as TagFunction, c as Value, i as RichValues, l as Values, n as MessagesFor, o as Translator, r as Missing, s as TranslatorOptions, t as Messages, u as createTranslator } from "./translator-BxDsP96P.js";
|
|
2
|
+
/** A language's catalogs by namespace, as imported: `{cart: cartJson, checkout: checkoutJson}`. */
|
|
3
|
+
type Namespaces = Readonly<Record<string, Messages>>;
|
|
4
|
+
/** The merged catalog's type: every `<namespace>.<key>` of `N`. */
|
|
5
|
+
type MessagesOf<N extends Namespaces> = { readonly [K in keyof N & string as `${K}.${keyof N[K] & string}`]: string; };
|
|
6
|
+
/** A catalog's keys: `KeysOf<typeof en>` is what an app's translator is typed with. */
|
|
7
|
+
type KeysOf<M> = keyof M & string;
|
|
8
|
+
/** The keys of `M` in the namespaces `N`: `NamespaceKeys<typeof en, "cart" | "common">`. */
|
|
9
|
+
type NamespaceKeys<M, N extends string> = Extract<KeysOf<M>, `${N}.${string}`>;
|
|
10
|
+
/**
|
|
11
|
+
* The messages of a merged catalog in the namespaces named: what a layout hands the
|
|
12
|
+
* browser for the client components under it, rather than the whole catalog.
|
|
13
|
+
*/
|
|
14
|
+
export declare function pickNamespaces<M extends Messages, const N extends string>(messages: M, namespaces: readonly N[]): { readonly [K in NamespaceKeys<M, N>]: string; };
|
|
15
|
+
/** One catalog out of a language's namespaces, each key prefixed with its namespace. */
|
|
16
|
+
export declare function mergeCatalogs<const N extends Namespaces>(namespaces: N): MessagesOf<N>;
|
|
17
|
+
/** The tag as BCP 47 spells it (`sr-latn` → `sr-Latn`), or undefined when it isn't one. */
|
|
18
|
+
export declare function canonicalLanguage(tag: string): string | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* The languages of an `Accept-Language` header, most wanted first (by `q`, then by
|
|
21
|
+
* position). Leaves out `*`, anything refused with `q=0` and what isn't a language tag.
|
|
22
|
+
*/
|
|
23
|
+
export declare function parseAcceptLanguage(header: string | null | undefined): string[];
|
|
24
|
+
/**
|
|
25
|
+
* The language of `available` for the first of `wanted` that has one, in `available`'s
|
|
26
|
+
* spelling. Each wanted tag is tried fully before the next: the exact tag, then the tag
|
|
27
|
+
* with its last parts taken off one at a time (`de-CH` → `de`, `sr-Latn-RS` →
|
|
28
|
+
* `sr-Latn` → `sr`), then wider, the first available tag of the same language (`sr` or
|
|
29
|
+
* `sr-RS` → `sr-Latn`, `de` → `de-AT`). Compared without case.
|
|
30
|
+
*
|
|
31
|
+
* So what a reader asks for first wins, even widened: `sr-RS, sr, en-US, en` against
|
|
32
|
+
* `en` and `sr-Latn` is `sr-Latn`. Widening never crosses scripts: a wanted tag that
|
|
33
|
+
* names one (`sr-Cyrl`, `zh-Hant`) only gets a tag with that script or with none, since
|
|
34
|
+
* its reader may not read another.
|
|
35
|
+
*/
|
|
36
|
+
export declare function matchLanguage(wanted: readonly string[], available: readonly string[]): string | undefined;
|
|
37
|
+
type Direction = "ltr" | "rtl";
|
|
38
|
+
/** The direction `language` is written in: by its script when the tag names one, else by the language. */
|
|
39
|
+
export declare function directionOf(language: string): Direction;
|
|
40
|
+
/**
|
|
41
|
+
* The locale to format numbers, money and dates with: the language in a country
|
|
42
|
+
* (`de` + `CH` → `de-CH`, `sr-Latn` + `rs` → `sr-Latn-RS`). A tag that already names a
|
|
43
|
+
* region keeps it; a tag that isn't one is returned as given.
|
|
44
|
+
*/
|
|
45
|
+
export declare function localeOf(language: string, country?: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* The locale list every `Intl.*` formatter takes: the locale, then English. A runtime
|
|
48
|
+
* without the locale's data then formats as English rather than as its own default,
|
|
49
|
+
* which differs between a server and a browser.
|
|
50
|
+
*/
|
|
51
|
+
export declare function withEnglish(locale: string): string[];
|
|
52
|
+
/** What a storefront URL's first segment names. */
|
|
53
|
+
interface LocaleSegment {
|
|
54
|
+
/** The language, when the segment names one: otherwise the market's default. */
|
|
55
|
+
language?: string;
|
|
56
|
+
/** The country, lower-cased as URLs have it. */
|
|
57
|
+
country: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Reads a storefront URL's locale segment: `de` is a country in its market's default
|
|
61
|
+
* language, `en-de` and `sr-latn-rs` a language (`en`, `sr-Latn`) in a country, the
|
|
62
|
+
* last part. Undefined for anything else.
|
|
63
|
+
*/
|
|
64
|
+
export declare function parseLocaleSegment(segment: string): LocaleSegment | undefined;
|
|
65
|
+
/** The segment for a country, in a language when one is named: `parseLocaleSegment`'s inverse. */
|
|
66
|
+
export declare function formatLocaleSegment(locale: LocaleSegment): string;
|
|
67
|
+
/** The catalog with every message in the pseudo-language. */
|
|
68
|
+
export declare function pseudo<M extends Messages>(messages: M): M;
|
|
69
|
+
/** One ICU message in the pseudo-language. */
|
|
70
|
+
export declare function pseudoMessage(message: string): string;
|
|
71
|
+
/** The catalog with every message's Serbian Cyrillic in Serbian Latin. */
|
|
72
|
+
export declare function serbianLatin<M extends Messages>(messages: M): M;
|
|
73
|
+
/**
|
|
74
|
+
* Serbian Cyrillic in `text` as Serbian Latin; everything else (Latin text, ICU syntax,
|
|
75
|
+
* placeholders, tags) as it is. A capital that becomes two letters is `Lj` in a
|
|
76
|
+
* capitalised word and `LJ` in one all in capitals.
|
|
77
|
+
*/
|
|
78
|
+
export declare function toSerbianLatin(text: string): string;
|
|
79
|
+
export { type Direction, type KeysOf, type LocaleSegment, type Messages, type MessagesFor, type MessagesOf, type Missing, type NamespaceKeys, type Namespaces, type RichValues, type TagFunction, type Translator, type TranslatorOptions, type Value, type Values, createTranslator };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { a as localeOf, c as parseLocaleSegment, i as formatLocaleSegment, l as withEnglish, n as canonicalLanguage, o as matchLanguage, r as directionOf, s as parseAcceptLanguage, t as createTranslator } from "./translator-B9SeoqOu.js";
|
|
2
|
+
// src/catalogs.ts
|
|
3
|
+
/**
|
|
4
|
+
* The messages of a merged catalog in the namespaces named: what a layout hands the
|
|
5
|
+
* browser for the client components under it, rather than the whole catalog.
|
|
6
|
+
*/
|
|
7
|
+
function pickNamespaces(messages, namespaces) {
|
|
8
|
+
const picked = {};
|
|
9
|
+
for (const [key, message] of Object.entries(messages)) if (namespaces.some((namespace) => key.startsWith(`${namespace}.`))) picked[key] = message;
|
|
10
|
+
return picked;
|
|
11
|
+
}
|
|
12
|
+
/** One catalog out of a language's namespaces, each key prefixed with its namespace. */
|
|
13
|
+
function mergeCatalogs(namespaces) {
|
|
14
|
+
const merged = {};
|
|
15
|
+
for (const [namespace, messages] of Object.entries(namespaces)) for (const [key, message] of Object.entries(messages)) merged[`${namespace}.${key}`] = message;
|
|
16
|
+
return merged;
|
|
17
|
+
}
|
|
18
|
+
// src/pseudo.ts
|
|
19
|
+
const PLAIN = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
20
|
+
const ACCENTED = "áƀçðéƒĝĥíĵķļɱñöþǫŕšţüṽŵẋýžÁƁÇÐÉƑĜĤÍĴĶĻṀÑÖÞǪŔŠŢÜṼŴẊÝŽ";
|
|
21
|
+
const VOWELS = "aeiouAEIOU";
|
|
22
|
+
const QUOTABLE = "{}<>#|";
|
|
23
|
+
/** The catalog with every message in the pseudo-language. */
|
|
24
|
+
function pseudo(messages) {
|
|
25
|
+
const out = {};
|
|
26
|
+
for (const [key, message] of Object.entries(messages)) out[key] = pseudoMessage(message);
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
/** One ICU message in the pseudo-language. */
|
|
30
|
+
function pseudoMessage(message) {
|
|
31
|
+
let out = "";
|
|
32
|
+
let depth = 0;
|
|
33
|
+
let i = 0;
|
|
34
|
+
while (i < message.length) {
|
|
35
|
+
const char = message.charAt(i);
|
|
36
|
+
let end = i + 1;
|
|
37
|
+
if (char === "'") {
|
|
38
|
+
end = quotedEnd(message, i);
|
|
39
|
+
out += message.slice(i, end);
|
|
40
|
+
} else if (char === "{") {
|
|
41
|
+
depth += 1;
|
|
42
|
+
out += char;
|
|
43
|
+
} else if (char === "}") {
|
|
44
|
+
depth = Math.max(0, depth - 1);
|
|
45
|
+
out += char;
|
|
46
|
+
} else if (depth % 2 === 1) out += char;
|
|
47
|
+
else if (char === "<") {
|
|
48
|
+
end = tagEnd(message, i) ?? end;
|
|
49
|
+
out += message.slice(i, end);
|
|
50
|
+
} else out += accent(char);
|
|
51
|
+
i = end;
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
function accent(char) {
|
|
56
|
+
const at = PLAIN.indexOf(char);
|
|
57
|
+
if (at === -1) return char;
|
|
58
|
+
const accented = ACCENTED.charAt(at);
|
|
59
|
+
return VOWELS.includes(char) ? accented + accented.toLowerCase() : accented;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Where the apostrophe at `start` stops mattering: after a doubled one (a literal
|
|
63
|
+
* apostrophe), after the closing one of a quoted run (`'{'`), or after itself when it
|
|
64
|
+
* quotes nothing.
|
|
65
|
+
*/
|
|
66
|
+
function quotedEnd(message, start) {
|
|
67
|
+
const next = message.charAt(start + 1);
|
|
68
|
+
if (next === "'") return start + 2;
|
|
69
|
+
if (next === "" || !QUOTABLE.includes(next)) return start + 1;
|
|
70
|
+
let i = start + 1;
|
|
71
|
+
while (i < message.length) if (message.charAt(i) !== "'") i += 1;
|
|
72
|
+
else if (message.charAt(i + 1) === "'") i += 2;
|
|
73
|
+
else return i + 1;
|
|
74
|
+
return message.length;
|
|
75
|
+
}
|
|
76
|
+
/** The end of the tag (`<link>`, `</link>`, `<br/>`) opening at `start`, if it is one. */
|
|
77
|
+
function tagEnd(message, start) {
|
|
78
|
+
const match = /^<\/?[A-Za-z][A-Za-z0-9_.:-]*\s*\/?>/.exec(message.slice(start));
|
|
79
|
+
return match ? start + match[0].length : void 0;
|
|
80
|
+
}
|
|
81
|
+
// src/serbian.ts
|
|
82
|
+
const CYRILLIC = "абвгдђежзијклљмнњопрстћуфхцчџш";
|
|
83
|
+
const LATIN = "a b v g d đ e ž z i j k l lj m n nj o p r s t ć u f h c č dž š".split(" ");
|
|
84
|
+
/** The catalog with every message's Serbian Cyrillic in Serbian Latin. */
|
|
85
|
+
function serbianLatin(messages) {
|
|
86
|
+
const out = {};
|
|
87
|
+
for (const [key, message] of Object.entries(messages)) out[key] = toSerbianLatin(message);
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Serbian Cyrillic in `text` as Serbian Latin; everything else (Latin text, ICU syntax,
|
|
92
|
+
* placeholders, tags) as it is. A capital that becomes two letters is `Lj` in a
|
|
93
|
+
* capitalised word and `LJ` in one all in capitals.
|
|
94
|
+
*/
|
|
95
|
+
function toSerbianLatin(text) {
|
|
96
|
+
let out = "";
|
|
97
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
98
|
+
const char = text.charAt(i);
|
|
99
|
+
const lower = char.toLowerCase();
|
|
100
|
+
const at = CYRILLIC.indexOf(lower);
|
|
101
|
+
const latin = at === -1 ? void 0 : LATIN[at];
|
|
102
|
+
if (latin === void 0) out += char;
|
|
103
|
+
else if (char === lower) out += latin;
|
|
104
|
+
else if (latin.length === 1 || inCapitals(text, i)) out += latin.toUpperCase();
|
|
105
|
+
else out += latin.charAt(0).toUpperCase() + latin.slice(1);
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** Whether the capital at `i` stands in a word of capitals: by the next letter, else the one before. */
|
|
110
|
+
function inCapitals(text, i) {
|
|
111
|
+
const next = text.charAt(i + 1);
|
|
112
|
+
if (isLetter(next)) return isUpper(next);
|
|
113
|
+
const before = text.charAt(i - 1);
|
|
114
|
+
return isLetter(before) && isUpper(before);
|
|
115
|
+
}
|
|
116
|
+
function isLetter(char) {
|
|
117
|
+
return /\p{L}/u.test(char);
|
|
118
|
+
}
|
|
119
|
+
function isUpper(char) {
|
|
120
|
+
return char !== char.toLowerCase();
|
|
121
|
+
}
|
|
122
|
+
export { canonicalLanguage, createTranslator, directionOf, formatLocaleSegment, localeOf, matchLanguage, mergeCatalogs, parseAcceptLanguage, parseLocaleSegment, pickNamespaces, pseudo, pseudoMessage, serbianLatin, toSerbianLatin, withEnglish };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { o as Translator, r as Missing, t as Messages } from "./translator-BxDsP96P.js";
|
|
2
|
+
import { ReactNode } from "react";
|
|
3
|
+
export interface I18nProviderProps {
|
|
4
|
+
/** The language of `messages`. */
|
|
5
|
+
language: string;
|
|
6
|
+
/** The language's catalog. */
|
|
7
|
+
messages: Messages;
|
|
8
|
+
/** The catalog for keys `messages` lacks: the source language's. */
|
|
9
|
+
fallback?: Messages;
|
|
10
|
+
/** What numbers and dates are formatted for (`de-CH`). Defaults to `language`. */
|
|
11
|
+
locale?: string;
|
|
12
|
+
/** Told once per key `messages` lacks. Only a client component can pass it. */
|
|
13
|
+
onMissing?: (missing: Missing) => void;
|
|
14
|
+
children?: ReactNode;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Gives the components under it their translator. A provider inside another of the same
|
|
18
|
+
* language adds its messages to the outer one's (its own win), so a nested layout hands
|
|
19
|
+
* over only the namespaces its routes add.
|
|
20
|
+
*/
|
|
21
|
+
export declare function I18nProvider(props: I18nProviderProps): ReactNode;
|
|
22
|
+
/**
|
|
23
|
+
* The translator of the nearest `I18nProvider`. An app types it with its keys once
|
|
24
|
+
* (`export const useAppT = () => useT<Key>()`), so an unknown key doesn't compile.
|
|
25
|
+
*/
|
|
26
|
+
export declare function useT<Keys extends string = string>(): Translator<Keys>;
|
|
27
|
+
/** The language of the nearest `I18nProvider`. */
|
|
28
|
+
export declare function useLanguage(): string;
|