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

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,826 @@
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
+ /** Names a module cannot bind; a message named so is exported under its name from a binding of its own. */
283
+ const RESERVED = new Set(["arguments", "await", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "eval", "export", "extends", "false", "finally", "for", "function", "if", "implements", "import", "in", "instanceof", "interface", "let", "new", "null", "package", "private", "protected", "public", "return", "static", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "yield"]);
284
+ /** Characters an HTML parser reads inside an inline script, and the line separators older engines refused in string literals. */
285
+ const SCRIPT_UNSAFE = new RegExp(`[<>${String.fromCodePoint(0x2028, 0x2029)}]`, "g");
286
+ /** The line breaks of a message's source, each starting a new line of its doc comment. */
287
+ const SOURCE_LINES = /\r\n|[\n\r\u2028\u2029]/;
288
+ /**
289
+ * A value written as JavaScript source: its JSON, with `<`, `>`, U+2028, and
290
+ * U+2029 escaped, so generated code stays inert even when a page inlines
291
+ * it in a script element.
292
+ */
293
+ function jsLiteral(value) {
294
+ return JSON.stringify(value).replace(SCRIPT_UNSAFE, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
295
+ }
296
+ /** Text for a `//` comment, kept on one line and with `<` written as `&lt;`, so it can end neither the comment nor an inline script. */
297
+ function commentText(text) {
298
+ return text.split(SOURCE_LINES).join(" ").replaceAll("<", "&lt;");
299
+ }
300
+ /** An argument or local name JavaScript can write as it is; MessageFormat also allows `-` and `.`, as in `$first-name`. */
301
+ const PLAIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
302
+ /** A property name as code: as it is when plain, quoted otherwise. */
303
+ function property(name) {
304
+ return PLAIN_NAME.test(name) ? name : jsLiteral(name);
305
+ }
306
+ function identifier(key) {
307
+ const words = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter((word) => word !== "");
308
+ const name = words.map((word, index) => (index === 0 ? word.charAt(0).toLowerCase() + word.slice(1) : word.charAt(0).toUpperCase() + word.slice(1))).join("");
309
+ return /^[0-9]/.test(name) ? `_${name}` : name === "" ? "_" : name;
310
+ }
311
+ class Emitter {
312
+ arguments = new Map();
313
+ locals = new Map();
314
+ prelude = [];
315
+ key;
316
+ message;
317
+ formatters;
318
+ used;
319
+ reads = 0;
320
+ constructor(key, message, formatters, used) {
321
+ this.key = key;
322
+ this.message = message;
323
+ this.formatters = formatters;
324
+ this.used = used;
325
+ }
326
+ /** The module-level binding of a formatter whose options are known at compile time, created on first use and shared by every message that creates it the same way. */
327
+ shared(create) {
328
+ this.used.add("once");
329
+ let binding = this.formatters.get(create);
330
+ if (binding === undefined) {
331
+ binding = `$f${this.formatters.size}`;
332
+ this.formatters.set(create, binding);
333
+ }
334
+ return binding;
335
+ }
336
+ fail(text) {
337
+ throw new Error(`zerolith/i18n: message "${this.key}": ${text}`);
338
+ }
339
+ argument(name, type) {
340
+ this.reads++;
341
+ const local = this.locals.get(name);
342
+ if (local !== undefined) {
343
+ return local;
344
+ }
345
+ const existing = this.arguments.get(name);
346
+ if (existing === undefined || existing === "string") {
347
+ this.arguments.set(name, type);
348
+ }
349
+ else if (existing !== type && type !== "string") {
350
+ this.fail(`$${name} is used both as ${existing} and as ${type}`);
351
+ }
352
+ return PLAIN_NAME.test(name) ? `args.${name}` : `args[${jsLiteral(name)}]`;
353
+ }
354
+ optionValue(value) {
355
+ if (value === undefined) {
356
+ return undefined;
357
+ }
358
+ return value.kind === "literal" ? jsLiteral(value.value) : `String(${this.argument(value.name, "string")})`;
359
+ }
360
+ numberOptions(expression) {
361
+ const entries = [];
362
+ const fn = expression.fn ?? "number";
363
+ if (fn === "integer") {
364
+ entries.push("maximumFractionDigits: 0");
365
+ }
366
+ else if (fn === "percent") {
367
+ entries.push("style: \"percent\"");
368
+ }
369
+ else if (fn === "currency") {
370
+ const currency = this.optionValue(expression.options["currency"]);
371
+ if (currency === undefined) {
372
+ this.fail(":currency needs a currency option");
373
+ }
374
+ entries.push("style: \"currency\"", `currency: ${currency}`);
375
+ }
376
+ for (const [option, value] of Object.entries(expression.options)) {
377
+ const mapped = NUMBER_OPTIONS[option];
378
+ if (mapped !== undefined) {
379
+ const literal = value.kind === "literal" ? value.value : undefined;
380
+ const numeric = literal !== undefined && /^[0-9]+$/.test(literal) ? literal : undefined;
381
+ entries.push(`${mapped}: ${numeric ?? this.optionValue(value) ?? "undefined"}`);
382
+ }
383
+ else if (option === "useGrouping" && value.kind === "literal") {
384
+ entries.push(`useGrouping: ${value.value === "never" ? "false" : value.value === "always" ? "true" : jsLiteral(value.value)}`);
385
+ }
386
+ else if (option === "fractionDigits" && value.kind === "literal" && /^[0-9]+$/.test(value.value)) {
387
+ entries.push(`minimumFractionDigits: ${value.value}`, `maximumFractionDigits: ${value.value}`);
388
+ }
389
+ }
390
+ return entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
391
+ }
392
+ dateOptions(expression) {
393
+ const entries = [];
394
+ const fn = expression.fn ?? "date";
395
+ const literal = (name) => {
396
+ const value = expression.options[name];
397
+ return value?.kind === "literal" ? value.value : undefined;
398
+ };
399
+ const length = literal(fn === "datetime" ? "dateLength" : "length") ?? (fn === "time" ? undefined : "medium");
400
+ if (length !== undefined && fn !== "time") {
401
+ entries.push(`dateStyle: ${jsLiteral(length)}`);
402
+ }
403
+ const precision = literal(fn === "datetime" ? "timePrecision" : "precision") ?? (fn === "date" ? undefined : "minute");
404
+ if (precision !== undefined && fn !== "date") {
405
+ entries.push(`timeStyle: ${jsLiteral(precision === "second" ? "medium" : "short")}`);
406
+ }
407
+ const zone = literal("timeZone");
408
+ if (zone !== undefined && zone !== "input") {
409
+ entries.push(`timeZone: ${jsLiteral(zone)}`);
410
+ }
411
+ const hour12 = literal("hour12");
412
+ if (hour12 !== undefined) {
413
+ entries.push(`hour12: ${hour12 === "true"}`);
414
+ }
415
+ const style = literal("timeZoneStyle");
416
+ if (style !== undefined) {
417
+ entries.push(`timeZoneName: ${jsLiteral(style)}`);
418
+ }
419
+ return entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
420
+ }
421
+ /** The JavaScript for an expression's numeric value, before formatting. */
422
+ numeric(expression) {
423
+ const operand = expression.operand;
424
+ let value;
425
+ if (operand === undefined) {
426
+ this.fail(`:${expression.fn ?? ""} needs an operand`);
427
+ }
428
+ else if (operand.kind === "literal") {
429
+ value = Number.isFinite(Number(operand.value)) ? String(Number(operand.value)) : this.fail(`${JSON.stringify(operand.value)} is not a number`);
430
+ }
431
+ else {
432
+ value = this.argument(operand.name, "number");
433
+ }
434
+ if (expression.fn === "offset") {
435
+ const add = this.optionValue(expression.options["add"]);
436
+ const subtract = this.optionValue(expression.options["subtract"]);
437
+ if ((add === undefined) === (subtract === undefined)) {
438
+ this.fail(":offset needs exactly one of add or subtract");
439
+ }
440
+ value = `(${value} ${add === undefined ? "-" : "+"} Number(${add ?? subtract ?? "0"}))`;
441
+ }
442
+ return value;
443
+ }
444
+ /** Resolves a plain `{$x}` to its `.input` declaration when one exists, or with `locals` to its `.local` one too, so a selector on a local selects as its expression does. */
445
+ resolve(expression, locals = false) {
446
+ if (expression.fn === undefined && expression.operand?.kind === "variable") {
447
+ const declared = this.message.declarations.get(expression.operand.name);
448
+ if (declared !== undefined && (locals || !declared.local)) {
449
+ return declared.expression;
450
+ }
451
+ }
452
+ return expression;
453
+ }
454
+ /** The JavaScript producing the formatted string of an expression. */
455
+ format(raw) {
456
+ const expression = this.resolve(raw);
457
+ const fn = expression.fn;
458
+ if (fn === undefined || fn === "string") {
459
+ const operand = expression.operand;
460
+ if (operand === undefined) {
461
+ this.fail(":string needs an operand");
462
+ }
463
+ return operand.kind === "literal" ? jsLiteral(operand.value) : `String(${this.argument(operand.name, "string")})`;
464
+ }
465
+ if (NUMBER_FUNCTIONS.has(fn)) {
466
+ const value = this.numeric(expression);
467
+ const reads = this.reads;
468
+ const options = this.numberOptions(expression);
469
+ if (this.reads === reads) {
470
+ return `${this.shared(`new Intl.NumberFormat(locale, ${options})`)}().format(${value})`;
471
+ }
472
+ this.used.add("number");
473
+ return `$number(${value}, ${options})`;
474
+ }
475
+ if (DATE_FUNCTIONS.has(fn)) {
476
+ const operand = expression.operand;
477
+ if (operand === undefined) {
478
+ this.fail(`:${fn} needs an operand`);
479
+ }
480
+ const value = operand.kind === "literal" ? `new Date(${jsLiteral(operand.value)})` : this.argument(operand.name, "date");
481
+ return `${this.shared(`new Intl.DateTimeFormat(locale, ${this.dateOptions(expression)})`)}().format(${value})`;
482
+ }
483
+ this.fail(`unknown function :${fn}`);
484
+ }
485
+ /** The JavaScript for a selector: its comparable value and the categories it matches. */
486
+ selector(raw) {
487
+ const expression = this.resolve(raw, true);
488
+ const fn = expression.fn ?? "string";
489
+ if (NUMBER_FUNCTIONS.has(fn)) {
490
+ const select = expression.options["select"];
491
+ const mode = select?.kind === "literal" ? select.value : "plural";
492
+ const value = fn === "percent" ? `(${this.numeric(expression)}) * 100` : this.numeric(expression);
493
+ if (mode === "exact") {
494
+ return `{ value: String(${value}), categories: [] }`;
495
+ }
496
+ const type = jsLiteral(mode === "ordinal" ? "ordinal" : "cardinal");
497
+ const reads = this.reads;
498
+ const options = this.numberOptions(expression);
499
+ if (this.reads === reads) {
500
+ return `{ value: String(${value}), categories: [${this.shared(`new Intl.PluralRules(locale, { ...new Intl.NumberFormat(locale, ${options}).resolvedOptions(), type: ${type} })`)}().select(${value})] }`;
501
+ }
502
+ this.used.add("plural");
503
+ return `{ value: String(${value}), categories: [$plural(${value}, ${type}, ${options})] }`;
504
+ }
505
+ if (fn === "string") {
506
+ const operand = expression.operand;
507
+ if (operand === undefined) {
508
+ this.fail("a selector needs an operand");
509
+ }
510
+ const value = operand.kind === "literal" ? jsLiteral(operand.value) : `String(${this.argument(operand.name, "string")})`;
511
+ return `{ value: ${value}, categories: [] }`;
512
+ }
513
+ this.fail(`:${fn} cannot select`);
514
+ }
515
+ pattern(parts) {
516
+ if (parts.length === 0) {
517
+ return "\"\"";
518
+ }
519
+ return parts.map((part) => (typeof part === "string" ? jsLiteral(part) : this.format(part))).join(" + ");
520
+ }
521
+ body() {
522
+ for (const [name, declaration] of this.message.declarations) {
523
+ if (declaration.local) {
524
+ const value = this.format(declaration.expression);
525
+ const binding = PLAIN_NAME.test(name) ? `local_${name}` : `local_${this.locals.size}`;
526
+ this.locals.set(name, binding);
527
+ this.prelude.push(`const ${binding} = ${value};`);
528
+ }
529
+ }
530
+ if (this.message.pattern !== undefined) {
531
+ return this.pattern(this.message.pattern);
532
+ }
533
+ const selectors = this.message.selectors.map((selector) => this.selector(selector));
534
+ const variants = this.message.variants.map((variant) => `{ keys: ${jsLiteral(variant.keys)}, pattern: () => ${this.pattern(variant.pattern)} }`);
535
+ this.used.add("select");
536
+ return `$select([${selectors.join(", ")}], [${variants.join(", ")}])`;
537
+ }
538
+ }
539
+ /** The helpers in JavaScript and in TypeScript, in the order a module writes them. */
540
+ const HELPERS = {
541
+ cache: {
542
+ js: `const $formats = new Map();
543
+ function $cached(kind, options, create)
544
+ {
545
+ const key = kind + JSON.stringify(options);
546
+ let instance = $formats.get(key);
547
+ if (instance === undefined)
548
+ {
549
+ instance = create();
550
+ $formats.set(key, instance);
551
+ }
552
+ return instance;
553
+ }`,
554
+ ts: `const $formats: Map<string, unknown> = new Map();
555
+ function $cached<T>(kind: string, options: object, create: () => T): T
556
+ {
557
+ const key = kind + JSON.stringify(options);
558
+ let instance = $formats.get(key) as T | undefined;
559
+ if (instance === undefined)
560
+ {
561
+ instance = create();
562
+ $formats.set(key, instance);
563
+ }
564
+ return instance;
565
+ }`
566
+ },
567
+ once: {
568
+ js: `function $once(create)
569
+ {
570
+ let instance;
571
+ return () => (instance ??= create());
572
+ }`,
573
+ ts: `function $once<T>(create: () => T): () => T
574
+ {
575
+ let instance: T | undefined;
576
+ return () => (instance ??= create());
577
+ }`
578
+ },
579
+ number: {
580
+ js: `function $number(value, options)
581
+ {
582
+ return $cached("n", options, () => new Intl.NumberFormat(locale, options)).format(value);
583
+ }`,
584
+ ts: `function $number(value: number, options: Intl.NumberFormatOptions): string
585
+ {
586
+ return $cached("n", options, () => new Intl.NumberFormat(locale, options)).format(value);
587
+ }`
588
+ },
589
+ plural: {
590
+ js: `function $plural(value, type, options)
591
+ {
592
+ return $cached("p" + type, options, () => new Intl.PluralRules(locale, { ...$cached("n", options, () => new Intl.NumberFormat(locale, options)).resolvedOptions(), type })).select(value);
593
+ }`,
594
+ ts: `function $plural(value: number, type: "cardinal" | "ordinal", options: Intl.NumberFormatOptions): string
595
+ {
596
+ return $cached("p" + type, options, () => new Intl.PluralRules(locale, { ...$cached("n", options, () => new Intl.NumberFormat(locale, options)).resolvedOptions(), type })).select(value);
597
+ }`
598
+ },
599
+ select: {
600
+ js: `function $select(selectors, variants)
601
+ {
602
+ let best;
603
+ let bestRank;
604
+ for (const variant of variants)
605
+ {
606
+ const rank = [];
607
+ let matches = true;
608
+ for (const [index, key] of variant.keys.entries())
609
+ {
610
+ const selector = selectors[index];
611
+ if (key === "*")
612
+ {
613
+ rank.push(0);
614
+ }
615
+ else if (key === selector.value)
616
+ {
617
+ rank.push(2);
618
+ }
619
+ else if (selector.categories.includes(key))
620
+ {
621
+ rank.push(1);
622
+ }
623
+ else
624
+ {
625
+ matches = false;
626
+ break;
627
+ }
628
+ }
629
+ if (!matches)
630
+ {
631
+ continue;
632
+ }
633
+ if (matches && $better(rank, bestRank))
634
+ {
635
+ best = variant;
636
+ bestRank = rank;
637
+ }
638
+ }
639
+ return best === undefined ? "" : best.pattern();
640
+ }
641
+ function $better(rank, current)
642
+ {
643
+ if (current === undefined)
644
+ {
645
+ return true;
646
+ }
647
+ for (const [index, score] of rank.entries())
648
+ {
649
+ const other = current[index] ?? 0;
650
+ if (score !== other)
651
+ {
652
+ return score > other;
653
+ }
654
+ }
655
+ return false;
656
+ }`,
657
+ ts: `interface Selector
658
+ {
659
+ value: string;
660
+ categories: string[];
661
+ }
662
+ interface Variant
663
+ {
664
+ keys: string[];
665
+ pattern: () => string;
666
+ }
667
+ function $better(rank: number[], current: number[] | undefined): boolean
668
+ {
669
+ if (current === undefined)
670
+ {
671
+ return true;
672
+ }
673
+ for (const [index, score] of rank.entries())
674
+ {
675
+ const other = current[index] ?? 0;
676
+ if (score !== other)
677
+ {
678
+ return score > other;
679
+ }
680
+ }
681
+ return false;
682
+ }
683
+ function $select(selectors: Selector[], variants: Variant[]): string
684
+ {
685
+ let best: Variant | undefined;
686
+ let bestRank: number[] | undefined;
687
+ for (const variant of variants)
688
+ {
689
+ const rank: number[] = [];
690
+ let matches = true;
691
+ for (const [index, key] of variant.keys.entries())
692
+ {
693
+ const selector = selectors[index];
694
+ if (key === "*")
695
+ {
696
+ rank.push(0);
697
+ }
698
+ else if (selector !== undefined && key === selector.value)
699
+ {
700
+ rank.push(2);
701
+ }
702
+ else if (selector !== undefined && selector.categories.includes(key))
703
+ {
704
+ rank.push(1);
705
+ }
706
+ else
707
+ {
708
+ matches = false;
709
+ break;
710
+ }
711
+ }
712
+ if (matches && $better(rank, bestRank))
713
+ {
714
+ best = variant;
715
+ bestRank = rank;
716
+ }
717
+ }
718
+ return best === undefined ? "" : best.pattern();
719
+ }`
720
+ }
721
+ };
722
+ /** The helpers a module's messages use, with the cache that `$number` and `$plural` share. */
723
+ function helpersFor(used, javascript) {
724
+ const needed = new Set(used);
725
+ if (needed.has("number") || needed.has("plural")) {
726
+ needed.add("cache");
727
+ }
728
+ return Object.keys(HELPERS).filter((name) => needed.has(name)).map((name) => HELPERS[name][javascript ? "js" : "ts"]).join("\n");
729
+ }
730
+ function typeOf(type) {
731
+ return type === "number" ? "number" : type === "date" ? "Date | number" : "string | number";
732
+ }
733
+ /**
734
+ * Compiles one locale's catalog into a module: `locale`, one exported
735
+ * function per message named from its key, and the `Intl` helpers they
736
+ * share. Each function takes an `args` object typed from the message's
737
+ * placeholders, or nothing when the message has none. A formatter whose
738
+ * options are all literals is a module-level binding created on first use
739
+ * and shared by every message that formats the same way; options that read
740
+ * an argument find their formatter in a cache keyed by the options. Only
741
+ * the helpers the messages use are written.
742
+ */
743
+ export function compileMessages(locale, catalog, options = {}) {
744
+ const javascript = options.language === "js";
745
+ const out = [];
746
+ out.push(`// Generated by @zerolith/i18n from ${commentText(options.source ?? `the ${locale} catalog`)}. Do not edit; regenerate instead.`);
747
+ if (javascript) {
748
+ out.push("// @ts-check");
749
+ }
750
+ out.push(`export const locale${javascript ? "" : ": string"} = ${jsLiteral(locale)};`);
751
+ out.push("");
752
+ const head = out.length;
753
+ const formatters = new Map();
754
+ const used = new Set();
755
+ const names = [];
756
+ const seen = new Set();
757
+ for (const [key, source] of Object.entries(catalog)) {
758
+ const name = identifier(key);
759
+ if (seen.has(name)) {
760
+ throw new Error(`zerolith/i18n: keys "${key}" and another one both become ${name}`);
761
+ }
762
+ if (name === "locale") {
763
+ throw new Error(`zerolith/i18n: key "${key}" becomes locale, which every compiled module exports; rename the key`);
764
+ }
765
+ const binding = RESERVED.has(name) ? `message_${name}` : name;
766
+ seen.add(name);
767
+ names.push(name);
768
+ const message = new Parser(source, key).parse();
769
+ const emitter = new Emitter(key, message, formatters, used);
770
+ const body = emitter.body();
771
+ const args = [...emitter.arguments.entries()].toSorted(([a], [b]) => a.localeCompare(b));
772
+ const doc = source.replace(/\*\//g, "* /").replaceAll("<", "&lt;").split(SOURCE_LINES).map((line) => ` * ${line}`.trimEnd()).join("\n");
773
+ const argumentType = `{ ${args.map(([argument, type]) => `${property(argument)}: ${typeOf(type)}`).join("; ")} }`;
774
+ if (javascript) {
775
+ out.push(`/**\n${doc}${args.length > 0 ? `\n * @param {${argumentType}} args` : ""}\n * @returns {string}\n */`);
776
+ out.push(`${binding === name ? "export " : ""}function ${binding}(${args.length > 0 ? "args" : ""})`);
777
+ }
778
+ else {
779
+ out.push(`/**\n${doc}\n */`);
780
+ out.push(`${binding === name ? "export " : ""}function ${binding}(${args.length > 0 ? `args: ${argumentType}` : ""}): string`);
781
+ }
782
+ out.push("{");
783
+ for (const line of emitter.prelude) {
784
+ out.push(` ${line}`);
785
+ }
786
+ out.push(` return ${body};`);
787
+ out.push("}");
788
+ if (binding !== name) {
789
+ out.push(`export { ${binding} as ${name} };`);
790
+ }
791
+ out.push("");
792
+ }
793
+ const helpers = helpersFor(used, javascript);
794
+ const shared = Array.from(formatters, ([create, binding]) => `const ${binding} = $once(() => ${create});`);
795
+ out.splice(head, 0, ...(helpers === "" ? [] : [helpers, ""]), ...(shared.length === 0 ? [] : [...shared, ""]));
796
+ return { code: out.join("\n"), names };
797
+ }
798
+ /** The keys of a catalog as function names, for comparing locales. */
799
+ export function messageNames(catalog) {
800
+ return Object.keys(catalog).map(identifier);
801
+ }
802
+ /**
803
+ * The index module for a set of locales: the list of locales and one lazy
804
+ * loader per locale, so each locale is its own chunk.
805
+ */
806
+ export function compileIndex(locales, options = {}) {
807
+ const javascript = options.language === "js";
808
+ const extension = javascript ? "js" : "ts";
809
+ const lines = [`// Generated by @zerolith/i18n. Do not edit; regenerate instead.`];
810
+ if (javascript) {
811
+ lines.push("// @ts-check");
812
+ }
813
+ if (!javascript) {
814
+ lines.push(`import type * as first from ${jsLiteral(`./${locales[0] ?? "en"}.${extension}`)};`);
815
+ lines.push("");
816
+ }
817
+ lines.push(`export const locales${javascript ? "" : ": readonly string[]"} = ${jsLiteral(locales)};`);
818
+ lines.push("");
819
+ lines.push(`/** Loads one locale's messages; each locale is its own module. */`);
820
+ lines.push(javascript ? "export const loaders = {" : "export const loaders: Readonly<Record<string, () => Promise<typeof first>>> = {");
821
+ lines.push(locales.map((locale) => ` ${jsLiteral(locale)}: () => import(${jsLiteral(`./${locale}.${extension}`)})`).join(",\n"));
822
+ lines.push("};");
823
+ lines.push("");
824
+ return lines.join("\n");
825
+ }
826
+ //# sourceMappingURL=compile.js.map