@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.
@@ -1,4 +1,4 @@
1
- import { n as MessagesSource, t as LocaleDefinition } from "./source-DJMnQ2hS.mjs";
1
+ import { c as ParamDefinition, n as Languages, o as LocaleDefinition, r as LocaleOptions, s as MessagesSource, t as I18n } from "./types-DC3XWG_J.mjs";
2
2
  import { z } from "zod";
3
3
 
4
4
  //#region src/segments.d.ts
@@ -31,6 +31,15 @@ type CatalogText = {
31
31
  */
32
32
  segments: Segment[];
33
33
  };
34
+ /**
35
+ * One param of a message.
36
+ */
37
+ type CatalogParam = {
38
+ /**
39
+ * The name the texts use, like `firstName` for `{firstName}`.
40
+ */
41
+ name: string;
42
+ } & ParamDefinition;
34
43
  /**
35
44
  * One message, with every language that wrote it.
36
45
  */
@@ -52,13 +61,9 @@ type CatalogMessage = {
52
61
  */
53
62
  maxLength?: number;
54
63
  /**
55
- * Sample values for the params.
56
- */
57
- examples?: Record<string, string>;
58
- /**
59
- * Every param, in the order they first appear in the base language.
64
+ * Every param, in the order the message declares them.
60
65
  */
61
- params: string[];
66
+ params: CatalogParam[];
62
67
  /**
63
68
  * Every tag, in the order they first appear in the base language.
64
69
  */
@@ -111,8 +116,8 @@ type Problem = {
111
116
  severity: 'error' | 'notice';
112
117
  };
113
118
  /**
114
- * Lists every problem in the messages: a missing language, a wrong param or tag, a text over its
115
- * length limit, and each language that shows its fallback's text.
119
+ * Lists every problem in the messages: a missing language, a param the message does not declare, a
120
+ * wrong tag, a text over its length limit, and each language that shows its fallback's text.
116
121
  */
117
122
  declare function problemsOf(source: MessagesSource): Problem[];
118
123
  /**
@@ -202,9 +207,9 @@ declare function defineTarget<Schema extends z.ZodType | undefined = undefined>(
202
207
  //#endregion
203
208
  //#region src/config.d.ts
204
209
  /**
205
- * What `i18n.config.ts` exports.
210
+ * What `i18n.config.ts` declares: the languages, where the messages are, and what to generate.
206
211
  */
207
- type I18nConfig = {
212
+ type I18nConfig<Locales extends Record<string, LocaleOptions> = Record<string, LocaleOptions>, Base extends keyof Locales & string = string> = Languages<Locales, Base> & {
208
213
  /**
209
214
  * The folder of message files, resolved against the config's folder. Every group a file
210
215
  * exports is read, named by its export.
@@ -219,10 +224,16 @@ type I18nConfig = {
219
224
  targets?: Target[];
220
225
  };
221
226
  /**
222
- * Declares where the messages are, and what `kizuna-i18n generate` writes from them.
227
+ * Declares your languages, where the messages are, and what `kizuna-i18n generate` writes from
228
+ * them. Export it as the default, and import it in message files as `i18n`.
223
229
  *
224
230
  * @example
225
231
  * export default defineConfig({
232
+ * base: 'en',
233
+ * locales: {
234
+ * en: {},
235
+ * nb: {},
236
+ * },
226
237
  * messages: './translations',
227
238
  * targets: [
228
239
  * typescriptTarget({
@@ -231,12 +242,12 @@ type I18nConfig = {
231
242
  * ],
232
243
  * });
233
244
  */
234
- declare function defineConfig(config: I18nConfig): I18nConfig;
245
+ declare function defineConfig<const Locales extends Record<string, LocaleOptions>, const Base extends keyof Locales & string>(config: I18nConfig<Locales, Base>): I18n<Locales, Base>;
235
246
  //#endregion
236
247
  //#region src/load.d.ts
237
248
  /**
238
249
  * Builds an app's messages from its groups, by name. Throws when two groups were made by
239
- * different `defineI18n` calls.
250
+ * different configs.
240
251
  */
241
252
  declare function sourceOf(groups: Record<string, unknown>): MessagesSource;
242
253
  /**
@@ -259,4 +270,4 @@ declare const typescriptTarget: (options: {
259
270
  output: string;
260
271
  }) => Target;
261
272
  //#endregion
262
- export { type Catalog, type CatalogMessage, type CatalogText, type I18nConfig, type LocaleDefinition, type MessagesSource, type Problem, type Segment, type Target, type TargetContext, defineConfig, defineTarget, formatProblems, loadMessages, problemsOf, sourceOf, toCatalog, typescriptTarget };
273
+ export { type Catalog, type CatalogMessage, type CatalogParam, type CatalogText, type I18nConfig, type LocaleDefinition, type MessagesSource, type Problem, type Segment, type Target, type TargetContext, defineConfig, defineTarget, formatProblems, loadMessages, problemsOf, sourceOf, toCatalog, typescriptTarget };
package/dist/generate.mjs CHANGED
@@ -1,22 +1,4 @@
1
- import { a as shownLocaleOf, i as problemsOf, n as sourceOf, o as toCatalog, r as formatProblems, t as loadMessages } from "./load-CE9FYddD.mjs";
2
- //#region src/config.ts
3
- /**
4
- * Declares where the messages are, and what `kizuna-i18n generate` writes from them.
5
- *
6
- * @example
7
- * export default defineConfig({
8
- * messages: './translations',
9
- * targets: [
10
- * typescriptTarget({
11
- * output: './src/translations.generated.ts',
12
- * }),
13
- * ],
14
- * });
15
- */
16
- function defineConfig(config) {
17
- return config;
18
- }
19
- //#endregion
1
+ import { a as formatProblems, c as toCatalog, i as defineConfig, n as sourceOf, o as problemsOf, s as shownLocaleOf, t as loadMessages } from "./load-EiVgmBB9.mjs";
20
2
  //#region src/target.ts
21
3
  /**
22
4
  * Declares a target for a language: the options a config passes it, and how it turns the catalog
@@ -61,29 +43,33 @@ function defineTarget(definition) {
61
43
  * messages it reads.
62
44
  */
63
45
  const runtimeSource = String.raw`/**
64
- * A message with params. Text values give a string. A rich value, like a React element, gives the
65
- * message as parts, which React renders directly.
46
+ * A message with params. A React element as a param returns parts in place of a string.
66
47
  */
67
48
  export type Message<Params> = {
68
49
  (params: Params): string;
69
- <Rich>(params: { [Name in keyof Params]: Params[Name] | Rich }): Array<string | Rich>;
50
+ <Rich extends object>(params: { [Name in keyof Params]: Params[Name] | Rich }): Array<string | Rich>;
70
51
  };
71
52
 
72
53
  /**
73
- * A message with tags. Each tag takes a renderer, which gets the text inside the tag and returns
74
- * what the tag becomes, like a link.
54
+ * A message with tags. Pass a function for each tag.
75
55
  */
76
- export type TaggedMessage<Params, Tags extends string> = <Result>(
77
- params: { [Name in keyof Params]: Params[Name] | Result } & {
78
- [Tag in Tags]: (text: string | Array<string | Result>) => Result;
79
- }
80
- ) => Array<string | Result>;
56
+ export type TaggedMessage<Params, Tags extends string> = {
57
+ <Result>(
58
+ params: Params & {
59
+ [Tag in Tags]: (text: string | Array<string | Result>) => Result;
60
+ }
61
+ ): Array<string | Result>;
62
+ <Result, Rich extends object>(
63
+ params: { [Name in keyof Params]: Params[Name] | Rich } & {
64
+ [Tag in Tags]: (text: string | Array<string | Rich | Result>) => Result;
65
+ }
66
+ ): Array<string | Rich | Result>;
67
+ };
81
68
 
82
69
  const cache = new Map<Locale, Translations>();
83
70
 
84
71
  /**
85
- * Returns the translations of a language. A language the app does not have gives the base
86
- * language.
72
+ * Returns the translations of a language.
87
73
  *
88
74
  * @example
89
75
  * const t = getTranslations('nb');
@@ -104,8 +90,8 @@ const sameLanguages: Record<string, string[]> = {
104
90
  };
105
91
 
106
92
  /**
107
- * Returns the language the app has that best matches the user's preferred languages, or the base
108
- * language. Takes an Accept-Language header or a list like navigator.languages.
93
+ * Returns the language that best matches an Accept-Language header or a list like
94
+ * navigator.languages, or the base language.
109
95
  *
110
96
  * @example
111
97
  * matchLocale(['nb-NO', 'en-US']);
@@ -149,8 +135,7 @@ const TAG_PAIR = '<(\\w+)>([\\s\\S]*?)<\\/\\1>';
149
135
  const PARAM = '\\{\\s*([A-Za-z_$][\\w$]*)\\s*\\}';
150
136
 
151
137
  /**
152
- * The marks React puts on its elements, so a part that is an element gets a key without importing
153
- * React.
138
+ * Marks React puts on its elements, so parts get keys without importing React.
154
139
  */
155
140
  const reactElements = new Set<symbol>([Symbol.for('react.element'), Symbol.for('react.transitional.element')]);
156
141
 
@@ -160,7 +145,9 @@ function text(template: string): any {
160
145
 
161
146
  function render(template: string, values: Record<string, unknown>): string | unknown[] {
162
147
  const hasTag = new RegExp(TAG_PAIR).test(template);
163
- const hasRichValue = Object.values(values).some((value) => typeof value !== 'string' && typeof value !== 'function');
148
+ const hasRichValue = Object.values(values).some(
149
+ (value) => typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'function'
150
+ );
164
151
  if (!hasTag && !hasRichValue) {
165
152
  return template.replace(new RegExp(PARAM, 'g'), (_, name: string) => String(values[name] ?? ''));
166
153
  }
@@ -198,8 +185,8 @@ function pushValues(parts: unknown[], stretch: string, values: Record<string, un
198
185
  while ((match = param.exec(stretch))) {
199
186
  pushText(parts, stretch.slice(lastIndex, match.index));
200
187
  const value = values[match[1] ?? ''] ?? '';
201
- if (typeof value === 'string') {
202
- pushText(parts, value);
188
+ if (typeof value === 'string' || typeof value === 'number') {
189
+ pushText(parts, String(value));
203
190
  } else {
204
191
  parts.push(value);
205
192
  }
@@ -248,27 +235,33 @@ function filledOf(segments, values) {
248
235
  return segments.map((segment) => {
249
236
  if (segment.type === "text") return segment.text;
250
237
  if (segment.type === "param") return values[segment.name] ?? "";
251
- return filledOf(segment.children, values);
238
+ return `<${segment.name}>${filledOf(segment.children, values)}</${segment.name}>`;
252
239
  }).join("");
253
240
  }
254
- function exampleOf(message, base) {
241
+ function textsOf(message, catalog, values) {
242
+ return catalog.locales.map((locale) => {
243
+ const text = message.translations[locale.name];
244
+ if (text === void 0) return `// ${locale.name}: shows ${shownLocaleOf(catalog, message.translations, locale.name)}`;
245
+ return `// ${locale.name}: ${stringOf(filledOf(text.segments, values))}`;
246
+ });
247
+ }
248
+ function exampleOf(message, catalog) {
255
249
  const access = `t.${message.path.map(keyOf).join(".")}`;
256
- const baseText = message.translations[base];
257
- if (message.params.length === 0 && message.tags.length === 0) return [`${access}; // ${stringOf(baseText?.source ?? "")}`];
258
- const values = Object.fromEntries(message.params.map((name) => [name, message.examples?.[name] ?? "…"]));
259
- const lines = [
250
+ const values = Object.fromEntries(message.params.map((param) => [param.name, param.example === void 0 ? "…" : String(param.example)]));
251
+ if (message.params.length === 0 && message.tags.length === 0) return [`${access};`, ...textsOf(message, catalog, values)];
252
+ return [
260
253
  `${access}({`,
261
- ...message.params.map((name) => ` ${keyOf(name)}: ${stringOf(values[name])},`),
262
- ...message.tags.map((tag) => ` ${keyOf(tag)}: (text) => text,`)
254
+ ...message.params.map((param) => ` ${keyOf(param.name)}: ${typeof param.example === "number" ? String(param.example) : stringOf(values[param.name])},`),
255
+ ...message.tags.map((tag) => ` ${keyOf(tag)}: (text) => text,`),
256
+ "});",
257
+ ...textsOf(message, catalog, values)
263
258
  ];
264
- const result = message.tags.length === 0 ? ` // ${stringOf(filledOf(baseText?.segments ?? [], values))}` : "";
265
- return [...lines, `});${result}`];
266
259
  }
267
- function docOf(message, base, indent) {
260
+ function docOf(message, catalog, indent) {
268
261
  const paragraphs = [];
269
262
  if (message.description !== void 0) paragraphs.push(commentOf(message.description).split("\n"));
270
263
  if (message.maxLength !== void 0) paragraphs.push([`@maxLength ${message.maxLength}`]);
271
- paragraphs.push(["@example", ...exampleOf(message, base).map(commentOf)]);
264
+ paragraphs.push(["@example", ...exampleOf(message, catalog).map(commentOf)]);
272
265
  const body = paragraphs.flatMap((lines, index) => [...index === 0 ? [] : [""], ...lines]);
273
266
  return [
274
267
  `${indent}/**`,
@@ -278,7 +271,7 @@ function docOf(message, base, indent) {
278
271
  }
279
272
  function typeOf(message) {
280
273
  if (message.params.length === 0 && message.tags.length === 0) return ["string"];
281
- const params = message.params.map((name) => ` ${keyOf(name)}: string;`);
274
+ const params = message.params.map((param) => ` ${keyOf(param.name)}: ${param.type};`);
282
275
  if (message.tags.length === 0) return [
283
276
  "Message<{",
284
277
  ...params,
@@ -291,48 +284,66 @@ function typeOf(message) {
291
284
  `}, ${tags}>`
292
285
  ];
293
286
  }
294
- const groupsOf = (catalog) => {
295
- const groups = /* @__PURE__ */ new Map();
287
+ function treeOf(catalog) {
288
+ const root = /* @__PURE__ */ new Map();
296
289
  for (const message of catalog.messages) {
297
- const name = message.path[0];
298
- groups.set(name, [...groups.get(name) ?? [], message]);
290
+ let branch = root;
291
+ for (const name of message.path.slice(0, -1)) {
292
+ let next = branch.get(name);
293
+ if (!(next instanceof Map)) {
294
+ next = /* @__PURE__ */ new Map();
295
+ branch.set(name, next);
296
+ }
297
+ branch = next;
298
+ }
299
+ branch.set(message.path[message.path.length - 1], message);
299
300
  }
300
- return groups;
301
- };
301
+ return root;
302
+ }
303
+ function typeLinesOf(branch, catalog, indent) {
304
+ return [...branch].flatMap(([name, node]) => {
305
+ if (node instanceof Map) return [
306
+ `${indent}${keyOf(name)}: {`,
307
+ ...typeLinesOf(node, catalog, `${indent} `),
308
+ `${indent}};`
309
+ ];
310
+ const [first = "string", ...rest] = typeOf(node);
311
+ return [
312
+ ...docOf(node, catalog, indent),
313
+ `${indent}${keyOf(name)}: ${first}${rest.length === 0 ? ";" : ""}`,
314
+ ...rest.map((line, index) => `${indent}${line}${index === rest.length - 1 ? ";" : ""}`)
315
+ ];
316
+ });
317
+ }
318
+ function valueLinesOf(branch, catalog, locale, indent) {
319
+ return [...branch].flatMap(([name, node]) => {
320
+ if (node instanceof Map) return [
321
+ `${indent}${keyOf(name)}: {`,
322
+ ...valueLinesOf(node, catalog, locale, `${indent} `),
323
+ `${indent}},`
324
+ ];
325
+ const shown = shownLocaleOf(catalog, node.translations, locale);
326
+ const source = node.translations[shown]?.source ?? "";
327
+ const value = node.params.length === 0 && node.tags.length === 0 ? stringOf(source) : `text(${stringOf(source)})`;
328
+ return [`${indent}${keyOf(name)}: ${value},`];
329
+ });
330
+ }
302
331
  function translationsTypeOf(catalog) {
303
- const lines = [
332
+ return [
304
333
  "/**",
305
334
  " * The translations of one language, as `getTranslations` returns them.",
306
335
  " */",
307
- "export type Translations = {"
336
+ "export type Translations = {",
337
+ ...typeLinesOf(treeOf(catalog), catalog, " "),
338
+ "};"
308
339
  ];
309
- for (const [group, messages] of groupsOf(catalog)) {
310
- lines.push(` ${keyOf(group)}: {`);
311
- for (const message of messages) {
312
- const [first = "string", ...rest] = typeOf(message);
313
- lines.push(...docOf(message, catalog.base, " "));
314
- lines.push(` ${keyOf(message.path[1])}: ${first}${rest.length === 0 ? ";" : ""}`);
315
- rest.forEach((line, index) => lines.push(` ${line}${index === rest.length - 1 ? ";" : ""}`));
316
- }
317
- lines.push(" };");
318
- }
319
- lines.push("};");
320
- return lines;
321
340
  }
322
341
  function translationsOfLocale(catalog, locale) {
323
- const lines = [` ${keyOf(locale)}: () => ({`];
324
- for (const [group, messages] of groupsOf(catalog)) {
325
- lines.push(` ${keyOf(group)}: {`);
326
- for (const message of messages) {
327
- const shown = shownLocaleOf(catalog, message.translations, locale);
328
- const source = message.translations[shown]?.source ?? "";
329
- const value = message.params.length === 0 && message.tags.length === 0 ? stringOf(source) : `text(${stringOf(source)})`;
330
- lines.push(` ${keyOf(message.path[1])}: ${value},`);
331
- }
332
- lines.push(" },");
333
- }
334
- lines.push(" }),");
335
- return lines;
342
+ return [
343
+ ` ${keyOf(locale)}: () => ({`,
344
+ ...valueLinesOf(treeOf(catalog), catalog, locale, " "),
345
+ " }),"
346
+ ];
336
347
  }
337
348
  function render(catalog) {
338
349
  const names = catalog.locales.map((locale) => locale.name);
package/dist/index.cjs CHANGED
@@ -1,72 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_source = require("./source-CDwD6Wcn.cjs");
3
- //#region src/define-i18n.ts
4
- function buildMessage(definition) {
5
- return {
6
- [require_source.messageSource]: definition,
7
- maxLength: (limit) => buildMessage({
8
- ...definition,
9
- maxLength: limit
10
- }),
11
- describe: (description) => buildMessage({
12
- ...definition,
13
- description
14
- }),
15
- example: (values) => buildMessage({
16
- ...definition,
17
- examples: {
18
- ...definition.examples,
19
- ...values
20
- }
21
- })
22
- };
23
- }
24
- function checkFallbacks(locales, base) {
25
- const names = locales.map((locale) => locale.name);
26
- if (!names.includes(base)) throw new Error(`The base language '${base}' is not one of the languages.`);
27
- for (const locale of locales) {
28
- const seen = [locale.name];
29
- let current = locale;
30
- while (current?.fallback !== void 0) {
31
- const next = current.fallback;
32
- if (!names.includes(next)) throw new Error(`'${current.name}' falls back to '${next}', which is not one of the languages.`);
33
- if (seen.includes(next)) throw new Error(`'${locale.name}' falls back in a circle: ${[...seen, next].join(", ")}.`);
34
- seen.push(next);
35
- current = locales.find((candidate) => candidate.name === next);
36
- }
37
- }
38
- }
39
- /**
40
- * Declares your languages and names the base language, the one every other language is checked
41
- * against. Returns `i18n`, which declares the messages.
42
- *
43
- * @example
44
- * export const i18n = defineI18n({
45
- * base: 'en',
46
- * locales: {
47
- * en: {},
48
- * nb: {},
49
- * },
50
- * });
51
- */
52
- function defineI18n(config) {
53
- const base = config.base;
54
- const locales = Object.entries(config.locales).map(([name, options]) => options.fallback === void 0 ? { name } : {
55
- name,
56
- fallback: options.fallback
57
- });
58
- checkFallbacks(locales, base);
59
- return {
60
- message: (texts) => buildMessage({ translations: { ...texts } }),
61
- messages: (messages) => {
62
- const group = {
63
- base,
64
- locales,
65
- messages: Object.fromEntries(Object.entries(messages).map(([key, message]) => [key, message[require_source.messageSource]]))
66
- };
67
- return { [require_source.messagesSource]: group };
68
- }
69
- };
70
- }
71
- //#endregion
72
- exports.defineI18n = defineI18n;
package/dist/index.d.cts CHANGED
@@ -1,150 +1,2 @@
1
- import { i as messagesSource, r as messageSource } from "./source-CAF21cuM.cjs";
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-BE4-k_kg.cjs";
2
+ export { type I18n, type Message, type Messages };