@zerolith/i18n 0.0.0-stage → 0.1.0-alpha.2

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.
@@ -0,0 +1,732 @@
1
+ /**
2
+ * The message compiler: MessageFormat 2 catalogs in, one module per locale
3
+ * out, with a plain function per message whose arguments are typed from
4
+ * the placeholders. Formatting and plural selection call `Intl` in the
5
+ * generated module, so no message runtime is shipped. The subset
6
+ * implemented is the one catalogs use: text and placeholders, quoted and
7
+ * unquoted literals, `.input` and `.local` declarations, `.match` with
8
+ * numeric and string selectors, and the default functions `:string`,
9
+ * `:number`, `:integer`, `:percent`, `:currency`, `:offset`, `:date`,
10
+ * `:time`, and `:datetime`. Markup is accepted and formats to nothing.
11
+ */
12
+ class Parser {
13
+ index = 0;
14
+ text;
15
+ key;
16
+ constructor(text, key) {
17
+ this.text = text;
18
+ this.key = key;
19
+ }
20
+ fail(message) {
21
+ throw new Error(`zerolith/i18n: message "${this.key}": ${message} at offset ${this.index}`);
22
+ }
23
+ peek(offset = 0) {
24
+ return this.text.charAt(this.index + offset);
25
+ }
26
+ skipSpace() {
27
+ while (/[ \t\r\n ]/.test(this.peek())) {
28
+ this.index++;
29
+ }
30
+ }
31
+ expect(token) {
32
+ if (!this.text.startsWith(token, this.index)) {
33
+ this.fail(`expected ${JSON.stringify(token)}`);
34
+ }
35
+ this.index += token.length;
36
+ }
37
+ name() {
38
+ const match = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(this.text.slice(this.index));
39
+ if (match === null) {
40
+ this.fail("expected a name");
41
+ }
42
+ this.index += match[0].length;
43
+ return match[0];
44
+ }
45
+ literal() {
46
+ if (this.peek() === "|") {
47
+ this.index++;
48
+ let value = "";
49
+ while (this.index < this.text.length && this.peek() !== "|") {
50
+ if (this.peek() === "\\") {
51
+ value += this.peek(1);
52
+ this.index += 2;
53
+ }
54
+ else {
55
+ value += this.peek();
56
+ this.index++;
57
+ }
58
+ }
59
+ this.expect("|");
60
+ return { kind: "literal", value };
61
+ }
62
+ const match = /^[A-Za-z0-9_.+:@%-]+/.exec(this.text.slice(this.index));
63
+ if (match === null) {
64
+ this.fail("expected a literal");
65
+ }
66
+ this.index += match[0].length;
67
+ return { kind: "literal", value: match[0] };
68
+ }
69
+ variable() {
70
+ this.expect("$");
71
+ return { kind: "variable", name: this.name() };
72
+ }
73
+ /** Parses the inside of `{ ... }` after the opening brace. */
74
+ expression() {
75
+ this.skipSpace();
76
+ if (this.peek() === "#" || this.peek() === "/") {
77
+ while (this.index < this.text.length && this.peek() !== "}") {
78
+ this.index++;
79
+ }
80
+ this.expect("}");
81
+ return undefined;
82
+ }
83
+ let operand;
84
+ if (this.peek() === "$") {
85
+ operand = this.variable();
86
+ }
87
+ else if (this.peek() !== ":") {
88
+ operand = this.literal();
89
+ }
90
+ this.skipSpace();
91
+ let fn;
92
+ const options = {};
93
+ if (this.peek() === ":") {
94
+ this.index++;
95
+ fn = this.name();
96
+ this.skipSpace();
97
+ while (this.peek() !== "}" && this.peek() !== "@" && this.index < this.text.length) {
98
+ const option = this.name();
99
+ this.skipSpace();
100
+ this.expect("=");
101
+ this.skipSpace();
102
+ options[option] = this.peek() === "$" ? this.variable() : this.literal();
103
+ this.skipSpace();
104
+ }
105
+ }
106
+ while (this.peek() === "@") {
107
+ this.index++;
108
+ this.name();
109
+ this.skipSpace();
110
+ if (this.peek() === "=") {
111
+ this.index++;
112
+ this.skipSpace();
113
+ if (this.peek() === "$") {
114
+ this.variable();
115
+ }
116
+ else {
117
+ this.literal();
118
+ }
119
+ this.skipSpace();
120
+ }
121
+ }
122
+ this.expect("}");
123
+ if (operand === undefined && fn === undefined) {
124
+ this.fail("an expression needs an operand or a function");
125
+ }
126
+ return { operand, fn, options };
127
+ }
128
+ /** Parses pattern text up to `end` (`}}` for quoted patterns, the end of input for simple ones). */
129
+ pattern(quoted) {
130
+ const parts = [];
131
+ let text = "";
132
+ while (this.index < this.text.length) {
133
+ const char = this.peek();
134
+ if (quoted && char === "}" && this.peek(1) === "}") {
135
+ break;
136
+ }
137
+ if (char === "\\") {
138
+ const next = this.peek(1);
139
+ if (next !== "{" && next !== "}" && next !== "\\" && next !== "|") {
140
+ this.fail("only \\{ \\} \\\\ and \\| can be escaped");
141
+ }
142
+ text += next;
143
+ this.index += 2;
144
+ }
145
+ else if (char === "{") {
146
+ if (text !== "") {
147
+ parts.push(text);
148
+ text = "";
149
+ }
150
+ this.index++;
151
+ const expression = this.expression();
152
+ if (expression !== undefined) {
153
+ parts.push(expression);
154
+ }
155
+ }
156
+ else if (char === "}") {
157
+ this.fail("a lone } must be escaped as \\}");
158
+ }
159
+ else {
160
+ text += char;
161
+ this.index++;
162
+ }
163
+ }
164
+ if (text !== "") {
165
+ parts.push(text);
166
+ }
167
+ return parts;
168
+ }
169
+ quotedPattern() {
170
+ this.expect("{{");
171
+ const parts = this.pattern(true);
172
+ this.expect("}}");
173
+ return parts;
174
+ }
175
+ parse() {
176
+ const message = { declarations: new Map(), pattern: undefined, selectors: [], variants: [] };
177
+ const trimmed = this.text.trimStart();
178
+ if (!trimmed.startsWith(".") && !trimmed.startsWith("{{")) {
179
+ message.pattern = this.pattern(false);
180
+ return message;
181
+ }
182
+ this.skipSpace();
183
+ while (this.text.startsWith(".input", this.index) || this.text.startsWith(".local", this.index)) {
184
+ const local = this.text.startsWith(".local", this.index);
185
+ this.index += 6;
186
+ this.skipSpace();
187
+ let name;
188
+ if (local) {
189
+ name = this.variable().name;
190
+ this.skipSpace();
191
+ this.expect("=");
192
+ this.skipSpace();
193
+ }
194
+ else {
195
+ name = "";
196
+ }
197
+ this.expect("{");
198
+ const expression = this.expression();
199
+ if (expression === undefined) {
200
+ this.fail("a declaration cannot be markup");
201
+ }
202
+ if (!local) {
203
+ if (expression.operand?.kind !== "variable") {
204
+ this.fail(".input needs a variable operand");
205
+ }
206
+ name = expression.operand.name;
207
+ }
208
+ if (message.declarations.has(name)) {
209
+ this.fail(`$${name} is declared twice`);
210
+ }
211
+ message.declarations.set(name, { expression, local });
212
+ this.skipSpace();
213
+ }
214
+ if (this.text.startsWith(".match", this.index)) {
215
+ this.index += 6;
216
+ this.skipSpace();
217
+ while (this.peek() === "$" || this.peek() === "{") {
218
+ if (this.peek() === "{") {
219
+ this.index++;
220
+ const expression = this.expression();
221
+ if (expression === undefined) {
222
+ this.fail("a selector cannot be markup");
223
+ }
224
+ message.selectors.push(expression);
225
+ }
226
+ else {
227
+ message.selectors.push({ operand: this.variable(), fn: undefined, options: {} });
228
+ }
229
+ this.skipSpace();
230
+ }
231
+ if (message.selectors.length === 0) {
232
+ this.fail(".match needs at least one selector");
233
+ }
234
+ while (this.index < this.text.length) {
235
+ const keys = [];
236
+ while (this.peek() !== "{") {
237
+ if (this.peek() === "*") {
238
+ this.index++;
239
+ keys.push("*");
240
+ }
241
+ else {
242
+ keys.push(this.literal().value);
243
+ }
244
+ this.skipSpace();
245
+ }
246
+ if (keys.length !== message.selectors.length) {
247
+ this.fail(`a variant needs ${message.selectors.length} key(s), found ${keys.length}`);
248
+ }
249
+ message.variants.push({ keys, pattern: this.quotedPattern() });
250
+ this.skipSpace();
251
+ }
252
+ if (!message.variants.some((variant) => variant.keys.every((key) => key === "*"))) {
253
+ this.fail("a matcher needs a variant whose keys are all *");
254
+ }
255
+ return message;
256
+ }
257
+ message.pattern = this.quotedPattern();
258
+ this.skipSpace();
259
+ if (this.index < this.text.length) {
260
+ this.fail("unexpected text after the pattern");
261
+ }
262
+ return message;
263
+ }
264
+ }
265
+ const NUMBER_FUNCTIONS = new Set(["number", "integer", "percent", "currency", "offset"]);
266
+ const DATE_FUNCTIONS = new Set(["date", "time", "datetime"]);
267
+ const NUMBER_OPTIONS = {
268
+ minimumFractionDigits: "minimumFractionDigits",
269
+ maximumFractionDigits: "maximumFractionDigits",
270
+ minimumIntegerDigits: "minimumIntegerDigits",
271
+ minimumSignificantDigits: "minimumSignificantDigits",
272
+ maximumSignificantDigits: "maximumSignificantDigits",
273
+ signDisplay: "signDisplay",
274
+ trailingZeroDisplay: "trailingZeroDisplay",
275
+ roundingMode: "roundingMode",
276
+ roundingIncrement: "roundingIncrement",
277
+ roundingPriority: "roundingPriority",
278
+ currencyDisplay: "currencyDisplay",
279
+ currencySign: "currencySign",
280
+ numberingSystem: "numberingSystem"
281
+ };
282
+ function identifier(key) {
283
+ const words = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter((word) => word !== "");
284
+ const name = words.map((word, index) => (index === 0 ? word.charAt(0).toLowerCase() + word.slice(1) : word.charAt(0).toUpperCase() + word.slice(1))).join("");
285
+ return /^[0-9]/.test(name) ? `_${name}` : name === "" ? "_" : name;
286
+ }
287
+ class Emitter {
288
+ arguments = new Map();
289
+ locals = new Map();
290
+ prelude = [];
291
+ key;
292
+ message;
293
+ constructor(key, message) {
294
+ this.key = key;
295
+ this.message = message;
296
+ }
297
+ fail(text) {
298
+ throw new Error(`zerolith/i18n: message "${this.key}": ${text}`);
299
+ }
300
+ argument(name, type) {
301
+ const local = this.locals.get(name);
302
+ if (local !== undefined) {
303
+ return local;
304
+ }
305
+ const existing = this.arguments.get(name);
306
+ if (existing === undefined || existing === "string") {
307
+ this.arguments.set(name, type);
308
+ }
309
+ else if (existing !== type && type !== "string") {
310
+ this.fail(`$${name} is used both as ${existing} and as ${type}`);
311
+ }
312
+ return `args.${name}`;
313
+ }
314
+ optionValue(value) {
315
+ if (value === undefined) {
316
+ return undefined;
317
+ }
318
+ return value.kind === "literal" ? JSON.stringify(value.value) : `String(${this.argument(value.name, "string")})`;
319
+ }
320
+ numberOptions(expression) {
321
+ const entries = [];
322
+ const fn = expression.fn ?? "number";
323
+ if (fn === "integer") {
324
+ entries.push("maximumFractionDigits: 0");
325
+ }
326
+ else if (fn === "percent") {
327
+ entries.push("style: \"percent\"");
328
+ }
329
+ else if (fn === "currency") {
330
+ const currency = this.optionValue(expression.options["currency"]);
331
+ if (currency === undefined) {
332
+ this.fail(":currency needs a currency option");
333
+ }
334
+ entries.push("style: \"currency\"", `currency: ${currency}`);
335
+ }
336
+ for (const [option, value] of Object.entries(expression.options)) {
337
+ const mapped = NUMBER_OPTIONS[option];
338
+ if (mapped !== undefined) {
339
+ const literal = value.kind === "literal" ? value.value : undefined;
340
+ const numeric = literal !== undefined && /^[0-9]+$/.test(literal) ? literal : undefined;
341
+ entries.push(`${mapped}: ${numeric ?? this.optionValue(value) ?? "undefined"}`);
342
+ }
343
+ else if (option === "useGrouping" && value.kind === "literal") {
344
+ entries.push(`useGrouping: ${value.value === "never" ? "false" : value.value === "always" ? "true" : JSON.stringify(value.value)}`);
345
+ }
346
+ else if (option === "fractionDigits" && value.kind === "literal" && /^[0-9]+$/.test(value.value)) {
347
+ entries.push(`minimumFractionDigits: ${value.value}`, `maximumFractionDigits: ${value.value}`);
348
+ }
349
+ }
350
+ return `{ ${entries.join(", ")} }`;
351
+ }
352
+ dateOptions(expression) {
353
+ const entries = [];
354
+ const fn = expression.fn ?? "date";
355
+ const literal = (name) => {
356
+ const value = expression.options[name];
357
+ return value?.kind === "literal" ? value.value : undefined;
358
+ };
359
+ const length = literal(fn === "datetime" ? "dateLength" : "length") ?? (fn === "time" ? undefined : "medium");
360
+ if (length !== undefined && fn !== "time") {
361
+ entries.push(`dateStyle: ${JSON.stringify(length)}`);
362
+ }
363
+ const precision = literal(fn === "datetime" ? "timePrecision" : "precision") ?? (fn === "date" ? undefined : "minute");
364
+ if (precision !== undefined && fn !== "date") {
365
+ entries.push(`timeStyle: ${JSON.stringify(precision === "second" ? "medium" : "short")}`);
366
+ }
367
+ const zone = literal("timeZone");
368
+ if (zone !== undefined && zone !== "input") {
369
+ entries.push(`timeZone: ${JSON.stringify(zone)}`);
370
+ }
371
+ const hour12 = literal("hour12");
372
+ if (hour12 !== undefined) {
373
+ entries.push(`hour12: ${hour12 === "true"}`);
374
+ }
375
+ const style = literal("timeZoneStyle");
376
+ if (style !== undefined) {
377
+ entries.push(`timeZoneName: ${JSON.stringify(style)}`);
378
+ }
379
+ return `{ ${entries.join(", ")} }`;
380
+ }
381
+ /** The JavaScript for an expression's numeric value, before formatting. */
382
+ numeric(expression) {
383
+ const operand = expression.operand;
384
+ let value;
385
+ if (operand === undefined) {
386
+ this.fail(`:${expression.fn ?? ""} needs an operand`);
387
+ }
388
+ else if (operand.kind === "literal") {
389
+ value = Number.isFinite(Number(operand.value)) ? String(Number(operand.value)) : this.fail(`${JSON.stringify(operand.value)} is not a number`);
390
+ }
391
+ else {
392
+ value = this.argument(operand.name, "number");
393
+ }
394
+ if (expression.fn === "offset") {
395
+ const add = this.optionValue(expression.options["add"]);
396
+ const subtract = this.optionValue(expression.options["subtract"]);
397
+ if ((add === undefined) === (subtract === undefined)) {
398
+ this.fail(":offset needs exactly one of add or subtract");
399
+ }
400
+ value = `(${value} ${add === undefined ? "-" : "+"} Number(${add ?? subtract ?? "0"}))`;
401
+ }
402
+ return value;
403
+ }
404
+ /** Resolves a plain `{$x}` to its declaration when one exists. */
405
+ resolve(expression) {
406
+ if (expression.fn === undefined && expression.operand?.kind === "variable") {
407
+ const declared = this.message.declarations.get(expression.operand.name);
408
+ if (declared !== undefined && !declared.local) {
409
+ return declared.expression;
410
+ }
411
+ }
412
+ return expression;
413
+ }
414
+ /** The JavaScript producing the formatted string of an expression. */
415
+ format(raw) {
416
+ const expression = this.resolve(raw);
417
+ const fn = expression.fn;
418
+ if (fn === undefined || fn === "string") {
419
+ const operand = expression.operand;
420
+ if (operand === undefined) {
421
+ this.fail(":string needs an operand");
422
+ }
423
+ return operand.kind === "literal" ? JSON.stringify(operand.value) : `String(${this.argument(operand.name, "string")})`;
424
+ }
425
+ if (NUMBER_FUNCTIONS.has(fn)) {
426
+ return `number(${this.numeric(expression)}, ${this.numberOptions(expression)})`;
427
+ }
428
+ if (DATE_FUNCTIONS.has(fn)) {
429
+ const operand = expression.operand;
430
+ if (operand === undefined) {
431
+ this.fail(`:${fn} needs an operand`);
432
+ }
433
+ const value = operand.kind === "literal" ? `new Date(${JSON.stringify(operand.value)})` : this.argument(operand.name, "date");
434
+ return `date(${value}, ${this.dateOptions(expression)})`;
435
+ }
436
+ this.fail(`unknown function :${fn}`);
437
+ }
438
+ /** The JavaScript for a selector: its comparable value and the categories it matches. */
439
+ selector(raw) {
440
+ const expression = this.resolve(raw);
441
+ const fn = expression.fn ?? "string";
442
+ if (NUMBER_FUNCTIONS.has(fn)) {
443
+ const select = expression.options["select"];
444
+ const mode = select?.kind === "literal" ? select.value : "plural";
445
+ const value = fn === "percent" ? `(${this.numeric(expression)}) * 100` : this.numeric(expression);
446
+ if (mode === "exact") {
447
+ return `{ value: String(${value}), categories: [] }`;
448
+ }
449
+ return `{ value: String(${value}), categories: [plural(${value}, ${JSON.stringify(mode === "ordinal" ? "ordinal" : "cardinal")})] }`;
450
+ }
451
+ if (fn === "string") {
452
+ const operand = expression.operand;
453
+ if (operand === undefined) {
454
+ this.fail("a selector needs an operand");
455
+ }
456
+ const value = operand.kind === "literal" ? JSON.stringify(operand.value) : `String(${this.argument(operand.name, "string")})`;
457
+ return `{ value: ${value}, categories: [] }`;
458
+ }
459
+ this.fail(`:${fn} cannot select`);
460
+ }
461
+ pattern(parts) {
462
+ if (parts.length === 0) {
463
+ return "\"\"";
464
+ }
465
+ return parts.map((part) => (typeof part === "string" ? JSON.stringify(part) : this.format(part))).join(" + ");
466
+ }
467
+ body() {
468
+ for (const [name, declaration] of this.message.declarations) {
469
+ if (declaration.local) {
470
+ const value = this.format(declaration.expression);
471
+ this.locals.set(name, `local_${name}`);
472
+ this.prelude.push(`const local_${name} = ${value};`);
473
+ }
474
+ }
475
+ if (this.message.pattern !== undefined) {
476
+ return this.pattern(this.message.pattern);
477
+ }
478
+ const selectors = this.message.selectors.map((selector) => this.selector(selector));
479
+ const variants = this.message.variants.map((variant) => `{ keys: ${JSON.stringify(variant.keys)}, pattern: () => ${this.pattern(variant.pattern)} }`);
480
+ return `select([${selectors.join(", ")}], [${variants.join(", ")}])`;
481
+ }
482
+ }
483
+ const HELPERS = `const formats = new Map();
484
+ function cached(kind, options, create)
485
+ {
486
+ const key = kind + JSON.stringify(options);
487
+ let instance = formats.get(key);
488
+ if (instance === undefined)
489
+ {
490
+ instance = create();
491
+ formats.set(key, instance);
492
+ }
493
+ return instance;
494
+ }
495
+ function number(value, options)
496
+ {
497
+ return cached("n", options, () => new Intl.NumberFormat(locale, options)).format(value);
498
+ }
499
+ function date(value, options)
500
+ {
501
+ return cached("d", options, () => new Intl.DateTimeFormat(locale, options)).format(value);
502
+ }
503
+ function plural(value, type)
504
+ {
505
+ return cached("p", { type }, () => new Intl.PluralRules(locale, { type })).select(value);
506
+ }
507
+ function select(selectors, variants)
508
+ {
509
+ let best;
510
+ let bestRank;
511
+ for (const variant of variants)
512
+ {
513
+ const rank = [];
514
+ let matches = true;
515
+ for (const [index, key] of variant.keys.entries())
516
+ {
517
+ const selector = selectors[index];
518
+ if (key === "*")
519
+ {
520
+ rank.push(0);
521
+ }
522
+ else if (key === selector.value)
523
+ {
524
+ rank.push(2);
525
+ }
526
+ else if (selector.categories.includes(key))
527
+ {
528
+ rank.push(1);
529
+ }
530
+ else
531
+ {
532
+ matches = false;
533
+ break;
534
+ }
535
+ }
536
+ if (!matches)
537
+ {
538
+ continue;
539
+ }
540
+ if (matches && better(rank, bestRank))
541
+ {
542
+ best = variant;
543
+ bestRank = rank;
544
+ }
545
+ }
546
+ return best === undefined ? "" : best.pattern();
547
+ }
548
+ function better(rank, current)
549
+ {
550
+ if (current === undefined)
551
+ {
552
+ return true;
553
+ }
554
+ for (const [index, score] of rank.entries())
555
+ {
556
+ const other = current[index] ?? 0;
557
+ if (score !== other)
558
+ {
559
+ return score > other;
560
+ }
561
+ }
562
+ return false;
563
+ }`;
564
+ const HELPERS_TS = `interface Selector
565
+ {
566
+ value: string;
567
+ categories: string[];
568
+ }
569
+ interface Variant
570
+ {
571
+ keys: string[];
572
+ pattern: () => string;
573
+ }
574
+ const formats: Map<string, unknown> = new Map();
575
+ function cached<T>(kind: string, options: object, create: () => T): T
576
+ {
577
+ const key = kind + JSON.stringify(options);
578
+ let instance = formats.get(key) as T | undefined;
579
+ if (instance === undefined)
580
+ {
581
+ instance = create();
582
+ formats.set(key, instance);
583
+ }
584
+ return instance;
585
+ }
586
+ function number(value: number, options: Intl.NumberFormatOptions): string
587
+ {
588
+ return cached("n", options, () => new Intl.NumberFormat(locale, options)).format(value);
589
+ }
590
+ function date(value: Date | number, options: Intl.DateTimeFormatOptions): string
591
+ {
592
+ return cached("d", options, () => new Intl.DateTimeFormat(locale, options)).format(value);
593
+ }
594
+ function plural(value: number, type: "cardinal" | "ordinal"): string
595
+ {
596
+ return cached("p", { type }, () => new Intl.PluralRules(locale, { type })).select(value);
597
+ }
598
+ function better(rank: number[], current: number[] | undefined): boolean
599
+ {
600
+ if (current === undefined)
601
+ {
602
+ return true;
603
+ }
604
+ for (const [index, score] of rank.entries())
605
+ {
606
+ const other = current[index] ?? 0;
607
+ if (score !== other)
608
+ {
609
+ return score > other;
610
+ }
611
+ }
612
+ return false;
613
+ }
614
+ function select(selectors: Selector[], variants: Variant[]): string
615
+ {
616
+ let best: Variant | undefined;
617
+ let bestRank: number[] | undefined;
618
+ for (const variant of variants)
619
+ {
620
+ const rank: number[] = [];
621
+ let matches = true;
622
+ for (const [index, key] of variant.keys.entries())
623
+ {
624
+ const selector = selectors[index];
625
+ if (key === "*")
626
+ {
627
+ rank.push(0);
628
+ }
629
+ else if (selector !== undefined && key === selector.value)
630
+ {
631
+ rank.push(2);
632
+ }
633
+ else if (selector !== undefined && selector.categories.includes(key))
634
+ {
635
+ rank.push(1);
636
+ }
637
+ else
638
+ {
639
+ matches = false;
640
+ break;
641
+ }
642
+ }
643
+ if (matches && better(rank, bestRank))
644
+ {
645
+ best = variant;
646
+ bestRank = rank;
647
+ }
648
+ }
649
+ return best === undefined ? "" : best.pattern();
650
+ }`;
651
+ function typeOf(type) {
652
+ return type === "number" ? "number" : type === "date" ? "Date | number" : "string | number";
653
+ }
654
+ /**
655
+ * Compiles one locale's catalog into a module: `locale`, one exported
656
+ * function per message named from its key, and the `Intl` helpers they
657
+ * share. Each function takes an `args` object typed from the message's
658
+ * placeholders, or nothing when the message has none.
659
+ */
660
+ export function compileMessages(locale, catalog, options = {}) {
661
+ const javascript = options.language === "js";
662
+ const out = [];
663
+ out.push(`// Generated by @zerolith/i18n from ${options.source ?? `the ${locale} catalog`}. Do not edit; regenerate instead.`);
664
+ if (javascript) {
665
+ out.push("// @ts-check");
666
+ }
667
+ out.push(`export const locale${javascript ? "" : ": string"} = ${JSON.stringify(locale)};`);
668
+ out.push("");
669
+ out.push(javascript ? HELPERS : HELPERS_TS);
670
+ out.push("");
671
+ const names = [];
672
+ const seen = new Set();
673
+ for (const [key, source] of Object.entries(catalog)) {
674
+ const name = identifier(key);
675
+ if (seen.has(name)) {
676
+ throw new Error(`zerolith/i18n: keys "${key}" and another one both become ${name}`);
677
+ }
678
+ seen.add(name);
679
+ names.push(name);
680
+ const message = new Parser(source, key).parse();
681
+ const emitter = new Emitter(key, message);
682
+ const body = emitter.body();
683
+ const args = [...emitter.arguments.entries()].toSorted(([a], [b]) => a.localeCompare(b));
684
+ const doc = source.replace(/\*\//g, "* /").split(/\r?\n/).map((line) => ` * ${line}`.trimEnd()).join("\n");
685
+ const argumentType = `{ ${args.map(([argument, type]) => `${argument}: ${typeOf(type)}`).join("; ")} }`;
686
+ if (javascript) {
687
+ out.push(`/**\n${doc}${args.length > 0 ? `\n * @param {${argumentType}} args` : ""}\n * @returns {string}\n */`);
688
+ out.push(`export function ${name}(${args.length > 0 ? "args" : ""})`);
689
+ }
690
+ else {
691
+ out.push(`/**\n${doc}\n */`);
692
+ out.push(`export function ${name}(${args.length > 0 ? `args: ${argumentType}` : ""}): string`);
693
+ }
694
+ out.push("{");
695
+ for (const line of emitter.prelude) {
696
+ out.push(` ${line}`);
697
+ }
698
+ out.push(` return ${body};`);
699
+ out.push("}");
700
+ out.push("");
701
+ }
702
+ return { code: out.join("\n"), names };
703
+ }
704
+ /** The keys of a catalog as function names, for comparing locales. */
705
+ export function messageNames(catalog) {
706
+ return Object.keys(catalog).map(identifier);
707
+ }
708
+ /**
709
+ * The index module for a set of locales: the list of locales and one lazy
710
+ * loader per locale, so each locale is its own chunk.
711
+ */
712
+ export function compileIndex(locales, options = {}) {
713
+ const javascript = options.language === "js";
714
+ const extension = javascript ? "js" : "ts";
715
+ const lines = [`// Generated by @zerolith/i18n. Do not edit; regenerate instead.`];
716
+ if (javascript) {
717
+ lines.push("// @ts-check");
718
+ }
719
+ if (!javascript) {
720
+ lines.push(`import type * as first from "./${locales[0] ?? "en"}.${extension}";`);
721
+ lines.push("");
722
+ }
723
+ lines.push(`export const locales${javascript ? "" : ": readonly string[]"} = ${JSON.stringify(locales)};`);
724
+ lines.push("");
725
+ lines.push(`/** Loads one locale's messages; each locale is its own module. */`);
726
+ lines.push(javascript ? "export const loaders = {" : "export const loaders: Readonly<Record<string, () => Promise<typeof first>>> = {");
727
+ lines.push(locales.map((locale) => ` ${JSON.stringify(locale)}: () => import("./${locale}.${extension}")`).join(",\n"));
728
+ lines.push("};");
729
+ lines.push("");
730
+ return lines.join("\n");
731
+ }
732
+ //# sourceMappingURL=compile.js.map