@kizunajs/i18n 0.1.1 → 0.3.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/dist/index.d.mts CHANGED
@@ -1,150 +1,2 @@
1
- import { i as messagesSource, r as messageSource } from "./source-DJMnQ2hS.mjs";
2
-
3
- //#region src/types.d.ts
4
- /**
5
- * What a language may set in `defineI18n`.
6
- */
7
- type LocaleOptions = {
8
- /**
9
- * The language whose text shows for a message this language leaves out.
10
- */
11
- fallback?: string;
12
- };
13
- type Trim<Text extends string> = Text extends ` ${infer Rest}` ? Trim<Rest> : Text extends `${infer Rest} ` ? Trim<Rest> : Text;
14
- type LastPart<Text extends string> = Text extends `${string}{${infer Rest}` ? LastPart<Rest> : Text;
15
- type ParamName<Inside extends string> = Trim<LastPart<Inside>> extends infer Name extends string ? (Name extends '' | `${string} ${string}` ? never : Name) : never;
16
- /**
17
- * The `{param}` names in a text, as a union.
18
- */
19
- type ParamsIn<Text> = Text extends `${string}{${infer Inside}}${infer Rest}` ? ParamName<Inside> | ParamsIn<Rest> : never;
20
- /**
21
- * The `<tag>` names in a text, as a union, nested tags included.
22
- */
23
- type TagsIn<Text> = Text extends `${string}<${infer Tag}>${infer Inner}</${infer Tag}>${infer Rest}` ? Tag | TagsIn<Inner> | TagsIn<Rest> : never;
24
- type RequiredLocalesOf<Locales> = { [Locale in keyof Locales]-?: Locales[Locale] extends {
25
- fallback: string;
26
- } ? never : Locale }[keyof Locales] & string;
27
- type CheckText<Locale extends string, Text, Params extends string, Tags extends string> = Text extends string ? string extends Text ? Text : [Exclude<ParamsIn<Text>, Params>] extends [never] ? CheckLeftOut<Locale, Text, Params, Tags> : [Exclude<Params, ParamsIn<Text>>] extends [never] ? `${Locale} uses {${Exclude<ParamsIn<Text>, Params>}}, which the message does not have` : `${Locale} uses {${Exclude<ParamsIn<Text>, Params>}}, the message has {${Params}}` : string;
28
- type CheckLeftOut<Locale extends string, Text, Params extends string, Tags extends string> = [Exclude<Params, ParamsIn<Text>>] extends [never] ? [Exclude<TagsIn<Text>, Tags>] extends [never] ? [Exclude<Tags, TagsIn<Text>>] extends [never] ? Text : `${Locale} leaves out <${Exclude<Tags, TagsIn<Text>>}>` : `${Locale} uses <${Exclude<TagsIn<Text>, Tags>}>, which the message does not have` : `${Locale} leaves out {${Exclude<Params, ParamsIn<Text>>}}`;
29
- type BaseTextOf<Texts, Base extends string> = Base extends keyof Texts ? Texts[Base] : never;
30
- /**
31
- * Checks every language of a message against the base language's params and tags. A wrong text
32
- * becomes the sentence that says what is wrong, so the compiler shows it on that text.
33
- */
34
- type CheckTexts<Texts, Locales, Base extends string> = { [Locale in keyof Texts]: Locale extends keyof Locales ? CheckText<Locale & string, Texts[Locale], ParamsIn<BaseTextOf<Texts, Base>>, TagsIn<BaseTextOf<Texts, Base>>> : `${Locale & string} is not one of the languages` } & { [Locale in RequiredLocalesOf<Locales>]: string };
35
- type LengthOf<Text extends string, Count extends unknown[] = []> = Text extends `${string}${infer Rest}` ? LengthOf<Rest, [...Count, unknown]> : Count['length'];
36
- type IsLonger<Text extends string, Limit extends number, Count extends unknown[] = []> = Count['length'] extends Limit ? Text extends '' ? false : true : Text extends `${string}${infer Rest}` ? IsLonger<Rest, Limit, [...Count, unknown]> : false;
37
- type TooLong<Texts, Limit extends number> = { [Locale in keyof Texts]: Texts[Locale] extends string ? [ParamsIn<Texts[Locale]>] extends [never] ? IsLonger<Texts[Locale], Limit> extends true ? `${Locale & string} is ${LengthOf<Texts[Locale]>} characters, the limit is ${Limit}` : never : never : never }[keyof Texts];
38
- /**
39
- * Checks that every text without params fits the limit. `kizuna-i18n check` checks a text with
40
- * params, with its example values filled in.
41
- */
42
- type CheckLimit<Texts, Limit extends number> = [TooLong<Texts, Limit>] extends [never] ? Limit : TooLong<Texts, Limit>;
43
- /**
44
- * A message made by `i18n.message`.
45
- */
46
- type Message<Texts = Record<string, string>, Base extends string = string> = {
47
- /**
48
- * Sets the most characters the message may have, in every language.
49
- *
50
- * @example
51
- * i18n
52
- * .message({
53
- * en: 'Your cart',
54
- * nb: 'Handlekurven din',
55
- * })
56
- * .maxLength(16);
57
- */
58
- maxLength: <const Limit extends number>(limit: CheckLimit<Texts, Limit>) => Message<Texts, Base>;
59
- /**
60
- * Tells whoever translates the message what it is for.
61
- *
62
- * @example
63
- * i18n
64
- * .message({
65
- * en: 'Save',
66
- * nb: 'Lagre',
67
- * })
68
- * .describe('Button that saves the order as a draft');
69
- */
70
- describe: (description: string) => Message<Texts, Base>;
71
- /**
72
- * Gives sample values for the params. The generated JSDoc shows them, and the length check fills
73
- * them in.
74
- *
75
- * @example
76
- * i18n
77
- * .message({
78
- * en: 'Welcome back, {firstName}',
79
- * nb: 'Velkommen tilbake, {firstName}',
80
- * })
81
- * .example({
82
- * firstName: 'Ada',
83
- * });
84
- */
85
- example: (values: { [Param in ParamsIn<BaseTextOf<Texts, Base>>]?: string }) => Message<Texts, Base>;
86
- readonly [messageSource]: unknown;
87
- };
88
- /**
89
- * A group of messages made by `i18n.messages`. `kizuna-i18n generate` reads every group the
90
- * translations folder exports, named by its export.
91
- */
92
- type Messages = {
93
- readonly [messagesSource]: unknown;
94
- };
95
- /**
96
- * What `defineI18n` returns.
97
- */
98
- type I18n<Locales extends Record<string, LocaleOptions>, Base extends keyof Locales & string> = {
99
- /**
100
- * Declares a message, with one text per language.
101
- *
102
- * @example
103
- * i18n.message({
104
- * en: 'Your cart',
105
- * nb: 'Handlekurven din',
106
- * });
107
- */
108
- message: <const Texts extends Record<string, string>>(texts: CheckTexts<Texts, Locales, Base>) => Message<Texts, Base>;
109
- /**
110
- * Groups messages. Each key names a message, like `t.cart.title`.
111
- *
112
- * @example
113
- * export const cart = i18n.messages({
114
- * title,
115
- * greeting,
116
- * });
117
- */
118
- messages: (messages: Record<string, Message<any, any>>) => Messages;
119
- };
120
- //#endregion
121
- //#region src/define-i18n.d.ts
122
- /**
123
- * Declares your languages and names the base language, the one every other language is checked
124
- * against. Returns `i18n`, which declares the messages.
125
- *
126
- * @example
127
- * export const i18n = defineI18n({
128
- * base: 'en',
129
- * locales: {
130
- * en: {},
131
- * nb: {},
132
- * },
133
- * });
134
- */
135
- declare function defineI18n<const Locales extends Record<string, LocaleOptions>, const Base extends keyof Locales & string>(config: {
136
- /**
137
- * The base language. Every other language is checked against its params and tags.
138
- */
139
- base: Base;
140
- /**
141
- * Every language, by its BCP 47 tag, like `en` or `pt-BR`.
142
- */
143
- locales: Locales & { [Locale in keyof Locales]: Locale extends Base ? {
144
- fallback?: never;
145
- } : {
146
- fallback?: Exclude<keyof Locales & string, Locale>;
147
- } };
148
- }): I18n<Locales, Base>;
149
- //#endregion
150
- export { type I18n, type Message, type Messages, defineI18n };
1
+ import { a as Messages, i as Message, t as I18n } from "./types-DC3XWG_J.mjs";
2
+ export { type I18n, type Message, type Messages };
package/dist/index.mjs CHANGED
@@ -1,71 +1 @@
1
- import { n as messagesSource, t as messageSource } from "./source-BrYHodVt.mjs";
2
- //#region src/define-i18n.ts
3
- function buildMessage(definition) {
4
- return {
5
- [messageSource]: definition,
6
- maxLength: (limit) => buildMessage({
7
- ...definition,
8
- maxLength: limit
9
- }),
10
- describe: (description) => buildMessage({
11
- ...definition,
12
- description
13
- }),
14
- example: (values) => buildMessage({
15
- ...definition,
16
- examples: {
17
- ...definition.examples,
18
- ...values
19
- }
20
- })
21
- };
22
- }
23
- function checkFallbacks(locales, base) {
24
- const names = locales.map((locale) => locale.name);
25
- if (!names.includes(base)) throw new Error(`The base language '${base}' is not one of the languages.`);
26
- for (const locale of locales) {
27
- const seen = [locale.name];
28
- let current = locale;
29
- while (current?.fallback !== void 0) {
30
- const next = current.fallback;
31
- if (!names.includes(next)) throw new Error(`'${current.name}' falls back to '${next}', which is not one of the languages.`);
32
- if (seen.includes(next)) throw new Error(`'${locale.name}' falls back in a circle: ${[...seen, next].join(", ")}.`);
33
- seen.push(next);
34
- current = locales.find((candidate) => candidate.name === next);
35
- }
36
- }
37
- }
38
- /**
39
- * Declares your languages and names the base language, the one every other language is checked
40
- * against. Returns `i18n`, which declares the messages.
41
- *
42
- * @example
43
- * export const i18n = defineI18n({
44
- * base: 'en',
45
- * locales: {
46
- * en: {},
47
- * nb: {},
48
- * },
49
- * });
50
- */
51
- function defineI18n(config) {
52
- const base = config.base;
53
- const locales = Object.entries(config.locales).map(([name, options]) => options.fallback === void 0 ? { name } : {
54
- name,
55
- fallback: options.fallback
56
- });
57
- checkFallbacks(locales, base);
58
- return {
59
- message: (texts) => buildMessage({ translations: { ...texts } }),
60
- messages: (messages) => {
61
- const group = {
62
- base,
63
- locales,
64
- messages: Object.fromEntries(Object.entries(messages).map(([key, message]) => [key, message[messageSource]]))
65
- };
66
- return { [messagesSource]: group };
67
- }
68
- };
69
- }
70
- //#endregion
71
- export { defineI18n };
1
+ export {};
@@ -1,4 +1,3 @@
1
- const require_source = require("./source-CDwD6Wcn.cjs");
2
1
  let node_fs = require("node:fs");
3
2
  let node_path = require("node:path");
4
3
  let jiti = require("jiti");
@@ -81,6 +80,7 @@ function renderedOf(segments, examples) {
81
80
  }
82
81
  const braced = (names) => names.map((name) => `{${name}}`).join(" and ");
83
82
  const angled = (names) => names.map((name) => `<${name}>`).join(" and ");
83
+ const examplesOf = (definition) => Object.fromEntries(Object.entries(definition.params).flatMap(([name, param]) => param.example === void 0 ? [] : [[name, String(param.example)]]));
84
84
  function checkText(text, definition, params, tags) {
85
85
  const names = namesOf(parseText(text));
86
86
  const extra = names.params.filter((name) => !params.includes(name));
@@ -94,7 +94,7 @@ function checkText(text, definition, params, tags) {
94
94
  if (extraTags.length > 0) problems.push(`uses ${angled(extraTags)}, which the message does not have`);
95
95
  if (missingTags.length > 0) problems.push(`leaves out ${angled(missingTags)}`);
96
96
  if (definition.maxLength !== void 0) {
97
- const length = lengthOf(renderedOf(parseText(text), definition.examples ?? {}));
97
+ const length = lengthOf(renderedOf(parseText(text), examplesOf(definition)));
98
98
  if (length > definition.maxLength) {
99
99
  const filled = names.params.length > 0 ? " with the examples filled in" : "";
100
100
  problems.push(`is ${length} characters${filled}, the limit is ${definition.maxLength}`);
@@ -117,18 +117,17 @@ function shownLocaleOf(source, translations, locale) {
117
117
  }
118
118
  return source.base;
119
119
  }
120
- const paramsOf = (definition, base) => namesOf(parseText(definition.translations[base] ?? "")).params;
121
120
  const tagsOf = (definition, base) => namesOf(parseText(definition.translations[base] ?? "")).tags;
122
121
  /**
123
- * Lists every problem in the messages: a missing language, a wrong param or tag, a text over its
124
- * length limit, and each language that shows its fallback's text.
122
+ * Lists every problem in the messages: a missing language, a param the message does not declare, a
123
+ * wrong tag, a text over its length limit, and each language that shows its fallback's text.
125
124
  */
126
125
  function problemsOf(source) {
127
126
  const names = source.locales.map((locale) => locale.name);
128
127
  const problems = [];
129
- for (const [groupName, group] of Object.entries(source.groups)) for (const [messageName, definition] of Object.entries(group)) {
130
- const key = `${groupName}.${messageName}`;
131
- const params = paramsOf(definition, source.base);
128
+ for (const { path, definition } of source.messages) {
129
+ const key = path.join(".");
130
+ const params = Object.keys(definition.params);
132
131
  const tags = tagsOf(definition, source.base);
133
132
  const add = (locale, message, severity = "error") => problems.push({
134
133
  key,
@@ -136,7 +135,6 @@ function problemsOf(source) {
136
135
  message,
137
136
  severity
138
137
  });
139
- for (const name of Object.keys(definition.examples ?? {})) if (!params.includes(name)) add(source.base, `has an example for {${name}}, which the message does not have`);
140
138
  for (const locale of Object.keys(definition.translations)) if (!names.includes(locale)) add(locale, "is not one of the languages");
141
139
  for (const locale of source.locales) {
142
140
  const text = definition.translations[locale.name];
@@ -166,15 +164,18 @@ function toCatalog(source) {
166
164
  const errors = problemsOf(source).filter((problem) => problem.severity === "error");
167
165
  if (errors.length > 0) throw new Error(`The messages have ${errors.length === 1 ? "a problem" : `${errors.length} problems`}:\n${formatProblems(errors)}`);
168
166
  const locales = [...source.locales.filter((locale) => locale.name === source.base), ...source.locales.filter((locale) => locale.name !== source.base)];
169
- const messages = Object.entries(source.groups).flatMap(([groupName, group]) => Object.entries(group).map(([messageName, definition]) => {
167
+ const messages = source.messages.map(({ path, definition }) => {
170
168
  const segments = parseText(definition.translations[source.base] ?? "");
171
169
  return {
172
- key: `${groupName}.${messageName}`,
173
- path: [groupName, messageName],
170
+ key: path.join("."),
171
+ path,
174
172
  ...definition.description === void 0 ? {} : { description: definition.description },
175
173
  ...definition.maxLength === void 0 ? {} : { maxLength: definition.maxLength },
176
- ...definition.examples === void 0 ? {} : { examples: definition.examples },
177
- ...namesOf(segments),
174
+ params: Object.entries(definition.params).map(([name, param]) => ({
175
+ name,
176
+ ...param
177
+ })),
178
+ tags: namesOf(segments).tags,
178
179
  translations: Object.fromEntries(locales.filter((locale) => definition.translations[locale.name] !== void 0).map((locale) => {
179
180
  const text = definition.translations[locale.name];
180
181
  return [locale.name, {
@@ -183,7 +184,7 @@ function toCatalog(source) {
183
184
  }];
184
185
  }))
185
186
  };
186
- }));
187
+ });
187
188
  return {
188
189
  format: 1,
189
190
  base: source.base,
@@ -192,17 +193,147 @@ function toCatalog(source) {
192
193
  };
193
194
  }
194
195
  //#endregion
196
+ //#region src/source.ts
197
+ /**
198
+ * Where a message made by `i18n.message` keeps its definition.
199
+ */
200
+ const messageSource = Symbol.for("kizuna-i18n.message");
201
+ /**
202
+ * Where a group made by `i18n.messages` keeps its messages.
203
+ */
204
+ const messagesSource = Symbol.for("kizuna-i18n.messages");
205
+ /**
206
+ * Where a param made by `i18n.string` or `i18n.number` keeps its definition.
207
+ */
208
+ const paramSource = Symbol.for("kizuna-i18n.param");
209
+ /**
210
+ * Where the `i18n` that `defineConfig` returns keeps the config.
211
+ */
212
+ const configSource = Symbol.for("kizuna-i18n.config");
213
+ //#endregion
214
+ //#region src/define-i18n.ts
215
+ function buildParam(definition) {
216
+ return {
217
+ [paramSource]: definition,
218
+ example: (value) => buildParam({
219
+ ...definition,
220
+ example: value
221
+ })
222
+ };
223
+ }
224
+ function buildMessage(declaration, translations) {
225
+ const definition = {
226
+ translations: { ...translations },
227
+ params: Object.fromEntries(Object.entries(declaration.params ?? {}).map(([name, param]) => [name, param[paramSource]])),
228
+ ...declaration.description === void 0 ? {} : { description: declaration.description },
229
+ ...declaration.maxLength === void 0 ? {} : { maxLength: declaration.maxLength }
230
+ };
231
+ return { [messageSource]: definition };
232
+ }
233
+ function messagesOf(tree, path) {
234
+ return Object.entries(tree).flatMap(([name, value]) => {
235
+ const definition = value[messageSource];
236
+ return definition === void 0 ? messagesOf(value, [...path, name]) : [{
237
+ path: [...path, name],
238
+ definition
239
+ }];
240
+ });
241
+ }
242
+ const languageNames = new Intl.DisplayNames(["en"], {
243
+ type: "language",
244
+ fallback: "none"
245
+ });
246
+ function checkTag(name) {
247
+ let canonical;
248
+ try {
249
+ canonical = Intl.getCanonicalLocales(name)[0];
250
+ } catch {
251
+ throw new Error(`'${name}' is not a language tag. Write one like 'en' or 'pt-BR'.`);
252
+ }
253
+ if (canonical !== name) throw new Error(`Write '${canonical}', not '${name}'.`);
254
+ if (languageNames.of(new Intl.Locale(name).language) === void 0) throw new Error(`'${name}' is not a known language.`);
255
+ }
256
+ function checkLocales(locales, base) {
257
+ const names = locales.map((locale) => locale.name);
258
+ for (const name of names) checkTag(name);
259
+ if (!names.includes(base)) throw new Error(`The base language '${base}' is not one of the languages.`);
260
+ for (const locale of locales) {
261
+ const seen = [locale.name];
262
+ let current = locale;
263
+ while (current?.fallback !== void 0) {
264
+ const next = current.fallback;
265
+ if (!names.includes(next)) throw new Error(`'${current.name}' falls back to '${next}', which is not one of the languages.`);
266
+ if (seen.includes(next)) throw new Error(`'${locale.name}' falls back in a circle: ${[...seen, next].join(", ")}.`);
267
+ seen.push(next);
268
+ current = locales.find((candidate) => candidate.name === next);
269
+ }
270
+ }
271
+ }
272
+ function defineI18n(config) {
273
+ const base = config.base;
274
+ const locales = Object.entries(config.locales).map(([name, options]) => options.fallback === void 0 ? { name } : {
275
+ name,
276
+ fallback: options.fallback
277
+ });
278
+ checkLocales(locales, base);
279
+ return {
280
+ message: (declaration = {}) => ({ translations: (texts) => buildMessage(declaration, texts) }),
281
+ string: () => buildParam({ type: "string" }),
282
+ number: () => buildParam({ type: "number" }),
283
+ messages: (messages) => {
284
+ const group = {
285
+ base,
286
+ locales,
287
+ messages: messagesOf(messages, [])
288
+ };
289
+ return { [messagesSource]: group };
290
+ }
291
+ };
292
+ }
293
+ //#endregion
294
+ //#region src/config.ts
295
+ /**
296
+ * Declares your languages, where the messages are, and what `kizuna-i18n generate` writes from
297
+ * them. Export it as the default, and import it in message files as `i18n`.
298
+ *
299
+ * @example
300
+ * export default defineConfig({
301
+ * base: 'en',
302
+ * locales: {
303
+ * en: {},
304
+ * nb: {},
305
+ * },
306
+ * messages: './translations',
307
+ * targets: [
308
+ * typescriptTarget({
309
+ * output: './src/translations.generated.ts',
310
+ * }),
311
+ * ],
312
+ * });
313
+ */
314
+ function defineConfig(config) {
315
+ return Object.assign(defineI18n(config), { [configSource]: config });
316
+ }
317
+ /**
318
+ * Returns the config an `i18n.config.ts` exports by default.
319
+ */
320
+ function configOf(exported) {
321
+ const config = typeof exported === "object" && exported !== null ? exported[configSource] : void 0;
322
+ if (config === void 0) throw new Error("The config does not export defineConfig({ ... }) as its default.");
323
+ return config;
324
+ }
325
+ //#endregion
195
326
  //#region src/load.ts
196
327
  const MODULE = /\.(ts|tsx|mts|cts|js|mjs|cjs)$/;
197
328
  const SKIPPED = /\.(test|spec)\.|\.d\.(ts|mts|cts)$/;
198
- const groupOf = (value) => typeof value === "object" && value !== null ? value[require_source.messagesSource] : void 0;
329
+ const groupOf = (value) => typeof value === "object" && value !== null ? value[messagesSource] : void 0;
199
330
  const languagesOf = (group) => JSON.stringify({
200
331
  base: group.base,
201
332
  locales: group.locales
202
333
  });
203
334
  /**
204
335
  * Builds an app's messages from its groups, by name. Throws when two groups were made by
205
- * different `defineI18n` calls.
336
+ * different configs.
206
337
  */
207
338
  function sourceOf(groups) {
208
339
  const definitions = Object.entries(groups).flatMap(([name, value]) => {
@@ -211,11 +342,14 @@ function sourceOf(groups) {
211
342
  });
212
343
  const first = definitions[0]?.[1];
213
344
  if (!first) throw new Error("There are no messages. Export a group made by i18n.messages({ ... }).");
214
- for (const [name, group] of definitions) if (languagesOf(group) !== languagesOf(first)) throw new Error(`The group '${name}' was made for other languages than the rest. Make every group with the same defineI18n.`);
345
+ for (const [name, group] of definitions) if (languagesOf(group) !== languagesOf(first)) throw new Error(`The group '${name}' was made for other languages than the rest. Make every group with the i18n your config exports.`);
215
346
  return {
216
347
  base: first.base,
217
348
  locales: first.locales,
218
- groups: Object.fromEntries(definitions.map(([name, group]) => [name, group.messages]))
349
+ messages: definitions.flatMap(([name, group]) => group.messages.map((message) => ({
350
+ path: [name, ...message.path],
351
+ definition: message.definition
352
+ })))
219
353
  };
220
354
  }
221
355
  function filesIn(folder) {
@@ -252,6 +386,18 @@ async function loadMessages(folder) {
252
386
  return sourceOf(groups);
253
387
  }
254
388
  //#endregion
389
+ Object.defineProperty(exports, "configOf", {
390
+ enumerable: true,
391
+ get: function() {
392
+ return configOf;
393
+ }
394
+ });
395
+ Object.defineProperty(exports, "defineConfig", {
396
+ enumerable: true,
397
+ get: function() {
398
+ return defineConfig;
399
+ }
400
+ });
255
401
  Object.defineProperty(exports, "formatProblems", {
256
402
  enumerable: true,
257
403
  get: function() {